Unity problems with OnTriggerStay and Input.GetKeyDown Background information Some weeks ago, I start by creating my own platform game. You control a character, that can collect logs and should hold all the campfires on in the game. When the user has collect more then one log, the player have to use this log to hold the fire on. So you should walk to the campfire and should press E to give the log to the fire. Problem What the problem momently is, is that when I press the E key, it will fired the input more then one time. This is because I use a OnTriggerStay2D function, to check every second if my Player is collide with the campfire object. Do some search on the internet, results in people with the same problem. So one of the solutions was to create an bool and set it to true on OnTriggerEnter2D. But this isn't working for me. The same problem as before will occur. Is there another solution to fix this conflict. When the user press the button, it should be fired ones. Below script is linked to the campfire object. Also tried it with if(Input.GetKeyDown(KeyCode.E)) isTrigger true and the same for GetKeyUp, but then isTrigger false My current working code public Animator anim public int campfireStatus bool inTrigger false Use this for initialization void Start () anim GetComponent lt Animator gt () Update is called once per frame void Update () anim.SetInteger("Intensity", campfireStatus) void OnTriggerEnter2D(Collider2D other) inTrigger true void OnTriggerExit2D(Collider2D other) inTrigger false void OnTriggerStay2D(Collider2D other) If player comes in contact with gameObject if (other.gameObject.tag "Player") print ("player") if(Input.GetKeyDown(KeyCode.E)) print ("E Pressed") if (WoodBehaviour.count gt 0) campfireStatus So when the Player is collide with the campfire object AND the player pressed the E key AND you have more then one logs (this counter will be set in the WoodBehaviour script, that is linked to the player object ) than it should increase the campfireStatus with plus one. The problem is, that the if statements will fired more then one times when pressing the E key.


How can I write an additive mesh shader that splits the RGB channels while accounting for depth? I'm trying to create a sort of "hologram" effect. So far, what I have is an additive, three pass shader that uses ColorMask for each pass to separate the RGB channels. The problem is that doing so requires ZWrite to be off (first image) so that each pass doesn't intersect the others (second image). However, doing so means that the model geometry overlaps itself, which I don't want. I've tried the various methods of taking depth into consideration with transparency (This, for example) but they all cause problems when trying to separate the RGB channels. Is there some way to have each pass take depth into consideration within itself, but not with the other passes?


Is it possible to use nav mesh in 2d game in Unity? I'm working on game that needs navigation and obstacle avoidance. I've used nav mesh on 3d project before but now I'm trying to use it in 2d sprite game but it seems like it doesn't work. I want to know if really it doesn't work and, if it doesn't, what would be a good replacement for a 2d project for the navigation of entities. I'm looking for free tools.


Projecting grid textures to select parts of the terrain (Unity) So I'm trying to be smart and not use 500 some tile prefabs to make a grid, and so far the back end portion has gone swimmingly. I initially used a dedicated mesh to represent the grid, but as I'm now opting for 3D terrain (and not tilemapping), I figured that was a lot of unnecessary vertices especially if I want to have the grid conform to the terrain. My shader inexperience, on the other hand, is causing me to stop and overthink this. Using FE as inspiration, I'm thinking about projecting the transparent grid texture onto a base terrain layer. If I wanted parts of the terrain to not be covered by the grid (such as the water area in the picture), would I simply use the world coordinates to tell the shader don't do anything there? The most confusing part for me, however, is how to go about highlighting tiles. I want movement and attack tiles to also be 'painted' onto the terrain in specific colors, but obviously they only affect an even smaller portion than the terrain than the grid. Would I simply be using the same shader to grab world coordinates once again and more or less start stop overlaying the movement attack texture over the grid terrain? And if I'm really being efficient, those textures belong to the same png and I just use UV's to switch between them like a sprite sheet? Is this even a good practice for shaders in the first place? Redrawing and adding textures to only parts of a material? Should I be redrawing and updating the whole texture instead? I guess I get thrown off because I'm only familiar with a 1 1 mesh to material design, so the so the thought of a single mesh but multiple textures on discrete parts that may or may not overlap makes somewhat sense on paper but implementation in Unity is just above me atm. Thanks!


When and where and how to turn on back the Player first person when loading a scene on button click ? In the Build Settings I have two scenes at index 0 and index 1 Then in the Hierarchy I have the two scenes The active scene is the MainMenu In the StartGameButton I added to it a script component. In the script using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class LoadSceneOnClick MonoBehaviour public void LoadByIndex(int sceneIndex) SceneManager.LoadScene(sceneIndex) And this is the StartGameButton Inspector I dragged the script on the OnClick I selected the function LoadSceneOnClick And set the index to 1 When the game start and I click on the button it stay on the Main Menu scene and not loading anything. The problem I guess is that I'm getting error in the game No cameras rendering The problem is that when I'm running the game and it start from the main menu scene in the space station scene I'm enable false the Player and the Player is a first person character with a camera You can see in the Inspector that the Player is unchecked the Player is not enabled. If I will enable the Player and even if the main menu scene is the active one it will show me the player and the player camera and not the main menu. So I had to turn off the Player. The question now is where by script do I enable back the Player when it's loading the scene ? Inside the LoadSceneOnClick script ?


How to retrieve the coordinates of an animated object? On Unity, I created a script in C to animate a cube. I am trying to create a script in C which, once the animated object and in support of a key of the keyboard (for example F) returns to me the coordinates of the object at the moment when I pressed F Can you give me this script? Thank you for your help


How can I instantiate in the current rotation in Unity 2d? Backstory I'm currently working on a 2D sidescroller platform game as a hobby, and I just started recently. Followed a few tutorials and such I managed to wrote my own code for basic command like walk, jump, health and so on. However my basic code wasnt perforning as I would expect, I needed a more "Tight" feeling with the movements so I followed a suggestion to use a physics based controller (Prime31's PC2D, Acrocatic or even Corgi Engine...) Well, now the movements are what I feel is good, So I kind of dived in the scripts to add remove customize some code. Question I'm stuck now on a simple issue, I added these lines public Transform weaponMuzzle public GameObject projectile float fireRate 0.5f float nextFire 0 then in my Update() if (Input.GetButtonDown("Fire2")) animator.Play.Weapon() fireProjectile () and here is the problem I have void fireProjectile () if (Time.time gt nextFire) nextFire Time.time fireRate if ( motor.facingLeft) Instantiate (projectile, weaponMuzzle.position, Quaternion.Euler (new Vector3 (0,0,180f))) else if (! motor.facingLeft) Instantiate (projectile, weaponMuzzle.position, Quaternion.Euler (new Vector3 (0, 0, 0))) The prefabs are also physics based and they are fired with no problems, however they don't want to follow the current rotation of the player, they always go in the right X axis. First of all, the facingLeft on my code is what I understand is the reference to the character controller motor, I tried with motor.normalizedXMovement gt 0 and motor.normalizedXMovement lt 0 (normalizedXMovement 1 is full left and 1 is full right) this just make it that you can only fire while moving, not stopped and the problem still persists. I also tried with Quaternion.Identity instead of Euler and it's the same. For a full source code https github.com prime31 CharacterController2D I'm kinda lost and it would means a lot if you can help me out on this issue. Ps I already searched here and other related forums but cannot find the answer, this is not a repost.


