_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | unity problem in limiting rotation of object? I am trying to make a game with unity. In this game, player uses mouse to rotate a container or box around x and z (rotate to left and right and also toward the camera and opposite). I used below code to control movement and limit it. float zRot transform.eulerAngles.z float xRot transform.eulerAngles.x float yRot transform.eulerAngles.y Debug.Log ( "xDir " xRot.ToString() " yDir " yRot.ToString() " zDir " zRot.ToString() ) if ((xRot gt 330 xRot lt 30) amp amp (zRot gt 330 zRot lt 30)) transform.Rotate (Input.GetAxis ("Mouse Y"), 0, Input.GetAxis ("Mouse X")) else Debug.Log(xRot.ToString() " " zRot.ToString ()) transform.Rotate ( transform.rotation.x , transform.rotation.y, transform.rotation.z ) The contatiner rotate 60 degrees in x and z and when it gets to the limits it stops, which is what I want. However when I rotate in both direction to the near the limits (330 or 30), the contatiner becomes out of control and it rotates freely and constantly. It's like the contatiner has passed the limits. The questions are Did I used a good approach to limit the rotation and how to stop the object completely when it get to the limit of rotation? When and why the object becomes out of control exactly? |
0 | Unity3D playing sound when Player collides with an object with a specific tag I using Unity 2019.2.14f1 to create a simple 3D game. In that game, I want to play a sound anytime my Player collides with a gameObject with a specific tag. The MainCamera has an Audio Listener and I am using Cinemachine Free Look, that is following my avatar, inside the ThridPersonController (I am using the one that comes on Standard Assets but I have hidden Ethan and added my own character avatar). The gameObject with the tag that I want to destroy have an Audio Source In order to make the sound playing on the collision, I started by creating an empty gameObject to serve as the AudioManager, and added a new component (C script) to it using UnityEngine.Audio using System using UnityEngine public class AudioManager MonoBehaviour public Sound sounds Start is called before the first frame update void Awake() foreach (Sound s in sounds) s.source gameObject.AddComponent lt AudioSource gt () s.source.clip s.clip s.source.volume s.volume s.source.pitch s.pitch Update is called once per frame public void Play (string name) Sound s Array.Find(sounds, sound gt sound.name name) s.source.Play() And created the script Sound.cs using UnityEngine.Audio using UnityEngine System.Serializable public class Sound public string name public AudioClip clip Range(0f, 1f) public float volume Range(.1f, 3f) public float pitch HideInInspector public AudioSource source After that, in the Unity UI, I went to the Inspector in the gameObject AudioManager, and added a new element in the script that I named CatchingPresent. On the Third Person Character script, in order to destroy a gameObject (with a specific tag) when colliding with it, I have added the following void OnCollisionEnter(Collision other) if (other.gameObject.CompareTag("Present")) Destroy(other.gameObject) count count 1 SetCountText() It is working properly as that specific object is disappearing on collision. Now, in order to play the sound "CatchingPresent" anytime the Player collides with the object with the tag, in this case, Present, I have tried adding the following to the if in the OnCollisionEnter FindObjectOfType lt AudioManager gt ().Play("CatchingPresent") But I get the error The type or namespace name 'AudioManager' could not be found (are you missing a using directive or an assembly reference?) AudioManager.instance.Play("CatchingPresent") But I get the error The name 'AudioManager' does not exist in the current context As all the compiler errors need to be fixed before entering the Playmode, any guidance on how to make the sound playing after a collision between the player and the gameObject with the tag Present is appreciated. |
0 | How to make it two seconds for Time.time? var targetscript Diamond var red Color var orange Color function Start () gameObject.camera.backgroundColor red function Update () if (targetscript.score gt 4) gameObject.camera.backgroundColor Color.Lerp(red, orange, Time.time) So right now, if the score is larger than 4 then it would change the camera background color to orange with lerp. But its too quick. I read on the internet that Time.time is 1 second. What is the alternative way but for 2 or 3 seconds? I tried this http answers.unity3d.com questions 328891 controlling duration of colorlerp in seconds.html I tried the code for the voted answer but it didn't work. It still lerps through quickly. Does anyone have any ideas? Thanks |
0 | Where is Advertisement.Banner class in Unity Advertisement v2.3.1 package? I'm implementing Unity Ads in my game, now i'm using Advertisement package v2.3.1 from package manager. I set up rewarded and video ad, but can't do anything with Banner ads. I set up id in a project dashboard and just call Show function with banner placement id. private IEnumerator ShowBannerWhenReady() while (!Advertisement.IsReady(bannerPlacementId)) yield return delay Debug.Log("Showing Banner") ShowOptions options new ShowOptions resultCallback HandleBannerShowResult Advertisement.Show(bannerPlacementId, options) As for unity documentation Advertisement namespace have Banner class, but i don't see it in my project. So on android build i don't see any banner or smth, other ads work as expected. |
0 | Export "Lite" and "Full" versions with different package names for Google Play Console On the Google Play Console, you can't have two games with the same package name. Is there a way to have two of the same game with different package names, exported from the same Unity project? For example, a quot lite version quot with ads and a quot full version quot without ads. |
0 | How can I destroy the trigger forever? I have a trigger that plays an animation but when i switch scene and i come back to the original scene, the animation plays again. I want to remember actioned triggers in order to play triggers once per scene. How can I do that? The GlobalScript public class GlobalScript MonoBehaviour public static GlobalScript Instance public Animator ani void Awake () if (Instance null) DontDestroyOnLoad(gameObject) Instance this else if (Instance ! this) Destroy (gameObject) The current script (Running every time i load the scene) public Animator ani public AudioClip sound public GameObject text private int seconds 2 var delay 2.0 This implies a delay of 2 seconds. public void SavePlayer() GlobalScript.Instance.ani ani Use this for initialization void Start () ani GlobalScript.Instance.ani ani.enabled false text.SetActive (false) void OnTriggerEnter(Collider other) AudioSource.PlayClipAtPoint (sound, transform.position) ani.enabled true text.SetActive (true) Destroy (gameObject) Destroy (text,3) text.SetActive (true) StartCoroutine(Die()) And function itself IEnumerator Die() play your sound text.SetActive(true) yield return new WaitForSeconds(2) waits 3 seconds Destroy(gameObject) this will work after 3 seconds. |
0 | How to use a whole new set of assets (reskinning) I need to be able to load my game with a different set of assets, basically reskinning it. I knew beforehand that I would need a way to do that in the future so right now i'm accessing my assets via a ScriptableObject that I call an "Accessor". Basically the accessor only hold references to the assets and when I want to get, for example, the sprite for my cards I make a call that looks like that Sprite cardSprite Accessors.Instance.GetCardFrame() Solution seem simple, I add a layer above the accessors that allow it to choose between differents sets of references. The problem is that right now I only use the accessors for dynamically generated gameobject ( When I instantiate a card for exemple ). How could I do that with, let's say, UI in the editor ? It will be nearly impossible to work on the UI if I can't see it due to the sprite not being loaded in editor mode. |
0 | Will Unity skills be transferable? I'm currently learning Unity and working my way through a video game maths primer text book. My goal is to create a racing game for WebGL (using Three.js and maybe Physic.js). I'm well aware that the Unity program shields you from a lot of what's going on and a lot of the grunt work attached to developing even a simple video game, but if I power through a bunch of Unity tutorials, will a lot of the skills I learn translate over to other frameworks engines? I'm pretty proficient at level design with WebGL, and I'm a good 3D modeller. My weaknesses are definitely AI and Physics. While I am rapidly shoring up my math, and while Physics is undeniably interesting there's only so many hours in the day and there's a wealth of engines out there to take care of this sort of thing. AI does appeal to me a lot more, and is a lot more necessary. AI changes drastically from game to game, is tweaked heavily during development, and the physics is a lot more constant. Will leaning AI concepts in Unity allow me to transfer this knowledge pretty much anywhere? Or will I just be paddling up Unity creek with these skills? |
0 | Unintended window opening when pressing Unity's "Submit" button I've been working on a top down 2D game for a while now, and yesterday I found a strange bug that I just can't explain to myself whatsoever. I have a loot window for looting enemies, as well as a character panel to equip gear see stats. I realized that after I open and close a loot window, if I press the space button (used for attacking, not for opening any windows) while holding A LeftArrow or W UpArrow it opens the character panel. Once this happens, I can press space to open close the character panel. Went to the character panels OpenClose() function (all it does is set the canvas group alpha to 0 and block raycast to false and vice versa) which is being called unintentionally, put a debug.log inside to verify if it really was being called, and yes, it is. I look up all references to see where I used it, but I only use it in a single place in the project that is behind an if statement looking for they keycode C (NOT space). I added a debug.log for the Input.inputstring to see if somehow a magic C button press is ending up in that function, but no. If I press C to open the window, the debug log pops up, if I press space, the inputstring appears to be empty, so the if statement to get to the only place in the code referencing that function cannot be met. Removed the space button from my Player entirely, the behaviour still persists. Added another debug.log with stackTrace.GetFrame(1).GetMethod().Name to show who is actually running this function, but it turns out that if I run it and press C, it says it's being opened by the update function in the UIManager (as expected). If I run it the strange, unintended way, it says it is being run by the EventSystems Invoke function. Coupled with the fact that the behaviour persists despite the space button being removed from the player, I realized that it's Unity's built in "Submit" button being pressed. Strange behaviour It appears to call the submit function on the OpenClose button for the character panel, but only under the circumstance that I closed a loot window and haven't clicked the mouse anywhere yet afterwards. If I deactivate the button that holds the character panels OpenClose function, the behaviour stops. The button shouldn't be pressed though, because it is on a canvas group with alpha 0 block raycast false, just like all the other buttons with the identical function that work fine. The loot window has no idea about the character panel either, and all the windows are properly wired to their own OpenClose function. Upon further inspection, the window only starts showing up if, after closing a loot window, i press A LeftArrow Space or W UpArrow Space. This is getting more and more confusing for me. So basically my issue is how do I figure out why this function is being called? It feels as if closing the loot window somehow "caches" the OpenClose button for the character panel onto the submit button, but only until I click elsewhere on the screen. Did you guys have any experience with a similar situation? Could you share some pointers on how to debug this? What is the "submit" button usually used for, and what would make it only work in combination with the left top directional buttons? I've spent about 4 hours on this now and don't know how to get any further. |
0 | How can I increase the speed and frequency of a spawn? I'm using the official Unity tutorial for the Space Shooter game, and I'm at the part where the ability to spawn a set amount of hazards in a wave at a certain delay is introduced. I want to make it so that at the end of a certain level, the speed of the hazards, and the amount of hazards both increase. I'm pretty sure that can be handled in the game controller, but I don't know the commands I would be needing to use to make that happen. This is the existing code public class GameController MonoBehaviour public GameObject hazard public Vector3 spawnValues public int hazardCount public float spawnWait public float startWait public float waveWait void Start () StartCoroutine (SpawnWaves()) IEnumerator SpawnWaves () yield return new WaitForSeconds (startWait) while (true) for (int i 0 i lt hazardCount i ) Vector3 spawnPosition new Vector3 (Random.Range ( spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z) Quaternion spawnRotation Quaternion.identity Instantiate (hazard, spawnPosition, spawnRotation) yield return new WaitForSeconds (spawnWait) yield return new WaitForSeconds(waveWait) What commands would I need to use to increase the amount of hazards that spawn at the end of each round? And likewise, how could I change the Hazard's script so that it will increase in speed by a certain factor at the end of each round? Is there a way I can reference the hazard's script in this script, by any chance? |
0 | How can I make alternate fragments drop (or make them black) based on a checkerboard texture? How can I make alternate fragments drop(or make them black) based on a checkerboard texture in a Unity fragment shader? I am using forward path rendering in my shader passes for lighting and shadows for every object in the scene. Now,I need a shader (or something) that drops alternate pixels from the overall screen space after everything is rendered. How can I achieve this effect? |
0 | gazing and lip syncing in Unity 5.2 Is it possible to achieve gazing or lip syncing in Unity 5.2 at all, similar to Locomotion done through MecAnim? |
0 | Unity how to have a ghost 3d game object I want to have a 3d game object (player) who converts to ghost. That means that the user must not collide with other players, but must not pass walls, trees, and must take care about terrain height levels (I mean, I can't put it as kinematic and remove the collider because the Vector3.MoveTowards which moves the player will ignore the height dimension and will pass the mountains, etc) My was thinking about tagging the players and in some way try to skip the collider between them. Any idea? Thanks |
0 | Write Data From List To CSV File I am trying to write to a CSV file the values that I put in lists from a key press in the keyboard. It does work somehow but in my csv file I get the values 2 times. Also, when I put values to only one of the lists, I don't get any data to CSV file. How can I save the values from the lists to my csv file but to be independent from each other? This is my code using UnityEngine using System.Collections using System.Collections.Generic using System.Text using System.IO using System public class record MonoBehaviour public List lt string gt inventory new List lt string gt () public List lt string gt OnlyX new List lt string gt () void Update() if (Input.GetKeyDown(KeyCode.F)) inventory.Add("F") if (Input.GetKeyDown(KeyCode.J)) inventory.Add("J") if (Input.GetKeyDown(KeyCode.X)) OnlyX.Add("X") string filePath getPath() StreamWriter writer new StreamWriter(filePath) writer.WriteLine("Inventory,OnlyX") for (int i 0 i lt inventory.Count i) for (int j 0 j lt OnlyX.Count j) writer.WriteLine(inventory i "," OnlyX j ) writer.Flush() writer.Close() private string getPath() if UNITY EDITOR return Application.dataPath " Data " "Saved Inventory.csv" elif UNITY ANDROID return Application.persistentDataPath "Saved Inventory.csv" elif UNITY IPHONE return Application.persistentDataPath " " "Saved Inventory.csv" else return Application.dataPath " " "Saved Inventory.csv" endif |
0 | How do I make Ground Check stop rotating with the character when it rotate? How do I make my character routice without Ground Check rotating with it, but still follow my character? Code using UnityEngine using System.Collections public class Player MonoBehaviour public float maxspeed 10f bool facingRight true Animator anim bool grounded false public Transform groundCheck float groundRadius 0.2f public LayerMask whatIsGround public Vector2 jumpDirection new Vector2(1f, 1f) public float jumpFocre 500f bool doubleJump false void Start () anim GetComponent lt Animator gt () void FixedUpdate () grounded Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround) anim.SetBool ("Ground", grounded) if (grounded) doubleJump false float move Input.GetAxis ("Horizontal") anim.SetFloat ("Speed", Mathf.Abs (move)) GetComponent lt Rigidbody2D gt ().velocity new Vector2(move maxspeed, GetComponent lt Rigidbody2D gt ().velocity.y) void Update() if((!doubleJump) amp amp Input.GetKeyDown ("up")) anim.SetBool("Ground", false) float move Input.GetAxis ("Horizontal") jumpDirection.x move GetComponent lt Rigidbody2D gt ().AddForce(jumpDirection.normalized jumpFocre) if(!doubleJump amp amp !grounded) doubleJump true void Flip() facingRight !facingRight Vector3 theScale transform.localScale theScale.x 1 transform.localScale theScale |
0 | How can I update a sprite sheet without affecting the sprites already being used? Every time I overwrite my sprite sheet with additional or updated sprites, I have to reattach the textures to all of my Animations and Sprite Renderers. How can I update a sprite sheet without affecting the sprites on that sheet which are already being used? During the development of even a small game, hundreds of textures are being used. And new textures are being added and updated every day. This results in many hours spent reattaching textures which could otherwise be used being productive. What strategy can I use to prevent this? This is an example of what I mean I have a sprite sheet with 40 textures. All of its sprites are attached to their relative GameObjects. I decide I want to change the color of one of my sprites' hat. I go into gimp and load the sprite sheet. I change the color of the hat. I overwrite the old sprite sheet. Back in Unity, all of the textures are no longer attached to their respective GameObjects. I go in and splice the sprite sheet again and manually reattach all of the textures. Then I decide I like the old hat better. I go back into gimp, change the sprite sheet, and am then forced to reattach all of the textures...again. There has to be a better way! (Also would like to be capable off adding new sprites in addition to editing old ones.) |
0 | Continous Movement and Gravity Switch With 1 button I have a sphere with a rigidbody on it, and it moves to the right continously as I need it, but as it moves I want the space bar to be able to switch the gravity (so it either rides on the ceiling or on the floor), as it moves along to the right. Please help, have been googling consistently for the past 3 hours. Here is the code I have so far public class movement MonoBehaviour public float movementSpeed 10 private bool haspressed void Start() void FixedUpdate() transform.Translate(Vector3.down movementSpeed Time.deltaTime) if (Input.GetKeyDown ("space") amp amp haspressed true) transform.Translate (Vector3.right movementSpeed Time.deltaTime) haspressed false else if (Input.GetKeyDown ("space") amp amp haspressed false) transform.Translate (Vector3.right movementSpeed Time.deltaTime) haspressed true Thank you sooo much! |
0 | Unity 2D Destroy object with dynamic collider after exiting object with static collider I'm using the Unity5 game engine and am programming a 2D shooter in bird's eye view. I have a static Box Collider 2D which covers the entire game area. It has "Is Trigger" checked and contains a very simple script which should destroy every object that exits it. using UnityEngine using System.Collections public class DestroyByBoundary MonoBehaviour void OnTriggerExit(Collider other) Debug.Log ("OnTriggerExit") Destroy (other.gameObject) The player character shoots bullets which have a dynamic Circle Collider 2D. However, the bullets are never destroyed when they leave the game area and just fly on indefinitely. The debug statement never gets executed either, of course. I have tried the same thing with OnTriggerEnter, which yields the same result. If any more information should be needed, I'll be happy to provide it. |
0 | remove sudden upward downward jerk from camera I have a scene with low poly assets amp NavMesh enabled for character navigation. When player climbs the bridge there's a sudden upward jerk in camera. Also, when the player comes down, there's a downward jerk in Camera. I want the camera movement to be smooth so it appears as if the y axis of the camera is floating like a drone. Below is my script that I'm using public class FollowCamera MonoBehaviour float MIN X 26.72f float MAX X 34f float MIN Z 6.22f float MAX Z 47.6f float MAX Y 15f float MIN Y 0.6f public float startYPositionOfCamera The target we are following public Transform target The distance in the x z plane to the target public float distance 10.0f the height we want the camera to be above the target public float height 5.0f How much we public float heightDamping 2f public float rotationDamping 3.0f AddComponentMenu("Camera Control Smooth Follow") void Start() startYPositionOfCamera transform.position.y void LateUpdate() Early out if we don't have a target if (!target) return Calculate the current rotation angles float wantedRotationAngle target.eulerAngles.y float wantedHeight target.position.y height float currentRotationAngle transform.eulerAngles.y float currentHeight transform.position.y Damp the rotation around the y axis currentRotationAngle Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping Time.deltaTime) Damp the height currentHeight Mathf.Lerp(currentHeight, wantedHeight, heightDamping Time.deltaTime) Convert the angle into a rotation var currentRotation Quaternion.Euler(0, currentRotationAngle, 0) Set the position of the camera on the x z plane to distance meters behind the target transform.position target.position transform.position currentRotation Vector3.forward distance Set the height of the camera transform.position new Vector3(transform.position.x, currentHeight, transform.position.z) Always look at the target transform.LookAt(target) Clamp the position of camera so it doesn't go back of mountains transform.position new Vector3( Mathf.Clamp(transform.position.x, MIN X, MAX X), Mathf.Clamp(transform.position.y, MIN Y, MAX Y), Mathf.Clamp(transform.position.z, MIN Z, MAX Z) ) |
0 | Unity loop through list and match PlayerPrefs I have a list of stickers and when a player completes a level they get awarded a sticker which I save into PlayerPrefs. I want to be able to return the list of sprites saved into PlayerPrefs on the awards scene. I have not been to loop and match the PlayerPrefs. I am not sure how to go about this. public class StickerManager MonoBehaviour public List lt Sprite gt stickers new List lt Sprite gt () public List lt Sprite gt unlockedStickers new List lt Sprite gt () public void UnlockSticker (int id) PlayerPrefs.SetInt("sticker", id) public List lt Sprite gt LoadUnlockedSticker () int i 0 foreach (Sprite spri in stickers) if (PlayerPrefs.GetInt("sticker", i) stickers i ) unlockedStickers.Add(stickers i ) i return unlockedStickers |
0 | Get width of a 2D GameObject in Unity I'm trying to get the width and height of a 2D GameObject. My GameObject is simply a prefab created using sprite. I have tried solutions from other posts but they don't work for me Vector2 size myGameObject.GetComponent lt CircleCollider2D gt ().bounds.size float width size.x float height size.y and Vector2 size myGameObject.GetComponent lt Collider2D gt ().bounds.size float width size.x float height size.y My prefab has a Circle Collider 2D but x and y always returns 0 I'm using Unity 5.5.0f3, not sure if previous solutions apply to this version. |
0 | Load nextLevel with a button click Can anyone help me someone with this code? I'd like to go to the next level by clicking a button example my level name is L1,L2,L3,L4,L5,L6,L7 and when I finish level L1, I want to go to level L2 with the click of a button, and from L5 go to L6 like this. public class GameLevels MonoBehaviour public Button Play private int idLevel Use this for initialization void Start () idLevel PlayerPrefs.GetInt("idLevel") Play.interactable false public void SelectLevel(int i) idLevel i PlayerPrefs.SetInt ("idLevel", idLevel) Play.interactable true public void LoadLevel(string Levels) SceneManager.LoadScene (Levels) public void Replay() SceneManager.LoadScene ("L" idLevel.ToString ()) public void loadNextLevel() |
0 | Unity 5 Cloth Constraints I'm trying out the new Version of Unity 3D (5.0.0.4f) and figure out whats new, whats possible now. My experience with Unity 4 free is also just a little. Anyway I work with the "new" cloth component and have some general questions to different funkctions. The documentation brought no knowledge to me. So I would be thankful if one of you could explain me the different points in an accessible way. First question touchs the constraints. When I edit the contraints (of a plane for example), there are two options to activate. What are the differents between "Max Distance" and "Surface penetration". "max Distance" is clear to me but i don't know what the second option does. Seceond question I have an tablecloth positioned over a sphere. In playmode when i move the sphere up and the tablecloth react correctly. But the sphere ist temporaliry visible trough the cloth. Its look like a graphicbug then, but ist there a way to prevent this? So I hope my questions a clear enough to understand. Thanks a lot for your educational effort. |
0 | Unity 3D Vive Focus conversion difficulties I Keep getting this error message below when I try to build and run the game. I have downloaded sdk package sdk tools windows 4333796.zip Android studio. I am new to this kinda technology any help will be appreciated. The VR device is Vive Focus. error Message below Extracting from com.htc.vr.samples.hellovr.unity manifest miniWaveSDKVersion is Null! NumDoFHmd is Null! NumDoFController is Null! NumController is Null! Please ensure that these metadata in your manifest matches the capabilities of your title. This metadata will affect how viveport store distributes and displays your title |
0 | Why is my custom Texture2D blurry? Have some WWW object downloading a .PNG image. ((SpriteRenderer)renderer).sprite Sprite.Create(request.texture, new Rect(0,0,100,100)) My sprite looks fine. Now, let's be a bit redundant and create a Texture2D out of the bytes from the download Texture2D t new Texture2D(100,100) t.LoadImage(request.bytes) ((SpriteRenderer)renderer).sprite Sprite.Create(t, new Rect(0,0,t.width,t.height)) Technically, this should produce something identical to the above snippet. However, the sprite is blurry (as in, low quality). I suppose it is when calling LoadImage. What may be causing this? |
0 | How to move object on local space not object space in unity I am watching this (game dev, space parenting amp rotation) Sebastian Lague video and found that there are three spaces actually (not two) and these are world space, local space and object space. World space The static space (0,0,0) Object space related to the object space Local Space related to the parent of the object I am amazed that i didn't find the distinction between these two spaces(local and object) on official unity forms but actually it exists. My question is that why there is no Space.Local? I found that there are Space. Self and Space.World. Space.Self is refer to object space. I can move my object to object space using this void Update () transform.Translate(new Vector3(0,0,1) Time.deltaTime 2,Space.Self) And i can move my object to world space using this void Update () transform.Translate(new Vector3(0,0,1) Time.deltaTime 2,Space.World) but there is no support for local space that i could move the object to local space (means move the object related to its parent object). There is a fair distinction between Local and Object space but unity didn't consider it i guess or i am wrong. |
0 | Going up and down stairs by Unity3d's NavMesh Purpose I want to create a navigation mesh that is optimized for going up and down stairs and stopping. Question I'm making a nav mesh to make a character go up and down stairs. I'm making a nav mesh that makes a character go up and down stairs, but when the character stops in the middle of a step, his foot floats or his foot gets stuck in the stairs. I'm having a hard time creating a good path for the nav mesh. I'm wondering if you have any knowledge on how to bake a nav mesh for ascending and descending stairs. Please let me know what you know about baking navmeshes for stair climbing and descending, and what pages or ideas I should refer to when implementing stair climbing. Please let me know what you know about baking a nav mesh for stair climbing. Preparation Create the stairs and the ground in Probuilder so that the nav mesh can be baked. Case 1 Bake the nav mesh of the stairs. Test result. When ascending and descending the stairs, my feet sink into the ground. Every time I ascend or descend a flight of stairs, the surrounding scenery wobbles up and down. Case 2 Make a board to accompany the stairs. Bake the nav mesh with the stairs hidden and the slope displayed. Test result. When ascending and descending the stairs, the feet do not sink in. But when I stop at the step, my foot floats away. The scenery does not wobble because you are running on a board. Case 3 I made a board to accompany the stairs. I want to make the nav mesh of the step part flat. I want to make the nav mesh of the step part flat, so I'll edit the step part with the Probuilder function. Instead of a straight slope, lower the knot to create a slope and bake it. Test result. There is not much change in the shape of the nav mesh from Case 2. The phenomenon that the foot lifts off the ground when stopping at the step was not improved. The scenery is not wobbly because you are running on a board. Navigation mesh we want to achieve Development environment Unity2019.4.9f1 Package used ProBuilder4.2.3 |
0 | How to achieve this kind of look of a cube in a most efficient way? It might be a trivial question, but I couldn't come up with a simple solution. I need to create a cube like on the image below in Unity. As always, I target mobile so it would be nice if it was made on a mobile diffuse shader. I was playing with lights a little bit, but in order to achieve this kind of look, I'd need to stack multiple lights because one shadow is not enough. Also, I tried adjusting the angles of the lighting with no luck. Do you have any tips, how could I make one in a most efficient way? |
0 | Help to Code Bowling Like Feature in Unity for Mobile I need Code or Guidelines for Touch Feature. When We Drag ball back and Send it Forward. I am Making feature like bowling, and I need Player to add force while dragging back and also curve the path of the Ball Anybody, Please Help |
0 | 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. |
0 | How to write properly shader with gradient based on vertex color? I took 4 squares with the outer corners painted in black, and the other ones in white. For some reason, they have a different gradient. fixed4 frag (v2f i) SV Target fixed4 mainTex tex2D( MainTex, i.uv) fixed4 overTex tex2D( OverTex, i.uv3) fixed4 final fixed4(lerp(mainTex.rgb, overTex.rgb, overTex.a) i.color, 1.0) final lerp(float4(0, 0, 0, 1.0), final, i.color.a) shadows return final How can i make the same gradients as bottom left and top right? In game this is faces of blocks (like minecraft) and gradients is smooth shadow light. So I cannot change tris |
0 | Unity shaders best way of handling data structures I'm working on a shader in Unity that uses a Binary Tree to store some precomputed values, this binary tree should be available to the shaders and would ideally also be constructed on the graphics card (each node in this tree is based on 1 pixel) is there a good way of doing this? |
0 | Camera Transition between 2 position rotation, and follow a 3rd target I have setup a transition of camera between 2 transform, here the result in video https youtu.be rcwQ6KuEfMw I have the information of the 2 transform position (vector3) rotation (Quaternion) And I do a Lerp, from Position1 to Position 2, and from Rotation1 to Rotation2 Vector3 finalPosition Vector3.Lerp(previousPosition, nextPosition, evaluateValueLerp) Quaternion finalRotation Quaternion.Slerp(previousRotation, nextRotation, evaluateValueLerp) Now the problem is, as you can see in the video the player target (the car) is lost durring the transition, I would like to keep it always in the view. How can I manage to do it ? Thanks you ! |
0 | shader tutorial for unity I would like to start developing my own shaders within unity. For starters I would like to do a screen spaced blur. Are there any good tutorials to learn shader development besides the official unity documentation, which i find a bit hard to understand? |
0 | AddForce not moving imported model in Unity I've got a Unity project with an imported .fbx model I'm attempting to add movement to. As a test, I've added a sphere primitive with a sphere collider, a rigid body, and the following script public class ball test MonoBehaviour private Rigidbody rb void Start () rb GetComponent lt Rigidbody gt () void FixedUpdate () Vector3 movement new Vector3 (1f, 0.0f, 1f) rb.AddForce (movement) This is partly copied from the Roll A Ball tutorial, and this works fine. The ball slowly rolls with no problem. I've imported a custom model, added a box collider, a rigid body, and assigned to it the same script. It doesn't move. Here's how they're set up |
0 | How to avoid game starting before start button is clicked? I've made a game with a Title Screen (Canvas), and a Start Button attached to the Title Screen. Points, GameOver, Restart, and even the Start Button sort of works, but it's possible to play the game before the user presses start. Is there a way to make the GameObjects only appear after the button is clicked? I've tried to move and change the "public void StartGame()", but I can't get it right. This is my first game ever, so hope the code provided is relevant. Enemy.cs void Start() enemyRb GetComponent lt Rigidbody gt () gameManager GameObject.Find("GameManager").GetComponent lt GameManager gt () player GameObject.Find("Player") GameManager.cs public void StartGame() powerup.transform.rotation) score 0 UpdateScore(0) isGameActive true titleScreen.gameObject.SetActive(false) void Update() enemyCount FindObjectsOfType lt Enemy gt ().Length if (enemyCount 0) roundNumber SpawnEnemyIntruders(roundNumber) Instantiate(powerup, GenerateSpawnPosition(), powerup.transform.rotation) void SpawnEnemyIntruders(int enemiesToSpawn) for (int i 0 i lt enemiesToSpawn i ) int enemyIndex Random.Range(0, enemies.Length) Instantiate(enemies enemyIndex , GenerateSpawnPosition(), enemies enemyIndex .gameObject.transform.rotation) public void GameOver() restartButton.gameObject.SetActive(true) gameOverText.gameObject.SetActive(true) isGameActive false PlayerController.cs void Start() playerRb GetComponent lt Rigidbody gt () playerAudio GetComponent lt AudioSource gt () StartButton.cs void Start() button GetComponent lt Button gt () gameManager GameObject.Find("GameManager").GetComponent lt GameManager gt () button.onClick.AddListener(StartThis) |
0 | Send a Push Notification from a device to another device (Unity, Firebase) I have setup Firebase authentication in my game for Android. I need to implement a feature in my Android game, where a user can challenge another player. I need to implement it this way The user is shown the list of all users registered on Firebase on the Game. To any user, he can tap on a button for respective user to send a challenge. When, he taps, a push notification is to be recieved by that user. When he taps on the notification, he is redirected to a specific part of the game. Maybe a specifc scene for now and he is shown there the Challenger's name. I have explored the Firebase documentation, but it does not provide information for client client push notifications. Maybe there are other options available like GameSparks and OneSignal. But I don't know if there is a requirement of own Server for implementing it. |
0 | Having player names over models in 3d space I wanted to have in my multiplayer game, the players name's over their models, however I am faced with the question of how? Should I create a new Canvas object for each game model or just use 1 main canvas and move their names around relative to position in 3D world space? My aim is to have an open world game. |
0 | Unity Animation Curve to change value over time I am trying to learn how to use AnimationCurve to change a float value over time. However i am not really sure how to do it Say i have the following class public class SpiritAway MonoBehaviour public List lt SkinnedMeshRenderer gt MeshList public List lt Material gt DissolveList public float percentage 0.0f public bool IsDissolveing public AnimationCurve Curve private void Start() percentage 0.0f for (int i 0 i lt MeshList.Count i ) for (int j 0 j lt MeshList i .materials.Length j ) if (MeshList i .materials j .shader.name "Dissolve") DissolveList.Add(MeshList i .materials j ) Update is called once per frame void Update() if (IsDissolveing) if (percentage lt 1) percentage 0.01f for (int i 0 i lt DissolveList.Count i ) DissolveList i .SetFloat(" alphaClipDissolve", percentage) Now i wish to incrase the percentage value with the percentage of the animation curve to get a more smooth and controlled transition of the value. Could anyone explain how this is possible? |
0 | Discarding triangles in Unity I have about 2 years of experience in computer gaming development and I just started writing my own shaders to help me utilize performance. I have this problem that I'm trying to work around but after several tries nothing seems to work. Basically, I have a plane that's made of 16641 vertices thats 32768 triangles and I know that is pretty much. The plain has a texture on it with some colors. Now, what I am trying to do is placing units on that plane. Where they stand, the vertex under them will have a certain color but all other vertexes on the plain will have the color white. The idea is to discard and don't draw vertexes that aren't white. Now in the shader, I tried two things. 1 In the vertex input I check if the vertex, called o, had the o.color.b value ! 0. If so it was given the alpha value of 0 and would not be seen when rendering. 2 In the vertex output, I checked the same thing ( if(i.color.b ! 0) discard ) and discarded the fragment so it would not be rendered. That way I thought Unity should not count these triangles and thus wouldn't waste performance. Now when I run my game and open the stats, with the plane active I have 85.8k triangles and only 28 draw calls. With the plane un active I have 20.2k triangles and 26 draw calls (Note there are some units, interface, skies etc around that counts up to 26 draw calls, thus the plane is just 2 draw calls). I thought this solution would be clever to save draw calls (developing for mobile games) by treating this plane and the colors under the units as one instead of making them all a separate gameobject. Turns out, I'm way over budget on the triangles. Does anyone know if this is possible and if so, give a good answer or explenation? Here is the following shader. Shader "Custom Ottar VertexBasic" Properties MainTex ("Particle Texture", 2D) "white" Transparency("Transparency", Range(0,1)) 1 SubShader Tags "Queue" "Transparent" Blend SrcAlpha OneMinusSrcAlpha AlphaTest Greater .01 ColorMask RGB Lighting Off ZWrite Off Fog Color (0,0,0,0) Pass CGPROGRAM pragma vertex vert pragma fragment frag pragma multi compile builtin pragma fragmentoption ARB precision hint fastest include "UnityCG.cginc" uniform float4 MainTex ST float Transparency VertexInput struct vI float4 vertex POSITION float4 texcoord TEXCOORD0 float4 color COLOR uniform sampler2D MainTex VertexOutput struct vO float4 pos SV POSITION float2 uv float4 color vO vert (vI v) vO o o.pos mul (UNITY MATRIX MVP, v.vertex) o.uv TRANSFORM TEX(v.texcoord, MainTex) float4 viewPos mul(UNITY MATRIX MV, v.vertex) o.color float4(v.color.rgb, v.color.a 1) if(o.color.b ! 0) o.color.a 0 else o.color.a 1 return o float4 frag (vO i) COLOR if(i.color.b ! 0) discard else half4 texcol tex2D( MainTex, i.uv ) return texcol i.color Transparency ENDCG Fallback "Particles Alpha Blended" |
0 | In Unity how can I know which direction is the screen auto rotated? From the Screen.orientation description I get If the value is set to ScreenOrientation.AutoRotation then the screen will select ... automatically as the device orientation changes. This seems to imply that if the screen does auto rotate, then Screen.orientation has been set to ScreenOrientation.AutoRotation. If that's so, how can I know in which direction it has been auto rotated? Disabling the auto rotation doesn't count (obviously), and I need to distinguish between LandscapeLeft and LandscapeRight, so checking height and width doesn't work either. This should be cross platform, without including any kind of non C plugin. (the answer, given this documentation, seems to be "you can't", but maybe I'm missing something) |
0 | Player going out of boundaries So, I been following up the Space shooter tutorial on Unity, I had an issue where the project was acting up with an alpha version, so I was able to get a version that worked on a old release and applied all the new things I developed But suddenly, my ship is acting up when getting closer to the boundary of its movement This is the player movement code public class playerMovement MonoBehaviour public float speed 0.0f public float tilt public Boundary boundary void FixedUpdate () float moveHorizontal Input.GetAxis("Horizontal") float moveVertical Input.GetAxis("Vertical") var movement new Vector3(moveHorizontal, 0.0f, moveVertical) var rigidBody GetComponent lt Rigidbody gt () rigidBody.velocity movement speed rigidBody.position new Vector3 ( Mathf.Clamp(rigidBody.position.x, boundary.xMin, boundary.xMax), 0.0f, Mathf.Clamp(rigidBody.position.z, boundary.zMin, boundary.zMax) ) rigidBody.rotation Quaternion.Euler(0.0f, 0.0f, rigidBody.velocity.x tilt) System.Serializable public class Boundary public float xMin, xMax, zMin, zMax And this is the player boundary properties It used to work previously moving forward to the alpha, now I'm working on 2019.2.0f1, but since working on the alpha this is the behaviour I'm having As you can see, getting closer to the player boundary, takes the player out of the play area, and I can't determine why this might be happening. I already tried removing the Math.Clamp, as I though there migth be bug with the function in this version, but even without it, the problem is present. |
0 | Frequent stuttering, high FPS spikes with VSync option turned on in Unity standalone build I'm experiencing an issue using Unity 4.3.2 and standalone builds. If I turn on VSync in the project's Quality settings, running the game at the native monitor resolution, I'll frequently get high framerate spikes (over 100FPS), and a strong stutter for a few frames, and then it drops back down to 60FPS and runs normally. If I run the game at a lower resolution (800x600 for example), the framerate stays at around 500FPS and the stuttering is consistent. However, if I turn off VSync in the Quality settings, and force it on in the Nvidia Control Panel, I don't experience any stuttering or framerate spikes, nor when I turn off VSync completely (but lots of screen tearing, which is very ugly and distracting). Can anyone explain this behavior? Is there anything that can be done to circumvent it? I'd imagine other Unity developers have used the built in Unity VSync with success before (or maybe not?!) so I'm hoping I'm just doing something wrong on my end. |
0 | Lightmapped prefabs for procedural content I'm doing a game with procedural content from handmade prefabs, but I ran into a problem as Unity bakes the scene instead of objects when lightmapping with Beast. So when the prefabs are instanced they are without lightmaps. Is there a way to get lightmaps for dynamically created prefabs with Unity's built in lightmapper? |
0 | How to draw texture with unlit effect on surface base texture I am writing a shader to my Unity game and I want to have effect this type of effect Base texture, for example, skin of character is a texture that will use shadows, lighting. Second texture, unlit, it will not be using shadows, it will be moving and changing alpha intensity. Second texture will be drawn after base texture. Only unlit or surface shader looks bad, I think I must connect those two shaders, to make nice looking effect. I wrote something this and I am stuck Shader "My SurfaceUnlitBlend" Properties MainTex("Base", 2D) "white" MainColor("Main Texture Color", Color) (1,1,1,1) SecTex("Second Texture", 2D) "white" SecColor("Second Texture Color", Color) (1,1,1,1) SecTexAnimHSpeed("Second Texture Animation Horizontal Speed", Float) 0 SecTexAnimVSpeed("Second Texture Animation Vertical Speed", Float) 0 BlendValueModifier("Blend Value Modifier", Range(0.5, 2.0)) 1 Glossiness("Smoothness", Range(0,1)) 0.5 Metallic("Metallic", Range(0,1)) 0.0 SubShader Tags "RenderType" "Opaque" LOD 200 CGPROGRAM pragma surface surf Standard fullforwardshadows pragma target 3.0 struct Input float2 uv MainTex float2 uv SecTex sampler2D MainTex sampler2D SecTex fixed4 MainColor fixed4 SecColor fixed SecTexAnimHSpeed fixed SecTexAnimVSpeed fixed BlendValueModifier half Glossiness half Metallic UNITY INSTANCING CBUFFER START(Props) UNITY INSTANCING CBUFFER END void surf(Input IN, inout SurfaceOutputStandard o) Albedo comes from a texture tinted by color fixed2 moveVector fixed2( SecTexAnimHSpeed, SecTexAnimVSpeed) moveVector Time 1 set blend modifier according to time float blendLevel (cos( Time 1 ) 1.5) BlendValueModifier set colors fixed4 col1 tex2D( MainTex, IN.uv MainTex) MainColor 2 fixed4 col2 tex2D( SecTex, (IN.uv SecTex moveVector) 15) SecColor blendLevel blend colors fixed4 result col1 col2 o.Albedo result ENDCG FallBack "Diffuse" Because I don't know what to do, to have unlit effect in second texture. |
0 | Unity how to change runtime code for different platforms? In Unity, how can I programmatically control what source code is compiled? I have a script with various BuildPipeline.BuildPlayer calls, allowing me to build all versions of my game. However, I'm using the AVPro Video asset to play video, and it doesn't support 32bit Mac. As such, I need to fall back other video playing code on 32bit Mac. There's no preprocessor directive to differentiate 32bit OSX (like you can do for other platforms https docs.unity3d.com Manual PlatformDependentCompilation.html ). However, since I'm building each version in sequence, it seems like I should be able to set some state so that during compilation, the right code is used. I tried this VersionHandler.onMac32 true BuildPipeline.BuildPlayer(levels, path, BuildTarget.StandaloneOSXIntel, BuildOptions.None) VersionHandler.onMac32 false And then checking that static variable in game. However, that static is "never set", presumably because the the state of the variable during compilation doesn't affect the value at runtime. Is there any other way I can "get at" the compiled code and set a flag for certain builds? As a fallback, I can manually swap code in every time I build for OSX 32 bit, but I'd prefer not to do that. |
0 | Why doesn't my orbit form an ellipse? I'm playing around and trying to build an orbit simulator. Unfortunately, it isn't working out to well. Instead of forming some sort of elliptical orbit, I get this Here is the code I'm using to generate the orbits public class OrbitBehaviour MonoBehaviour public Double Mass private List lt GameObject gt bodies new List lt GameObject gt () private float gravConstant 6.673f Mathf.Pow(10.0f, 11.0f) Units m3 kg 1 s 2 private int delay 0 private float distanceConversion 6.68458712f Mathf.Pow(10.0f, 12.0f) m gt AU (Astronomical Units) private float massConversion 1.67403241f Mathf.Pow(10.0f, 25.0f) kg gt E (Earth masses) private float timeConversion 1.1574074074074074074074074074074e 5f s gt D (Days) Use this for initialization void Start() bodies GameObject.FindGameObjectsWithTag("mass").ToList() gravConstant Mathf.Pow( distanceConversion, 3.0f) gravConstant massConversion gravConstant Mathf.Pow( timeConversion, 2.0f) gameObject.GetComponent lt Rigidbody gt ().AddForce(Vector3.left 10f) Mass Mass massConversion Time.timeScale 99.0f Update is called once per frame void FixedUpdate() StepSimulation() private void StepSimulation() Walk each body in the system foreach (GameObject body in bodies) if (gameObject body) continue skip self Vector3 tSeparationVector body.transform.position gameObject.transform.position tSeparationVector tSeparationVector.normalized OrbitBehaviour bodyBehaviour body.GetComponent lt OrbitBehaviour gt () Double tForceValue gravConstant (this.Mass bodyBehaviour.Mass tSeparationVector.sqrMagnitude) gameObject.GetComponent lt Rigidbody gt ().AddForce(tSeparationVector.normalized (float)tForceValue) Does anyone know what I am doing wrong here? |
0 | Unity Profiler What would cause PlayerEndOfFrame to have 10 16MB in GC Alloc? I can't find much documentation on what "PlayerEndOfFrame" does. Sure it is the end of a frame but what would cause the GC Alloc to go so high? This is the profiler results from a debug build on a remote machine using the IP connect to unity profiler. |
0 | Why does my AI Enemy slide towards its target when it is supposed to be idle? So using Unity standard assets to get a stage rolling, Ive built a simple terrain and used FPSController as the player and AI ThirdPersonController (Ethan) as the enamy. Ive built the navmesh and everything was working in its default state, but then I changed the AI script slightly as I wanted Ethan to follow me only if I come within a certain range, so I changed it to the following public float dangerRadius 5f private void Start() get the components on the object we need ( should not be null due to require component so no need to check ) agent GetComponentInChildren lt UnityEngine.AI.NavMeshAgent gt () character GetComponent lt ThirdPersonCharacter gt () agent.updateRotation false agent.updatePosition true private void Update() if (target ! null) agent.SetDestination(target.position) if (agent.remainingDistance lt dangerRadius) character.Move(agent.desiredVelocity, false, false) else character.Move(Vector3.zero, false, false) public void SetTarget(Transform target) this.target target But the problem is that when the remainingDistance is greater than dangerRadius or when I am out of range, Ethan just slides slowly towards the target in idle state and as the distance becomes lower than the threshold he starts running as expected. Ive tried adding friction materials to the terrain and the collider on Ethan but he still slides. Help thanks |
0 | Select a button without calling click i have a grid layout group containing buttons. My game must be playable with a joystick and so I have to navigate the buttons using horizontal vertical input. My problem right now is when the layout group first becomes visible. Once I click on a button (with my mouse), it becomes "selected" and I can navigate through the layout group with my keyboard and 'click' with spacebar. This functionality is all fine, except for the need to click the button with a mouse to set the first selection. I've tried both of the following void buttonClicked() Debug.Log("clicked") void Start () this button is actually instantiated from a prefab, not shown here Button btn inventorySlot.button btn.onClick.AddListener(buttonClicked) attempt 1 btn.Select() attempt 2 eventSystem.SetSelectedGameObject( btn.gameObject, new BaseEventData(eventSystem) ) both these commands do select the button, but they also inadvertently call the onClick, and the button is clearly being clicked because it changes color (I have configured this through button opts in the inspector). My question is how can I "select" the button without clicking it? I perhaps should also note, I am populating the layout group with buttons at runtime. Each button is intantiated from a prefab in Start() (not showing that here). I only add the event listeners and try to select the button after it's already added to actual game objects in my scene. |
0 | How can I make a trail renderer flat with the normal of the nearest face? I'm making a basic skid system for a car model using a trail renderer. I have everything setup and working properly except that the trail renderer always faces the camera. I want the trails to be perfectly flat with the ground. So I thought if unity can make the faces all rotate towards the camera, then would it be able to rotate towards the normals of the nearest faces? |
0 | Unity3d Transform rotation(angle) help Im trying to rotate an object 90 degrees to the left but instead of rotating straight left it rotates 270 degrees to the right. Here's the part of the code which controls the rotation rotationDestination new Vector3(60, 270, 0) if (Vector3.Distance(transform.eulerAngles, rotationDestination) gt 0.2f) transform.eulerAngles Vector3.Lerp(transform.rotation.eulerAngles, rotationDestination, rotationSpeed Time.deltaTime) If I try to make the Y axis 90 a.k.a (60, 90, 0) then it rotates constantly to the left. How do I make it rotate straight to the left (90 degrees) ? Thank you. |
0 | Which collider to use on "island" situation? I have a 2d top down unity game where the player is on an island. The shape of the island is random generated and he is not able to "escape" from the island. So which Collider should I use for realizing this? Is there some form of an "inverted" collider? Are colliders able to have a hole in them? Or should I create a polygon collider with a small gap (This could be quite difficult if the polygon bends the wrong way)? |
0 | How to set keys for emission on off for a prefab? I am making a prototype for a Mario game and am having difficulty completing a canned animation for a prefab. There is an item box asset that has 3 materials and an "ItemGet" animation. One of these materials has an active emission property that is supposed to turn off during a specific frame of the "ItemGet" animation. These boxes will have an "Active" and "Inactive" state. While "Active", the item box just bobs up and down and IF Mario hits the trigger, the "ItemGet" animation plays (and the player gets a unique item). The box then becomes "Inactive". While "Inactive", no animations play, the emission effect is gone and the trigger cannot be reactivated. Challenges finding the correct property to set a keyframe for in the Animations panel. Making sure Active versions of the prefab remain Active after any ItemBox becomes Inactive and that all materials don't change when GetItem plays. Ideas Instead of keying the emission on off property (assuming that exists and does what I think it does trouble finding it), swap the materials. ( . . . ), swap the mesh. Can somebody please help me find a viable way to finish this animation that fits this object's intended use case? |
0 | Character Controller and Reverse Gravity So I have a Game object with Rigid Body, a Character controller and my Movement script. On a specific condition I am reversing gravity. The problem is that the velocity.Y when the gravity is reversed, keeps increasing to the infinity. If I try to reset it like in the first if statement (which works for normal gravity) the object keeps bouncing from the ground. Gravity scale is either 1 or 1 in order to reverse gravity and movement. This is the code void Update() isGrounded Physics.CheckSphere(groundCheck.position, 0.4f, whatIsGround) Move() void Move() Reseting States for new cycle , unless the object is falling if (( isGrounded amp amp velocity.y lt 0)) velocity.y 2f isRunning false isJumping false isFalling false else if (velocity.y lt 0 amp amp ! isGrounded) isFalling true Moving on X axis float x Input.GetAxis(KeyInputMove) if (x ! 0) isRunning true moveDirection gravityScale transform.right x controller.Move(moveDirection moveSpeed Time.deltaTime) Perfoming jump if (Input.GetButtonDown(KeyInputJump) amp amp isGrounded) velocity.y (float) Math.Sqrt(1 2f globalGravity) isJumping true velocity.y gravityScale globalGravity Time.deltaTime controller.Move(velocity Time.deltaTime) Updating animation states animator.SetBool( quot Grounded quot , isGrounded) This is the idle state animator.SetBool( quot Running quot , isRunning) animator.SetBool( quot Jumping quot , isJumping) animator.SetBool( quot Falling quot , isFalling) private void OnTriggerExit(Collider other) Reverse Gravity and Model Rotation if (other.gameObject.tag quot Portal quot ) transform.Rotate(0,0,gravityScale 180) gravityScale 1 |
0 | Unity C Using Linecast with collider bounds I'm trying to to detect when two 3D objects overlap each other 'visually' without actually touching. For example, if I have two spheres in a scene that are 1 meter apart and I rotate my camera around the objects so that one sphere is blocked by the sphere in front of it, I want to detect when this occurs. After many searches in this forum, I patched together the solution below. However, it only partially works it only detects overlap when the center of the occluded object is reached (i.e., "bounds.center"). I read that there is a way to use the bounds in this scenario so that it samples multiple rays from around the object. This way, overlap is detected at the objects visual boundary and not just it's center. Unfortunately, my coding abilities are meager and I can't figure out how to do it. Any help would be greatly appreciated. using UnityEngine using System.Collections public class OverlapCheck MonoBehaviour public Transform myCamera private Color mouseOverColor Color.green private Color originalColor private Vector3 objectExtents Use this for initialization void Start () originalColor gameObject.GetComponent lt Renderer gt ().material.color objectExtents gameObject.GetComponent lt Collider gt ().bounds.center Update is called once per frame void Update () if (Physics.Linecast (objectExtents, myCamera.position)) gameObject.GetComponent lt Renderer gt ().material.color Color.yellow else gameObject.GetComponent lt Renderer gt ().material.color originalColor |
0 | How to use MaterialPropertyBlocks to randomly change the color of multiple materials on an object? I have a character prefab for a civilian with 5 materials. Each one should be a random color but I don't want a new material for every civilian in the game. I asked a question earlier and had a good answer. However I was pointed towards this question with MaterialPropertyBlocks. This is the code I currently have void Start () Color newShirtColor shirtColor Random.Range(0, shirtColor.Length) MaterialPropertyBlock props new MaterialPropertyBlock() props.AddColor(" Color", newShirtColor) GetComponent lt SkinnedMeshRenderer gt ().SetPropertyBlock(props) It works really well but the color is assigned to the whole mesh. How can I do this for each of the 5 materials on the object so that it only changed the color for the assigned parts of the mesh, with only one material for each section? |
0 | What to use instead of UNet? If you look at this Link you'll see UNet is deprecated and will be removed in the future. I'm developing a mobile multiplayer game, i've red official advise about it but they say "You can publish it with 2018.4 (LTS)" and I can't use 2018.4 version because in my project i use LWRP which is not in the 2018.X versions. I've found the alpha version of the new system right here My questions are 1 Should i use the alpha version of the new system? And can i publish my game with it? 2 Should i wait for the new system came out? (I can't wait for months) 3 Should i try to use other third party systems like Photon? Or is there any way to publish my game with nice multiplayer system? Note I can't pay for multiplayer matchmaking system. Because of that i want to make Hosting multiplayer game. |
0 | How to change pre splash image for iOS? When I launched my game on my iPad, the screen first displayed a faulty splash image with a black lower half momentarily, before displaying the normal splash image. No matter what I tried, I couldn't get rid of this faulty 'pre splash image'. I have tried the following Entered my Plus package serial number and updated my seat in Unity. Deleted and left all splash images blank in Unity. Checked all the LaunchScreen XXX.png images in Xcode. Checked the files referenced by Images.xcassets in Xcode. Changed all the above images to a completely black image. Still, the old faulty picture would appear. Cleared all the data and installation files on my iPad. Deleted General Launch Images Source. I wonder where Xcode kept the faulty image. I am using Unity 5.5.1 and Xcode 9.2. Could someone please help? |
0 | How do I override a SteamVR Controller's transforms in Unity? I'm trying to provide an illusion to the user by rotating the controller about an arbitrary axis in the LateUpdate() method. But this doesn't seem to be having any effect as the controller probably is constantly getting updated by its real world location. Is there any way to override its real world position and orientation with a transformation in script? |
0 | Unity How can I control a Shadergraph effect on multiple enemies with the same prefab? So I made a simple White Flash Dissolve effect with shader graph 2D, it's my 1st time using shaders. I'm controlling the effect using a float inside the shader, with Material.SetFloat("FLOAT NAME", 0 1f) And I'm wandering how can a control only a single instance of my Shader without affecting all my enemies. Example I have 20 enemies, all from the same prefab with the same material. I want to be able to make 1 enemy dissolve whenever I shoot at him. |
0 | Unity Debug UnityGfxDeviceWorker (34) EXC RESOURCE RESOURCE TYPE MEMORY Unity How does one debug this Xcode error on an iOS device? Debug UnityGfxDeviceWorker (34) EXC RESOURCE RESOURCE TYPE MEMORY |
0 | How to optimize Floor Meshes with different material in unity I have several meshes (floor tiles) that consist of unique materials as they have different textures. I see that it is taking too many batches and it has around 100m vertexes. Is there any way to improve it through programming? The long way, it should be ported to 3d modeling and combine. I also see the mesh combine but it requires the same material. Edit Around 17k Floor tiles (LoD 9) with details around 5 or 6 large tiles (Floor LoD 7) with fewer details that are placed beneath the LoD 9 tiles lod9 tiles are display based camera culling otherwise LoD7 floor shows all the time. Here are some of the screenshots Lod 7 Tile example (there total 16 tiles) |
0 | In Unity displaying long lists of information to screen? Tables? Hello folks I'm making a little game for fun in unity, Its a boxing management sim. I've got the code done to create boxers and give them many properties such as names, weights, stats, etc. I've made another screen , lets call it 'office screen' for now. In that I want to open a panel which will show all the boxers in the game (ideally I'd like to be able to make the player be able to filter these results by which company he's signed to etc but I think that might be out of my skill range so maybe i will just make a separate screen for Owned Boxers) But I cannot seem to find a way to display all these infos in a table with columns such as Name Age Company etc I have had a go just using the UI Text components and panels. But thing is, there will be approx 100 boxers or more and this number will always change also. Any ideas for this in Unity specifically? EDIT I am storing all the data just as variables (i think fields) in a class called Boxer which is assigned as a component of a new GameObject i instantiate at the time each boxer is created. So each boxer has its own gameobject. EDIT 2 D i've found this https docs.microsoft.com en us aspnet mvc overview older versions 1 models data displaying a table of database data cs would this be the sort of thing I can add to Unity (assuming I can follow along with the guide)? Thanks for any help |
0 | How do I hide an Input field? I have in my hierarchy tab a Canvas. Inside the canvas I have an Input Field that holds a placeholder and a text. I read the documentations and didn't find how to hide the Input field. I want that if a if statement is true, then it will show the input field. Else you won't see it. How can I implement it? EDIT I thought about an idea to test If I press the O key on the keyboard it disappears, and if I press again it appears and so on. This is what I tried bool shown true Use this for initialization void Start () Update is called once per frame void Update () GameObject inputField GameObject.Find("InputField") if (Input.GetKeyDown (KeyCode.O)) shown !shown inputField.SetActive (shown) I play the scene and when I press the O key I get NullReferenceException Object reference not set to an instance of an object If I double click on the console message it highlights me the if (Input.GetKeyDown (KeyCode.O)) line. Something not good does the SetActive(bool) method, I suppose. |
0 | Why can't I sample a texture in a vertex shader? I'm old in Game Development but very new in shader writing. I just want a shader that transform from 1 texture to another. So I did start learning shader writing and wrote my desired shader. But during writing one thing I cannot understand as I am very dumb in shader writing that if I assign fixed4 color with COLOR semantic in vertex method then compiler gives the following error. Shader error in 'Hamza TwoTextures' cannot map expression to vs 4 0 instruction set at line 39 (on glcore) Compiling Vertex program Platform defines UNITY ENABLE REFLECTION BUFFERS UNITY PBS USE BRDF1 UNITY SPECCUBE BOX PROJECTION UNITY SPECCUBE BLENDING SHADER API DESKTOP UNITY TEXTURE ALPHASPLIT ALLOWED Here is the not working shader code, Shader "Hamza TwoTextures" Properties NoScaleOffset Texture1 ("Texture 1",2D) "white" NoScaleOffset Texture2 ("Texture 2",2D) "white" Mixer ("Mixer", Range(0,1)) 0 SubShader Pass CGPROGRAM pragma vertex vert pragma fragment frag sampler2D Texture1 sampler2D Texture2 float Mixer struct appdata fixed4 vertex POSITION fixed2 tex TEXCOORD0 struct v2f fixed4 pos SV POSITION fixed2 tex TEXCOORD0 fixed4 col COLOR v2f vert(appdata i) v2f o o.pos mul(UNITY MATRIX MVP,i.vertex) o.tex i.tex Giving error on this line o.col (tex2D( Texture1,i.tex) Mixer) (tex2D( Texture2,i.tex) (1 Mixer)) return o fixed4 frag(v2f v) COLOR return v.col ENDCG And if I write same expression to throw it as return fixed4 value in fragment method then everything is working fine. Here is working shader code, Shader "Hamza TwoTextures" Properties NoScaleOffset Texture1 ("Texture 1",2D) "white" NoScaleOffset Texture2 ("Texture 2",2D) "white" Mixer ("Mixer", Range(0,1)) 0 SubShader Pass CGPROGRAM pragma vertex vert pragma fragment frag sampler2D Texture1 sampler2D Texture2 float Mixer struct appdata fixed4 vertex POSITION fixed2 tex TEXCOORD0 struct v2f fixed4 pos SV POSITION fixed2 tex TEXCOORD0 v2f vert(appdata i) v2f o o.pos mul(UNITY MATRIX MVP,i.vertex) o.tex i.tex return o fixed4 frag(v2f i) COLOR It is giving me no error return (tex2D( Texture1,i.tex) Mixer) (tex2D( Texture2,i.tex) (1 Mixer)) ENDCG Can anyone explain me that why it is happening? And what is the difference between them? As I mentioned that I did start learning only two days before. I'm sort of noob in this. |
0 | Unity3D) Is there a way not to draw line renderer if vertex pos is zero? I make a curved line with line renderer. and a sphere move along it. i want to draw a line only behind the sphere. so i do something like this. lr.positionCount 256 while (delta lt time) lr.SetPosition(i , curPos) yield return new WaitForFixedUpdate() and the problem is, because of i set the size of Positions 256, if time is short, there are zero vectors in position. so line renderer draw meaningless line. is there a way to set PositionCount dynamically like List? or any good way to not draw if positions are zero? |
0 | How to make Scriptable Objects derive from other Gameobejcts? I encountered a problem where I want to make a Scriptable Object that derives from another class, but C does not support multiple inheritance. Further, I do not think it would not make sense to make interfaces for this example. There is a lot of duplicate code within methods that only an abstract class could contain implementations of. Basically, I want an abstract class that models "anything that can take a turn." I call it a TurnTakeable. But I also want the TurnTakeable to be split into friend and foe derived types, as the two are slightly different. Yet they mostly have the same behavior. Is there a workaround, or do I have to make an interface? ( |
0 | Why is my A object resetting to (0, 0, 0), instead of following its path? I'm working on an RTS project, and I'd like to use the A Project by Aron Granberg to navigate around obstacles. The problem is that the correct path is displayed in the scene, the unit is still walking forwards, but the unit just jumps to (0, 0, 0). As is, this as a workaround to have some progress in my build script. Why is my A object resetting to (0, 0, 0), instead of following its path? I don't know where I made the mistake that leads to this behavior. Here is script responsible for the movement using UnityEngine using Pathfinding using RTS public class Unit WorldObject public float moveSpeed public Path path public float nextWaypointDistance 3 private int currentWaypoint 0 protected override void Update() Vector3 dir (path.vectorPath currentWaypoint transform.position).normalized MakeMove(dir) if (Vector3.Distance(transform.position, path.vectorPath currentWaypoint ) lt nextWaypointDistance) currentWaypoint return private void MakeMove(Vector3 dir) transform.position Vector3.MoveTowards(transform.position, dir, Time.deltaTime moveSpeed) |
0 | How can I attract repel the mouse cursor from particular UI controls? This question came from some of my students. I wanted to share it here so others can find amp improve on the solutions we've found so far. In particular, my answer below doesn't behave as well as I'd like in windowed editor mode UI buttons no longer respond to hovering the cursor. I welcome alternative answers that solve this more completely. We're making a visual novel game using the Fungus asset for Unity. We want to add a twist where some dialogue options are easier or harder to press, because they attract or repulse your mouse cursor. Unfortunately, we haven't been able to identify a cross platform way to manipulate the mouse's position, nor a way to create a "Fake" mouse cursor image that can still interact with Fungus's UI buttons. How can we pull this off? |
0 | Problem with Raycasting in a 2D Game I'm new to using unity and came across a problem when I was following a tutorial. The game is in two dimensional space, and when my player walks over a certain tile the detection never goes off. Here's the code that I have, function calculateWalk() yield WaitForSeconds(0.3) var hit RaycastHit if(Physics.Raycast (transform.position, Vector3.down, 100.0)) Never evaluates to being true var distanceToGround hit.distance Debug.Log("Hit") if(hit.collider.gameObject.tag "tallGrass") walkCounter Debug.Log("Tall Grass") END if END if END calculateWalk() I've made sure to attach the script to my player, as well as tag the tiles that I want with "tallGrass". I've followed what was done in the tutorial, but for some reason it's not working out for me, not sure if this is all the code needed to help solve this problem, if more information is needed let me know, I also set my player 1 unit above the tiles. |
0 | Inheritance accessing child class values I want to use the same variable for five different child classes. It is basically a boolean that is true when a player purchases an item(represented by a child class) and false when the player is yet to purchase that item. Then save the bool status. Can someone tell me how to do just that? Do I create five different bool variables each on their respective classes(the child classes), then access them individually when a player wants to buy the item? If I change the bool value of a parent class, it'll change it across all of it's child class. |
0 | How can I rotate an object with random speed with some delays? using System.Collections using System.Collections.Generic using UnityEngine public class Turn Move MonoBehaviour public int TurnX public int TurnY public int TurnZ public int MoveX public int MoveY public int MoveZ public bool World Use this for initialization void Start () Update is called once per frame void Update () if (World true) transform.Rotate(TurnX Time.deltaTime,TurnY Time.deltaTime,TurnZ Time.deltaTime, Space.World) transform.Translate(MoveX Time.deltaTime, MoveY Time.deltaTime, MoveZ Time.deltaTime, Space.World) else transform.Rotate(TurnX Time.deltaTime,Random.Range(3,300) Time.deltaTime,TurnZ Time.deltaTime, Space.Self) transform.Translate(MoveX Time.deltaTime, MoveY Time.deltaTime, MoveZ Time.deltaTime, Space.Self) This is the random part Random.Range(3,300) but sine it's changing the random numbers too quick the changes are almost not visible. I want somehow to make that if for example the next random will stay for example 5 seconds at this speed number then move to the next random number and again stay at this number 5 seconds and so on. Tried this using System.Collections using System.Collections.Generic using UnityEngine public class Turn Move MonoBehaviour public int TurnX public int TurnY public int TurnZ public int MoveX public int MoveY public int MoveZ public bool World private bool IsGameRunning false Use this for initialization void Start () IsGameRunning true StartCoroutine(SpeedWaitForSeconds()) Update is called once per frame void Update () IEnumerator SpeedWaitForSeconds() var delay new WaitForSeconds(3) define ONCE to avoid memory leak while (IsGameRunning) if (World true) transform.Rotate(TurnX Time.deltaTime, TurnY Time.deltaTime, TurnZ Time.deltaTime, Space.World) transform.Translate(MoveX Time.deltaTime, MoveY Time.deltaTime, MoveZ Time.deltaTime, Space.World) else transform.Rotate(TurnX Time.deltaTime, Random.Range(3, 300) Time.deltaTime, TurnZ Time.deltaTime, Space.Self) transform.Translate(MoveX Time.deltaTime, MoveY Time.deltaTime, MoveZ Time.deltaTime, Space.Self) yield return delay wait but that just rotate the object once each 3 seconds. and not rotating it all the time with speed changing every 3 seconds. but now it's not rotating for 3 seconds it rotating every 3 seconds. better to describe what I want is like intervals. The object should spin all the time nonstop like i Update but then each 3 seconds to change for a random speed. for example spin at speed 5 ....after 3 seconds spin at speed 77 ....after 3 second spin at speed 199 |
0 | Gradient Input in Game view I want to develop a little tool to help visualize fireworks before using them in a show in Unity where the user can set several parameters and gets a preview of the firework effect in a preview window. To allow the user to customize color over time like I can currently statically do in the visual effects graph, I wanted to add a Gradient input field to my UI. After fiddling around with manually trying to make things work, I stumbled upon the new UIElements UI Toolkit and following this Medium post was able to render a simple text UI in a Panel Renderer. However the Gradient Field I added won't show up (which is quite reasonable because in the UI Builder it said something about quot Editor only quot ). Just to make sure, the box on the left is what I mean I was strolling around in the Asset Store for a while but couldn't find anything like what I was looking for (just shaders and stuff to apply a gradient to UI elements amongst other things). Other searches led to tutorials on how to completely custom build a single color selection tool which both seemed like a larger effort and didn't allow creating a full gradient. The question is Is there some sort of library, package or tool I could use to add an input like that to my quot game quot ? Or am I taking a completely wrong approach with this? |
0 | pass by reference a transformation I create a C script in which I declare a transformation public Transform Origin When I put this script on an object of the hierarchy, in the Inspector a field Origin appears at the level of the script in which I have to drag and drop a transformation of a GameObject or a GameObject. How does the Origin transformation deal with the GameObject transformation to move in this field? Thank you for your help |
0 | Unity Autoscroll when selecting buttons out of viewport I have a ScrollView element, that contains many buttons. I want that when I select buttons (via arrow keys), the panel scrolls so that the selected button is contained within the viewport. How could I achieve this? UPDATE This is example of my structure (with 2 buttons only, but you get the gist...) |
0 | GameObjects deleted before scene loads I am trying to persist objects on scene loading, but the objects always get deleted when the scene does load. LevelManager.CS public void LoadLevel(string name) if (name "Main") SceneManager.LoadSceneAsync(name) GameManager.LoadState() else GameManager.SaveState() SceneManager.LoadScene(name) Debug.Log("the scene is " name) I placed the LoadScene method ontop in the hopes it would complete loading the scene before moving onto the next method call. In the next method call, I restore objects to their state. GameManager.CS public static void LoadState() ES3.Load lt Dictionary lt Vector2, Building gt gt ("Buildings") foreach(Vector2 v2 in buildingPositions.Keys) Building b buildingPositions v2 if(b.GetType() typeof(Farm)) newFarm Instantiate(farmPrefab) as Farm Debug.Log("Build " newFarm) newFarm.transform.position v2 Debug.Log(newFarm.transform.position) newFarm.level b.level newFarm.name b.name newFarm.levelText newFarm.GetComponentInChildren lt Text gt () CheckTheCall() What actually happens is when the scene is changed, the LoadState code is run at the same time, which then causes my object to be deleted after the scene has finished loading, because its created before the scene changes. The third last line "newFarm.name b.name" gives me an error that newFarm was destroyed. The last line "CheckTheCall()" calls newFarm (which I declare at the top of the script to ensure scope wasn't the issue) and that shows newFarm exists as a farm. THEN after all this, the scene changes, so my instantiated object is deleted. I'm so confused I tried with just SceneManager.LoadScene(name) but the result is still the same. It's like the entire function completes and then the scene loads. Any ideas on how to get around this one? I need the objects to spawn back into the main scene in the same state they were. |
0 | Hold button down by mouse? When I hold down a button by mouse for 5 seconds, print a message. How to do this ? I wrote this script but is not working. I don't know if there other methods. Public float clock Public Button out public void quit out mouse() clock Time.time if(Time.time clock gt 3.0f ) Debug.Log (" gone !! ") |
0 | Why when using editor script with handles with DrawSolidArc it's not drawing any arc over the object? This is the editor script is in the Assets Editor using UnityEngine using UnityEditor CustomEditor(typeof(DrawSolidArc)) public class DrawSolidArcEditor Editor public float arrowSize 1 void OnSceneGUI() DrawSolidArc t target as DrawSolidArc Handles.color Color.blue Handles.Label(t.transform.position Vector3.up 2, t.transform.position.ToString() quot nShieldArea quot t.shieldArea.ToString()) Handles.BeginGUI() GUILayout.BeginArea(new Rect(Screen.width 100, Screen.height 80, 90, 50)) if (GUILayout.Button( quot Reset Area quot )) t.shieldArea 5 GUILayout.EndArea() Handles.EndGUI() Handles.color new Color(1, 1, 1, 0.2f) Handles.DrawSolidArc(t.transform.position, t.transform.up, t.transform.right, 180, t.shieldArea) Handles.color Color.white t.shieldArea Handles.ScaleValueHandle(t.shieldArea, t.transform.position t.transform.forward t.shieldArea, t.transform.rotation, 1, Handles.ConeHandleCap, 1) And the mono script for example this script is attached to a simple 3d cube using UnityEngine ExecuteInEditMode public class DrawSolidArc MonoBehaviour public float shieldArea 5 but there is nothing around the cube. not also near it nothing. it should draw arch in the editor. Later I want to be able to use the mouse with a click down and drag to be able to change the arc size but for not it's not drawing any arc. I took the example from the unity official docs https docs.unity3d.com 540 Documentation ScriptReference Handles.DrawSolidArc.html I noticed now also for example that I don't see the gui button in the inspector of the object that the mono script is attached to if (GUILayout.Button( quot Reset Area quot )) not sure what's wrong with the editor script. This is working. I still wonder why the unity docs example didn't work but this is working and I don't need the editor script. The problem with this script is that I must to turn on the Gizmos in the editor and I don't want to make it turned on all the time. So it's working but not as I wanted. I want to draw the arc without the gizmos. using UnityEngine ExecuteInEditMode public class DrawSolidArc MonoBehaviour public Vector3 offset Vector3.one public float fieldOfViewAngle 20 public float viewDistance 4 public bool usePhysics2D false public void OnDrawGizmos() DrawLineOfSight(this.transform, offset, fieldOfViewAngle, viewDistance, usePhysics2D) public static void DrawLineOfSight(Transform transform, Vector3 positionOffset, float fieldOfViewAngle, float viewDistance, bool usePhysics2D) if UNITY EDITOR var oldColor UnityEditor.Handles.color var color Color.yellow color.a 0.1f UnityEditor.Handles.color color var halfFOV fieldOfViewAngle 0.5f var beginDirection Quaternion.AngleAxis( halfFOV, (usePhysics2D ? Vector3.forward Vector3.up)) (usePhysics2D ? transform.up transform.forward) UnityEditor.Handles.DrawSolidArc(transform.TransformPoint(positionOffset), (usePhysics2D ? transform.forward transform.up), beginDirection, fieldOfViewAngle, viewDistance) UnityEditor.Handles.color oldColor endif |
0 | How do I deal with scale of the universe when generating a simulated universe? I have a dataset of 100,000 actual stars. I wish to create a game where I can fly between the stars and fly up to them and click on them etc. How do I go about dealing with the problem of the scaling of the universe, even If I were to allow fast as light travel it would be too vast. Should I cluster my data and then implement a subtle sort of scaling to move around? Sorry for the broad question but I'm rather stuck at the moment. |
0 | In Unity C , how can I change weapon a few frames later? I have this Input code to change weapon if (d left) if (!p d left) states.inventoryManager.ChangeWeaponToNextWeapon(true) p d left true if (d right) if (!p d right) states.inventoryManager.ChangeWeaponToNextWeapon(false) p d right true And in the InventoryManager I have the weapon changed by this public void ChangeWeaponToNextWeapon(bool isLeft) if (isLeft) if (l index lt r l weapons.Count 1) l index else l index 0 EquipWeapon(r l weapons l index , true) else if (r index lt r r weapons.Count 1) r index else r index 0 EquipWeapon(r r weapons r index ) states.actionManager.UpdateActionsOneHanded() Then equip the weapon along with animation and other stuff public void EquipWeapon(RuntimeWeapon w, bool isLeft false) if (isLeft) if (leftHandWeapon ! null) leftHandWeapon.weaponModel.SetActive(false) leftHandWeapon w else if (rightHandWeapon ! null) rightHandWeapon.weaponModel.SetActive(false) rightHandWeapon w string targetIdle w.instance.oh idle targetIdle (isLeft) ? " l" " r" states.anim.SetBool(StaticStrings.mirror, isLeft) states.anim.Play(StaticStrings.changeWeapon) states.anim.Play(targetIdle) UI.Slot uiSlot UI.Slot.singleton uiSlot.UpdateSlot( (isLeft) ? UI.QSlotType.lh UI.QSlotType.rh, w.instance.icon) w.weaponModel.SetActive(true) But the problem is the weapon changes immediately after pressing the button. How can I switch my weapon a few frames later while playing the animation? |
0 | How to generate objects at specific intervals and make them move with same speed? I'm creating an infinite runner where character has to jump on randomly generated pillars. The pillars are positioned with a gap between each of them. The gaps are dmin and dmax. In addition to this, i want the pillars to move to the left of screen with increasing velocity. But they all need to move with same velocity so that the gap in between them is maintained. I have the script as follows pillar is a prefab.go is an empty gameobject which will later be used to Instantiate pillars. first is the first pillar, manually positioned in the scene. using UnityEngine using System.Collections public class GM MonoBehaviour float tempx,dmin 1.3f,dmax 3.5f GameObject bins Vector2 speed,pos,tempvel public GameObject pillar,go public Transform first Use this for initialization void Start () speed new Vector2 ( 0.005f,0) tempx first.transform.position.x tempvel new Vector2 (0, 0) void Update () if ((Vector3.Distance (go.transform.position,transform.position) lt 40f)) tempx Random.Range(dmin,dmax) pos new Vector2(tempx, 2.22f) go Instantiate(pillar,pos,Quaternion.identity) as GameObject bins GameObject.FindGameObjectsWithTag("trash") tempvel new Vector2 ( 0.0005f, 0) foreach (GameObject bin in bins) bin.GetComponent lt Rigidbody2D gt ().velocity new Vector2(Random.Range( 0.005f, 0.05f),0) bin.GetComponent lt Rigidbody2D gt ().velocity tempvel Problem is, the speed of pillars increases way too fast. They move to the left at nearly invisible speeds. Also, after a certain speed, the gap between the pillars increases. They become so far apart, one is in camera view, another is somewhere far away. Is there a way to accomplish this? |
0 | Spawning random items to drop from the top of the screen I'm wondering how to make specific random objects drop. In my case, from the top of the screen. I have 16 objects, named recycle items 0 through recycle items 15. IEnumerator CreateRoutine() while (true) yield return new WaitForSeconds(3) CreateItems0() private void CreateItems0() Vector3 pos Camera.main.ViewportToWorldPoint(new Vector3(UnityEngine.Random.Range(0.0f,1.0f),1.1f,0)) pos.z 0.0f Instantiate(recycle items 0, pos, Quaternion.identity) |
0 | Unity uNet Low Level API which values should I snyc? I am using unitys unet low level api TransportLayer. I send my own message by converting strings to byte arrays. I want a server authoritive setting, so that I can try to implement my own client side prediction. I am also using unitys physics2d, rigidbodies and so on. I thought about to move the rigidbodies with it's velocity. I wonder which values I should send from client to server and backwards, to avoid the rigidbody jittering. I know that I cannot simply send the clients position to the server, because that will cause the jittering "effect". Would be nice, if anyone can give me guidance. Thanks ) |
0 | Unity 2D Cinemachine weird behavior for non rectangular confiner I have been trying to emulate a sort of Megaman X4 way of following the player around platforming levels, where the camera is confined to certain boundaries of such levels. However, all the tutorials and guides out there only show rectangular or square shaped confiners for the virtual cameras, and not odd shapes like an L shaped confiner, when using a weirdly shaped confiner the camera just tends to snap from one position to another and the game ends up feeling bad when that happens. I have tried solving this problem by using dolly tracks, which work nicely... But I end up having tons of virtual cameras to change to on sections that are weirdly shaped since the camera ends up also suddenly snapping on to weird positions on sharp turns and it also tends to get way off track, even when the settings of the virtual camera are configured to have very little damping and if there's no damping the camera just stutters all the time. Is there a way to have this kind of behavior to confine a virtual camera to oddly shaped level boundaries? |
0 | My unity game fails to open in my mobile I'm new to Unity, and want to make a android game. I made a very simple scene A sphere A cube (floor) A simple script that moves the sphere by touch. I tried it with unity remote and it works fine. But the problem manifests when I build it to test it. When I run it on my mobile, it opens and suddenly gets closed. I don't know what is the actual problem. what should i do? |
0 | How to zoom image on Unity UI to particular point where mouse cursor is located? I have some RectTransform on Unity UI. I have already implemented some Zoom functionality but now I need it to zoom to the area where the mouse cursor is located. Currently, it zooms to the anchor point. How can I zoom to the mouse cursor? Here are some screenshots from a hierarchy. I have already implemented zoom itself. public class ZoomableRect MonoBehaviour SerializeField private RectTransform rectToZoom SerializeField private ZoomConfigs zoomConfigs private bool onObj false SerializeField private ScrollRect scrollRect public ScrollRect ScrollRect get return scrollRect set scrollRect value private bool isZoomAllowed public bool IsZoomAllowed get return isZoomAllowed set isZoomAllowed value private bool isFullScreen public bool IsFullScreen get return isFullScreen set isFullScreen value void Start() if (!rectToZoom) rectToZoom GetComponent lt RectTransform gt () void Update() float scrollWheel Input.GetAxis("Mouse ScrollWheel") if (isZoomAllowed amp amp scrollWheel ! 0) ChangeZoom(scrollWheel) SetPosition(Input.mousePosition) private void ChangeZoom(float scrollWheel) float rate 1 zoomConfigs.zoomRate Time.unscaledDeltaTime if (scrollWheel gt 0) SetZoom(Mathf.Clamp(transform.localScale.y rate, zoomConfigs.minSize, zoomConfigs.maxSize)) else SetZoom(Mathf.Clamp(transform.localScale.y rate, zoomConfigs.minSize, zoomConfigs.maxSize)) private void SetZoom(float targetSize) transform.localScale new Vector3(targetSize, targetSize, 1) public void SetPosition(Vector2 mouseInput) float rectWidth rectToZoom.rect.width float rectHeight rectToZoom.rect.height float mousePosX mouseInput.x float mousePosY mouseInput.y float widthPivot mousePosX rectWidth float heightPivot mousePosY rectHeight Debug.Log("widthPivot " widthPivot " heightPivot " heightPivot) rectToZoom.anchorMin new Vector2(widthPivot, heightPivot) rectToZoom.anchorMax new Vector2(widthPivot, heightPivot) rectToZoom.transform.position new Vector2(mousePosX, mousePosY) Debug.Log("MousePosX " mousePosX " MousePosY " mousePosY) public void SetAnchors(bool isFullScreen) if (!isFullScreen) rectToZoom.anchorMin new Vector2(1, 1) rectToZoom.anchorMax new Vector2(1, 1) But anchors always snap to the bottom left corner. And widthPivot and heigtPivot values are always bigger than 1. Actually, after testing, I see that anchors are less than 1 when the cursor is located in the bottom left part of the screen. And bigger than 1 when the cursor is in the top right part of the screen. When zooming it always snaps to the bottom left corner. It seems that mouse position connected to the current resolution at the same time canvas on which zoomableRect is potisioned has reference resolution of 1920 x 1080. Changing a pivot in the same way instead of anchors doesn't have any effect. Same result. |
0 | Dual touch controls turning on one axis I wanted a swift look around functionality to be put in the middle of a room and just look around. So obviously I imported the standard assets and put the FPS controller in the middle and then dragged in the Dual touch controls and build it to android. The problem is that it only rotates horizontally and not vertically. I tried playing around with the values a bit but nothing seems to be working. |
0 | How to adjust the width of a LineRenderer I wrote a code that draws a line by mouse movement. I am searching for some way to give it pencil style and head and end of the line have thinner width. As we know the LineRenderer draws the line between points. How can I access first and last point elements to set the width of them and how can I do that? |
0 | Game build crashes on scene load I built out my project to Android to do some testing and stuff, but I can't get any further than the main menu scene. I built it out previously and it was running fine. Now as I try loading level0 it crashes with no error messages from adb logcat. Just exits the game and that's it. It works fine in the editor. I tried several things. I changed the color space back and forth, I built my addressables, tried development built and non development one, and the Split application binary checkbox is false as well... Unity 2019.2 My adb catlog output |
0 | How to add user created data to drop down menu options So I'm trying to make it that I can have a dropdown that will have user created info appear in it. List lt engines gt engineList new List lt engines gt () public Dropdown engineSelect public class engines public string engineName public int featureNumber public int totalDevPoints public string optimizedGenre public engines(string name, int feature, int totalPoints, string opt) engineName name featureNumber feature totalDevPoints totalPoints optimizedGenre opt engines playerEngine new engines(engineName, numFeature, 0, whatGenre) Pretend player set engineName, numFeature, and whatGenre with text fields. I wanted to have it that the drop down would add in whatever new engines the player makes. How would I do that? I want to have it say select engine and then the player would pick from dropdown from engines they made(only saying engine names). |
0 | How can I make alternate fragments drop (or make them black) based on a checkerboard texture? How can I make alternate fragments drop(or make them black) based on a checkerboard texture in a Unity fragment shader? I am using forward path rendering in my shader passes for lighting and shadows for every object in the scene. Now,I need a shader (or something) that drops alternate pixels from the overall screen space after everything is rendered. How can I achieve this effect? |
0 | Setting up sequential animation clips in Unity I'm trying to play two animation clips sequentially using Unity 2D. I've been using Mecanim for this so I've imported the two clips in a newly created controller and connected the first one to the next one. I also want the last clip to be looping so I set that toggle in the settings of the clip. Now for some reason the first clip is played just fine but the second one doesn't animate at runtime. It loops fine in the Animator window and the clip itself works in the preview window but not at runtime. I've also tried setting it up using the Animation Component and use the PlayQueued method but this doesn't give any animation. I'm kind of lost on what to try next EDIT This is to be used on a Canvas UI Image |
0 | Make gameObject stick to another gameObject after it has collided with it? Currently, I am using the following code to make objects stick to other gameObjects. rb GetComponent lt Rigidbody gt () rb.isKinematic true gameObject.transform.SetParent (col.gameObject.transform) It works perfectly, but it causes many other problems... For example, after colliding, it can no longer detect collisions... Is there an alternative to this code (which makes a gameObject stick to another one after collision)? |
0 | Why does my Unity Android game get a small amount of lag when not being touched for some time? I have made a 3d version of space invaders. I made all the assets myself in Blender. I feel that it's a very basic game and my Galaxy Note 3 test device should handle it no problem. (Although it's a few years old now so perhaps some kind of shader issue or something that my phone not updated enough for ?) There are 55 enemies all with one mesh each. There's the flying saucer model and the player model. Then there's a plane for a background, and 4 defensive meshes (although I've tested without these and the result is the same). Basically, it all runs superbly (I have turned down much of the lighting and graphics quality etc, but have left basic shadows in). However I notice that if the player just lets the phone sit there in game without touching it, there is very slight (but noticeable) frame lag. All the enemies have a very short animation which moves its arms a small amount. I could post the code but its massively unorganized and really quite an embarrassment (HAHA!). Also I'm not sure what parts are relevant so it would be a huge post. Is there any known issues that can cause the lag only when not being touched? As I feel like some of my old projects might have had this happening too but they've been deleted now unfortunately so I can't really dabble with it. It works smooth as silk in the Unity Editor Android 'emulator' and as I say, if I actually play the game on my phone it's smooth too. |
0 | Why is there a discrepancy between these two transform.up vectors? I was trying to implement a feature which required transform.up, the result didn't match the green axis gizmo displayed in the editor so I assumed it was being put off by the rotation of the object despite expecting the gizmo to adapt to that. I then modified the prefab such that everything was now child to an empty object and the secondary objects were child to that instead of the rotating model, and wrote a script that simply copies the transform so that it tracks. This still didn't show the values expected from what the gizmo in the editor showed. I then did a Debug.LogError in the track script and this time the result was as expected. Why is transform.up showing the value expected from the local y axis gizmo but when passing a reference to the original script and checking tracked.transform.up gives off results? To reproduce in a simpler environment I set up a simple test scene. Simple default cube with the hierarchy structure shown in the screenshot. The transform values are as follows parent zeroed x 0, y 90, z 0 for cube x 0, y 90, z 90 for TrackPoint Scripts are as follows test.cs attached to trackpoint private void Update() Debug.LogError(transform.up) Track.cs attached to tracker public Transform transformToTrack private void Update() transform.position transformToTrack.position transform.rotation transformToTrack.rotation Debug.LogError(transform.up) byref.cs attached to cube public GameObject refObj private void Update() Debug.LogError(refObj.transform.up) When run, if you clear the console then click pause you'll see that one of them differs from the others. I don't understand why. My project and this sample scene differ in which it is that is giving unexpected results but the results are inconsistent with what I would expect. But wouldn't they all give the same result? |
0 | World space coords for 2d images How can I make an 2d image using World space coords with a shape? Like a circle instead of a quad.In 3d you can modify the vertices but if I want a smooth circle there will be too much vertices. What I want to achieve is something like a cirle mask that will be move over the global texture at runtime. So has anyone done something similar? I've tried combining some shaders with two uv's one for world space and one for alpha uv mesh but it gives some weird artifacts. This is the how the shader looks on the right Shader "Unlit WorldspaceTiling" Properties MainTex ("Texture", 2D) "white" SubShader Tags "Queue" "Transparent" "IgnoreProjector" "True" "RenderType" "Transparent" LOD 100 ZWrite Off Blend SrcAlpha OneMinusSrcAlpha Cull Off Lighting Off ZWrite Off Fog Mode Off Pass CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" struct appdata float4 vertex POSITION float2 uv TEXCOORD0 struct v2f float2 uv TEXCOORD0 float4 vertex SV POSITION sampler2D MainTex float4 MainTex ST v2f vert (appdata v) v2f o o.vertex mul(UNITY MATRIX MVP, v.vertex) Gets the xy position of the vertex in worldspace. float2 worldXY mul( Object2World, v.vertex).xy Use the worldspace coords instead of the mesh's UVs. o.uv TRANSFORM TEX(worldXY, MainTex) return o fixed4 frag (v2f i) SV Target fixed4 col tex2D( MainTex, i.uv) return col ENDCG |
0 | How to share microgame with WebGL Publisher? (Unity) I did unity lego microgame tutorials and now I want to publish it with WebGL publisher. I created build files but I can't publish. I get this error I rebuild again to solve this problem. (3 more times..) And clicked quot locate existing building quot again but I still get this error. What should I do? |
0 | How to efficiently keep the player from moving outside the gameobject he is colliding with? I am developing a game with Unity 2017. The game mechanics are as follow Classic top down RPG Movements are UP, DOWN, LEFT and RIGHT Player evolves in a 16 16 map He can dig in the direction he wants to make his way through the map one tile at a time At first I was using a very classical approach using tilemaps, RigidBody2D and BoxCollider2D on tiles and the player GameObjects. Collision detections went fine and my tilemap looked pretty much like that (red being the walls and white the empty spaces) The problem with this approach is that I have to keep in memory the state of 256 tiles in a List lt Vector2f gt and to create the 256 expected GameObjects representing either my walls (which a totally black), or my floor (the empty space). Creating a black GameObject with its own BoxCollider2D for each of the tile seems a little bit overkill. And this brings me to the second iteration of my game to keep in memory only the tiles the player digged. What I would like to achieve efficiently, is to let the player evolve as long as he is colliding with an underlying tile, but stop moving as soon as he doesn't. This is ok This isn't, and player should be placed to previous state. I could take advantage of OnTriggerEnter2d and handle custom collision and response, but I have the feeling that something more simple and more optimized may exists somehwhere in the wild! Thanks to any help provided! |
0 | Using CNN's in Unity via Tensorflow and TensorFlowSharp I have a project that tracks hands made in python, shown here https github.com timctho convolutional pose machines tensorflow I want to effectively import this into Unity. I have generates the .bytes file from the model, but have no idea how to do anything further than this. If anyone has worked with ML Agents or TensorflowSharp in Unity and or would be willing to have a look, this would be great. The image processing stuff would be done probably in a C file beforehand, I just want to know how to run the network. Thanks. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.