_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | Public variable changed in script isn't stored in playmode I have a public variable float x in script Foo.cs. I have a Bar.cs script with a function like this bar() Foo foo FindObjectOfType lt Foo gt () foo.x 1f And a custom editor which calls bar() when a button is pressed. All of that works fine in the editor, my float x is changed to 1, but when I enter playmode the value changes itself. If I change it manually in the inspector it works fine too. So for example I set x manually in the inspector to 10. I enter play mode, x is still 10. I exit playmode and call the bar() function. x has changed to 1 in the inspector. After hitting "Play" x changes back to 10. How can I fix this? |
0 | In Unity, does a reference delegate clear out when its parent GameObject is destroyed? If I have a GameObject with a component like some class SomeComponent MonoBehaviour System.Action DoStuff class SomeOtherComponentInAnotherGameObject public GameObject ObjectWithThatComponent void Start() ObjectWithThatComponent.GetComponent lt SomeComponent gt ().DoStuff SomeFunc Destroy(ObjectWithThatComponent) is there still a reference to SomeComponent somewhere? I'm getting some odd behaviour random crashing when deleting this stuff but I'm not sure if it's being caused by these delegates. |
0 | Black screen when building apk Unity Alright, I have a bit of a confession to make I accidentally posted this question in the wrong place Stack Overflow. Whoops. Anyway, here's my problem. Sorry if you've seen this before. Here's the original post. I've been struggling with this issue for a few days now. Windows builds for my game work fine, but when I build it to Android, it loads, shows the "made with Unity" screen, then fades to black. Now, I know the next scene (an animated logo) is running because it is playing the audio in real time. However, nothing in the scene is visible. Then, the UI for the in game loading screen appears. Normally, the game would then load, and it does, but again, the camera thinks there are no sprites in the scene. I can still play the game, and the audio sounds just normal, but I can't see. Then, when I die, the game over UI appears, and I can use it as normal. The shop menu works absolutely fine, but the game itself does not. It's as if Unity decided that all SpriteRenderers in the game just didn't exist, and that the camera background color was now black. There are no scripts or animations causing this directly, as it does work in editor and on a PC build. The game also works fine using Unity remote, but the build has the issue. I also made sure that none of the textures were too large for Android (to the point where not one of them is larger than 256x256, which looks terrible but proves a point). Now, before anyone asks, yes, I have seen the other question on this topic, and no, sadly, it did not help. My camera is set to "solid color", not "don't clear." I tried "skybox" too, just to be safe. I have also tried disabling post processing, hoping that Android was just unable to handle it. It did nothing. I have even tried entirely disabling all of the sprites in the scene, but even then, the background is still black, indicating that the camera is still not playing nice. Also, here is a screenshot showing the quality settings for the Android build. |
0 | Error CS1585 Member modifier 'private' must precede the member type and name I've been knocking errors out of my script after working thoroughly through them but this one has me stumped, even though I'm sure it's something really simple. This is the following error that I'm getting Assets Scripts Movement Scripts FirstPersonCharacter Scripts FirstPersonController.cs(44,9) error CS1585 Member modifier 'private' must precede the member type and name From my script using UnityEngine using UnityStandardAssets.CrossPlatformInput using UnityStandardAssets.Utility using Random UnityEngine.Random using MouseLook UnityEngine.MouseLook public class FirstPersonController MonoBehaviour SerializeField private bool m IsWalking SerializeField private float m WalkSpeed SerializeField private float m RunSpeed SerializeField Range(0f, 1f) private float m RunstepLenghten SerializeField private float m JumpSpeed SerializeField private float m StickToGroundForce SerializeField private float m GravityMultiplier SerializeField private MouseLook m MouseLook SerializeField private bool m UseFovKick SerializeField private FOVKick m FovKick new FOVKick() SerializeField private bool m UseHeadBob SerializeField private CurveControlledBob m HeadBob new CurveControlledBob() SerializeField private LerpControlledBob m JumpBob new LerpControlledBob() SerializeField private float m StepInterval SerializeField private AudioClip m FootstepSounds an array of footstep sounds that will be randomly selected from. SerializeField private AudioClip m JumpSound the sound played when character leaves the ground. SerializeField private AudioClip m LandSound the sound played when character touches back on ground. private Camera m Camera private bool m Jump private float m YRotation private Vector2 m Input private Vector3 m MoveDir Vector3.zero private CharacterController m CharacterController private CollisionFlags m CollisionFlags private bool m PreviouslyGrounded private Vector3 m OriginalCameraPosition private float m StepCycle private float m NextStep private bool m Jumping private AudioSource m AudioSource readonly AudioSource AudioSource public UnityStandardAssets.Characters.FirstPerson.MouseLook Use this for initialization private void Start() This is line 44 m CharacterController GetComponent lt CharacterController gt () m Camera Camera.main m OriginalCameraPosition m Camera.transform.localPosition m FovKick.Setup(m Camera) m HeadBob.Setup(m Camera, m StepInterval) m StepCycle 0f m NextStep m StepCycle 2f m Jumping false m AudioSource GetComponent lt AudioSource gt () m MouseLook.Init(transform, m Camera.transform) Update is called once per frame private void Update() RotateView() the jump state needs to read here to make sure it is not missed if (!m Jump) m Jump CrossPlatformInputManager.GetButtonDown("Jump") if (!m PreviouslyGrounded amp amp m CharacterController.isGrounded) StartCoroutine(m JumpBob.DoBobCycle()) PlayLandingSound() m MoveDir.y 0f m Jumping false if (!m CharacterController.isGrounded amp amp !m Jumping amp amp m PreviouslyGrounded) m MoveDir.y 0f m PreviouslyGrounded m CharacterController.isGrounded ... Now I know the problem is private void Start() on line 44, and from everything I've read, it's in the wrong place (to make sure, I changed it to public void, then just left it as void, both resulting in errors) however I'm stumped as to where I should move Private Void too. I appreciate any and all advice on this. |
0 | How can I make my image to be blur like the one in my message content? Should I use post processing v2 depth of field or something else ? I want to do it for my main menu. I have my own image and I want to make it blur like this one. I changed my images texture type to Sprite (2D and UI) and assigned it to a ui image component. Now the question how to make it blur ? |
0 | How to save persist a GameObject with incremental levels? Dictionary? List? I create buildings and they have child Text objects that will reflect the building level. The Problem What can I use to store the buildings a player has built so the data can be persisted? I've looked at Lists, but when I upgrade a building, how would I update the list so that particular building has its new level reflected? I'm working on a dictionary so I can update the key with the new value (level) but running into a problem with the keys and names. If I have lets say 10 "Farms" and try to add them to the dictionary, even though they have different properties, I get an error that I have a duplicate. Currently I am learning how to persist that data through scenes GameManager.CS public class GameManager MonoBehaviour public static Dictionary lt Building, int gt playerBuilt new Dictionary lt Building, int gt () public void SaveState() BinaryFormatter bf new BinaryFormatter() FileStream file File.Open(Application.persistentDataPath " EmpireGame", FileMode.Open) SaveClass sc new SaveClass() food Player.food.amount, buildingList playerBuilt bf.Serialize(file, sc) file.Close() Serializable class SaveClass public int food, wood, iron, stone public Dictionary lt Building, int gt buildingList new Dictionary lt Building, int gt () Building.CS public abstract class Building MonoBehaviour, IUpgradable public int ID level this building is public Text levelText public int level 0 starting cost to amplify the upgrade cost public int foodBase, woodBase, ironBase, stoneBase Upgrade cost public int foodCost, woodCost, ironCost, stoneCost public float BuildingCostPercentage 5f public void UpdateDictionary() if (GameManager.playerBuilt.ContainsKey(this)) GameManager.playerBuilt this level else GameManager.playerBuilt.Add(this, level) Note I have not tested the save function so I expect errors. |
0 | Jerky motion when standing on hovering object In a level of a 3D FPS I'm making, I have several floating pillars that move up and down (the x and z positions are always the same). When the player stands on one of the pillars, the motion is incredibly jerky going up, but smooth going down. I think the player is sinking into the pillar slightly and then catching up. I've tried different colliders, all sorts of combinations with rigidbodys and character controllers. I've tried setting the pillar as a parent of the character and then having the player hover slightly. I've just hit a brick wall and would appreciate an outside perspective. Here's my code just in case the issue is in there. Player movement public float walkSpeed 6.0F public float runSpeed 10.0F public float jumpSpeed 8.0F public float gravity 20.0F private Vector3 moveDirection Vector3.zero void FixedUpdate() CharacterController controller GetComponent lt CharacterController gt () moveDirection new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")) moveDirection transform.TransformDirection(moveDirection) moveDirection walkSpeed if (Input.GetButtonDown("Jump")) moveDirection.y jumpSpeed if (Input.GetButton("Sprint")) walkSpeed runSpeed else walkSpeed 6.0F moveDirection.y gravity Time.deltaTime controller.Move(moveDirection Time.deltaTime) void OnCollisionStay(Collision hit) if (hit.gameObject.tag "Column") transform.parent hit.transform else transform.parent null Pillar movement float height float speed Vector3 start Vector3 end Vector3 startOrEnd void Start() speed 0.01F start new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, gameObject.transform.position.z) void Update () motionControl(speed) float randomNumber(float min, float max) float number Random.Range(min, max) return number void motionControl(float speed) if (gameObject.transform.position start) end new Vector3(gameObject.transform.position.x, randomNumber(0, 10), gameObject.transform.position.z) startOrEnd end else if (gameObject.transform.position end) startOrEnd start gameObject.transform.position Vector3.MoveTowards(gameObject.transform.position, startOrEnd, speed) |
0 | Use of NetworkHash128 assetId in Custom Spawn Handler I was learning Custom spawn handler on Unity Manual. It says before spawning we need to Register Spawn handler using ClientScene.RegisterSpawnHandler(coinAssetId, SpawnCoin, UnSpawnCoin) I understood SpawnCoin and UnSpawnCoin is Handler function that will be invoked on clients but what is the use of coinAssetId? |
0 | Background generation with sprites in 2D dimension in Unity I am making 2D game with Unity. I want to create a procedurally generated background with a bunch of sprites (space background, I have sprites of nebulas and stars). I want some area around the player to be filled with sprites to some extent. How to make background filling with sprites inside area around player but outside camera visible area? How to control generation according to players movement for generating in player moving direction only? How to control the amount of filling sprites while generating? |
0 | Should I use scenes in Unity for menus? I assume scenes are for different levels, but should I use them for menu screens or is there a specific tool for menu screens? |
0 | Reading data from files in Unity on Android I have successfully read in and written level data using .dat files on unity PC builds, but compiling for android stops me from being able to read in information from the resources folder. I was under the impression that when it's compiled the resources folder was still accessible? I could create a .dat file in the persistent data path but that means hard coding the information only to serialize it, rather than the data originating from the .dat file itself. How can I include this data within the apk without hard coding it? Here is my code, working on PC Stream file File.Open("Assets Resources levelData.dat", FileMode.Open) levelData (LevelDataFile)bf.Deserialize(file) file.Close() Edit for context, the level data is very simple as this is just a puzzle game, and each level will just have a few starting positions and obstacles etc, and there will be 100 levels, hence I'm not doing a scene per level. |
0 | Why the plane is not black? I created a new material and changed the material colors to make it black R,G,B all value is 0 and A value is 255 The shader on the Plane is Legacy Shaders Transparent Diffuse But the Plane seems to be transparent. The main goal is put a plane in front of the camera the FPSCamera and then using a script to fade in out the alpha color. |
0 | why child class can access object while parent can't I have Block class which is the parent and StandardBlock the child , the prefab block have StandardBlock script attached to it, and according to my small knowledge in inheriting I though this would work public class Block MonoBehaviour HUD HUDscript Start is called before the first frame update void Start() HUDscript GameObject.FindWithTag("Canvas").GetComponent lt HUD gt () public void OnCollisionEnter2D(Collision2D col) HUDscript.addPoints() Destroy(gameObject) and child class public class StandardBlock Block some code but this is the error that i got NullReferenceException Object reference not set to an instance of an object Block.OnCollisionEnter2D (UnityEngine.Collision2D col) (at Assets Scripts Gameplay Block.cs 24) while writing OnCollisionEnter2D in the child class worked fine |
0 | Creating a unit selection box in Unity (2D) I've been trying to get my head around how to create a selection box for a selected unit in a 2D top down type game. When you click on a unit, a small box would appear around that unit based on some sort of box size. I do not know understand how to either calculate the size that box needs to be, draw the box (have an object under the game object that is sized appropriately with the selection box texture?) or how to make the selection box adjust it's size shape like in this gif http i.imgur.com xY7XW6C.gif I don't expect anyone here to hand feed me what I need to use, but some idea of how to go about doing this in Unity (starting from the smallest, and most simple thing, like just making the box) would be very much appreciated. Thanks! |
0 | Unity. Input in function for UI button OnClick I am trying to create multiple selections for some items on my UI. To perform multiple selections of items I want a user to hold left control button. But then I add if (Input.GetKeyDown(KeyCode.LeftControl)) Logic It registers in debugger what LeftControl is pressed but it skips all logic in brackets. This function is public and created for UI button. Is Input and Button.OnClick compatible at all? |
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 | In Unity, how do I make a 3D flight arc preview? I'm stuck on how to make a preview trajectory for a projectile appear when holding a button. The trajectory should start at a certain position on the scene and end wherever the player points their mouse. On mouse click, a projectile should be launched along that trajectory with the clicked position as its target. How can I do this? |
0 | How to read the binary file generated by the Unity profiler? I'd like to know how can I read the binary file generated by profiling Unity game and how can I save it on external hard disk. |
0 | Why Does unity LightPosition 0 Seem to Depend on Camera Position? I'm trying to write a fairly basic shader but I keep running into lighting issues with Unity. My first problem was trying to figure out which variable stored the light's position in world space. (I'm only working with one light, at least at the moment). I finally found something that responds to movement of my light source unity LightPosition 0 . However the shader still didn't do what I wanted it to do, so I did some debugging I have a basic vertex and fragment shader and what I'm currently doing in the fragment shader is float4 c float4(0, 0, 0, 1) float3 lp normalize(unity LightPosition 0 ) c.rgb lp return c This should just set the color of my object to the normalized position of the light source, correct? What I see in my scene is my object changes colors when I move my camera around it (I'm not moving the light source at all, it is a separate entity). The color also seems to increase in strength as I zoom in. To me, it seems as if unity LightPosition 0 is related to my camera's position, as well as orientation and zoom level, yet the documentation I've found says it should represent the position of the light in world space. I tried switching to using the following float3 lp float4( unity 4LightPosX0 0 , unity 4LightPosY0 0 , unity 4LightPosZ0 0 , 1.0 ) ...but that only colors my object red regardless of the light's actual position. Additionally, I've set the LightMode tag to Vertex. It seems like simply getting the world position of the light source shouldn't be this difficult. What am I not doing correctly? EDIT I've been playing around with the camera and light position and I think that unity LightPosition 0 actually puts out position in the projection space. If I place the light source in the lower left corner of the screen, the object is black. Upper left the object is green (0, 1), upper right is orange (1, 1), and lower right is red (1, 0). When I place it in the lower left (0, 0) and move the camera in front of it, it becomes blue. This is consistent with the depth value behavior. (0, 0, 0) would appear as blue. Now, how to get it from projection back to world?...or should I use a different variable? |
0 | Why can't I change the size of my spheres in Unity? I started to learn Unity. Now I make something like a solar system. I have one problem. What are the min and max sizes of the sphere? E.g. I have a radius of the Sun 1.5 but it shows like the Sun has radius 1, I can't make bigger. But also I have the Earth with 0.01 size and the Moon with 0.009. But I can't make the Mercury with 0.03 radius. So why when I'm creating a new sphere now I have only radius 1 and can't change it in Scene window? |
0 | Make enemy move diagonally in 2D I'm making the enemy follow the player only straight or diagonally e.g.(1,1)(1,0)(0,1)( 1,1). I expected the problem that I have, but I don't really know how to fix it. When my enemy is placed diagonally (relative to the player but not exactly), It will alternate rapidly between going diagonally and straight, causing it to appear like its vibrating. here is the simple script returning the Vector2 to follow Vector2 direction (player.position goblinTr.position).normalized direction.x Mathf.Round(direction.x) direction.y Mathf.Round(direction.y) return direction |
0 | How to create a material with variable color I'm new to Unity and trying to create a Carrom game. Since all the White and Black pieces, Queen basically have the same material and physical properties and texture except for their color, I'm trying to create a single material that I could assign to all 3 types of objects but could then set the material color per object type. Can this be achieved in Unity (I'm using 5.3.2)? |
0 | Why does 'InvalidCastException Specified cast is not valid.' occur for ARKitFaceSubsystem? Why does 'InvalidCastException Specified cast is not valid.' occur for ARKitFaceSubsystem in the snippet below? var faceManager FindObjectOfType lt ARFaceManager gt () if (faceManager ! null) m ARKitFaceSubsystem (ARKitFaceSubsystem)faceManager.subsystem |
0 | How can I tell if a Gameobject is currently touching another Gameobject with a specific tag? I've seen similar questions to this here on Stack Exchange Game Development, but none of the answers to them have helped my problem. I am working in Unity 2019.2.18f1 with Visual Studios 2019 Community. What I want to know how to tell when one Gameobject (the player) is currently touching another game object with a tag name of "Block". When the player collides with a "block" I want it to set jumpPossible true But when it leaves the block (by jumping or falling off) jumpPossible false What I currently have in my PlayerController script (the important stuff anyways) private void OnCollisionEnter(Collision collision) if (collision.gameObject.CompareTag("Block")) jumpPossible true private void OnCollisionExit(Collision collision) if (collision.gameObject.CompareTag("Block")) jumpPossible false The problem I am having is when the player is currently on a block and then touches another block. When it leaves the one of the blocks, it will set jumpPossible false and so you can't jump. What I want for this script to do is whenever the player is touching any Gameobject with a tag of "Block" it should allow it to jump. |
0 | Multiplayer Synchronization I am developing multiplayer game in unity. For multiplayer i am using photon networking library. I created room and join client successfully. But Problem is I am doing gameobject movent by this code public GameObject player IEnumerator Moving (String temp) for (int i 0 i lt 3 i ) player.transform.DOMove (CurrentPositionHolder, 0.5f).SetEase (Ease.Linear) yield return new WaitForSeconds (0.5f) DoMoveis library here. Problem is player movement is not synchronized. For Synchronization I add photonview component to player gameobject. And i call coroutine though RPC like this. player.GetComponent lt PhotonView gt ().RPC ("Moving", PhotonTargets.All, "temp") Accordingly i changed coroutine like this PunRPC IEnumerator Moving (String temp) for (int i 0 i lt 3 i ) player.transform.DOMove (CurrentPositionHolder, 0.5f).SetEase (Ease.Linear) yield return new WaitForSeconds (0.5f) I got this error Illegal view ID 0 method Moving GO player UnityEngine.Debug LogError(Object) |
0 | Data structure for objects in a galaxy of star systems I'm having some difficulty coming up with the appropriate data structure to use for a game. I'm aiming for a galaxy view with tens of thousands of visitable star systems. Structure Hierarchically, each star system can contain one or more of the following Planets and their moons Asteroid Belts Megastructures and their moons sub structures All of the above can have quot points of interest quot POI eg a station in low orbit, a surface resource node, a docking bay. Usage I don't particularly care about physical location within a system beyond knowing its order in the hierarchy (I'll be showing a list of locations, rather than trying to render them in 3D space). So I can treat all objects within a system as located at the star for the pursposes of calculation. I do, however, need a way to specify routes from any Planet AsteroidBelt Moon Megastructure POI to any other. I also need to be able to search for other locations meeting certain criteria both to offer as destinations in the UI and to handle rendering . Each type of location will have some unique properties (Asteroid belts have resource distributions, for example whereas planets ave atmospheres) but they also have lots of common properties (inventory, owner, comms network node id, etc). Ideas so far Obviously, with the numbers I'm considering I need to take a sparse lazy generated approach. Currently the galaxy is built entirely in the GPU and stars are only presented to the CPU when the user first clicks on them. That lends itself nicely to a hierarchical data structure with a load on first access approach. Click on a star and it's added to the list, so the name is saved. Scan visit it and I'll generate the system contents. Unfortunately, I also need to be able to search across all generated locations efficiently (given an ID, find the star system coordinates, find planets with an atmosphere like X, find any location with X in its inventory) in a potentially huge search space. That doesn't align with recursively walking up down trees. I considered using a heirarchy and manually maintaining a number of separate indices to speed up searching. It's doable but a pain and error prone. It also feels like one of those solutions where I'm going to keep finding one more type of query I need to support and before long I'm trying to implement a minimal database. Speaking of which I also need to persist this data at some point. Currently I'm serializing to a densely packed binary blob. So... I took a step back and wondered whether I should actually use a database. I can see the benefits of using something like SQLite which I could bundle with the game and would handle persistence, indices, and the rest. Db? After spending a couple of days implementing the basics, I can see this is going to be quite a long and involved process. None of the friendly tooling works well in Unity, so I can't take advantage of entity framework w code first, nor nice Linq To Sqlite predicate handling. Even worse, most of the libraries to work with EF are tightly coupled to windows. EF Core seems like an option but I haven't been able to get it working in Unity (I need to do some assembly version mapping but as Unity overwrites the project file regularly and doesn't seem to support this itself, I think it's a losing battle). So I've headed down the route of implementing a data layer that generates SQL as needed. I can do that, but it opens up a huge can of worms in terms of manually maintaining the DB schema. I'm going to have to start tracking a DB version and bundling migration scripts with any update patch. It's a whole new maintenance burden. Question So... What am I missing? What's the elegant way to store a sparse hierarchy of data whilst still supporting flexible search across disparate object types that just happen to have a lot of common properties? |
0 | Rotate arrow without using Unity3d physics engine I have this code that simulates the movement of a projectile without using the unity physics engine IEnumerator LaunchProjectile(int angle, float speed) Move projectile to the position of throwing object add some offset if needed. Projectile.position transform.position new Vector3(0, 0f, 0) Projectile.rotation transform.root.rotation Debug.Log(transform.root.eulerAngles) Calculate distance to target float target Distance speed (Mathf.Sin(2 firingAngle Mathf.Deg2Rad) gravity) Extract the X Y componenent of the velocity float Vx Mathf.Sqrt(speed) Mathf.Cos(firingAngle Mathf.Deg2Rad) float Vy Mathf.Sqrt(speed) Mathf.Sin(firingAngle Mathf.Deg2Rad) Calculate flight time. float flightDuration target Distance Vx this.arrowSimulationScript Projectile.gameObject.GetComponentInChildren lt ArrowSimulation gt () float elapse time 0 while (!arrowSimulationScript.Collided()) Projectile.Translate(0, (Vy (gravity elapse time)) Time.deltaTime, Vx Time.deltaTime) Projectile.LookAt(Projectile.position new Vector3(0, (Vy (gravity elapse time)) Time.deltaTime, Vx Time.deltaTime)) arrowSimulationScript.Velocity new Vector3(0, (Vy (gravity elapse time)) Time.deltaTime, Vx Time.deltaTime).magnitude elapse time Time.deltaTime yield return null The arrow is fired in the direction of the object which has this script attached. To make the arrow rotate I use this line of code Projectile.LookAt(Projectile.position new Vector3(0, (Vy (gravity elapse time)) Time.deltaTime, Vx Time.deltaTime)) The arrow moves towards the right direction but with the tip facing the z axis direction, instead of the direction of the bow. Here is a video of the problem https www.youtube.com watch?v cyK6DXxTw E If I comment out that line of code the arrow fly with the tip facing the direction of the bow, but it doesn't rotate. |
0 | How to customize player script with different abilities in each scene? I'm making a game with Unity. I wanted the player script to not have some features in some scenes but couldn't remove them from the script because I needed them for other scenes. So far, I just unpacked those player prefabs, created new scripts for each of them and removed the lines that I didn't want to have. I know this was not the best idea but I don't know any other way. One of its problems is that it makes managing the scripts hard and confusing. Is there a way that I can change them without creating new ones? Since I'm going to switch to the new Input system, I want to avoid the possible problems and headaches around these scripts. I also did this (creating a new script) for pause menu script as well. I provided two examples below to make the situation more clear. Example A) The player can use a shotgun in one of the scenes and I chose to not let him to use the knife in there. So I created a new script for that player and copied and pasted the original script (which had the melee attack ability) and then removed those lines from the new script. Example B) Pause menu can disable the health bar game object whenever the escape button is pressed. But for one of the levels, I don't want to use the health bar, so I pasted the code in a new pause menu script and removed the line that disables the bar. |
0 | How would I make my player controls respond quicker? I'm working on this game in Unity 2D where the user swipes to make a game object move in the direction that the user swiped in. Currently, when the user swipes it takes about a quarter of a second for the game object to respond and move in the new direction. What should I do to make the controls respond quicker? I know that with Input.GetAxis, I could make it Input.GetAxisRaw to make it more responsive. Right now it's like Input.GetAxis but I'm trying make it like Input.GetAxisRaw. (I can't use Input.GetAxisRaw because this is for a mobile game). Thanks. private Rigidbody2D rb private Vector2 moveVelocity in void Update() if (Mathf.Abs(lp.x fp.x) gt Mathf.Abs(lp.y fp.y)) If the horizontal movement is greater than the vertical movement... if ((lp.x gt fp.x)) Right swipe if(moveVelocity ! Vector2.left) moveVelocity Vector2.right else Left swipe if(moveVelocity ! Vector2.right) moveVelocity Vector2.left else the vertical movement is greater than the horizontal movement if (lp.y gt fp.y) Up swipe if(moveVelocity ! Vector2.down) moveVelocity Vector2.up else Down swipe if(moveVelocity ! Vector2.up) moveVelocity Vector2.down And void FixedUpdate() void FixedUpdate() rb.MovePosition(rb.position moveVelocity speed Time.deltaTime) |
0 | Make a object render behind trough another but make hide it if its behind some other object So first of all sorry for this strange title... I know it may sounds worse and a bit complicated... But heres my problem My player belongs to the "Player" layer. He stands somewhere on my map, which belongs to the "Map" layer. When the falls trough the map he isnt visible anymore... but he should ( dont ask why... he just should ). But the should still be hidden by other objects ( Walls, Trees, other players ). Player is standing ontop of the ground. He is hidden by the tree ( works fine ) . But he also should be visible while in the ground... and than while hes in the ground he also should be hidden by the tree for example. I already tried to modify the shaders by setting ZTest to Less or Greater. But this caused strange iusses ( Half of the player was rendered and he wasnt hidden by any objects ). I also tried to modify the render que... but this doesnt worked somehow... it just didnt changed anything... So what else i could do to achieve this effect ? I really appreciate any help ! D |
0 | Unity Controller to Make Reticle Orbit based on the right stick input d platformer arena like game. Right now I have it so a reticle moves around the player based on a controller's right stick's horizontal movement using the rotate around function and while it works great on keyboard on it is funky on controllers since you have to hold it left to rotate counter clockwise and right to make it rotate clockwise. I've been working on changing this for well over a month and a half. I've tried coding it myself and then googling it like crazy but I came up with nothing. the input they give you based on vertical and horizontal is what perplexes me the most. in the debugger comes up like this from a debug.log when tilting it up "H 0.02528, V .9874454". Which makes sense but when going to the top right it looks like "H 0.7592, V .842965". That's the part that confuses me. I can't find a way to use this data in any of the functions I have experience with and experimenting with new ones has gone nowhere. Any suggestions or ideas would help me greatly and would be even more appreciated! Based on the above image I want my reticle to be placed in a spot on it's orbit around a player's center based on the right stick's position on the controller. So if I completely titled up my stick the reticle goes up but if I release it stays there. Then if I tilt it to the left bottom corner it will "teleport" there without moving along the orbit. So think of old school twin stick shooters where you can aim instantly in the direction of your choice. This is my old code that used rotate around that slowly makes the reticle orbit as you hold the stick constantly left or right. I added a new axis called AV which is for vertical instead of just horizontal so now I just need a way to use these together somehow. void AimControllers() if (currentControllerAimAxisH ! null) AH Input.GetAxis (currentControllerAimAxisH) if (Mathf.Abs (AH) gt stickTol) reticle.transform.RotateAround(this.transform.position,new Vector3(0,0, AH),orbitAngle) |
0 | Transparency issues Unity5 I made a potion that displayed and rendered perfectly in 3DS max. When I imported it to Unity it didn t render correctly as the transparency was all over the place. I first imported it with a png texture with a separate png map for the alphas. I then tried using a .tga and a .psd file with alpha channels set up within the file but I got the same issues happen with both file formats. Does anyone know how to fix this I cannot seem to work it out. |
0 | Unity Car Rollover Protection I have a standart Unity car with Unity Car physics. What would be the best approach to protect my car from a rollover? I dont want to mess up and try and error 10 different approaches, so maybe here is an expert who really knows how to do it right? I couldnt find anything decent on the internet. |
0 | How to prevent object from moving when it's mesh collider is being updated? So I a made a script that lets the player grab a vertex, move it, and then update the mesh. To help prevent the player from trying to clip it through other objects I made it so the mesh collider is constantly being updated. It works however there is an issue where it keeps falling into itself. So I tried updating the constraints to prevent this but it doesn't seem to help anything. Visualization... With the mesh being updated after the LMB is released http gifyu.com images withnocollisionprevetnion.gif (SE doesn't like non imgur links apparently and they are too big for imgur). With the mesh being updated in real time http gifyu.com images withcollisionprevetnion.gif Also here is a gif showing how constraints on the RB don't solve the problem (I've tried freezing on different axes but those still cause issues too) http gifyu.com images constprob.gif So basically what can I do to prevent the object from moving when it's mesh collider is being updated? |
0 | Do I have to re assign localized text every time the game loads? I am trying to build a localization system for games. And I have stumbled upon a problem where in Unity you basically have to change all the text in Text components any other references like audio when loading a game every time. To better explain it if the default language is English and user decided to change language to any other. Even if you localize all the files used in the game via code, later on you will have to do it again, when user loads the game after quiting it. Because components don't persist data changed via code in run time. How do I make it so that user would be able to change the language once, and all of those references and text... would persist and didn't require re set up every time the game is loaded? Is that even possible in Unity? Or should I just localize after the game has been made. And just allow people to download different language versions. But then again, it makes it difficult for people who want to change their language. |
0 | Problem with camera deapth culling only option and objects in front of each other I have a prefab with 2 cameras. the 1st is rendering the world, the 2nd one all the suff in front of the 1st person characters "face". Now i have a problem with a gun using a muzzleflash both on the deapth only camera. The muzzleflash is on the very front tip of the gun and i assume because the 2nd face camera is set to "deapth only" it causes the muzzleflash to be off place. I came up with 3 ideas 1 changing the layer of the muzzleflash to world for some frames everytime a muzzleflash appears 2 having a 3rd camera rendering the muzzleflash only 3 adjusting the gun on the face camera, the muzzleflash on the world camera I assume the 1st two options have a huge overload, i prefer the 3rd one. But is it a good way to do it? How should i proceed in this situation? Or how do others? I also have animations so it can appear on 2 positions, normal and scoped. Edit Here is an image i added Debug.Break() as it was instantiated, its totally correct aligned. |
0 | How to give individual tiles their own collider in Unity's tilemaps? My floor tile is a 2D drawing of a 3D platform, for lack of a better description. I want my player character to stand not on the top of the tile but a little inside it, as the red circle does in the picture. How do I give this tile its own collider that would fit this shape, while letting others have a normal, square one? |
0 | How to model classes to be serialisation friendly in c ? It is going to be just a fraction of the code but for the sake of the example let's say I have a class Stat class Stat private string name public Name get return name public Stat(string name) name name When I serialise object of type Stat with for example TinyJSON, it produces "Name" "some random name" So I figured I will create StatData with public property and not a getter so then I can use it for serialisation. class StatData public string name As far as I can tell I have now 2 choices Write converter method and, upon serialisation request, convert Stat to StatData and serialise StatData. Pros single responsibility principle preserved Cons more code and nested dependencies Go with private StatData data in Stat class and using getters as previously and adding, eg. ToJSON() method on Stat Pros public interface Cons generics to handle inheritance eg. StatComposite and serialiser dependency Is are there any other method(s) or potentially design pattern to deal with the problem? |
0 | Make 2d sprite move in unity At the moment I have a movement script which moves my player in Bothe directions but it only faces 1 way using System.Collections using System.Collections.Generic using UnityEngine public class Movement MonoBehaviour public float moveSpeed 5f Start is called before the first frame update void Start() Update is called once per frame void Update() Jump() Vector3 movement new Vector3(Input.GetAxis( quot Horizontal quot ), 0f, 0f) transform.position movement Time.deltaTime moveSpeed void Jump() if (Input.GetButtonDown( quot Jump quot )) gameObject.GetComponent lt Rigidbody2D gt ().AddForce(new Vector2(0f, 5f), ForceMode2D.Impulse) How can I make the sprite face the other way when I move west not east? |
0 | Unable to Set Up unity remote? I have installed Android Studio and set the path in unity. And I am able to build apks with no problem. But when I try to test in unity remote unity gives an warning as Set up Android SDK path to make Android remote work I don't know what is happening. If Android SDK path is not set then how am I able build the apks. I tried to solutions like enabling usb debugging mode , running unity editor first then opening Unity Remote , installing Google USB driver component of Android SDK but none of them worked for me. |
0 | Unity what are the rules for determining sizes of gameobjects I am making a game for windows phone. I am a newbie so currently I am unable to understand if I have to make a simple menu for a game targeting portrait mode always, what should I give the background size ,camera size ,button size , position? For example I have to set a background on renderer full screen size in portrait mode and fis a gui test between it.. I am using 2d orthographic camera |
0 | How to position spawned objects in diamond and grid (row x column) arrangements I am creating clones of my objects using the code below public List lt Vector3 gt clonePositions public List lt GameObject gt cloneObjects for (int i 0 i lt clonePositions.Count i ) cloneObjects.Add(Instantiate(clonedObject, clonePositions i , quaternion.identity)) How can I create and position the cloned game objects in a grid matrix (row x column) arrangement (with equal spacing between and at equal spacing at the sides)? as seen below and also in a diamond shape arrangement as below I would like to keep the clones centered around the original game object. |
0 | Why the cube is getting to the other cube instead stopping when both colliders hit? I don't want to use a script with OnTriggerEnter or something like that but to simulate the red cube as a wall and when the blue cube collider hit the red cube collider it should stop. Both cubes have a box collider and on both the Is Trigger is checked true I also tried one of them or both when not checked true. And both colliders size on Z set to 3. But the blue cube is getting to the red one and not stop when colliding The blue cube is getting inside the red one I tried to add a rigidbody to the moving cube the blue cube but if using Is Kinematic same behaviour if not using Is Kinematic the blue cube is falling down. This is the script attached to the blue cube to move it to the target red cube using System.Collections using System.Collections.Generic using UnityEngine public class MoveObject MonoBehaviour public GameObject target public float speed Update is called once per frame void Update() transform.position Vector3.MoveTowards(transform.position, target.transform.position, Time.deltaTime speed) I want that the blue cube will stop when colliding the red cube collider that's why I set them on Z to 3. I don't need physics for now. Do I need must using OnTriggerEnter in my script for that ? I thought I tried it too but this seems to be working Both box colliders on the cubes unchecked set false the is trigger and I added a rigidbody to the moving cube the blue one and unchecked the use gravity and now it seems to be working. So I need a rigidbody even if I'm not using physics. I wonder why. |
0 | How to create a minecraft style world that is based of a heightmap For my game I am trying to create a Minecraft style world that is based off a heightmap that I made In Photoshop. I am trying to make the map which is 7km squared where each cube is 1m cubed but I haven't found a way to do it. The heightmap converts to a terrain file(in unity), but my problem is that I can't create the Minecraft look. what I have done so far looks like this what i want looks like this |
0 | How can I do unit testing in Unity? How to implement Unit Test at Unity3D. I wonder if it would be possible to extend the Unity editor to have some sort of testing framework in it. Is there any guideline to implement it? Any reference like book, blog? Any working example or project? |
0 | Generating a sprite using a list of points I am trying to dynamically generate a sprite in Unity to visualize a list of points. What I've got so far is creating a small Texture2D object and then trying to override the geometry static SpriteRenderer SpriteRendererFromPoints(SpriteRenderer spriteRenderer, List lt Vector2 gt points) var texture Texture2D.whiteTexture spriteRenderer.sprite Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f)) Sprite sprite spriteRenderer.sprite sprite.OverrideGeometry(points.ToArray lt Vector2 gt (), sprite.triangles) return spriteRenderer I am adding this SpriteRenderer and a PolygonCollider2D to my gameobject and the instantiate it like this GameObject meshObject new GameObject() PolygonCollider2D polygonCollider meshObject.AddComponent lt PolygonCollider2D gt () PolygonCollider2DFromPoints(polygonCollider, points) SpriteRenderer spriteRenderer meshObject.AddComponent lt SpriteRenderer gt () SpriteRendererFromPoints(spriteRenderer, (from point in points select new Vector2(point.x, point.y)).ToList lt Vector2 gt ()) Instantiate(meshObject) It all runs fine but when running this, the sprite is nowhere to be seen Any help as to what I'm missing here or alternative ways of accomplishing this would be much appreciated. |
0 | Attaching scripts which trigger on specified events to objects I'm new to Unity and C . For concreteness, I'll phrase the question in terms of building a TCG like Magic the Gathering or Hearhtstone, although the method seems of more general utility. Suppose we wish to create cards that have special properties, such as quot when played, does a thing quot , or quot Immunity to fire quot . Having created a card class, here is the pseudo code that I would like to write, when initializing the 'library' of cards Card testCard new Card( generic arguments here like HP, etc ) testCard.abilities fireImmunity, drawCardOnPlay, ... Where I would have defined the abilities fireImmunity, drawCardOnPlay, and all others in some convenient location. Of course, I could manually define these abilities on each card, but that seems like a short route to insanity many cards will share the abilities. First question it seems I need to create a 'container' on each card to hold the abilities of that card how does one do this, and what's it called? How where to write the abilities list that will go into these containers? First thought was the container should be a list, but I don't know what type of objects we should populate it with. Second question in order to handle effects that occur at specified times ( quot when drawn quot , quot at end of turn quot , etc) I think I need to be able to create custom events, similar to the built in ones such as onCollisionEnter. These custom events would then be referenced in the scripts such as drawCardOnPlay. How to do this and what's it called? Third question is this unnecessary? Is there a more obvious way to do these things? I'm certain this has answers somewhere (here, probably), but without knowing what these things are called I haven't made any progress. I've read some similar questions here but none that have addressed the implementation. |
0 | Unity RTS Single Selection Problem I am trying to build an RTS game and I have managed to form a way to select a unit using Raycast and the tag system. I made it so that if the object the ray falls onto is of tag "TankUnit" Make so and so variable true and allow it to move to another place. However, Units of the same tag even when not selected also move. How do I fix this problem? The script is bound to each unit. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.AI public class UnitController MonoBehaviour bool clicked false public float speed 10f public float rotationSpeed 10f public LayerMask groundLayer public NavMeshAgent playerAgent Update is called once per frame void Update() if (Input.GetMouseButton(0)) Debug.Log("Clicked") FindClickPos() if (Input.GetMouseButton(1) amp amp clicked true) Debug.Log("I clicked right mouse") Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit)) MoveTo(hit) private void FindClickPos() RaycastHit hitInfo new RaycastHit() bool hit Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo) if (hit true) Debug.Log("I hit " hitInfo.collider.name) if (hitInfo.collider.tag "TankUnit") Debug.Log("I hit" hitInfo.collider.tag "!") clicked true else Debug.Log("I didnt hit a unit ") clicked false else Debug.Log("I didnt hit anything...") clicked false void MoveTo(RaycastHit hit) Debug.Log("Position " hit.point) playerAgent.SetDestination(hit.point) |
0 | Why do I get a "Value Cannot be Null" error on material.SetTexture? Probably a really noob question, but I'm following this tutorial here and, using the code in the tutorial, I'm getting an annoying error Here's the code in question, the error is referring to line 20 (highlighted in the comments) public class RayTracingMaster MonoBehaviour public ComputeShader RayTracingShader public Texture SkyboxTexture private RenderTexture target private Camera camera private void Awake() camera GetComponent lt Camera gt () private void SetShaderParameters() RayTracingShader.SetTexture(0, " SkyboxTexture", SkyboxTexture) lt Line 20 is here RayTracingShader.SetMatrix(" CameraToWorld", camera.cameraToWorldMatrix) RayTracingShader.SetMatrix(" CameraInverseProjection", camera.projectionMatrix.inverse) private void OnRenderImage(RenderTexture source, RenderTexture destination) Render(destination) SetShaderParameters() private void Render(RenderTexture destination) Make sure we have a current render target InitRenderTexture() Set the target and dispatch the compute shader RayTracingShader.SetTexture(0, "Result", target) int threadGroupsX Mathf.CeilToInt(Screen.width 8.0f) int threadGroupsY Mathf.CeilToInt(Screen.height 8.0f) RayTracingShader.Dispatch(0, threadGroupsX, threadGroupsY, 1) Blit the result texture to the screen Graphics.Blit( target, destination) private void InitRenderTexture() if ( target null target.width ! Screen.width target.height ! Screen.height) Release render texture if we already have one if ( target ! null) target.Release() Get a render target for Ray Tracing target new RenderTexture(Screen.width, Screen.height, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear) target.enableRandomWrite true target.Create() I really can't see why it's telling me the value is null when I'm calling the name of an already defined Texture class. I have set the texture from the inspector. Any help would be appreciated. |
0 | Flat and crispy shading Im trying to create a mobile game that has flat, bright colors and I want every place to be lightened the same. Like this game and this is my game's current state I don't know what the problem is. It is too dark and not as good looking as the first image. If i increase the light, it gets bright, not saturated and crispy. Maybe wrong lighting or wrong material usage? First image looks so crispy and it almost like a Vector art. I modeled all of the assets myself in Blender. I tried using Ambient lighting but it didn't work. I also turned off shadows but still the same. Also there is a distortion in the big red circle i drew and i don't know why is it hapening. And i don't want the shiny light in the little red circle. |
0 | How can I get the Selector dialog to include my prefabs When setting a variable for an object in Unity, for built in types there is an option on the right hand side to bring up a dialog that lists the possible values that can be chosen for that variable, for example when selecting a Sprite for a Sprite Renderer Is it possible, and if so what do I need to do, to have that list populated with the prefabs within my project? In this example, there are a number of Item prefabs (both inside and outside the Resources folder if that makes a difference), however they do not appear in that dialog. Is there an attribute I am missing that needs to be specified on the Item class, or something else to enable this? using UnityEngine using System.Collections.Generic public class Item MonoBehaviour, IIdentifiable, IFilterable SerializeField private int IdField SerializeField private bool ActiveField public int Id gt IdField public bool Active gt ActiveField public class ItemRandomiser MonoBehaviour, IWeightedObject SerializeField private List lt string gt NamesField SerializeField private List lt Item gt ItemTemplatesField |
0 | Unity's "Stats" window displays bizzare number of triangles and vertices In my Unity scene I have 7 8 Barrels (with lids) each at about 2 400 triangles. 4 planes, each at at the very most 200 triangles camera, 3 lights, a FPS controller When I turn on the "Status" button in the lower left view port, it reports "14.1K triangles and 12.k vertices" I've double checked everything, there's no way the elemens in the scene can amount to so many triangles. The barrels in both Blender and Unity report having the number of triangles I've specified above Here's a Blender screen shot And here's one from Unity I've also checked the Hierarchy panel to see if I haven't accidentally duplicated stuff which might get to be on top of stuff (such as 100 barrels all in the same position so as to look as if there's just one there), and this is not the case. So my question is am I misinterpreting the Unity stats window? Is it a bug in the reported triangles count there? Or am I just completely missing how all this works ? |
0 | How can I reduce this code? Could you help me to reduce this code as much as possible? public GameObject TextPage public void Skin0() foreach (GameObject go in TextPage) go.SetActive(false) TextPage 0 .SetActive(true) public void Skin1() foreach (GameObject go in TextPage) go.SetActive(false) TextPage 1 .SetActive(true) public void Skin2() foreach (GameObject go in TextPage) go.SetActive(false) TextPage 2 .SetActive(true) |
0 | Instantiate random different gameObjects in specific spaces? I need to instantiate different gameObjects of different shapes and sizes on top of the left third and the right third of a table, and all this objects need to be random every time the scene loads. I have a library of around 80 GO but the most I'll instantiate, for now, is 30. All the instantiated GO have to be different, that means no duplicates. I thought that maybe I could create 30 empty gameObjects on the table, where I want to instantiate them in random, but I'm not sure if this is the most intelligent way to do it. Is there any other way? Also, since I have a library of GO so large, would it be possible to load the folder in the script instead of defining a list and populating it in the editor? I'm a bit new at coding for Unity, but I'm an experienced programmer. |
0 | Importing FBX model with updated textures into unity creating duplicate textures when using "Extract Textures" I am trying to figure out the best way to update models, textures and materials. I have a city model (city.fbx) that comes into unity with baked textures and materials from C4D. I bring it in to unity, extract the textures into a local folder called quot Textures quot and extract the materials into a local folder called quot Materials quot . Everything is remapped automatically by Unity. Let's say I then update the model using a file syncing program which replaces city.fbx with the same model, but with updated textures. In this case, the textures have been updated to green, where as before they were blue textures. when I extract the textures into the local quot Textures quot folder, unity creates duplicate textures instead of replacing the old ones. So we now have buildingtexture (the old blue texture) amp buildingtexture 1 (a new green texture) what is the correct way to import the updated model so as to avoid this? |
0 | How to sync random incidents over network? In my Photon powered game, I have a shotgun weapon and when a player fires a bullet, I call an RPC on other clients and it's bullets get direction from a random function, Random.Range, and on different clients it acts differently. How can I sync this so in every client, the bullets behave the same, i.e. in this case they would have same directions? I tried setting the same seed via Random.Seed but it didn't help. |
0 | Move enemies over the network without sending their positions I am trying to move enemies on two clients without sharing their positions. I use this startingPosition GetRandomDir() Random.Range(1f, 10f) To have the same movement on clients and server, I set the same seed to get the same directions with Unity Random. I set it with the system datetime now ticks on server and clients Random.InitState(newTicks) I am getting the same movements on the server and on the clients until a enemy starts looking for a player and chasing that player. When this happens, the enemy on one client is not at the same position on the other client. One enemy is targeting a player on one client, but on the other client he hasn't targeted that player yet. The enemy keeps wandering creating a different position on one client than on the server or other clients for example. Is there a better way to synchronize the enemy movement ? My idea was not to send the positions of the enemies from the server to the clients but rather have the clients move their enemies themselves. I would also like to know what to search for on Google to get help with this problem networking ai movement doesn't help, synchronize movement over the network without sending position does not return the results I would like either. What I think is strange and I don't understand is that the same code is executed on both the client and the server. The players and the enemies are at the same positions. Yet the enemy will choose to chase a player on the server and not to chase a player on the client. Resulting on the client to view the enemy at a different position than the position of the enemy on the server. |
0 | I Can't spawn buttons in my Grid. why? Today i was following a tutorial about making a shop, but i got a problem. and i've followed the scripting tutorial, but it seems i can't spawn a button inside the grid when i pressed GetItemButton. here's how the script goes public class ItemCatalogue MonoBehaviour public Items AvailableItems public Text DisplayArray public void GetItem() Items item AvailableItems Random.Range(0, AvailableItems.Length) InventoryCatalogue.Instance.AddMaterialToCatalogue(new ItemStack(item, 1)) DisplayArray.text item.name Use this for initialization void Start () Update is called once per frame void Update () and another one public class InventoryCatalogue MonoBehaviour public static InventoryCatalogue Instance public List lt ItemStack gt MatStorage public Transform ScrollList public GameObject ItemPrefab void Start() if (Instance ! null) return Instance this MatStorage new List lt ItemStack gt () public void AddMaterialToCatalogue(ItemStack Stack) bool hasItem false foreach (ItemStack i in MatStorage) if (i.item.name Stack.item.name) hasItem true i.amount Stack.amount if (!hasItem) MatStorage.Add(Stack) Anybody know why? |
0 | How can I assign a layer to tiles on an individual level? I've just started out with my first game in Unity. It's a simple 2D Platformer with a tile based level. When coding in the movement, I used the Physics2D.OverlapCircle() and an empty to check whether my player was touching the ground. However, I need to use a layer to make sure only the ground is detected. my code below fixed update used for physics calculations void FixedUpdate() right or left arrows being pressed float moveX Input.GetAxis( quot Horizontal quot ) Vector2 moveDir new Vector2(moveX playerSpeed, rb.velocity.y) rb.velocity moveDir update used for spacebar input and force void Update() if (Input.GetKeyDown(KeyCode.Space)) rb.velocity Vector2.up jumpForce Time.deltaTime is my circle overlapping any other colliders Collider2D collider Physics2D.OverlapCircle(feet.position, checkRadius, groundLayer) Debug.Log(collider) When I tried assigning layers to my tiles, I couldn't find a way to do it. I would be really grateful if anyone could show me how to, or if anyone can tell me a more efficient way to deal with jumping in a 2D platformer. |
0 | Update and merge Unity coordinate systems multiplayer Hololens Project Summary Creating a multiplayer HoloLens app that allows players to spawn and move objects around the local space they share. Problem I am able to connect to the other HoloLens and see the other player in the correct location but, for some reason the objects that I spawn I offset. I determined that the offset was based off of where the application started off. When developing in HoloLens the device always starts at (0,0,0). However, once the client has connected to the host and imported their world anchor the client's coordinate system is never updated event though the anchor is in the same physical location. This creates a problem because if the client is offset by 180 degrees everything that the host does is offset by the same amount when moving an object if that makes sense. Moving toward a solution After doing a lot of research I found this pertaining to sharing and HoloLens "After a GameObject is locked via the LockObject call, it will have a WorldAnchor which will keep it in the same physical position in the world, but it may be at a different location in the Unity coordinate space than other users." I found this on Microsoft's website here https developer.microsoft.com en us windows mixed reality shared experiences in unity Question So obviously my question is basically, is there a way to update the x,y,z coordinates of (0,0,0) during runtime? |
0 | Disable default unity editor behaviour on input I'm creating a tool to create scenes easier on edition mode. I'm using the right click to delete elements, and I'd like to be able to delete several elements by keeping the right mouse button pressed and moving the mouse around. The issue is that when I keep the right mouse button pressed over the scene window, the Hand Tool automatically activates, making the camera pan as I move the mouse. Is there a way to disable this behaviour? |
0 | Unity max scene limit I want to model the earth 1 1 in unity, but I can only zoom to a certain value in the scne window of unity |
0 | Preload multiple scenes at the same time and activate them on demand in Unity. Unity, async, simultaneous Preload scene in unity this question tells us about how we can pre load a scene in Unity and load it on demand. What it doesn't tell us how do we pre load multiple scenes at the same time and also keep the other scenes in memory waiting to be activated when we load another scene? Use case pre loading multiple scenes at the start of the application, so they are ready when required. Example You have a Scene Intro which takes 20s to complete where you start pre reloading Scene Main Menu that takes 10s to load. When Scene Main Menu has finished pre loading, you still have 10s to spare, those could be used to pre load Scene Main Game. You have a Scene Main Menu. Depending on user choice you load Scene Main Game or Scene Sandbox. You pre load both scenes while user is still in Scene Main Menu. When user makes their choice, chosen pre loaded scene is loaded. |
0 | Unity 5 light reflection on the water surface How to adjust reflection in Unity 5 to show up it on the water surface. So I have few light elements in the scene. So I want my water pro to reflect this lights. As example you can see red and yellow lights from the Shanghai's build on the water, that's what I am trying to achieve I've added water pro and setup flare Looks liker here some small reflection on the rect I market as red. But if comparing with real reflection it's more vertical reflection I've marked it as red well If you can see it unity example does not look natural. So if we compare distance from sun to the beach border on real photo, there is a huge sun line over the water surface, but there is not the same line on water pro in unity. Here is a video link with what I did http screencast.com t bq8Ocl24ZAJH |
0 | fish tank water distortion Shader for unity I am working on unity and trying to make a fish tank water distortion Shader effect with the following requirement 1.its a 2D top down prospective. 2.every object under in the fish tank has to be distorted, game objects might pass trough under the fish tank (distortion) and game object might pass over the fish tank (no distortion) as well. 3.the fish tank does not follow the main camera. I try to search online and most of the solution I get is to apply the shader to an object or to the main camera which will not meet requirement 3 or 2, can someone give me an ideal on what is the best way to deal with this ? I am working on a mobile game so the solution has to be light weighted on processing power. Many thanks ! |
0 | Stop Mesh render on intersect I am generating camera frustum mesh through code, it is working fine. Now I am searching a solution (shader based or else) to restrict the camera frustum mesh if it intersect with any object. Like you can see in the image my frustum is passing through the plane which is not correct. How can I control it, I search and apply different kind of shader but nothing worked. |
0 | Humanoid Retargetting Number of frames in LateUpdate is not the same as frames in animation I need to play an animation in such a way that each frame is for sure being played and not skipped. Why? I want to transfer an animation from 1 model to another. One model is Humanoid, the other one is Generic. This way, I can quot save out quot the Humanoid retargetting and process it in an external animation editor later. To transfer the animations, I need to make sure that I don't miss any frame while copying the pose to the other model. To do that, I use a very slow animator speed like this animator.speed 0.01f The Unity editor says this about the animation To make sure that each frame is really shown played, I have implemented my own counter. My counter however returns 43 frames and not 51 frames as the Inspector. No matter how often I repeat this process, it always return 43 frames. What am I missing? Thank you! private void LateUpdate() float f animator.GetCurrentAnimatorClipInfo(0) 0 .clip.length ( animator.GetCurrentAnimatorStateInfo(0).normalizedTime 1) animator.GetCurrentAnimatorClipInfo(0) 0 .clip.frameRate int iCurrentFrameIDInAnimationFile (int)f bool bIsNewFrame (iCurrentFrameIDInAnimationFile ! iLastFrameIDInAnimationFile) if (!bIsNewFrame) return else if (bIsNewFrame) iFrameCount 1 iLastFrameIDInAnimationFile iCurrentFrameIDInAnimationFile if ( animator.GetCurrentAnimatorStateInfo(0).normalizedTime gt 1 amp amp ! animator.IsInTransition(0)) animation has finished playing Debug.Log( quot Frames quot iFrameCount) this returns 43 frames. Why??? |
0 | Unity NavMesh Step Issue I have a scene in my game that takes place in a subway. I created a NavMesh so I can easily have the enemies chase the player. There seems to be a problem though as them enemies sometimes have a problem crossing the track. When looking at the NavMesh it appears that some parts of the track stick out above the NavMesh and I believe this is the reason the enemies sometimes have problems crossing the track. I have tried changing the step height up and down but that doesn't seem to change anything. What can I do to make the NavMesh cover the track in all spots so enemies can cross the track anywhere? Or is there maybe something else causing the enemies to not be able to cross the track in some spots? EDIT The rails and the ground are the same object and it is set as Navigation Static. Do they need to be 2 different objects for this to work? |
0 | Calculate corner rotation to fit between 2 waypoints I'm currently working on a system where I create a linear path by spawning waypoints, but i'm struggling to figure out how to compute the rotation needed to render the corner waypoints correctly. if I rotate it towards (nextSegment.Coordinate myCoordinate) it almost seems correct, most corners are behaving how I want. but you can see the first 2 corners, and one near the end are incorrect. if I rotate it towards (prevSegment.Coordinate myCoordinate) it solves the rotation for the incorrect segments in the previous solution. I know the coordinate of the next cell, and the previous cell and the cell i'm trying to rotate. But then the other segments are incorrect. I cannot figure out the pattern on how to decide which segment to rotate towards. Any ideas? |
0 | Start a progress bar when clicking a button This is basically what i am trying to do Click first scene Button Start A Progress Bar When the Progress Bar finishes, then... Second Scene instantiate my Game object This is my code First Scene public class LoadingScreen MonoBehaviour first scene script public GameObject slidercanvas public void NextScene() StartCoroutine(LoadNextLevel()) IEnumerator LoadNextLevel() slidercanvas.SetActive(true) Slider s slidercanvas.GetComponentInChildren lt Slider gt () AsyncOperation sceneLoading SceneManager.LoadSceneAsync("ScrollGrids") while (!sceneLoading.isDone) float progress Mathf.Clamp01(sceneLoading.progress 0.9f) s.value progress yield return null second scene public class ScrollGridScript MonoBehaviour public static ScrollGridScript Instance public GameObject SpawnPrefab GameObject newobj public GameObject parent Vector3 pos string msgSpeech int counter 0,totalVal public List lt GameObject gt btns float progress void Start() btns new List lt GameObject gt () StartCoroutine(Populate()) void Update() if (totalVal counter) for (int i 0 i lt btns.Count i ) btns i .SetActive(true) IEnumerator Populate() code here(encoding jsonurl) StartCoroutine(Downloadimage(newobj, msgSpeech,tname)) totalVal data "categorylist" .Count public void OnButtonclick(string imgname) effector.Instance.setEffector(imgname) Debug.Log("ButtonId" imgname) IEnumerator Downloadimage(GameObject newobj, string imgUrl, string catid) UnityWebRequest www UnityWebRequestTexture.GetTexture(msgSpeech) DownloadHandler handle www.downloadHandler yield return www.SendWebRequest() Texture2D texture2d DownloadHandlerTexture.GetContent(www) if (www.isHttpError www.isNetworkError) UnityEngine.Debug.Log("Error while Receiving " www.error) else counter newobj (GameObject)Instantiate(SpawnPrefab, pos, Quaternion.identity) newobj.transform.SetParent(parent.transform) newobj.transform.localPosition pos newobj.GetComponent lt Button gt ().onClick.AddListener(() gt OnButtonclick(catid)) Image sprite newobj.transform.GetComponent lt Image gt () sprite.sprite Sprite.Create(texture2d, new Rect(0, 0, texture2d.width, texture2d.height), new Vector2(0, 0)) fetch the images from the serve and convert it newobj.SetActive(false) btns.Add(newobj) instantiate object store in list And here is the output I see when I run this code |
0 | Gyroscope Parallax Effect In Unity I want to make a parallax effect in Unity 3D with gyroscope like the one on this site http matthew.wagerfield.com parallax I found an asset, but it is too expensive. So I need a script which I can set to the GameObject, so it would move depending phone's gyroscope. |
0 | Finer collision detection with multi path Polygon2DCollider from Tiled2Unity I'm in the process of incorporating Tiled2Unity prefabs into my code. Their exporter creates a collision object (shown below) that amalgamates the collider of each tile into a single Polygon Collider 2D made up of multiple "subcollider" paths, shown below as green polygons. What I'm trying to do is to adapt my old corner detection code to work with the new collider, but when OnTriggerStay2D(Collider2D other) is triggered, I'm not provided with the specific path I've collided with. In the picture, each green polygon is a path, and together they make up the Collider2D (other) provided in the argument. Is there any way to find out which path I've collided with, without looping through each of the 1000ish points every time I want to detect a nearby corner? So far I am only able to discover via events that I've collided somewhere in the ENTIRE collection of green polygonal paths. Thanks! |
0 | Custom shadow mapping in Unity. Works with preservative Light view but not with Orthographic So about a week ago I decided to make my own shadow mapping technique in Unity based on my understanding of the whole thing. The entire experience was somewhat successful. I learned a lot and I get to correct a lot of things such as the MVP matrix and the math behind it. One thing though didn't work as planned and I don't know why. First lets talk about what worked. I wrote a replacement shader that will show the depth of every object based on the Light Position perspective. Therefore I made a custom Light GameObject that act as a camera light with that replacement shader attached to it, and I record everything the Light sees into a render texture. Then I made a second Camera which is basically a child of the main camera, and sees what the main camera see with the exception of the replacement Shader that I attached previously to the Light gameobject. again I recorded everything from the camera to a render texture as well. After that, I wrote a basic Shader that does a basic light calculation and make a the shadow comparison between the two textures, and determines whether a fragment in a shadow or light. Also, I added a shadow Bias as well to eliminate any artifacts. struct appdata float4 position POSITION float3 normal NORMAL float2 uv TEXCOORD0 struct v2f float4 position SV POSITION float2 uv TEXCOORD0 float3 normal TEXCOORD1 float3 worldPos TEXCOORD2 float4 Tint sampler2D MainTex sampler2D SahdowMap Light, SahdowMap View float4 MainTex ST float4x4 WorldToCamera, WorldToLight float3 LightDir1 v2f VertexProgram(appdata v) v2f i i.position UnityObjectToClipPos(v.position) i.worldPos mul(unity ObjectToWorld, v.position) i.normal UnityObjectToWorldNormal(v.normal) i.uv TRANSFORM TEX(v.uv, MainTex) return i float Shadow Cal(v2f i, sampler2D DepthMap,float4x4 space) float4 projected2 mul(space, float4(i.worldPos, 1.0f)) float2 uv ( projected2.xy projected2.w) 0.5 0.5 float Shadow tex2D(DepthMap, uv).r if (uv.y gt 1.0) Shadow 0.0 return Shadow float4 FragmentProgram (v2f i) SV TARGET float LightDepth Shadow Cal(i, SahdowMap Light, WorldToLight) float ViewDepth Shadow Cal(i, SahdowMap View, WorldToCamera) float bias max(0.05 (1.0 dot(i.normal, LightDir1)), 0.015) float Shadow LightDepth bias lt ViewDepth ? 0 1 float4 Texture tex2D( MainTex, i.uv) float3 lightpos LightDir1 i.worldPos return saturate(dot(lightpos, i.normal)) Tint Texture Shadow The problem is when the Light is on perspective, this works perfectly fine as shown above, but when I switch the light camera to Orthographic this happen I tried many different things to fix it but I failed. I would love your insight in this whole thing, your thought, solution or even a suggestions. You are free to download the whole project as a package here Download Special thanks to DMGregory. |
0 | Unity Vertical Input will not return negative values I am trying to make a 'single stick' shooter, where the character faces the direction they are moving, but I'm struggling to get the movement working correctly no matter what I've tried, the player won't move down. Through some investigation, the issue seems to be that hitting the s key does not return a negative Vertical axis value, and I don't know enough about the workings of the Input manager to understand why. Here's the code, to check I haven't made a glaring mistake there public void FixedUpdate() Controls() ... public void Controls() if (gameStateManager.gameState SingleStickShooter) Variables float xInput Input.GetAxis( quot controller Horizontal quot ) float yInput Input.GetAxis( quot controller Vertical quot ) Vector2 controlThrow new Vector2(xInput, yInput) print( quot Control Throw quot controlThrow.x quot , quot controlThrow.y) currentSpeed runSpeed Movement Vector2 playerVelocity controlThrow currentSpeed rigidbody.velocity playerVelocity print( quot Velocity quot rigidbody.velocity.x quot , quot rigidbody.velocity.y) Rotation float angle Mathf.Atan2(yInput, xInput) Mathf.Rad2Deg if (xInput ! 0f yInput ! 0f) transform.rotation Quaternion.Euler(0f, 0f, angle) I would love to go tinkering around in the Input Manager and learn through mistakes, but it's a collaborative project where other games using this system are working, so I don't want to risk breaking something by going in blind. Also, those games are successfully using the down key, but mine isn't which makes me think it's something else I'm too green to realise. This is my first question so I don't know what else I should add, so let me know what other context you need and I'll add what I can. EDIT Below I've added the debugging info Ben Johnson requested. Console output returns over 1000 values due to being called in Update() the section shown is specifically when I go from pressing right and up to right and down. Gravity value for input manager is the only thing I can see that's different, but changing it doesn't seem to fix my problem. I thought that obviously having the vertical axis set to the Y axis would be obvious too, but that also didn't help so I reverted to the one above it. |
0 | Material colours in unity not displaying correctly? Even though I've picked blue the color is displayed as something pinkish. All colors are like this |
0 | Setting SteamVR Camera Target Eye before SteamVR installed in Unity I'm writing a plugin that can be used in both VR and non VR projects. I have a Camera that is used to display UI containing some game info on a secondary monitor. My problem is that when the end user adds my plugin and then imports steam vr, this UI camera's Target Eye is set to "Both" by default. I can't have any SteamVR code in my plugin. But I can't adjust Target eye property of the camera without it. I just want it so that the camera doesn't change when a user imports SteamVR. I want it to always render to the main display (target eye none) So just to clarify, I have my plugin, written in a non vr project with a standard Unity camera. There is no Target Eye setting for this standard camera. User wants to use it in VR project, imports plugin into SteamVR Project Camera used to render UI gets automatically converted (wrongly) into SteamVR camera Defaults to Target Eye Both Need it to be Target Eye None At the moment to avoid users submitting countless bug reports, I have to provide warnings in like 6 places telling users to dig way into my built in prefabs to adjust this setting manually if they use SteamVR. It's not easy for new Unity users, and I want to make adoption as easy as possible. |
0 | Moving a top down camera while keeping its height constant I'm currently writing the script for the player to explore the plane below. The camera view is set to be slightly rotated as to look down. And I have set the code to make the camera move. This is the code, and everything is set in the update method. if (Input.GetKey("w")) transform.Translate(Vector3.forward panSpeed Time.deltaTime) , Space.World if want to avoid camera going down if (Input.GetKey("s")) transform.Translate(Vector3.back panSpeed Time.deltaTime) if (Input.GetKey("d")) transform.Translate(Vector3.right panSpeed Time.deltaTime) if (Input.GetKey("a")) transform.Translate(Vector3.left panSpeed Time.deltaTime) The problem is that everytime that the camera goes forward, it goes straight down. And I don't want it to do that. I want to keep the "height" from the plane below to be the same as in the picture below. I want the camera to move along the red axis. I know of the existence of Space.World in order to achieve this, but the problem is that if I do that, whenever I rotate, now the controllers are all screwed up, because if I rotate to the right for example. Now Forward (W) moves the camera to the left, Right (D), moves the camera forward, etc etc. So basically what I need is 1 to make the camera keep the distance to the plane below while moving (not going down). and 2. To make it possible that even with rotations, the controllers are kept, and not having this weird behavior, when forward is not longer forward. Any ideas how to achieve this? |
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 | Does CharacterController benefit from adding lerp? Does CharacterController benefit from adding lerp? as in this script. mouse Input.GetAxis("Mouse X") current Mathf.Lerp(current, mouse, Time.deltaTime 10) transform.Rotate(0, current 600 Time.deltaTime, 0) I was using, transform.Rotate(0, mouse 18, 0) But read into the idea of lerp and wrote that. |
0 | Prevent Unity optimizing local variables out Is there a way to instruct Unity compiler not optimize (best only for builds run from Unity editor)? More precisely, I would like it to stop removing local variables, because it complicates debugging. For example, inspecting node void Generate() var node new Node() node node breakpoint here, node cannot be inspected var x nearest Nearest(new node) Debug.Log(new node) new node still cannot be inspected, but x nearest can Node Nearest(Node node) node is an argument here and can be inspected in Visual Studio produces error rather than displaying its value. The identifier node is not in the scope A solution would be make every local variable a private member instead private Node node void Generate() node new Node() node node breakpoint here, node can be inspected this would, however require frequent back and forth refactoring. I am using Unity 5.6.0f3 with C 6.0 support and Visual Studio 2017. note provided code is for illustration only and the question is not about debugging said code because reproducing specific compiler behavior is not trivial |
0 | How to prevent intepolated texture in fragment shader (Unity CG) Think about minecraft all the textures in minecraft have a very nice crisp pixelated look. Well, I'm trying to write a shader that will do this but it appears "sampler2d" returns some sort of interpolation between pixels of the underlying texture. I'm pretty new to shader writing and I'm not even sure if it can be done but I'm hoping to get a nice crisp blow up of small textures rather than a blurry one like this If anyone knows a way to make a shader crisp rather than interpolated like this (using Unity), I'd be thrilled to know as this hitch is pretty detrimental to what I'm trying to accomplish... Here's the subshader as it is right now (it's skipping all the light calculations and just outputting the sampler as I'm just trying to resolve the blurry texture sampling) SubShader Pass Tags "LightMode" "ForwardBase" CGPROGRAM pragma vertex vert pragma fragment frag user uniform float BlendVal uniform sampler2D DiffuseTex uniform sampler2D NMTex uniform sampler2D PixelMap uniform float4 DiffuseTex SV uniform float4 SpecColor uniform float SpecIntensity uniform float4 RimColor uniform float RimIntensity uniform float RimCoefficient unity uniform float4 LightColor0 struct vI float4 pos POSITION float3 norm NORMAL float4 uv TEXCOORD0 struct vO float4 pos SV POSITION float4 uv TEXCOORD0 float3 worldPos TEXCOORD1 float3 normDir TEXCOORD2 vO vert(vI i) vO o o.uv i.uv o.worldPos mul( Object2World, i.pos).xyz o.normDir normalize(mul( float4(i.norm, 0.0), World2Object).xyz) o.pos mul(UNITY MATRIX MVP, i.pos) return o float4 frag(vO i) COLOR float3 lightDir float3 viewDir normalize( i.worldPos WorldSpaceCameraPos.xyz) float atten float3 normDir normalize(i.normDir) float4 RimLight float4 DiffuseLight float4 SpecularLight float2 UVCoord i.uv.xy float4 test tex2D( PixelMap, UVCoord) float4 Clrx0 lerp( Directional Light if( WorldSpaceLightPos0.w 0) lightDir normalize( WorldSpaceLightPos0.xyz) atten dot(lightDir, normDir) point light else float3 dist i.worldPos.xyz WorldSpaceLightPos0.xyz lightDir normalize(dist) atten (1 length(dist)) (dot(lightDir, normDir)) DiffuseLight atten LightColor0 SpecularLight atten LightColor0 SpecColor SpecIntensity pow(max(0.0,dot(reflect(lightDir, normDir), viewDir)), 1) (1 tex2D( DiffuseTex, i.uv.xy).w) RimLight atten LightColor0 RimColor RimCoefficient pow((1 saturate(dot( viewDir, normDir))), RimIntensity) saturate(dot(lightDir, normDir)) float4 totalLight DiffuseLight SpecularLight RimLight float4 fin float4(UVCoord.xy,0,0) return test Fin totalLight ENDCG |
0 | Child GameObject doesn't follow parent's transform Look at this picture first I have model that has sword in his hand. I added a cube named "Attack Collision" and located to blade position. And then set the hand to parent. But when the game starts, sword moves but it's children "Attack Collision" doesn't move at all. The funny thing is in the scene, I tried to move the "sword", but only it's children "Attack Collision" was moved. Seems like the sword is somekind of locked, because it's transform can be change but not applied at all, it's just stand still there and only it's children that made from Unity was moved like this I made this model and animation by Blender and imported to Unity as .FBX file. What am I missing? |
0 | In Unity, how do I create a drag and drop object? I have a 2d scene. I want the player to be able to pick up an object, move it around the scene and drop it somewhere. I can't find any way to do this, and all of the resources for Unity are really daunting and I can't find anything relevant to what I'm doing. I've tried adding the drag rigidbody script to both my camera and the sprite I want to drag, to no effect. Where can I find relevant documentation for stuff like this? Basic things like how to implement a script or what objects I need to attach these scripts to the stuff on the unity website is a little too advanced. |
0 | How to determine size of art assets for Unity UI? Previously when I made games, I used ui assets from the asset store. Working with those assets was easy as the backgrounds were plain. However, I'm now working on a game where custom graphics are used for UI. So, I need to specify size of backgrounds,icons etc to the art team. I understand how aspect ratio works with regards to unity camera, but having trouble understanding the relation between camera size and Canvas. For example, for a camera size of 4.6, an image size of 517X920 will cover the whole screen in 9 16 aspect. However, the same image is considerably larger when used as UI image under the Canvas. Can someone please help me understand how Canvas deals with image sizes? |
0 | Unity3d AudioSource is not playing if gameObject is removed after play was started I am not able to play my audio source if I deactivate the panel where the AudioSource is attached to AFTER it. audioBtnEnter tmpBtnGeneral.GetComponent lt AudioSource gt () audioBtnEnter.Play() tmpBtnGeneral.SetActive(false) I would totaly understand if this would not be possible tmpBtnGeneral.SetActive(false) audioBtnEnter.Play() But why does the first code not trigger the audio play? Is this a race condition problem? |
0 | UNITY 3D Saving last scene I can't find working solution for this problem anywhere. Here is what I'm trying to do My Android game contains 10 levels, user quits game on level 2. Next time user starts game it load level 2 automatically. Thats all I want, no need to save objects, just load last scene. I prefer simple javascript, but examples on the unity tutorials confuse me. Thanks for answers. |
0 | Accessing a char array from another class I'm working on a crossword puzzle game. In order to set the letters in my tiles, I have a script attached to text components that accessing a char array that stores my letters. It looks like this First class public class GenerateBoard MonoBehaviour public static char , gameBoard new char 15,15 void Start() gameBoard 0, 0 'W' Second class public class SetLetter MonoBehaviour Text letter public int x public int y Start is called before the first frame update void Start() letter GetComponent lt Text gt () letter.text GenerateBoard.gameBoard x,y "" Update is called once per frame void Update() Debug.Log("glitch " GenerateBoard.gameBoard 0, 0 ) I would expect Debug.Log to print 'W' but it appears to be empty. Why isn't it accessing the letter 'W' from the first class? When I use Debug.Log in my first class it properly prints 'W'. |
0 | Create button in NGUI I try to create a button with the help of the NGUI. Here are screenshots of me doing that So the problem here is the next. When clicking play button in game mode I hope to get the following line in the console play. But actually nothing happens. What am I doing wrong? |
0 | How are game menus logically structured? I've been struggling with making a game menu system in Unity for some time now. I spent time developing a way to help myself understand how game menus are connected together. Right now, I'm calling it the Screen Menu relationship. In this relationship, Screens (e.g. Main Menu, Game Over and Inventory screens) hold access to Menus (e.g. Options Menu, Level Select menu). These Menus are accessed via MenuButtons (e.g. Options menu button via the Pause Screen). Is this a valid way of thinking about how game menus are structured? How should I be thinking about it? |
0 | Reshapable polygonsprite I have an sprite I want to use as a texture. I want to create an area, defined by a polygon collider, where the sprite is drawn. For example Having the following sprite And the following polygon collider 2d I want to have the resulting sprite mesh This way I would have an image that covers exactly the polygon collider area. Having an sprite and modifying it's vertexes doesn't seem to do the trick, as they are only editable while loading the sprite into unity. Is there a way to make it editable in the editor, so while I change my collider, the image is updated to fit inside of it? |
0 | How to programmatically change sprite sheet sub sprite name I am trying to change the name of the sub sprites of a sprite sheet. I have searched and tried everything I can think of and cannot get it to work, which makes me think it can't be done at this point in time. Let's say I have a sprite sheet that has already been split up into individual sprites inside of Unity. I am attempting to change the sub sprite names programmatically. I tried using AssetDatabase.RenameAsset (...) on the sprite sheet asset, which only changes the sprite sheet name and not sub sprites. I then thought to obtain a sub sprite and attempt to change its name using the below code. if (AssetDatabase.IsSubAsset (subSprite)) AssetDatabase.RenameAsset (AssetDatabase.GetAssetPath (subSprite), "newSprite" i.ToString ()) However, this too only changes the sprite sheet name. I'm not sure where else I can take this to achieve my desired outcome, apart from programmatically copying the original sprite sheet and using that to create a copy. But even then, I still am unable to alter the sub sprite names. I also tried changing subSprite.name, but this just changes the internal name and not the asset name. Any ideas? |
0 | How to make an event happen only at the first start of the game? I want to know how to make something happen only once like a tutorial in a game which appears only when you first start your game and then when your game got saved to a further point it never appears again even when you close your game and start again. I want to give players some amount of gold when they first got their hands on my game ... but I do not want to give them that again and again whenever they restart the game ... So I want to know how to make something happen only once in a game application.. I hope you get my point ... thanks .. |
0 | Code for making Material offset follow Bone transform not exactly working In my game, I have an Eye Bone that is constantly moving. I'm trying to make a material attached to the eye (pupil material) move in relation to the Eye bone's transform. This Script is indeed moving the Material's offset, but it is seemingly ignoring the offsetMultiplier bit. For instance, if I set offsetMultiplier to 0, the material offset never equals 0 but instead keeps exactly following the Bone transform numbers. What might be the mistake here? using System.Collections using System.Collections.Generic using UnityEngine public class EyeBoneMatOffset MonoBehaviour public Transform targetBone public Material mat public float offsetMultiplier 0.0f 0 for testing purposes Start is called before the first frame update void Start() Update is called once per frame void Update() Create a vector to offset the material var offset new Vector2(targetBone.transform.localRotation.eulerAngles.x offsetMultiplier, targetBone.transform.localRotation.eulerAngles.y offsetMultiplier) Apply the offset mat.mainTextureOffset offset Script inspector set up Edit I'm having issues getting the Eye(Pupil) Material to correctly move with the Eye bone movement. You can see that when I hit play, the script does get the Eye Material to Initially move, but then it is (visually) frozen instead of moving back and forth. The goal is for it to correctly Eye Track the cube. As a sidenote, for the Eye Material's X and Y offset, the visually correct range of its pupil movement is 0.45 to 0.45 (X), and 0.45 to 0.45 (Y). So it's weird to me that the X and Y offset of the Eye Materials are shown to be moving within that range (which should be good!), yet are not actually moving visually except for when the game first starts. |
0 | Addressable Asset Loading with Queue And Coroutine I have around 17000 addressable assets (prefab) tiles that I am loading near the position of the camera. Here is my algorithm Get all Reference of the 17000 tiles in the array Loop through the array and get the tiles that are within the proximity of my Player and queue It. Based on the first enqueue item, start downloading the tiles with Addreessabl.Instantiate. Load one by one and wait for the first item download to finish. here is the main loop that is doing the work public IEnumerator StartDownloading() isDownloadStarted true while (singleAbLoader.Count gt 0) SingleADLoader singleAbLoaderCurrent singleAdLoader.Dequeue() if (abLoaderUnloaderManager.GetTilesWithinPlayerRange(singleAbLoaderCurrent) true) Debug.Log( quot Starting to call quot singleAbLoaderCurrent.gameObject.name) yield return singleAbLoaderCurrent.DownloadAB() Debug.Log( quot Finsihed to call quot singleAbLoaderCurrent.gameObject.name) loadingSlider.value sliderIncrementValue else Debug.Log( quot escaping the download quot singleAbLoaderCurrent.name) yield return null isDownloadStarted false whereas the DownloadAD() public IEnumerator DownloadAD() AsyncOperationHandle lt GameObject gt handle Addressables.InstantiateAsync(prefabToLoad) yield return handle The tiles are loading fine but the problem is they are way too slow. I mean it takes much time to load tile. |
0 | Why can't I reference "targetVelocity" variable to this script? Recently, I implemented a shooting system for my 2D game but this system has a problem. The problem is that when the player is facing left, the bullets are still being shoot to the right. For fixing this, I need to access a Vector2 named targetVelocity to check whether the player is facing right or not. targetVelocity is defined in another script called PhysicsObject that is specifically for the player physics and the player script inherits from it (the variable was protected but I changed it to public). I just don't know how to reference this in my Bullet script and I don't want to add the player script to the bullet. Also, I've read the past questions and answers that were similar to this but I haven't found the answer yet because this is a different case. Thanks in advance. This is my Bullet script and I want to somehow reference targetVelocity. using System.Collections using System.Collections.Generic using UnityEngine public class Bullet MonoBehaviour SerializeField float speed SerializeField float lifeTime public GameObject destroyEffect private void Start() Invoke( quot DestroyBullet quot , lifeTime) private void Update() transform.Translate(Vector2.right speed Time.deltaTime) void DestroyBullet() Instantiate(destroyEffect, transform.position, Quaternion.identity) Destroy(gameObject) Here is the weapon script. using System.Collections using System.Collections.Generic using UnityEngine public class Weapon MonoBehaviour public GameObject bullet public Transform firePoint private float timeBtwShots public float startTimeBtwShots private void Update() if (timeBtwShots lt 0) if (Input.GetButton( quot Fire1 quot )) Instantiate(bullet, firePoint.position, transform.rotation) timeBtwShots startTimeBtwShots else timeBtwShots Time.deltaTime This is the player script. using System.Collections using System.Collections.Generic using UnityEngine public class NewPlayer PhysicsObject Header( quot Attributes quot ) SerializeField private float jumpPower 10 SerializeField private float maxSpeed 1 Singleton instantation private static NewPlayer instance public static NewPlayer Instance get if (instance null) instance GameObject.FindObjectOfType lt NewPlayer gt () return instance Update is called once per frame void Update() targetVelocity new Vector2(Input.GetAxis( quot Horizontal quot ) maxSpeed, 0) If the player presses quot Jump quot and we're grounded, set the velocity to a jump power value if (Input.GetButtonDown( quot Jump quot ) amp amp grounded) velocity.y jumpPower Flip the player's localScale.x if the move speed is greater than .01 or less than .01 if (targetVelocity.x lt .01) transform.localScale new Vector2( 1, 1) else if (targetVelocity.x gt .01) transform.localScale new Vector2(1, 1) |
0 | Dot product not working as expected Recently I am learning dot product, While below code works from Unity's documentation, http docs.unity3d.com ScriptReference Vector3.Dot.html public Transform other void Update() if (other) Vector3 forward transform.TransformDirection(Vector3.forward) Vector3 toOther other.position transform.position var dot (Vector3.Dot(forward, toOther) Debug.Log(dot) But it doesn't work when I change direction of "other".It keeps giving same value no matter how much I rotate other unlike when I rotate transform,it does change values. For example, transform is at 0 0 0 and other is at 0 0 10 both has 0 rotation so facing straight in Z axis. The desiire out put I get is negative. Now suppose I change rotation of transform to 180 then the output gets positive as expected. I undo the rotation of trasnform and rotate other to 180 i.e., facing transform, then the output doesn't get change and show negative value only.Which is not correct as other is facing player.. Why is that the case? I am not able to get around it. |
0 | Unity Unsharp edges I have a Unity Project and somehow the edges of objects in my Scene (Scene view and game view) look like this I think I already had that problem once, but in my recent projects, this didnt happen anymore. Is there any solution to that? |
0 | Why does ForceMode.VelocityChange work but not Rigidbody.velocity ... in script? I have a FPS movement script that I created that has a jump function that looks like this public void Jump() if (jumpAble amp amp grounded) jumpAble false gameObject.GetComponent lt Rigidbody gt ().velocity (Vector3.up jumpForce Time.deltaTime) For some reason, this does not make the player jump. However, replacing the .velocity ... to gameObject.GetComponent lt Rigidbody gt ().AddForce(Vector3.up jumpForce Time.deltaTime, ForceMode.VelocityChange) makes the player jump. Why is this? I'm under the impression that the two are essentially the same thing, but is there a slight difference? Also, not sure if it affects the function, but this is the whole script public class Player Movement MonoBehaviour public Transform camera public Transform groundCheck public float groundDistance 0.4f public LayerMask groundMask public bool grounded public GameObject joystick public bool isWalking false public bool isRunning false public float walkForce 12f public float runForce 30f public float jumpForce public bool jumpAble true public GameObject playerRotationHandler public float cameraTouchSensitivity public Animator animator Update is called once per frame void Update() grounded Physics.CheckSphere(groundCheck.position, groundDistance, groundMask) if (grounded) jumpAble true Vector3 direction joystick.GetComponent lt Joystick gt ().inputDirection.x transform.right joystick.GetComponent lt Joystick gt ().inputDirection.y transform.forward if (isRunning) gameObject.GetComponent lt Rigidbody gt ().velocity (direction runForce Time.deltaTime) else if (isWalking) gameObject.GetComponent lt Rigidbody gt ().velocity (direction walkForce Time.deltaTime) else gameObject.GetComponent lt Rigidbody gt ().velocity Vector3.zero public void Jump() if (jumpAble amp amp grounded) jumpAble false gameObject.GetComponent lt Rigidbody gt ().velocity (Vector3.up jumpForce Time.deltaTime) gameObject.GetComponent lt Rigidbody gt ().AddForce (Vector3.up jumpForce Time.deltaTime, ForceMode.VelocityChange) public void Rotate(float xMoveValue, float yMoveValue) float xRotation Mathf.Atan2(yMoveValue, cameraTouchSensitivity) Mathf.Rad2Deg float yRotation Mathf.Atan2(xMoveValue, cameraTouchSensitivity) Mathf.Rad2Deg playerRotationHandler.transform.Rotate(xRotation, 0, 0) transform.Rotate(0, yRotation, 0, Space.World) if (playerRotationHandler.transform.localEulerAngles.x lt 300 amp amp playerRotationHandler.transform.localEulerAngles.x gt 60) if (xRotation lt 0) playerRotationHandler.transform.localEulerAngles new Vector3(300, playerRotationHandler.transform.localEulerAngles.y, 0) if (xRotation gt 0) playerRotationHandler.transform.localEulerAngles new Vector3(60, playerRotationHandler.transform.localEulerAngles.y, 0) |
0 | How can I keep track of which "rooms" characters and NPCs are in? I have a Unity 2D project which has a player character and numerous NPCs all potentially moving (top down) at the same time during play. The number of NPCs is not to exceed 100 (and will be, probably, more like 40 50) but I'd still like to be performant. The "rooms" are really just rectangles that correspond to sections of my tilemap. All the "rooms" are contiguous, and hence all characters will always be in exactly 1 "room". Like if you picture the floorplan of a house, you're in the "Hallway" or the "Living Room" or the "Front Porch" or the "Driveway", and so on. My tilemap is not complete, so it would be nice to be able to easily move the rooms around in the Scene editor as I refine it. I was thinking I could... Create Rect objects (or maybe an AABE, although I just read very briefly about what this even is) for each room inside a "RoomsController" GameObject, and then on each Update() iterate through each and see who is within the bounds of each room. But that seems majorly wasteful, and pretty brute force even if done every few frames. Create a GameObject for each room with an appropriately sized BoxCollider 2D, and look for collisions with NPCs, and have a script that handles changing the active room on the NPC when he "collides" with a new room. But this requires a RigidBody 2D for each room, and it feels like overkill. Is there an existing "right way" to solve this problem? |
0 | Add a tag in Unity editor in code How to add a tag in editor? I am working on automatic asset generation and I would like to use tags for certain objects. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.