Why do I get these "Invalid command android" errors trying to build for Android in Unity? Trying to move a unity project over to android using gradle as the build system. I get the following 3 errors Error Invalid command android CommandInvokationFailure Unable to list target platforms. Please make sure the android sdk path is correct. See the Console for more details. Library Java JavaVirtualMachines jdk1.8.0 91.jdk Contents Home bin java Xmx2048M Dcom.android.sdkmanager.toolsdir " Users joeljohnson Library Android sdk tools" Dfile.encoding UTF8 jar " Applications Unity PlaybackEngines AndroidPlayer Tools sdktools.jar" stderr Error Invalid command android stdout exit code 64 UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.AndroidSDKTools.RunCommandInternal (System.String javaExe, System.String sdkToolsDir, System.String sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.AndroidSDKTools.RunCommandSafe (System.String javaExe, System.String sdkToolsDir, System.String sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.HostView OnGUI() and Error building Player CommandInvokationFailure Unable to list target platforms. Please make sure the android sdk path is correct. See the Console for more details. Library Java JavaVirtualMachines jdk1.8.0 91.jdk Contents Home bin java Xmx2048M Dcom.android.sdkmanager.toolsdir " Users joeljohnson Library Android sdk tools" Dfile.encoding UTF8 jar " Applications Unity PlaybackEngines AndroidPlayer Tools sdktools.jar" stderr Error Invalid command android stdout It turns out a lot of people have been having this problem and the most common solution is to move to an earlier version of the apk. When I tried that, I still received the same three errors. I moved down to api level 23 from the most current. I am one a mac. exit code 64


Physics2D.Raycast not hitting any colliders I am making a topdown 2d game and want to get the x,y of mouse clicks so I can move the character to that location. I am writing a CharacterController script which performs the mouse click check and raycast in the Update function void Update () if (Input.GetMouseButtonDown (0)) RaycastHit2D hit Physics2D.Raycast(Input.mousePosition, Vector2.up) if (hit.collider ! null) Debug.Log (hit.point) This runs whenever I click the mouse, but the if(hit.collider ! null) condition is never met. I've looked around for other solutions, such as Unity Raycast not hitting to BoxCollider2D objects, but when I change my code to the one used in that answer RaycastHit2D hit Physics2D.Raycast( Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector3.back ) then the if(hit.collider ! null) block is always true, even if I click on empty space, and it always returns the same coordinate. To illustrate this, here is a video of me clicking the game view. The green area has a 2d box collider that is very closely mapped to its boundaries. You can see that the logged hit.point is always the same. video is here https i.imgur.com uhNp8wC.gifv screenshot


Unity splash is starting in progress after white screen When I export my Unity project (on Windows), there is a brief white screen before the Unity splash screen renders, already in progress. Discretely cutting to the already in progress splash screen looks pretty bad, so I'd like to fix this. Here is a video showing what I mean. After some googling, I did find other reports of a white screen, but only on Android. My project is very simple and I am not loading anything intensive on boot, so I'm not sure what is causing this white screen. Does anyone know what might be causing this issue or have ideas to troubleshoot it?


How should I manage my data that needs to be associated with rank (Unity) So I am making a game with a similar content progression to Clash Royale. Essentially u have ranking points (Identified as Trophies), and the number of trophies you have will determine what content you will have access to in the game. So for example every 100 ranking points, you will be able to find new types of cards in chests, new chests in general or new maps. In my game, I want it to be somewhat similar, but I also have some other data that changes based on rank points that is more specific to my game, such as army supply. I'm trying to figure out how I can implement this in a manageable way. Maybe this is overkill, but this is my design so far Basically I have my RankContentItemBase class which has a ranking points int and an IsUnlocked method that returns whether or not the passed in rank is gt than the rank passed in. Then I extend this with classes with classes that add the data type I wanna work with (Int, Troop, Map, w e). I then have a Generic base container class that has a method for getting all unlocked item in the list of T contents that is extended to contain the concrete RankUnlockItembase types. I've basically structured things this way so it's easy for me to add new types of items that I want unlocked by rank without having to do much work. Also it prevents things from being coupled together. Just curious what ppl think of this setup, and what kinda setup you would go with? One concern I have with this design was that if I wanted to see whether a troop was unlocked or not, I can't just say troop.IsUnlocked(). Instead I have to create a new means of determining whether or not a troop is unlocked yet, like for example maybe a method on the RankUnlockedTroopContainer that determines this. Maybe this is ok? I feel like I'm sacrificing simplicity for the sake of maintainability flexibility. Thanks


How to express AI area ownership? Situation Big open world ish level Different types of real estate Houses including some land around it Just houses without land Flats on different floors How to express AI ownership of any of those types that I could use in game logic? My first thought was to use collider around the area as a trigger that I could use to detect if "guest" enters the area and program AI to only react if certain criteria is met (e.g sees the guest, friend vs enemy) but Most areas are pretty complex I would need to use mesh colliders It would get rather expesive if I had many areas around the player active (urban environment) I also need the concept of "my area" for other logic e.g pathfinding, place items etc


Animation rotates model but I don't see how I have 2 animations. In the following animation preview, the same model is being used. As you can see in the animator, there is no significant rotation difference. However, one animation rotates the model 90 degrees to the left. I have inspected all the rotation values in the animation tab. I just don't see any difference. What causes this signifant rotation difference? Thank you!


Two Points Rotating Around Circle? Currently I am working on a 2D game just like duet game, it is my first game (Unity 2D). When I press left key both points rotate fine. But when I press right, the points are not rotated. So my problem is why do both points rotated only in one direction Code public class TouchControll MonoBehaviour float movespeed 3 float angle 45 void Update() if (Input.GetKey(KeyCode.LeftArrow)) when i m press leftarrow both point should be rotate fine transform.Rotate(Vector3.forward Time.deltaTime Input.GetAxis("Horizontal") angle movespeed) Debug.Log("moveleft") if (Input.GetKey(KeyCode.RightArrow)) problem is here when i m press right arrow key both point are not rotated transform.Rotate(Vector3.forward Time.deltaTime Input.GetAxis("Vertical") angle movespeed) Debug.Log("moveright") Output create a empty gameobject first circle second circle


Why doesn't my SpriteRenderer's color change when setting .color new Color(166, 33, 33)? I need to change the color of my SpriteRenderer, and so I looked up how to do it and come up with this code spaceOne.GetComponent lt SpriteRenderer gt ().color new Color(166, 33, 33) (In case you are wondering, yes I checked that 'spaceOne' is correctly linked to a GameObject.) This should change the color, but it doesn't. As I was writing this, I found that replacing new Color(166, 33, 33) with Color.red actually does change it to red. So now I am wondering, why does the new Color(166, 33, 33) code not work, and how can I fix it? P.S. I made sure that it wasn't something simple, like it being RGBA rather than RGB, but no, it still doesn't work with new Color(166, 33, 33, 255) .


Unity Texture Problem http www.gfycat.com FlawedLimpingGrizzlybear http www.gfycat.com UnawareQuerulousHawk Every texture and shader has the same problem. It seems like the problem has nothing to do with either. Tried all the things my friends suggested I should, reimported everything, restarted my machine, nothing seems to work.


How to display a text in the impact point position In my 3d game, i would like to display a text 'near' the impact point of a bullet. I think i'm having problems setting properly text position. This is my code. The script is attached to an object Canvas. position is the Vector3 impact position. GameObject obj new GameObject () Text text obj.AddComponent lt Text gt () text.transform.position position text.text message text.fontSize startSize text.color color I'm pretty sure i've to convert from a world space to a 'user interface' space. Thanks


AndroidManifest file was deleted by accident I deleted the AndroidManifest file of my project which was located in Assets Plugins Android , so I tried creating new project and copying the Assets and everything but it seems that something is missing ,it's perfectly working in the editor , but as apk there are few things aren't working, I can't figure out why, and there isn't even a Plugins folder in my new project !


Make Build and Run faster Is there a way to build an apk faster? (by disabling some shader compilation, for example Hidden Post FX Uber Shader takes most of the build time) p.s. Yes I know about Unity Remote and use it this time I need exactly Build and Run.


Why the camera is not moving only up but also to the right? using System.Collections using System.Collections.Generic using UnityEngine public class CameraMove MonoBehaviour public float smoothSpeed 3f Use this for initialization void Start() Update is called once per frame void Update() private void FixedUpdate() transform.localPosition Vector3.MoveTowards(transform.localPosition, new Vector3(0, 500, 0), smoothSpeed Time.deltaTime) The script is attached to the Main Camera. I want the camera to move directly up and a little bit also to the back. But the way it is now it's moving up but also to the right. Why it's moving also to the right ? I tried transform.localPosition and also only transform.position


Difference between Unity's Camera.ScreenPointToRay and Camera.ScreenToWorldPoint? What is the difference between Unity's Camera.ScreenPointToRay and Camera.ScreenToWorldPoint. And where we can use these. I've watched some tutorial and documentation but I didn't get a clear understanding.


Why i'm not getting the FPSController Rotation values? using System.Collections using System.Collections.Generic using UnityEngine using UnityStandardAssets.Characters.FirstPerson public class RotateObject MonoBehaviour public UnityStandardAssets.ImageEffects.Blur blur public UnityStandardAssets.ImageEffects.BlurOptimized blurOptimized public FadeScript fadescript SerializeField Quaternion targetRotation lt summary gt Rotation you want to achieve. lt summary gt SerializeField private float s lt summary gt Rotation duration. lt summary gt private Quaternion initialRotation lt summary gt Your GameObject's initial rotation. lt summary gt private float t lt summary gt Your 't' reference. lt summary gt private FirstPersonController fpcscript void Awake() fpcscript.enabled false fpcscript transform.GetComponent lt FirstPersonController gt () initialRotation transform.localRotation void Update() if (fadescript.alphaZero true) if (t lt 1.0f) transform.rotation Quaternion.Lerp(initialRotation, targetRotation, t) t (Time.deltaTime s) Each 60 frames optimally t reaches 1, divided by your duration, it will reach 1 on 'x' seconds. else Your rotation ends here reset 't' if you please , and reset 'initialRotation' initialRotation transform.rotation blur.enabled false blurOptimized.enabled false fpcscript.enabled true The script is attached to FPSController. In the Inspector the Rotation of the FPSController is X 7 Y 112 Z 31 But when i'm using a break point on the line in the Awake initialRotation transform.localRotation I see that initialRotation values are ( 0.2, 0.8, 0.2, 0.5) What i want to do is to rotate the transofrm from X 7 Y 112 Z 31 to rotation 0,0,0 That is why i also didn't set any values to targetRotation since i want it to rotate to 0,0,0


Model colors look much better in blender than Unity (LWRP), how to fix bad colors in Unity LWRP? I made some models in blender 2.8 After importing them to Unity, they look much worse Still the same material as in blender, I use the LWRP and have had nothing but issues with it, the lack of AO being one. Is there something I'm missing because it should not look this much worse in the Game Engine?


How to remove a component of an object in a script? I want to remove a Sphere Mesh Renderer component from a certain gameobject. I want to do this in a script. How do I do it? I do not want to destroy the sphere itself, just the component


How to calculate 2D viewport coordinates in a shader? In Unity, I use the following shader to calculate 2D viewport coordinates Shader "Foo" SubShader Pass CGPROGRAM pragma vertex vert pragma fragment frag struct vertInput float4 pos POSITION struct vertOutput float4 pos SV POSITION float4 uv TEXCOORD0 vertOutput vert (vertInput input) vertOutput o o.pos mul(UNITY MATRIX MVP, input.pos) o.uv mul(UNITY MATRIX MVP, input.pos) return o fixed4 frag (vertOutput output) SV Target float2 viewport output.uv.xy output.uv.z return float4(sin(viewport.x 10.0), sin(viewport.y 10.0), 0.0, 1.0) ENDCG At first, it seems to work great. Here is results However if I move camera very close to the surface, the following unexpected glitch occurs


Drawing visibility polygons in Unity (for vision cones with occlusion) I'm currently trying to create an effect like the one displayed below in Unity However, it seems that I can't do this with any of Unity's built in light objects, and I simply cannot find anything online that talks about this. Is there a way to achieve this in Unity? 2D or 3D solutions are fine, as I'm sure that they're both very similar to each other,


Photon Realtime, StripKeysWithNullValues cause heavy GC Alloc In our current project, we use Photon room properties to sync entities. and i noticed some heavy GC Allocs while deep profiling the game and it always ends down to this method. Have anyone faced this issue before ? or attempted to fix it ? here is the source code of that method. lt summary gt This removes all key value pairs that have a null reference as value. Photon properties are removed by setting their value to null. Changes the original passed IDictionary! lt summary gt lt param name "original" gt The IDictionary to strip of keys with null values. lt param gt public static void StripKeysWithNullValues(this IDictionary original) object keys new object original.Count original.Keys.CopyTo(keys, 0) for (int index 0 index lt keys.Length index ) var key keys index if (original key null) original.Remove(key)


How do I roll a ball with a Rigidbody? I have a ball in a game that rolls around just fine with Rigidbody.AddForce(). I have other non physics balls, however, that I control directly with Rigidbody.MovePosition(). It seems that no matter what I do, no matter how interpolation and collision detection are set, the ball does not "roll" when moved with Rigidbody.MovePosition(). It teleports, but IsKinematic is not set , as instructed by the documentation. How do I get the ball to roll properly with Rigidbody.MovePosition()? Alternatively, if that's not possible, how do I calculate the rotations manually?


When creating a UI scene in Unity, should I render the canvas in camera space? I'm working on a scene that is strictly going to be used for character creation. Can anyone explain what the best practice is for a scene like this? Should I render the canvas to the camera, or should I render it in world space, or as an overlay?


Unity3D Problems drawing on duplicated texture I'm trying to load texture from assets folder create a clone of said texture that will be manipulated during runtime set pixels on cloned texture I have successfully set pixels on the original texture (ie. discarding the code in the start function), but I cannot seem to be able to draw to the duplicated version. void Start () canvas gameObject.GetComponent(typeof(SpriteRenderer)) as SpriteRenderer Sprite oldSprite canvas.sprite Texture2D oldTex oldSprite.texture Rect oldRect oldSprite.textureRect tex new Texture2D(oldTex.width, oldTex.height, TextureFormat.RGB24, false) tex.SetPixels32(oldTex.GetPixels32()) tex.Apply() Rect r new Rect(oldRect.x, oldRect.y, oldRect.width, oldRect.height) Vector2 pivot new Vector2(oldSprite.pivot.x, oldSprite.pivot.y) float pixelsPerUnit oldSprite.pixelsPerUnit Sprite sprite Sprite.Create(tex, r, pivot, pixelsPerUnit, 0, SpriteMeshType.FullRect) canvas.sprite sprite public void draw(Tool tool, Color32 color, List lt Vector2 gt locations) Color32 pixels tex.GetPixels32(0) for(int i 0 i lt pixels.Length i) pixels i color tex.SetPixels32(pixels) tex.Apply() Please ignore the unused vars, I'm just trying to set the whole texture's color for now. Anyways, any help is always appreciated thanks )


Fading Text in one character at a time I'm a Unity game developer. I have a bit of a conundrum. I have two enumerators, one that displays text one character at a time, and the other takes the whole text and fades it in over time private IEnumerator FadeTo(float aValue, float tValue) float alpha GameText.GetComponent lt Text gt ().color.a for (float i 0 i lt 1.0f i Time.deltaTime tValue) Color alphaChange new Color(1, 1, 1, Mathf.Lerp(alpha, aValue, i)) GameText.GetComponent lt Text gt ().color alphaChange yield return null private IEnumerator CharXChar(string text) for (int i 0 i lt text.Length i ) yield return new WaitForSeconds(0.1f) GameText.GetComponent lt Text gt ().text GameText.GetComponent lt Text gt ().text text i The problem is, I do not know how to get the FadeTo enumerator to modify each character individually. I just need a step in the right direction. Any help would be greatly thanked.


Make an animation repeat X times I am using Unity Mecanim and I would like an animation ( walking animation about 2 seconds longs ) to repeat X times before moving to the next animation. How can I achieve this?


How can I change the list of enum options displayed in the inspector? I have an array of enums using UnityEngine public class EnumsInInspector MonoBehaviour SerializeField public EnumType myEnums new EnumType 3 public enum EnumType A, B, C I want it so that if the enum at index 0 is B, then when selecting the enum at index 1, only A and C are options, and B is no longer available. How can I achieve this?


Change unity physics engine speed Is there a simple way to change the speed of unity's physics engine like in the game SuperHot? Any script language is ok but javascript is preferred. I am not sure if speed is the correct term.


Unity 3D, Making contiguous looking worlds Im currently involved in making a third person cooperative mobile game in Unity and in said game there will be an area for players to walk around in with various elevations and whatnot throughout the field. Its designed to be set up with 4 biomes in the area to go along with the games theme but I was wondering what would be the best way to mask the "boundaries" or "cut off points" in this area? From certain vantage points its pretty obvious that the terrain used to make the world simply stops and I was wondering if anyone knew any tips and insights on how to best mask these boundaries without too much "padding" in the game area in order to keep it relatively less taxing on a mobile device. Thank you in advance.


Inflating a balloon while the user touches holds the screen I'm trying to create a simple balloon which will enlarge as the user touches and holds the screen. So I wrote something like this while ( Input.GetMouseButtonDown(0) ) transform.localScale new Vector3(1, 1, 1) yield return new WaitForSeconds(1) It causes a compiler an error The body of 'enlargeBalloon.Update()' cannot be an iterator block because 'void' is not an iterator interface type How can I fix this?


Anchor a health bar to a character enemy I have a game I'm working on where the player can see the health bars of the player's avatar and other creatures in the game. I want this health bar to always follow the character creature around. However, I can't figure out how to do this. I thought having the position change when the respective object moved would do the trick, but apparently, it doesn't. When watching the health bar's transform, however, it shows that it is moving with it's respective object but I don't see it on the game screen. Can anyone explain how I go about accomplishing this? Here's the Dropbox link to the project. HealthBar Script public class EnemyHealthBar MonoBehaviour public Texture2D healthBar public Texture2D health public Rect healthBarPosition public Rect healthPosition public GameObject monster void Start() void Update() transform.position new Vector3(monster.transform.position.x, monster.transform.position.y, monster.transform.position.z) Debug.Log(transform.position) void OnGUI() GUI.DrawTexture(healthBarPosition, healthBar) Video of what's currently happening Dropbox Link


2D Platformer Methods to Implement a Whip Weapon I hope posting here isn't a faux pax, if it is please feel free to direct me to the correct location. Or, if there is a thread that already covered this I would love to be pointed in its direction. I've tried looking in quite a few different forums and I can't seem to find very much information about this. What I'm looking to do is implement a whip weapon for a character that's similar to that of Castlevania 4's whip. I have no idea where to start. I'm really just looking for any information. Things like how to program it, the idea of how it was done in the game, really just anything to help me figure out how to make a whip like Castlevania 4. I would appreciate any help. Thank you.


How do I change a background in movement in Unity? I'm developing a game and the background is moving and I wanna change to another image without losing the current speed of the movement. File public class BackgroundMovement MonoBehaviour Material material Vector2 offset GameManager gameManager UIManager uiManager SpawnManager spawnManager public float speed 0.3f private void Awake() material GetComponent lt Renderer gt ().material gameManager GameObject.Find( quot GameManager quot ).GetComponent lt GameManager gt () uiManager GameObject.Find( quot Canvas quot ).GetComponent lt UIManager gt () spawnManager GameObject.Find( quot SpawnManager quot ).GetComponent lt SpawnManager gt () Update is called once per frame void Update() offset new Vector2(speed, 0) if(gameManager.gameOver false) GameSpeed() material.mainTextureOffset offset Time.deltaTime In Unity, I added to the material of the background a shader quot unlit transparent quot and added the background in it. The object that this material is in, is a quad. I tried to change creating a list of background images that I wanted on the game. One of the times I tried, I managed to change the background, but the image didn't move, only the first. This is the inspector of the background.


Unity doesn't change particle color when render is set to mesh? I've got a particle system with Render Mode set to Mesh. Then I applied a material to it, which is just white with the default shader. Now I can't change the start color nor the color over lifetime etc. As far as I know that shouldn't happen, right? I'm using Unity 5.5.0f3 This is what my PS looks like with the material This is what I achieved with 3 particle systems with 3 different materials, but actually, I don't want these materials. Instead, I want to set the start color property of the particle system to apply some color. The material solution restricts me in terms of random start color and stuff like this.


How do I calculate a new position from current and target position for intuitive non instant dragging? I have a simple 2D game where I can move an object using the mouse. I've been improving on the 'feel' of the movement gradually, however it still doesn't behave as you'd expect if the object were to be moved by human hands in a real world scenario. My improvements were as follows New position mouse position Sharp unrealistic movement. No max speed. Cap the maximum speed Nicer. Still stops abruptly. Doesn't accelerate smoothly Add 'inertia', recording last change in position and applying it to subsequent moves Vastly improved, however... Object is dragged as if on elastic, slow to accelerate, very slow to stop. Once moving, object oscillates or orbits around a stationary mouse position. I'm looking for suggestions on how to make the movement more intuitive Moving an object from A to B a human would rarely overshoot A user shouldn't need to correct against inertia to stop an object I'd like to be able to adjust the weight of the object so that heavier things are harder to get moving My current code is as follows float maxInertiaChange 0.1 Vector2 lastPosition Vector2.negativeInfinity Vector2 inertia Vector2.zero private Vector2 InterpretPosition(Vector2 mousePosition) Vector2 newPosition if (lastPosition.x ! float.NegativeInfinity) newPosition lastPosition (inertia Time.deltaTime) newPosition GetPointTowardsTargetWithMaxDistance(newPosition, mousePosition, maxInertiaChange) inertia (newPosition lastPosition) Time.deltaTime else newPosition mousePosition lastPosition newPosition return newPosition private static Vector2 GetPointTowardsTargetWithMaxDistance(Vector2 startVector, Vector2 targetVector, float maxDistance) float lerpScale maxDistance Vector2.Distance(startVector, targetVector) return Vector2.Lerp(startVector, targetVector, lerpScale) Thanks in advance!


How can I make tree foliage work with baked lighting? I have an issue in Unity where my trees are black and it seems to be due to the fact that I'm using baked lighting in my scene. Luckily, it seems that I'm not the only one who's experienced this. I found a post on the unity3d subreddit which goes into more detail about basically the same problem. I'll repost it here for convenience So, I have some custom trees using the "Nature Tree Soft Occlusion" shaders and they looked great before baking a lightmap. However, now that I have baked the lightmap, the trees have turned black. Or rather, when I tried baking with the trees set to static, they turned invisible, and now that Ive tried without, they're black. Also, they're not casting shadows. Anyone know how to fix this issue? Perhaps I need to use light probes? http imgur.com a 21At5 before and after (fyi the bark is not using the nature occlusion shader. The shader definitely seems to be the root of the issue, but Im just not sure how to fix it without using a different shader) Ultimately, the author of this post eventually "solved" his problem by just switching to realtime lighting instead of baked lighting. Unfortunately, this is not an option for me. However, the author did receive some useful comments before giving up. One of the comments asks if the leaves have properly laid out UVs. The commenter goes on to say that the leaves all need to have their own unique space in the UV grid. I think this makes sense because I enabled the Generate Lightmap UVs option on my tree model in Unity. But it did nothing. The author apparently also had no luck with that option. In any case, Maya was suggested (among other software) to check these leaves' UVs. Unfortunately, I've never used Maya and I absolutely can't make heads or tails out of it. I'm just using a borrowed copy from a friend so I've never gone through any tutorials or anything for it. I'm just trying to check this one thing, but I am really at a loss. EDIT According to some comments from DMGregory, he suggests that since trees get spawned and varied dynamically, there's no single mesh to pull apart and check its UVs. His logic seems to make sense, so perhaps Maya is not the solution that I'm looking for. Now, though I'm having trouble with figuring out how to get my tree shaders to work with lightmapping. Details are in the comments.


Unity IUnityLifecycleManager already exists I followed this tutorial https www.youtube.com watch?v OElh7wda4Qc in Unity version 2019.3.1f.1 Personal Edition, but I got 6 errors like this in the console, also I updated to version 3.4.4 via the package manager, because it said that the asset store version was not compatible anymore. Library PackageCache com.unity.ads 3.4.4 Runtime Monetization AndroidPlacementContentOperations.cs(55,40) error CS0433 The type 'IUnityLifecycleManager' exists in both 'UnityEngine.Advertisements.Editor, Version 3.4.2.0, Culture neutral, PublicKeyToken null' and 'UnityEngine.Advertisements, Version 3.4.2.0, Culture neutral, PublicKeyToken null' This is the code I am using, its the same as the code in the official website, but personalized to my project. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Advertisements using UnityEngine.UI public class adsController MonoBehaviour, IUnityAdsListener public bool testMode true public Button rewardedAd private string storeID "3509232" private string rewardedVideo "rewardedVideo" private void Start() rewardedAd.interactable Advertisement.IsReady(rewardedVideo) rewardedAd.onClick.AddListener(ShowRewardedVideo) Advertisement.Initialize(storeID, testMode) private void Update() private void ShowRewardedVideo() Advertisement.Show(rewardedVideo) Implement IUnityAdsListener interface methods public void OnUnityAdsReady(string placementId) If the ready Placement is rewarded, activate the button if (placementId rewardedVideo) rewardedAd.interactable true public void OnUnityAdsDidFinish(string placementId, ShowResult showResult) Define conditional logic for each ad completion status if (showResult ShowResult.Finished) Reward the user for watching the ad to completion. Debug.Log("Reward") else if (showResult ShowResult.Skipped) Do not reward the user for skipping the ad. Debug.Log("Not Reward") else if (showResult ShowResult.Failed) Debug.LogWarning("The ad did not finish due to an error.") public void OnUnityAdsDidError(string message) Log the error. public void OnUnityAdsDidStart(string placementId) Optional actions to take when the end users triggers an ad. EDIT Looks like I forgot a line in the code and reinstalling the unity ads package now it runs but still gives this warning. Please consider upgrading to the Packman Distribution of the Unity Ads SDK. The Asset Store distribution will not longer be supported after Unity 2018.3


Texture2D GetPixels Finding pixels that are not transparent. Problem as finding more than expected I am trying to make a level design system where I use a low resolution png file with certain pixels filled. My code will turn this location of the pixel in the image into placement of platforms in my game. But I test the following code with a png i made with only 1 pixel in it (the rest are transparent). But the result is it finds 4 every time. Is it possible there is a discrepancy between the Gimp png and the texture that Unity sees. (In GIMP I used pencil 100 hardness 1px width. There are also settings for 'resolution' of the image, which i left at defaults) public class LevelBuilder MonoBehaviour public Texture2D sourceTex Color32 pixels int pixelsFound 0 private void Start() pixels sourceTex.GetPixels32() for (int i 0 i lt pixels.Length i ) if (pixels i .a ! 0) Debug.Log("found colored pixel. total " pixelsFound)


How to make a visible area in unity3d the simple way to explain it is an image I want to have a black background and to show only a small area around player. Which way I have to look? I have no clue where to start searching ) Thanks.


How does Unity know that you make more than one hundred thousand dollars on the Personal plan? How do they check if you make more than 100k? That is really puzzling me.


Scale object based on another object's position Despite an hour or so of Googling I can't seem to figure out how to calculate the scale factor based on distance. Here's the illustration of my problem. I've tried manipulating the x values and such, but until now I still cannot figure it out. Here's the snippet Vector3 v3Scale frontWall.transform.localScale frontWall.transform.localScale new Vector3(v3Pos.x 2.0f , v3Scale.y , v3Scale.z) Any ideas? Thanks in advance! UPDATE if(getTarget.CompareTag("LeftRightWall") amp amp getTarget.transform.childCount 1) float translate getTarget.transform.position.x getTarget.transform.GetChild(0).gameObject.transform.position.x Debug.Log("value " translate) foreach (GameObject frontWall in GameObject.FindGameObjectsWithTag("FrontWall")) Vector3 v3Scale frontWall.transform.localScale float scaleFactor translate frontWall.transform.localScale.x frontWall.transform.localScale new Vector3(translate , v3Scale.y , v3Scale.z) v3Pos.z getTarget.transform.position.z v3Pos.y getTarget.transform.position.y getTarget.transform.position v3Pos getTarget.transform.GetChild(0).gameObject.transform.position new Vector3( v3Pos.x, v3Pos.y, v3Pos.z) The LeftRightWall is the ones that I drag on the picture, with another vertical line as its child. The FrontWall is the horizontal line that is stretched when the LeftRightWall is dragged. Hope its clear enough. Thanks UPDATE This is the closest one from what I'm trying to achieve... (( Here's the code float translate getTarget.transform.position.x getTarget.transform.GetChild(0).gameObject.transform.position.x Debug.Log("value " translate) foreach (GameObject frontWall in GameObject.FindGameObjectsWithTag("FrontWall")) Vector3 v3Scale frontWall.transform.localScale frontWall.transform.localScale new Vector3(translate v3Pos.x, v3Scale.y , v3Scale.z) UPDATE This is what I'm able to do so far, thanks to the answer below. However I still don't know why the other side of the panel is behaving like that. The scale of horizontal lines also shrinks when I click on the vertical line. This is the updated code ray mainCamera.ScreenPointToRay(Input.mousePosition) float dist plane.Raycast(ray, out dist) Vector3 v3Pos ray.GetPoint(dist) if(getTarget.CompareTag("LeftRightWall") amp amp getTarget.transform.childCount 1) float translate getTarget.transform.localPosition.x getTarget.transform.GetChild(0).gameObject.transform.position.x Debug.Log("value " getTarget.transform.GetChild(0).gameObject.transform.localPosition.x) foreach (GameObject frontWall in GameObject.FindGameObjectsWithTag("FrontWall")) Vector3 v3Scale frontWall.transform.localScale float scaleFactor (translate v3Scale.x) frontWall.transform.localScale new Vector3(v3Scale.x scaleFactor, v3Scale.y, v3Scale.z) v3Pos.z getTarget.transform.localPosition.z v3Pos.y getTarget.transform.localPosition.y getTarget.transform.localPosition v3Pos getTarget.transform.GetChild(0).gameObject.transform.position new Vector3( v3Pos.x, v3Pos.y, v3Pos.z)


Project vertex on a line V,A and B are 3 points in 3D space and We have d0 (distance of V from (AB)line). I want to calculate question mark point in the image above!


Understanding pixel art in Unity 2d I am struggling to understand the basics behind pixel art in Unity. I understand what a unit is, and that if I draw my sprite with 16x16 pixels, I should set PPU to 16. Take stardew valley for example, in the image below you can clearly see that the player is not square. The creator of the game said he made everything in 16x16, but then how is there so much detail in the characters? Surely you do not patch several 16x16 squares together to make a character (as you would with a tilemap)? What is the "common" way of dealing with things that are not square, like the characters in the image. Do you just make 16x32 sprite and set PPU to 16? Wont that make it look a bit weird next to 16x16 sprites? Do you generally pick one size (i.e 16, 32, 64) And then stick to that for everything in the game? The visual Issue I've seen is this, where a 32x32 sprite looks very out of place (too sharp) next to a 16x16 sprite. So I am wondering, how do you mix sizes wihout getting this effect where one image looks much sharper than the other. If I for example wanted a character to be 16x32, or any non square value, when my tiles are 16x16


Unity Non Power of 2 Textures I have a texture that is 1024x900. Should I resize it in Photoshop to be 1024x1024 or leave it as it is? What about a texture sized 1000x900?


How to set a specific face's texture color in Unity? First off, let me describe my situation... So I'm building a voxel engine based on this tutorial. I'm using my own texture tilesheet. Most of the tiles have their own color except grass, leaves, and a few others. These specific ones are meant to be colored based on the temperature and humidity of the location. AlexStv (the author of the tutorial linked above) said the mesh colors array could be set, but I tried that and nothing happened. I probably did it wrong though, not sure. But he also said "you may need a shader that render vertex colors, not sure if the standard shader does that anymore" so that could also be the issue. So... Do I need a custom shader? If not how do set the face's colors? EDIT, Note I just tried a custom shader called UnityVC, it still didn't work so I guess I must be doing the color thing he suggested wrong.


Things disappear in front of Canvas I'm trying to add some text to my Canvas but it seems to disappear in front of it? So does particle systems and other things? It is a child object of the canvas.


Playing a video in AR using Vuforia and Unity 5 I am trying to play a video in augmented reality using Vuforia and Unity5. I followed a few videos but I am still not able to play it. Can anybody help? I get the "error texture icon" instead of the play icon.


Finding the "top" of a mesh representing the terrain I'm generating a low poly mesh for terrain, and for a given world coordinate I'd like to know where the "ground" is. My game uses fairly standard infinite terrain I generate noise values for world coordinates and use them to generate this mesh procedurally. This is done in chunks of 16x16. I'm planning to begin decorating the terrain with plants and such and I need a good way to determine how high the ground is. So for example, if I want a rock at x 5, z 5, what's the best most efficient way to figure out the "height" of the ground at that location? I've considered trying to inspect the mesh vertices, or maybe using a top down ray cast and picking the collision point, but I'm looking for advice before I begin. I've tried the raycast method, and it works perfectly, I'm just not sure how efficient that is. I'll profile if any alternatives seem worth comparing.


Is it possible to move a parent object independent of the child object I need to be able to move a Parent Object without moving the Child Objects.


Get a point inside an ellipse So I have a sprite of an ellipse ( it is a 2D game). I would like to get a point inside this ellipse so I can instantiate something. How would I do that? Sprite won t be changing the scale, so uniform scale. The point shouldn t be on the edge and a bit further away from the edge


Unity Android Button Select (Highlight) by touch, before clicking I have a multiplatform game with dozens of buttons in many menus. I used the animated buttons setup to have a normal state and highlight state. Highlight will most of the time resize the button with a nice anim AS WELL as make a dedicated text box appear with extra information. So far so good. Everything works perfectly on PC. However, as I am testing my build on android, I cannot find how to access the "highlight" state since touching the screen click and it execute the on click () associated. What I need is a way to select a button when it is first touched, since selected highlight (somewhat) then if it is touched (clicked) a second time while selected then to do the on click ( ) function. I have a few theory on how to do it, but it would require recreating every of my 80 or so buttons as well as changing everything from using the Unity GUI system to make my own C version which would take weeks. I am also trying a few other way to achieve the same thing. One of which is using the "button.select()" to select the button on its first click. That works. problem is I cannot seem to write a way to do "if (thisbutton.IsSelected true)" that just refuses to work.


AddForce results in stuttering movement I'm currently developing a simple breakout arkanoid mobile game. Now, I noticed that my ball movement is noticably stuttering. I've read various approaches about how to make the ball move and decided to go for AddForce so I don't have to do any physics calculations myself. The only thing im currently doing is using AddForce on my ball's rigidbody2D and have it collide with the walls and blocks. There's nothing done manually in Update or FixedUpdate and there are no other scripts running while the ball is moving. The scene is pretty empty actually. Things I have tried so far without success Disable V Synch Increase the velocity iterations (I tried values 15 500) Set the RigidBody2D's interpolation mode to Interpolate Extrapolate Using different mass values and force values in AddForce Checking, whether it's just an optical illusion (it seems to run more smoothly in editor and other breakout arkanoid games don't have that problem on my Galaxy S7) RigidBody settings of the ball Body Type Dynamic Material Friction 0 Bounciness 1 Mass 0.025 Linear Drag 0 Angular Drag 0 Gravity Scale 0 Collision Detection Continous Sleeping Mode Start Awake Interpolate Interpolate The walls and blocks are simple BoxCollider2D components. And I'm calling AddForce(new Vector2(0f, GameConstants.DESIRED BALL SPEED)) on the ball's RigidBody2D. Edit public void OnPointerUp(PointerEventData eventData) if(! ballStarted) PaddleController.ShootStickingBalls() ballStarted true public void ShootStickingBalls() int stickyBallsAmount stickingBallsRigidBody2D.Count for (int i 0 i lt stickyBallsAmount i ) stickingBallsRigidBody2D i .AddForce(new Vector2(0f, GameConstants.DESIRED BALL SPEED)) stickingBallsRigidBody2D i .transform.SetParent( nonStickyBallsTransform) Sticky false


How can I make the objects to move at the same speed as the lines? void Update() if (animateLines) counter for (int i 0 i lt allLines.Length i ) Vector3 endPos allLines i .GetComponent lt EndHolder gt ().EndVector Vector3 startPos allLines i .GetComponent lt LineRenderer gt ().GetPosition(0) Vector3 tempPos Vector3.Lerp(startPos, endPos, counter 500f speed) allLines i .GetComponent lt LineRenderer gt ().SetPosition(1, tempPos) instancesToMove i .transform.position Vector3.MoveTowards(endPos, startPos, counter 500f speed) else counter 0 foreach (GameObject thisline in allLines) thisline.GetComponent lt LineRenderer gt ().SetPosition(1, thisline.GetComponent lt LineRenderer gt ().GetPosition(0)) The lines are LineRenderer. void SpawnLineGenerator(Vector3 start, Vector3 end, Color color) GameObject myLine new GameObject() myLine.tag "FrameLine" myLine.name "FrameLine" myLine.AddComponent lt LineRenderer gt () myLine.AddComponent lt EndHolder gt () myLine.GetComponent lt EndHolder gt ().EndVector end LineRenderer lr myLine.GetComponent lt LineRenderer gt () lr.material new Material(Shader.Find("Particles Alpha Blended Premultiply")) lr.startColor color lr.useWorldSpace false lr.endColor color lr.startWidth 0.1f 0.03f lr.endWidth 0.1f 0.03f lr.SetPosition(0, start) lr.SetPosition(1, start) So I have lines each new gameobject have a LineRenderer component and inside Update I'm animating the lines with some speed. Now I want to move the instancesToMove (GameObject ) with the same speed as the lines but the instancesToMove are moving much slower then the lines. I tried instancesToMove i .transform.position Vector3.MoveTowards(endPos, startPos, speed) Then instancesToMove i .transform.position Vector3.MoveTowards(endPos, startPos, speed Time.deltaTime) But it's never moving with the same lines speed.


Selecting all GameObjects in Unity I want to rotate all my GameObjects by 90 degrees. To do that I need to select all my GameObjects, how can I do so?


I am getting different results when using 'Maximize on play '? so i'll be straight to point. when i move my character without using 'max on play' it works fine just as i wanted it to be. but when i switch to 'max on play' my character moves very fast. i am using addForce() to make me character move in Update(). after some googling i found that as i am working with physics i need to use FixedUpdate() But when i tried with fixed update i felt like it was not registering the keystrokes as it would in Update(). i would really appreciate if someone would help me out here. Edit Movement Script Added using UnityEngine public class PlayerController MonoBehaviour SerializeField float jump speed SerializeField float walk speed SerializeField float max speed Rigidbody2D rb int jump counter Animator animator void Start() rb GetComponent lt Rigidbody2D gt () animator GetComponent lt Animator gt () jump counter 0 animator.SetBool( quot isIdle quot , true) animator.SetBool( quot isWalkingLeft quot , false) animator.SetBool( quot isWalkingRight quot , false) void Update() if (Input.GetKeyDown(KeyCode.Space) amp amp jump counter lt 1) rb.AddForce(transform.up jump speed) jump counter else if (Input.GetKey(KeyCode.D)) rb.AddForce(transform.right walk speed) PlayWalkingRightAnimation() else if (Input.GetKey(KeyCode.A)) rb.AddForce( transform.right walk speed) PlayWalkingLeftAnimation() else if(jump counter lt 0) PlayIdleAnimation() void FixedUpdate() rb.velocity Vector2.ClampMagnitude(rb.velocity, max speed) private void OnCollisionEnter2D(Collision2D collision) jump counter 0 void PlayWalkingLeftAnimation() animator.SetBool( quot isWalkingLeft quot , true) animator.SetBool( quot isWalkingRight quot , false) animator.SetBool( quot isIdle quot , false) void PlayWalkingRightAnimation() animator.SetBool( quot isWalkingRight quot , true) animator.SetBool( quot isWalkingLeft quot , false) animator.SetBool( quot isIdle quot , false) void PlayIdleAnimation() animator.SetBool( quot isWalkingLeft quot , false) animator.SetBool( quot isWalkingRight quot , false) animator.SetBool( quot isIdle quot , true) I have added whole script hope this helps understand my problems.


Why does my first person camera attached to a rigid body vibrates? I'm trying to make a first person character with a rigid body. I need a rigid body because I want to add areas where the gravity comes from different directions so I also need to rotate the character accordingly. And as far as I know you cant rotate a character controller. So I wrote a script for movement and camera rotation. The problem I now face is that the camera vibrates. I recorded this video to show it. Why do I get this and how do I fix this? Movement code using System.Collections using System.Collections.Generic using UnityEngine public class PlayerMovementRigidBody MonoBehaviour public float speed 10.0f public Rigidbody rb public LayerMask groundLayers public float jumpForce 7 public CapsuleCollider col float transelation float straffe Start is called before the first frame update void Start() Cursor.lockState CursorLockMode.Locked rb this.GetComponent lt Rigidbody gt () col GetComponent lt CapsuleCollider gt () Update is called once per frame void Update() transelation Input.GetAxis("Vertical") speed straffe Input.GetAxis("Horizontal") speed bool jumping Input.GetKeyDown(KeyCode.Space) transelation Time.smoothDeltaTime straffe Time.smoothDeltaTime if (IsGrounded()) rb.useGravity false else rb.useGravity true if (IsGrounded() amp amp Input.GetKeyDown(KeyCode.Space)) rb.AddForce(Vector3.up jumpForce, ForceMode.Impulse) if (Input.GetKeyDown("escape")) Cursor.lockState CursorLockMode.None void FixedUpdate() transform.Translate(straffe, 0, transelation) private bool IsGrounded() return Physics.CheckCapsule(col.bounds.center, new Vector3(col.bounds.center.x, col.bounds.min.y, col.bounds.center.z), col.radius .9f, groundLayers) Mouse look code using System.Collections using System.Collections.Generic using UnityEngine public class MouseLookRigidBody MonoBehaviour public float mouseSensitivity 100f public Transform playerBody Rigidbody rig float xRotation 0f Start is called before the first frame update void Start() Cursor.lockState CursorLockMode.Locked rig this.transform.parent.gameObject.GetComponent lt Rigidbody gt () Update is called once per frame public void Update() float mouseX Input.GetAxis("Mouse X") mouseSensitivity Time.deltaTime float mouseY Input.GetAxis("Mouse Y") mouseSensitivity Time.deltaTime xRotation mouseY xRotation Mathf.Clamp(xRotation, 90f, 90f) transform.localRotation Quaternion.Euler(xRotation, 0f, 0f) playerBody.Rotate(Vector3.up mouseX)


I need my timer to go up every 30 seconds I wrote code for a jackpot to increase from one date to the next, and it works beautifully. The client wants the numbers to stay put for a while, and then increase. This is the code if (timerRunning1) timerValue1 Time.deltaTime 14.4 (timerValue1F timerValue1) (finish1 start).TotalSeconds Jack1.text timerValue1.ToString ("F2") PlayerPrefs.SetFloat ("Jackpot1", float.Parse(Jackpot1.text)) PlayerPrefs.SetFloat ("Jackpot1f", float.Parse(Jackpot1F.text)) if (timerValue1 gt (timerValue1F 0.1)) timerRunning1 false print ("ALTO") PagPrincipal.SetActive (false) Victoria.SetActive (true) Debug.Log ("FUNCIONA!!!") Invoke ("apagavictoria", 10f) I tried WaitForSeconds(30f), and it didn't work. How can I make my timer go up every 30 seconds?


Alternatives to Camera.main.ScreenToWorldPoint in Unity What are alternatives to Camera.main.ScreenToWorldPoint in Unity? So, here is my code (just the piece which is relevant for the question) void sendPointerMove(ref Vector3 mousePosition) lastMousePosition mousePosition Vector3 mousePositionInWorld Camera.main.ScreenToWorldPoint(Input.mousePosition) PointerData pointerData new PointerData( mousePositionInWorld mousePositionInWorld ) void FixedUpdate() Vector3 mousePosition Input.mousePosition if (needToSendPointerMove(mousePosition)) sendPointerMove(ref mousePosition) I am using JetBrains Rider to develop for Unity. And the ide suggests me the following about my sendPointerMove function invocation inside the FixedUpdate Expensive method invocation I am sure that the issue is due to the Camera.main.ScreenToWorldPoint because when I comment out the part the warning disappears. Thank you.


How can I spin a child capsule of a cube parent? I have a parent cube and to make it like a surface I had to change the rotation of the cube on the X to 90. and as a child, I added a capsule, and to make the capsule like standing I had to change the capsule X also to 90. The result is The reason I put the capsule child of the cube is that I want the capsule to move with the cube. The capsule rotation on the X is also 90 Then in a script at the top, I added speed and index variables for the rotation private int index 0 private int rotationIndex 0 In the Update RotateTo() And the method curvedLinePoints is a List private void RotateTo() var distance Vector3.Distance(capsule.position, curvedLinePoints rotationIndex .transform.position) if(distance lt 0.1f) rotationIndex Determine which direction to rotate towards Vector3 targetDirection curvedLinePoints rotationIndex .transform.position capsule.position The step size is equal to speed times frame time. float singleStep rotationSpeed Time.deltaTime Rotate the forward vector towards the target direction by one step Vector3 newDirection Vector3.RotateTowards(capsule.forward, targetDirection, singleStep, 0.0f) Draw a ray pointing at our target in Debug.DrawRay(capsule.position, newDirection, Color.red) Calculate a rotation a step closer to the target and applies rotation to this object capsule.rotation Quaternion.LookRotation(newDirection) The problem is that because the capsule is a child when I rotate the capsule it looks like the capsule changes its shape and not spinning around itself. If I remove ut the capsule from the prefab and will rotate it on its own it will spin fine but when it's a child of the cube the result is I tried before running the game to play with the capsule rotation in the editor in the inspector changing the Y and Z values and the result is like in this screenshot. but I want to spin it around itself but because it's a child of the cube it's not spinning but looks like it's changing its shape. The workaround I found is to create an empty GameObject at 0,0,0 and put both Platform and Capsule as a child of it. Then I added this part to the script above private void LateUpdate() capsule.localPosition transform.localPosition new Vector3(0, 1.4f, 0) This way the Capsule is following the Platform. The empty GameObject is just to put them both together. and for testing I just did in the Update capsule.Rotate(0, 10, 0) and it's working fine. Now I have to figure out how to make this rotation with the code in the RotateTo method.


Unity Animation Tracking Background I've recently reached a bottle neck in my game's code that forced me to completely decouple the logic networking from the graphics. Thanks to the nature of my board game, I was able to build the following architecture Logic update loop gt wait for event gt process event gt dispatch graphic events Graphics update loop gt wait for event gt process event gt wait for animation Question From the previous design, tracking animation timing and knowing when they end is crucial, since that marks the end of the third phase in the graphics loop, allowing us to proceed to the next phase. I'm using Unity, and I am not sure how to go about this. I am using Unity's animation system as well as LeanTween to perform animations on the 2D NGUI level as well as the 3d game scene level. Proposed Solutions Solutions that have occurred to me so far are Callbacks Pass on a callback, and make the animation system trigger that callback when the animation finishes. This has proven to be high maintenance and redundant, as I have to manage passing data back and forth maintaining the overall animation state somehow (if multiple animations were triggered). Global Monitor Animations register under a global monitor, and I can emit a signal when the monitor becomes empty, triggering the end of the animations phase. I must make sure animations are registered immediately at the beginning of the animation phase, which I should be able to do. I should also maintain a list of animation IDs or a simple "anonymous" counter, which animations increment and decrement. Kinda like manual memory management. I might do this. Any of those seem viable? Am I overlooking details about this system? Any better alternatives come to mind?


How can I clean this if Statement up? I am busy working on a full solo project with no assistance from tutorials or guides. But I have created a monstrosity of an If statement. How could I clean this up and save on memory since I'm calling this in my Update() method and the game is for android? the hp1 to hp5 are images used as health bars on the hud, I need to deactivate the ones that are not in use when the hp value decreases. if(hp gt 81) hp1.enabled true hp2.enabled true hp3.enabled true hp4.enabled true hp5.enabled true else if(hp gt 61) hp1.enabled true hp2.enabled true hp3.enabled true hp4.enabled true hp5.enabled false else if(hp gt 41) hp1.enabled true hp2.enabled true hp3.enabled true hp4.enabled false hp5.enabled false else if (hp gt 21) hp1.enabled true hp2.enabled true hp3.enabled false hp4.enabled false hp5.enabled false else if (hp gt 1) hp1.enabled true hp2.enabled false hp3.enabled false hp4.enabled false hp5.enabled false else if(hp lt 1) hp1.enabled false hp2.enabled false hp3.enabled false hp4.enabled false hp5.enabled false


Unity Make sprite visible only to shaders I have made a shader for my UI buttons, the sprites should be black and white, so they can be used as a mask when blending. They should allow for the image behind them to pass through the whiter pixels and be blocked by the darker ones. I want to use this effect for my menu, have a black background and a colored one (like a gradient or a pattern), let the colored one pass only through the buttons and the black one everywhere else. My shader does just that, but with one problem. I can't hide the colored background from the camera. If I change it's layer it is useless (I guess because it is the child of a canvas), and if I use a regular sprite (non UI) it is just ignored by the camera and the buttons don't pick up the color. How can I achieve this effect, having the sprite be invisible to the camera but visible to the shaders of the buttons.


How can I debug a GameObject's rotation? I have a model of a dragon, with an animation of it flying. When I play the animation in the Animator's preview, the dragon flies in a straight line, but when I run it in game, it flies around in circles about 10 units in diameter. If the turning isn't coming from the animator, it has to be coming from somewhere else, but I have no idea where. There aren't any scripts on the dragon that would influence it like that. Is there any way to discover what's causing my dragon to turn? (It's times like this that I really miss the ability to set a memory breakpoint on an object when working in .NET. That would make this trivial!)


Unet how to control child gameobject? I'm currently getting into the Unity networking system called unet. I have a child of the local player authority, the weapon. The weapon (PlasmaCannon left and right) have a script handling firing, because weapons can be replaced, and have different firing intervals, this seemed to me to be the easier way. However, they won't fire. Hierarchy (simplified) Weapon Code public void Start() Debug.Log("Weapon Spawned.") if (isLocalPlayer) Debug.Log("Weapon set as local player") public void Update() if (isLocalPlayer) if (firingTimer lt firingInterval) firingTimer Time.deltaTime if (firingTimer gt firingInterval) if (Input.GetButton("Fire1") amp amp firingMode FiringMode.Primary) CmdFire() if (Input.GetButton("Fire2") amp amp firingMode FiringMode.Secondary) CmdFire() Command public void CmdFire() Debug.Log("Firing Bullet.") I am getting the "Weapon Spawned." log message, but nothing inside isLocalPlayer conditions is happening even though I have added a networkidentity component and set Local Player Authority to true. Like I said, I'm still learning so I have no clue what's going wrong here.


How can I return the class as a Transform in the array instead of each property? public class TransformInfo public string sceneName public string name public Transform parent public Vector3 pos public Quaternion rot public Vector3 scale Then the method public static TransformInfo LoadTransformInfo() string jsonTransform File.ReadAllText( "d json json.txt") if (jsonTransform null) return null TransformInfo savedTransforms JsonHelper.FromJson lt TransformInfo gt (jsonTransform) return savedTransforms The return is But then when using it var test TransformSaver.LoadTransformInfo() Each item in the array contain the the TransfomInfo but instead I want it to return a Transform with already the info. So I can do for example Transform test1 test 0 Instead make a loop and assign each property from the Test to the new Transform test1.


Is it possible to prevent the collider 2D outline from hiding in Unity? Is it possible to prevent the collider 2D outline from hiding in Unity? I am creating some animations in Unity. To create animations I select different parts of a hero and move them frame by frame. Now I am working on the run animation and would like to see the bottom collider during parts movement for the animation creation. In my case the collider outline is red I don't want the red bottom line (which is the collider outline) to disappear while I am creating animations. Should I research the Unity extensions and maybe write my own which would prevent the collider from hiding or is it possible to achieve what I want out of the box somehow?


Do I lose any functionality using Visual Studio for Unity 3d? MonoDevelop has always had a strange tendency to stop functioning in basic ways ... autocompletion, copy paste clipboard, error detecting, and other silly things. I routinely fix this by running clean rebuild all, then restarting MonoDevelop. But this is time consuming. I've read that Monodevelop has issues... If I switch to Visual Studio will I lose anything at all that I rely on with Monodevelop's integration to unity? Or will I in fact gain?


Unity Custom EventManager, multiple arguments, and order I have some hard question for me... I have a nice EventManager, who handle multiple arguments. (no argument, one int, one bool, a GameObject and a bool... but for each sort, I have to create a special dictionnary for this... public class EventManager SingletonMono lt EventManager gt here I have many, many class who handle all sorte of different arguments... private class UnityEventInt UnityEvent lt int gt here definition of all dictionnnary for each class... private Dictionary lt GameData.Event, UnityEvent gt eventDictionary private Dictionary lt GameData.Event, UnityEventInt gt eventDictionaryInt private void Awake() Init() void Init() here initialise all dictionnary if (eventDictionary null) eventDictionary new Dictionary lt GameData.Event, UnityEvent gt () if (eventDictionaryInt null) eventDictionaryInt new Dictionary lt GameData.Event, UnityEventInt gt () ... One of the startListening public static void StartListening(GameData.Event eventName, UnityAction lt int gt listener) if (!Instance) return UnityEventInt thisEvent null if (Instance.eventDictionaryInt.TryGetValue(eventName, out thisEvent)) thisEvent.AddListener(listener) else thisEvent new UnityEventInt() thisEvent.AddListener(listener) Instance.eventDictionaryInt.Add(eventName, thisEvent) one of the stop public static void StopListening(GameData.Event eventName, UnityAction listener) if (EventManager.Instance null) au cas ou on a d ja supprim l'eventManager return UnityEvent thisEvent null si on veut unregister et que la cl existe dans le dico.. if (Instance.eventDictionary.TryGetValue(eventName, out thisEvent)) thisEvent.RemoveListener(listener) and one of the trigger public static void TriggerEvent(GameData.Event eventName, int param1) if (EventManager.Instance null) au cas ou on a d ja supprim l'eventManager return UnityEventInt thisEvent null if (Instance.eventDictionaryInt.TryGetValue(eventName, out thisEvent)) thisEvent.Invoke(param1) And... when I want, in some script I do EventManager.StopListening(GameData.Event.PlayerAddScore, SomeFuncntion) EventManager.StartListening(GameData.Event.PlayerAddScore, SomeFuncntion) EventManager.TriggerEvent(GameData.Event.PlayerAddScore, 1) here SomeFunction take 1 argument, but if i wanted to have 2... i have to hard code the case in my EventManager So... My question is... how can I make that dynamic ? with only one Dictionary ? with only one list ? with good OOP or something ? And secondly, how can I handle order or the call ? Let's say 2 functions are listening for PlayerAddScore from 2 different script, how can I handle an order between the 2 function ? Thanks you for help.


Wrong contineous rotation to car In my 2d game, I want to rotate car face based on collision detected. But at present after 3 to 4 collision its doing continuous rotation only rather than moving straight after collision. Here is my straight movement related code myRigidbody.MovePosition (transform.position transform.up Time.deltaTime GameManager.Instance.VehicleFreeMovingSpeed) For better collision purpose, I have used Rigidbody position change approach. Here is my collision time code public void OnCollisionEnter2D (Collision2D other) if (other.gameObject.CompareTag (GameConstants.TAG BOUNDARY)) ContactPoint2D contact contact other.contacts 0 Vector3 reflectedVelocity Vector3.Reflect (transform.up, contact.normal) direction reflectedVelocity if (direction ! Vector3.zero amp amp pathGenerator.positionList.Count lt 0) float angle Mathf.Atan2 (direction.y, direction.x) Mathf.Rad2Deg Quaternion targetRot Quaternion.AngleAxis (angle 90f, Vector3.forward) transform.rotation Quaternion.Slerp (transform.rotation, targetRot, 0.1f) if (Quaternion.Angle (transform.rotation, targetRot) lt 5f) transform.rotation targetRot direction Vector3.zero Rotation get applied within other code so that car was changing its face correctly and that method not affecting here that I have checked by placing debug statement. Share you side thought for this.


Implicit conversion error why is this code trying to convert a 'World' to an 'int'? using System.Collections using System.Collections.Generic using UnityEngine public class World Tile , tiles int width int height public World (int width 200, int height 200) this.width width this.height height tiles new Tile width, height for (int x 0 x lt width x ) for (int y 0 y lt height y ) tiles x, y new Tile this, x, y public Tile GetTileAt(int x, int y) if (x gt width x lt 0 y gt height y lt 0) Debug.LogError ("Tile (" x ", " y ") is out of range") return null return tiles x, y anyone see anything wrong with this code because on line 18 of my code i get this error "cannot implicitly convert type 'World' to 'int' and i don't know what is going wrong.


Rotate an object smoothly by using Accelerometer Input in Unity There is a simple script where the object orientation is equal to the mobile devices orientation. it works but the object doesn't rotate smoothly. void FixedUpdate() float accelx Input.acceleration.x float angle Mathf.Asin(accelx) Mathf.Rad2Deg transform.eulerAngles new Vector3(angle , 0, 0) How to rotate an object smoothly by using Accelerometer Input ?


How to make game scene bigger in 2d platformer? Hi i am current making a 2D platformer game but after i reach an end of screen then it doesn't move forward how to increase the game play screen area so that i will be able to go in vertical direction i am pasting an image of the problem i am new to unity please help me! 1


How to destroy an object, and then instantiate it again later? I'm creating an enemy spawner in Unity (2D). At long last, I have something that is quite close to working, but the problem is that I want it to destroy all instances of the enemy when the player can no longer see the spawn area. That is, the player happens upon the spawn area to find several enemies, but if they move so that the camera can no longer see the spawn area, I want those enemies to be deleted and then a different set of the same enemies to be instantiated when the player (camera) happens upon the spawn area again. But when I attempt this initial delete, the script component no longer has an object to instantiate when the player returns. Here's a snippet of what I have if (!notOnScreen amp amp spawned false) int numberOfEnemies Random.Range(1, enemyMax) for (int i 1 i lt numberOfEnemies i ) spawnX Random.Range(minX 1, maxX 1) spawnY Random.Range(minY 1, maxY 1) Vector3 spawnpoint new Vector3 (spawnX, spawnY, 0) if (enemies.Length 1) typeOfEnemy 0 else if (enemies.Length gt 1) typeOfEnemy Random.Range(0, enemies.Length) else typeOfEnemy 1 Instantiate(enemies typeOfEnemy , spawnpoint, Quaternion.identity) spawned true if (notOnScreen) spawned false currentEnemies GameObject.FindGameObjectsWithTag("Enemy") for (int i 0 i lt currentEnemies.Length i ) Destroy(currentEnemies i ) I'm sure there's a way to preserve an instance of the enemy so that they can be instantiated again later, but I'm not sure how (sorry very new to this). I thought about cheating and having one enemy remain at a different z coordinate behind the map (as this is a 2D game), but that doesn't seem like an appropriate solution. Any thoughts or advice?


Texture atlasing in Unity I'm researching new ways to optimize games for better performance. Currently I am working on texture atlasing, which is giving me a hard time. I made the atlas using Texture2D.PackTextures and saved the offset and height and width values to a text file. Now when I insert the values to a material the texture is shown correctly, but since batching requires that the same material is used how I can I use the same material with different offsets? Picture All the cubes use the same texture. Only the two on the right batch as they use the same material.


Unlit Node Shadow Shader Graph How to make unlit node cast shadows? Is is possible with the current state of Shader Graph in LWRP? In this great article Toon Shader OP grabs pass from VertexLit shader. Is something similar achievable with Shader Graph?


Declaring Keycodes as strings How do I declare the keycodes as strings instead of selecting the keys from a list? Such that the user can input a key in inspector window and it will be read? public string StringKey quot a quot void Update () if (Input.GetKeyDown (KeyCode.StringKey))


How to access random material in a renderer besides first without cloning any materials except accessed one? Clones only first material renderer.material Clones all materials in the same renderer renderer.materials 0


Why does my material look blotchy on this mesh? This is a generative mesh wireframe looks like this Here's the material But the shaded object looks like a tie dye tshirt I've no idea what settings are causing it to look like this. These are the settings of the mesh renderer


How can I prevent my bullet from influencing other players when colliding with them? So when my bullet which is a Rigidbody is hitting another player which is also a Rigidbody, the bullet is getting destroyed immediately. But it seems that this isn't enough to prevent the physics to be applied. I guess that's why my player is getting pushed backward all the time when he is getting hit. I don't want this behaviour, so I tried to fix it I tried to lower the mass of the bullet which didn't help. I also tried to change the bullet behavior to a trigger, but the collision detection failed very often.


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


How can I make the y extent height also to be random when instantiate new objects? With the script I instantiate random objects above the terrain. But the random was only on x and z. Now I want the height of the objects to be random as well. The terrain position is X 250, Y 0, Z 250. So I changed the line var y Extents.y To var y Random.Range( Extents.y, Extents.y) But now half of the objects above the terrain and half below the terrain, and I want them all to be above the terrain thus the random height should be above the terrain. My full code for reference using System using UnityEngine using Random UnityEngine.Random ExecuteInEditMode public class SphereBuilder MonoBehaviour for tracking properties change private Vector3 extents private int sphereCount private float sphereSize lt summary gt How far to place spheres randomly. lt summary gt public Vector3 Extents lt summary gt How many spheres wanted. lt summary gt public int SphereCount public float SphereSize private GameObject parent private void Start() parent GameObject.Find("Target Builder") private void OnValidate() prevent wrong values to be entered Extents new Vector3(Mathf.Max(0.0f, Extents.x), Mathf.Max(0.0f, Extents.y), Mathf.Max(0.0f, Extents.z)) SphereCount Mathf.Max(0, SphereCount) SphereSize Mathf.Max(0.0f, SphereSize) private void Reset() Extents new Vector3(250.0f, 20.0f, 250.0f) SphereCount 100 SphereSize 20.0f private void Update() UpdateSpheres() private void UpdateSpheres() if (Extents extents amp amp SphereCount sphereCount amp amp Mathf.Approximately(SphereSize, sphereSize)) return cleanup var spheres GameObject.FindGameObjectsWithTag("Target") foreach (var t in spheres) if (Application.isEditor) DestroyImmediate(t) else Destroy(t) var withTag GameObject.FindWithTag("Terrain") if (withTag null) throw new InvalidOperationException("Terrain not found") for (var i 0 i lt SphereCount i ) var o GameObject.CreatePrimitive(PrimitiveType.Sphere) o.tag "Target" o.transform.localScale new Vector3(SphereSize, SphereSize, SphereSize) o.transform.parent parent.transform get random position var x Random.Range( Extents.x, Extents.x) var y Extents.y sphere altitude relative to terrain below var y Random.Range( Extents.y, Extents.y) var z Random.Range( Extents.z, Extents.z) now send a ray down terrain to adjust Y according terrain below var height 10000.0f should be higher than highest terrain altitude var origin new Vector3(x, height, z) var ray new Ray(origin, Vector3.down) RaycastHit hit var maxDistance 20000.0f var nameToLayer LayerMask.NameToLayer("Terrain") var layerMask 1 lt lt nameToLayer if (Physics.Raycast(ray, out hit, maxDistance, layerMask)) var distance hit.distance y height distance y adjust else Debug.LogWarning("Terrain not hit, using default height !") place ! o.transform.position new Vector3(x, y, z) extents Extents sphereCount SphereCount sphereSize SphereSize


Unity Ball moving inside the surface My ball is jumping on a 3d cylinder, and sometimes the ball gets stuck inside the cylinder. The ball has a rigid body and it's continuously dynamic. The circle also has a mesh collider. Here is the code to make the ball jump void Update () if(Mathf.Sign(rg.velocity.y) 1) isforceApplied true void OnCollisionEnter(Collision collisionInfo) if(isforceApplied true) isforceApplied false rg.AddForce(transform.up forceAmount,ForceMode.Impulse)


Reusing tilemap segments I'm wondering how I can incorporate reusable tilemap segments in my workflow. For example I construct a room out of my tile palette, and I want to reuse this room in multiple places. Is there some way to "prefab" a section of a tilemap? I haven't found such a thing. Or perhaps I should just prefab the whole tilemap, and use multiple tilemap objects within one grid? Won't that introduce significant overhead? What if I want to prefab a section of a tilemap with some additional, non tilemap objects?


Unity Free Inverse Depth Mask? How would it be possible to create an inverse depth mask? In this case, I refer to a depth mask as a shader attached to a mesh that 'pokes a hole' through the current camera layer to let you see the camera render layer one depth down, usually by using ColorMask 0. What I want is for, instead, the mesh to determine what ISN'T cut out, without everything that is NOT seen through the mesh being cut out.


How does Aspect Ratio and Resolution work in Unity? I am trying to make progress in Unity on understanding how aspect ratios and resolution work. I can't quite wrap my head around the topic. For example, I am trying to make a simple breakout style game, but in order to do that, I need to consider the world units and how each brick would fit into the scene. From what I have read, world units are dependent on screen resolution and aspect ratio. How would I be able to make something like this if mobile games are played on different devices (and ones with notches nonetheless). Also I'd like to know how to achieve this without using the tacky black bars that some games use. Any information regarding this would be extremely appreciated.


Fade a texture effect as it nears the end of a cylinder mesh In my game I have a laser beam that travels for about 15m, but abruptly stops due to the mesh the texture is attached to. How can I setup my shader graph so that the end of the texture fades away? I can't find anything similar to this anywhere online, and have tried multiple things (gradient colors with lerp attached to alpha) but just can't figure it out as I'm too new to the whole shader graph thing. Anything helps, thank you. Note The texture is 'animated' and scrolls along the path of the beam using the shader graph


Select Unity Prefab from enum choice After a couple tries, I still haven't found any solution to this problem of mine. Currently, I have a script inheriting from MonoBehavior which creates a map with Perlin Noise. Let's call it mapGenerator. It instantiates a HexTile object from another script, which does not inherit from MonoBehaviour, that contains a refere to my terrain prefab and an enum value which says its type (so water, grass, wood, etc.). There is an array declared at the beginning of the script that I manually change as I'm adding terrains. Everything works fine except when tweaking the map generation, If I want to change some values for perlin intervals, I might have to add another value to my HexTile and then drag my terrain prefab and set the enum value. What I want is to know if there is a way to make the script select a prefab depending on the value the enum was set to. Here is the code (simplified) public class ProceduralTerrainGenerator MonoBehaviour public bool regenerateMap true public Hextile hexTiles void Update() CreateMap() private void CreateMap() Some code for Perlin Noise generation inside perlinMap , for (int i 0 i lt mapLength i ) for (int j 0 j lt mapHeight j ) Setting up position from i and j index foreach (HexTile hexTile in hexTiles) if (ValueInRange(perlinMap i,j , hexTile.LowLimit, hexTile.HighLimit) Instantiate lt HexTile gt (hexTile.tile, position, Quaternion.Euler(0f, 0f, 0f), this.transform) and my other script System.Serializable public class HexTile public GameObject tile public HexMetrics.HexType hexType public float perlinNoiseLowLimit public float perlinNoiseHighLimit EDIT 1 I tried simplifing my problem, because I'm more interested in the concept, but here are more details. I have a class named HexSettings, which contains the hex prefab (HexTile) named tile, its HexType, and the perlin noise bundaries. System.Serializable public class HexSettings public HexTile tile public HexMetrics.HexType hexType public float perlinNoiseLowLimit public float perlinNoiseHighLimit Here is the HexType enum contained inside HexMetrics public class HexMetrics Hex metrics data for placement in grid data public enum HexType GRASS, FOREST, WATER, SNOW, DESERT, LAKE What I would like is to have some soprt of dictionnary that contains the correct prefab according to the selected HexType. As you can see in the image below, I can set my HexType to my terrain types, but I also have to set the HexTile object manually, where it could be set automatically according to the HexType value set. That is what I'm looking for. I tried adding it in a dictionnary (something like Dictionnary lt Hextype, HexTile gt ), looking for prefabs in my folder prefab with Resources.LoadAll lt HexTile gt ("prefab") , no success, prefabs couldn't be loaded in HexSettings.


Unity animator controller animations don't work I'm having problems animating a character pack I purchased from unity asset store. I've placed the character in an environment and created an animator controller. After I drag the animation that to the animator tab, there aren't any motions. Even if I place triggers or booleans in my script as parameters in the animator it doesn't work. It worked with other characters but the animations were somehow embedded in the 3d models. How is this supposed to work?


Move enemy left in sin wave motion over time I'm trying to create a top down shooting game where the enemy moves in sinusoidal motion over time. For the first 10 seconds the enemy needs to move only left and after that it needs to move left in sin wave motion. This is the code I'm using. public float enemySpeed float frequency 5.0f float magnitude 1.8f void FixedUpdate() if(Time.time lt 10.0f) transform.Translate((enemySpeed Vector2.left) Time.deltaTime) if(Time.time gt 10.0f) transform.Translate(enemySpeed 1.0f Time.deltaTime, 1.0f Mathf.Sin(Time.time frequency) magnitude Time.deltaTime, 0) What's happening is that for the first 10 seconds the enemy just moves left but after that all the enemies in the screen start moving in sin wave motion. What I want to achieve is that if the enemy has already spawned before the 10th second, it should move left without sin motion. Right now if the enemy is in the middle of the screen and the time is over 10 seconds, even this enemy starts moving in sin motion.


Moving my character camera makes environnement jerky I'm learning to make a Tilebased game with Unity and for that I use the Zelda alttp assets. I just have Tiles, a Camera and a moving Character with a rigidbody2D and a CircleCollider. When the Camera follows the Character, the scene feels Jerky. Info The Camera uses the 2D Pixel Perfect package. The Character is moving via Rigidbody2D.MovePosition() in the FixedUpdate Method code void Update() float yInput float xInput region yMovement if (Input.GetKey(keyMoveTop)) if (Input.GetKey(keyMoveBot)) yInput 0f else yInput 1f else if (Input.GetKey(keyMoveBot)) yInput 1f else yInput 0f endregion region xMovement if (Input.GetKey(keyMoveLeft)) if (Input.GetKey(keyMoveRight)) xInput 0f else xInput 1f else if (Input.GetKey(keyMoveRight)) xInput 1f else xInput 0f endregion Walking isWalking Input.GetKey(keyMoveWalk) moveDirection Vector2.ClampMagnitude(transform.right xInput transform.up yInput, 1f) private void FixedUpdate() rb.MovePosition( rb.position moveDirection (isWalking ? walkSpeed runSpeed) Time.fixedDeltaTime) You can see the problem here https youtu.be MA2zZPME5X4 Edit Added all my movement code


Rect transform stretch of a child object is set to 0 after instantiation I have the following hierarchy of my prefab PopupParent Popup ScreenDim They all have Rect Transform set to Stretch. Anchor mins are set to 0 and Anchor maxes to 1. Left, top, right and bottom are set to 0. When I pull this prefab to a Canvas manually, all works as expected. When I instantiate the prefab the problem I am encountering is, that the PopupParent is stretched as expected, to the full screen, but all its children are not. PopupParent looks like this Children Popup and ScreenDim look like this The instantiation I am doing using the Spawn Prefab Node in the Event editor provided by the ORK Framework. I am Mounting the PopupParent to my UICanvas. It could be, that the issue is caused by some Framework settings, but it might very well be related to how Unity works in general. I am not sure and can't find a way to figure it out. SOLUTION I got ORK support to reply and solve the issue for me http forum.orkframework.com discussion 6465 spawning a prefab with a stretch property latest TL DR Regular mounting and UI mounting works slightly different.


"ArgumentNullException Value cannot be null" for AudioSource.PlayOneShot I am working on a game and I am trying to add a sound effect. using System.Collections using System.Collections.Generic using UnityEngine public class PlayerController MonoBehaviour private Rigidbody playerbody private Animator playerAnim private bool grounded public bool gameover public float jumpforce public float gravmod public ParticleSystem explosion public ParticleSystem dirt public AudioClip jumpSound public AudioClip crashSound private AudioSource playerAudio Start is called before the first frame update void Start() playerbody GetComponent lt Rigidbody gt () playerAnim GetComponent lt Animator gt () playerAudio GetComponent lt AudioSource gt () Physics.gravity gravmod Update is called once per frame void Update() if (Input.GetKeyDown(KeyCode.Space) amp amp grounded amp amp gameover false) playerAudio.PlayOneShot(jumpSound, 1.0f) playerbody.AddForce(Vector3.up jumpforce, ForceMode.Impulse) playerAnim.SetTrigger( quot Jump trig quot ) grounded false dirt.Stop() private void OnCollisionEnter(Collision collision) if (collision.gameObject.CompareTag( quot Ground quot )) grounded true dirt.Play() if (collision.gameObject.CompareTag( quot Obstacle quot )) playerAudio.PlayOneShot(crashSound, 1.0f) gameover true playerAnim.SetBool( quot Death b quot , true) playerAnim.SetInteger( quot DeathType int quot , 1) explosion.Play() dirt.Stop() At playerAudio.PlayOneShot, it just won't play and the rest of that part of the code stops working. It returns ArgumentNullException Value cannot be null even though jumpSound and crashSound are both clearly defined. What is wrong?


Mask not applying to gameobjects in UI layer I have a bunch of item slots in my scroll view. The item slots contain 3d objects, but they are all set to use the UI layer. My problem is that they are not being masked the same as the 2D elements are. See this example Notice how the 3D items in the scroll view are overflowing, but the 3D item slot panels are not. Like I said, I put everything in the UI layer. I'm not sure how to fix this. Is there a simple fix for this?


Unity How to make grass details look good from top down I have an issue with the terrain details. Since it only draws a single plane per texture, it looks quite crappy with a angled top down camera, for example for an RTS camera. Is there some way around this, I know one solution people use is to angle the grass towards the camera a bit, but that isnt possible with the terrain details painter. The issue is circled in red If there is no solution to this, are there some techniques I can use to make some interesting looking grass for an RTS camera?


Instantiate creates a clone in wrong position I have this prefab with this transform And then using this code to create a clone (the prefab is assigned to a public property of a script, which I assign using the editor, which is the e.Weapon) Instantiate(e.Weapon, new Vector3(0f, 0f, 0f), Quaternion.identity, rightHand.transform) I am parenting it to my character's right hand. But whenever the clone gets created, it has different position than the one I have in my code. It appears like this Any idea why this is happening?


just download first assetbundle In the Start of my scenes I call the method that downloads the assetBundles for that scene. The problem is that it only downloads the first assetBundle from the list, the second does not download it. My code is Note The Debug that shows the url shows the correct url both times, first http mihost.com assetbundles asset1 and then http mihost.com assetbundles asset2. However, in the Debug that shows the assets 'added' in both cases it shows the name only of those in asset1 public virtual IEnumerator LoadBundleFromServer() var AssetPathOnServer "http mihost.com assetbundles " var assetBundleNames new List lt string gt () assetBundleNames.Add("asset1") assetBundleNames.Add("asset2") for (int i 0 i lt assetBundleNames.Count i ) var currentAssetBundleName assetBundleNames i var url AssetPathOnServer currentAssetBundleName Debug.Log("url " url) var request UnityWebRequestAssetBundle.GetAssetBundle(url) yield return request.SendWebRequest() if (!request.isHttpError amp amp !request.isNetworkError) var asseBundle DownloadHandlerAssetBundle.GetContent(request,) Debug.Log("count assets " AssetNames.Count) for (int j 0 j lt AssetNames.Count j ) string assetName AssetNames j AssetBundleRequest asset asseBundle.LoadAssetAsync lt AudioClip gt (assetName) yield return asset AudioClip myClip asset.asset as AudioClip if (!assetDictionary.ContainsKey(assetName)) assetDictionary.Add(assetName, myClip) Debug.Log("added " assetName) asseBundle.Unload(false) else TODO aqui hay que mostrar un error Debug.LogErrorFormat("error request 0 , 1 ", url, request.error) public abstract List lt string gt AssetNames get


Why Unity3d takes so long time to "rebuild" when I change build platform? I would like to know what happens "behind the scenes" when I change my unity game target platform . If I switch from Android to iOS or Pc or etc, Unity rebuild something and takes a lot of hours to complete. What is the reason ? Thanks


How to move 3D Object With Touch Dragging Finger By the screen In android Unity Game My Code is As Followed using System.Collections using System.Collections.Generic using UnityEngine public class Sphere MonoBehaviour SerializeField private Touch touch private float speedModifier Start is called before the first frame update void Start() speedModifier 0.01f Update is called once per frame void Update() if (Input.touchCount gt 0) touch Input.GetTouch(0) if (touch.phase TouchPhase.Moved) transform.position new Vector3( transform.position.x touch.deltaPosition.x speedModifier, transform.position.y, transform.position.z touch.deltaPosition.y speedModifier) I tried with this code but object is not even responding