_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 |
Massive CPU Usage by WaitForTargetFPS in the Profiler So I was checking the Standard Assets Example Projects of Unity, and they all have high FPS numbers in the Profiler. I started a little project myself, just a simple sprite with movement via rigidbody and a plane as a floor, and suddenly this I searched for what exactly does WaitForTargetFPS represents, but apparently there is not a general consensus about what can cause such high CPU usage. So why exactly such a little and simple project have this performance (in contrast with the more complex Unity Example Projects)?
|
0 |
How to load unload chunks data where view port is currently focused on? I have a 2D tile based engine with infinite procedural chunk generation. But I can't invent an algorithm, that will fill only chunk tiles on view port (and destroy old). Pls help ViewPort size can changing on the fly (2 100) I can't load all chunks completely, because I need to analyze the tiles in the visibility zone class Map public List lt Chunk gt get set public int viewPortWidth 2 ... 100 public int viewPortHeight viewPortWidth public Vector2Int playerPosition get set class Chunk Tile Tiles get set public int chunkWidth 16 public int chunkHeight chunkWidth public Chunk(int leftX, int bottomY) for (int y 0 y lt chunkHeight y ) for (int x 0 x lt chunkWidth x ) randomNumberGenerator.InitState(x leftX, y bottomY) chunk x, y randomNumberGenerator.Range(100) Tiles.Add chunk x, y
|
0 |
Exporting unity features to your game I wonder if it is possible to export Unity features to my game. For example if I want user to be able to modify scale or rotation of object, do I have to scritp it myself or can i somehow export it ? Same question about some simple texturing, adding lights, etc.
|
0 |
Unity Collider2D Know the collider type ob the object collider with the other object I have my GameObject which represents a soldier in my game. It has the following colliders 1st BoxCollider2D in child named "sword". Is Trigger checked. Tag Sword. This collider is enable when player attacks and disabled otherwise. 2nd BoxCollider2D in parent GameObject. Is Trigger unchecked, since it's the body. Always enabled. When the sword (1st) collider collides with the the body (2nd) collider, damage happens. Until now everything works fine. Here is the OnTriggerEnter2D function I have void OnTriggerEnter2D(Collider2D collision) if (collision is BoxCollider2D) Debug.Log( " this.name collided with collision.name ") if (collision null collision.tag Constants.TAG WEAPONS collision.tag Constants.TAG SIGHT) return if (collision.GetComponent lt LivingObjects gt ().AreEnemies(this)) Debug.Log( " this.name attacked with collision.name ") Attack(collision.GetComponent lt LivingObjects gt ()) else return Now I want my unit to search for enemies within a said range. I added a new collider 3rd CircleCollider2D in child named "sight". Is Trigger checked. Tag Sight. Always enabled. Now, when the sight (3rd) collider collides with the body collider, damage is trigger into the unit colliding with the sight collider. That is because I block damage one way around with the condition if (collision is BoxCollider2D) but not the other collision happening at the same moment. If i can discrimate collision from CircleCollider2D into BoxCollider2D, I can remove the attack function. However, I cannot see how to do it. My question is how do I know what Collider2D type is my object colliding with the other ? I'm open to other suggestion if this is impossible.
|
0 |
Why is it that I m still able to call a coroutine from another script, even though I marked it as private? I have this private coroutine in my WinDialogue script private IEnumerator ActivateStars(int count) for (int i 0 i lt count i ) stars i .SetActive(true) yield return new WaitForSeconds(.3f) And somehow I m still able to call it from my UIManager script winDialogue.GetComponent lt WinDialogue gt ().StartCoroutine("ActivateStars", starCount) How can that be if I marked it as private?
|
0 |
How to check if gun may shoot again (because animation has stopped playing)? When the user presses the fire button, I set a trigger animator.SetTrigger( quot HG Shoot quot ) This trigger causes a quot pistol shoot quot animation to be played. The gun should only be able to shoot again as soon as the shoot animation has finished. I could check at each Update() if that certain animation is still being played like this bool isAnimationStatePlaying(Animator anim, int animLayer, string stateName) if (anim.GetCurrentAnimatorStateInfo(animLayer).IsName(stateName) amp amp anim.GetCurrentAnimatorStateInfo(animLayer).normalizedTime lt 1.0f) return true else return false But I don't like the frequent checks. I would rather like to have a variable to would be set by the animator. Or I would set it at the beginning of the shoot animation. Because there are other animations that I have to check that would disallow shooting of the gun, too, like reloading the gun. This would make everything even more complicated. How can I solve this problem?
|
0 |
Variable Variables in unity using JavaScript? I'm working on a custom built save system for a project a friend an myself are working on. Currently all variables that are saved to file, are stored as static variables in a global variables script file. The current save system involves running through each variable individually and saving it a line on a document, completely hard coded and very annoying to expand upon with new variables and elements in the game. I've decided to look into serialization of the global variables file, however static variables are not serializable. My solution is to use a getter and setter function, that is called instead of the direct GV.whatevervariable, that we currently use. Ive been looking for something that allows me to store a variables name inside of another variable and then call it. for example, say the variable in the GV script is A , the function would look like static function getter(vget) return GV 'vget' var A string "testcode" where the call code would look like var stuff string GV.Getter("A") the problem with this though is that I keep getting "system.type does not support slicing" I currently cannot think of any other way to do this, and would really prefer not to hard code a getter and setter for each variable.
|
0 |
Shader and Texture Scrolling depending on Direction I am trying to scroll a texture using its uv in Unity but I don't get the result I need. The aim is to have two components, the speed and the direction. I would like to define the direction in normalized values and the speed should influence the velocity of the scrolling according to the direction. If I change the speed at runtime, I don't want to have some hiccups but maybe this should not be handled but the GPU. How can I do that in a better way, maybe using matrix ? Here is an example but the result is not as good as expected. uv.xy uv.xy frac( Time.y float2( Direction.x, Direction.y))
|
0 |
How to animate alpha channel of sprite color using Animator in code in Unity3D? I tried Animator AnimationClipPlayable, but failed. Sprite disappears completely after 1 second, without animation happening. If I set "1" instead of "0" for final point, then nothing happens. Code AnimationClip clip new AnimationClip() AnimationClipPlayable playable AnimationClipPlayable.Create(clip) gameObject.AddComponent lt Animator gt () AnimationCurve alpha AnimationCurve.Linear(0, 255, 1, 0) clip.SetCurve("", typeof(SpriteRenderer), "m Color.a", alpha) gameObject.GetComponent lt Animator gt ().Play(playable)
|
0 |
In Cricket games, how is the ball synced with batsman's shot animation? How does the ball hit right at the center of the bat? How does this work? I've been trying to figure this out for quite some time now. In Cricket games, when the bowler bowls, and batsman takes a shot, how does the ball sync with batsman's shot animation? For example, let's say the batsman hits a straight drive, how does the ball hit the bat perfectly? Can anyone help me out with this? I'm also curious about how in football games, the player animations sync with the football. How does the player's foot correctly hit the ball? Thanks in advance.
|
0 |
Smooth Lighting Falloff So, I'm having some issues with lighting in my Unity game. I had implemented torches, which seem to be working fine, but I have a creature (gelatinous cube) that I've put spot lights facing to give it a "glow". The reflected and refracted light ends up having two issues the light abruptly ends at the edge of floor tiles, and depending on the position, the light sometimes goes from it's blue color to a reddish color. I have a short (11 second) video here http www.labyrintheer.com wp content uploads 2016 11 Nov 17 2016 21 07 57.mp4 so that you can see what I'm talking about. I've tried changing global lighting settings and playing with the settings on the spot lights, but nothing seems to resolve the issue. Still images for anyone hesitant to click the video link Hard falloff Reddish color Using a single point light inside the cube, instead You can see it on the wall in the upper right and the floor at the top a bit. The upload seems to have lowered the quality a bit, but you can still see it. The single light makes it a little bit better, but there's still complete falloff.
|
0 |
How to determine the amount of idel time left in main thread for Unity before next frame? Hi I'm trying to improve a thread tool and would like to make a function which use the idle time before the next frame. So how can I determine the time left?
|
0 |
Prevent Unity click go trough Canvas I'm currently facing this problem If I click on a Button on my Canvas, the currently selected Unit moves towards the location under the Button. Is is there any option to solve this? I'm using the A Project for this. Sadly, I can not provide a lot of things I've done so far as I absolutely have no clue how to solve this problem. If I disable the Button Option "Raycast Target" ist still moves to this position but holds a bit earlier. Also, adding this as check didn't work if (!EventSystem.current.IsPointerOverGameObject() ) I also checked if the Raycast hit's the layer of the GUI My Movement code so far public override void MouseClick(GameObject hitObject, Vector3 hitPoint, Player controller) base.MouseClick(hitObject, hitPoint, controller) if (hasAuthority amp amp player amp amp player.human amp amp currentlySelected) if (hitObject.name "Ground" amp amp hitObject.name ! "UI" amp amp hitPoint ! ResourceManager.InvalidPosition) float x hitPoint.x float y hitPoint.y player.SelectedObject.transform.position.y float z hitPoint.z destination new Vector3(x, y, z) Debug.Log("Start Move") StartMove(destination)
|
0 |
Unity, Which side of Collider2D was hit by raycast? I've got a player firing out 2d raycasts. If one of them hits a boxcollider2d I would like to know if it hit the top side, bottom side, left side, or right side. How would I go about doing this? I've tried using Bounds but that didn't work out very well.
|
0 |
Player movement vs world movement in infinite runner game? Well I'm developing a Temple Run or Subway Surfer style infinite runner game. Which is more good? Moving the player and make the Main Camera follow, or keep the player in one position and move the generated worlds? And the generated paths or worlds will have many animations in it. So which choice ouuld be good and why?
|
0 |
Two Points Rotating Around Circle? Currently I am working on a 2D game just like duet game, it is my first game (Unity 2D). When I press left key both points rotate fine. But when I press right, the points are not rotated. So my problem is why do both points rotated only in one direction Code public class TouchControll MonoBehaviour float movespeed 3 float angle 45 void Update() if (Input.GetKey(KeyCode.LeftArrow)) when i m press leftarrow both point should be rotate fine transform.Rotate(Vector3.forward Time.deltaTime Input.GetAxis("Horizontal") angle movespeed) Debug.Log("moveleft") if (Input.GetKey(KeyCode.RightArrow)) problem is here when i m press right arrow key both point are not rotated transform.Rotate(Vector3.forward Time.deltaTime Input.GetAxis("Vertical") angle movespeed) Debug.Log("moveright") Output create a empty gameobject first circle second circle
|
0 |
Pressing the jump button also makes my character fire their weapon In my game I want my player jump without firing their weapon, but when I press the button it jumps and also fires too in same moment. In this Update method, I used Input.GetButton so my player will fire continuously while holding the button. void Start () isJumped true Update is called once per frame void Update() if (!transform.GetChild (0).gameObject.GetComponent lt PlayerHealth gt ().hasDied) if (Input.GetButton ("Fire1") amp amp Time.time gt firespeed amp amp isJumped true) nextFire myTime firespeed newProjectile Instantiate (projectile, transform.position, transform.rotation) as GameObject nextFire nextFire myTime myTime 0.0F EnergyCharging () void JumpButton() if(!transform.GetChild(0).gameObject.GetComponent lt PlayerHealth gt ().hasDied) if (grounded) grounded true myRigidBody.AddForce (new Vector2 (0, jumpPower), ForceMode2D.Impulse) if(myRigidBody.velocity.y gt jumpPower) myRigidBody.velocity new Vector2 (0, jumpPower) animator.SetBool ("isGrounded", grounded)
|
0 |
How to keep AI goalkeeper inside their bounds I'm making a soccer themed top down 2D endless game, but I have a problem with the goalkeeper AI. My game looks like this As you can see, the goalKeeper is moving out of bounds. I have tried to clamp them with transform.Translate(Mathf.Clamp(target.transform.position.x, 1,1),0,0) ...but I think this for clamping the speed, not the area boundaries. What should I do instead? What I want is to have two kinds of goalkeeper Active Goalkeeper (Call them GKA) This goalkeeper should chase the player, but only within the bounds of the goal area. Stationary Goalkeeper (Call them just GK) This goalkeeper should just stand in the middle of the goal, like in the first animation. But before the player reaches them I want this goal keeper to move forward slightly, to pretend it's defending the goal. Here is my goalkeeper script if (gameObject.CompareTag( quot GK quot )) anim.SetBool( quot GKRun quot , false) gkballInRange Physics2D.OverlapCircle(transform.position, gkballRange, playerMask) float distancePlayer Vector2.Distance(target.position, transform.position) if (gkballInRange) transform.Translate(0, .3f Time.deltaTime, 0) if (distancePlayer lt gkballRange) if (theBall.isOver) anim.SetBool( quot GkC quot , true) anim.SetBool( quot GKRun quot , false) transform.Translate(0, 0, 0) else Animation anim.SetBool( quot GKRun quot , true) transform.Translate(target.transform.position.x speed Time.deltaTime, 0, 0) and this one is GKA script if (gameObject.CompareTag( quot GKA quot )) Animation gkballInRange Physics2D.OverlapCircle(transform.position, gkballRange, playerMask) float distancePlayer Vector2.Distance(target.position, transform.position) if (gkballInRange) transform.Translate((target.position.x Time.deltaTime), 0, 0) if (distancePlayer lt gkballRange) if (theBall.isOver) anim.SetBool( quot GkC quot , true) anim.SetBool( quot GKRun quot , false) transform.Translate(0, 0, 0) else anim.SetBool( quot GKRun quot , true) transform.Translate(0, speed Time.deltaTime, 0)
|
0 |
Collision detection not working on some parts of mesh Racing game with a single mesh to act as a collider for all the track sides. Recently revised the mesh and now it is behaving strangely. The player correctly collides (bounces off) some parts, on other parts it is hit and miss whether the collider works and on others the player acts like there is no collider present at all. I have checked that all the meshes normals are facing the correct direction and that there are no gaps in the mesh. I have set the collisions on the player rigid body to be continuous. Can anyone suggest what might be happening? I was previously using the exact same technique but re created the collider mesh to clean it up and upon importing from Blender into Unity the collider behaviour is now all over the place. This picture shows part of the collider where the player just passes straight through the walls. Car collider in Unity Track mesh collider in Unity
|
0 |
Working with retina graphics on Unity 2D I begun trying Unity for iOS 2D development. I am curious about how to work with retina devices. The first thing I did was create a 1136x640 solid rectangle sprite and throw it into my scene, then run the game on my iPhone 5. My expectation was that this image would perfectly fill the screen that is, the retina would "kick in". Alas, this was not the case my sprite was much smaller than the iPhone's screen. Then I saw the main camera game object, and played around with the size property. By default is was like 5, but I determined that the number I needed for my sprite was somewhere around 3.2. This works and looks fine in my phone. But I am unsure if this is how I am suppose to do things what is the correct way of supporting retina images? I feel like guessing the size property of the main camera is a bit hackish. Actually, how do I know if Unity is indeed using retina?
|
0 |
Unity Syncing Downloading overwriting files to a local folder accessed by the game when offline? I currently have a game application (PC Standalone only) made in Unity which features a multitude of buttons which all link to external webpages which open up in the user's browser window. Recently my client expressed an interest in having an offline version, where all the online content is available locally offline, as their users regularly go offsite to areas without an internet connection and the buttons are then useless. I have done a new version which has all the webpages, PDFs and videos saved off as local files and placed in a folder within the build folder, the buttons now use the following script to read the files from there instead public class URLOpener OFFLINE MonoBehaviour public void relativeURL(string url) Application.OpenURL(url) This works perfectly on a basic level. However my client has expressed an interest in being able to update the offline content without having to make a new build each time or manually go and update the folder content. So basically what I need is to be able to store all the offline files somewhere online, which can be overwritten as and when is needed. Then I need some way of syncing the game with this online location (when the user is online), to pull down the latest files into the offline folder and overwrite the files in there, so the latest offline files are included when they go offsite to an area without internet. Is this possible at all? I am more than happy to pay for a plugin or service that would provide this sort of feature. I already have a plugin for translated languages which essentially does this (https www.assetstore.unity3d.com en ! content 14884) changes to the online spreadsheet containing all the text is pulled down when the game syncs. But this is obviously a bit different to downloading actual files and placing them in a specific folder. Any help or advice would be appreciated. Many thanks in advance
|
0 |
Unity3d calling a web service in unity editor works, but not in standalone. Why? I have this line of code SDE3D webService new SDE3D() int result webService.UserLogin(txtLoginUsername.text, hashString) My UserLogin function looks like this System.Web.Services.Protocols.SoapDocumentMethodAttribute("http www.something.com UserLogin", RequestNamespace "http www.something.com ", ResponseNamespace "http www.something.com ", Use System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle System.Web.Services.Protocols.SoapParameterStyle.Wrapped) public int UserLogin(string username, string password) object results this.Invoke("UserLogin", new object username, password ) return ((int)(results 0 )) In the Unity Editor it works well. At runtime, in my Unity game build, it doesn't work and doesn't return any error message! What is the issue? Thanks
|
0 |
Problem with the Layer System Tilemap Layer from Unity This is my first time using Unity (and my third time creating a game in general), so I hope I can provide the needed information to solve this problem. My character overlaps with the upper wall, but doesnt with the lower wall. This is the right behaviour given the layers (seen in the picture). But I want him to be behind the lower wall AND in front of the upper wall. Side Information The Wall Tile is one piece, which covers two tiles. Movement is depended on the existents of a ground tile. The reason behind this is, that I wanted the character to always move one tile at a time. And since this is my first time with unity, that was the easiest way of doing it. So there is no actual interaction with the wall. No collsions or anything. There are three Layers (Ground, Creature, Wall) and two tilemap layers (Ground and Wall) (see picture) and the character doesnt interact with the tilemaps at all, he just gets drawn above the ground tilemap layer. What I see as answers Split the wall tile into two tiles and let the wall part be on another layer, then the roof part. Split the character into two parts and do the same thing. Both seem like a good way of solving it, but I dont even know where do start there. I think I can split the walls into two tiles, but I dont know if this is a good way to solve this issue. The other option, to split my character, there I really dont know where to start. What I tried Trying around with layers and order in layers. Trying around with the tile atlas (adding the sprite, removing tiles)
|
0 |
Vuforia AR VR sample with Google Cardboard SDK I cannot switch from augmented reality to virtual reality I have followed the Integrating Cardboard to the AR VR Sample latest tutorial. I have configured the provided scene sample according to that tutorial. I have compiled it to Android without any problem. The game load an AR scene with a yellow pointer in the center. If I understood well, if a glaze at the ImageTargetStones GameObject, it will switch to VR. Unfortunately I cannot find that GameObject anywhere. I only see the AR scene with nothing than the yellow pointer. I don't find what I'm missing. Why is not that ImageTargetStones GameObject in the AR scene? UPDATE 1 I think I want to use Vuforia for an uncommon use. I think that's a reason of a possible misunderstanding. I don't want to use its image recognition possibilities. I want to switch between AR to VR when glazing to a button. I have tried to duplicate the VRButton to move it to an independent place of the scene with no parent. I have checked its IsTrigger checkbox. I have added a PointerEnter EventTrigger that set Focused to true. I have added a PhysicsRaycaster to both AR Camera and MainCamera (child of CardboardMain Head). Nothing happens when I gaze at the button. I have to compile everytime I want to try it by the way. I did not manage to make it work in the editor. UPDATE 2 I haven't been able to do it with vuforia yet. I have done it with WebCamTexture. Specifically, I have used the scripts of this answer http answers.unity3d.com answers 687987 view.html . The result is not nice because the image from camera seems closer than it actually is (with Vuforia, there is not that problem)
|
0 |
How Can Create Line Renderer Runtime When Player in Gravity I want to Create functionality Like Rock Runner Game.when player into the gravity and hold the button then generate line and player hold the line and move forward. After So many Research i couldn't find anything in google and also in YouTube then i post the question. I put some snippets to very well understand what i want actually. if any one have idea how to do this then tell me. thanks in advance
|
0 |
How to Animate a Mechanical Model to work with Unity's Mechanim? I made a relatively simple model in 3D Studio Max to be used in a game. It's a simple stationary laser turret with an openable maintenance hatch. I want to use Mechanim to handle the animation states. The parts of the model are parented in a way that it's easy to just make it move from code but I rather have it use Mechanim and animation files to make it easier to add details like idle animations. I tried animating it with Unity's build in animation editor which looked nice enough but I couldn't get the animation created with that in Mechanim for some reason. If I have to use an external editor to add animations, I can't seem to find any. Google only gives results on how to animate character models or how to make an animation just to be exported to video. How would I animate this model to work with mechanim, what programs should I use and what should I pay attention to?
|
0 |
Why do not Easy Mobile Pro scripts know about each other? I am getting this error when I try to build the project Assets EasyMobile Scripts Modules NativeAPIs NativeUI Nati veUI AlertPopup.cs(68,17) error CS0103 The name 'AndroidNativeAlert' does not exist in the current context I tried adding this to my NativeUI AlertPopup.cs if UNITY ANDROID using EasyMobile.Internal.StoreReview.Android endif Hint says unnecessary using. Googling, searching Unity EMP forum and thread did not bring any results. Unity version 2019.2 .net 4.x EMP 2.5 If I try adding a breakpoint it says The breakpoint will not currently be hit. Unable to find a corresponding location. AndroidNativeAlert is a static class, have have no clue why it can't been seen from the other one.
|
0 |
Unity3D Multiple OnTriggerEnters are called before the first one could finish and destroy the object I'm working on a projectile which explodes when it reaches a destructible object and damages its voxels. (The projectile is a trigger) But the problem is that I use raycasting in OnTriggerEnter which makes it slow to finish. Which lets multiple OnTriggerEnter to be called before it could be finally destroyed. I fixed it by having a flag which lets only one call to be executed. But it feels a bit hacky, so I decided to ask you, maybe you have some better solutions. void OnTriggerEnter(Collider collider) if (!hit amp amp LayerMask.LayerToName(collider.gameObject.layer) "Destructible") hit true DoImpact() Destroy(gameObject) void DoImpact() Do 1 SphereCast RaycastHit hits Physics.SphereCastAll(transform.position, ExplosionRange, transform.forward, 0.0001f, 1 lt lt LayerMask.NameToLayer("Destructible")) Iterate through voxels foreach(var hit in hits) the parent object which manages its voxels var destructible FindDestructibleParent(hit.transform) Make some damage to that voxel based on the projectile, the voxel, and some "whole container parent object properties" destructible.TakeDamage(this, hit.transform.gameObject)
|
0 |
Rigidbody slows down when its going up a slope. What can I do? I am using unity and I am creating a 3d topdown game. There is no jump feature. The input handling supports only x and z axis player movement. Climbing slopes or falling from gaps is something I want to happen without certain input. So, I have a rigidbody which I move by directly setting its velocity. When it goes up a slope it slows down. I would like it to keep the same speed. Now I do it like this void Update() moveInput new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical")) void FixedUpdate() MyRB.velocity moveInput.normalized runSpeed I am using a capsule collider on the rigidbody and a box collider for the slope. The physics materials of the colliders are the default none (not changed).
|
0 |
Trying to get reference to Button in Javascript Unity3d I've this simple script in Unity3d pragma strict public var topLeft UnityEngine.UI.Button public var topCenter UnityEngine.UI.Button public var topRight UnityEngine.UI.Button public var midLeft UnityEngine.UI.Button public var midCenter UnityEngine.UI.Button public var midpRight UnityEngine.UI.Button public var bottomLeft UnityEngine.UI.Button public var bottomCenter UnityEngine.UI.Button public var bottomRight UnityEngine.UI.Button private var x "X" private var o "O" function Start () var board topLeft, topCenter, topRight , midLeft, midCenter, midpRight , bottomLeft, bottomCenter, bottomRight for (var i 0 i lt board.length i) var row board i for (var j 0 j lt row.length j ) var button row j button.onClick.AddListener(function() onTileClicked(button) ) function onTileClicked(tile UnityEngine.UI.Button) Debug.Log("Click click!") Here is how I reference the buttons Why are all the buttons in 'board' variable null even if I referenced them through the GUI (the red rectangle in the image)?
|
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 |
How to change transform.position.x after a state is changed? When I press attack button, player will change to Normal Attack state to perform Normal Attack animation and you will notice the player seem like step back a little bit as the width of sprite for Normal Attack animation is longer than Idle animation. http youtu.be hnPXt kprqQ To solve this issue. I need to change the transform.position.x 0.5 to move a bit further to match the position of Idle animation stands and transform.position.x 0.5 when Normal Attack state done its animation and back to Idle state. How can I perform transform.position.x 0.5 when when Normal Attack state done its animation and back to Idle state?
|
0 |
Ridiculous Error on Unity 5.6.4p4 Method Name doesn't exists I am facing a strange issue on Unity version 5.6.4p4 The code compiles and runs just perfectly fine in editor but when I build it for android I see an error message saying that my method doesn't exists. I have checked many times but there is no such issue. I am not doing anything wrong. Can anyone suggest what could be wrong ?
|
0 |
Move around the object using head tracking movement in Unity I am developing an app for Samsung Gear VR with unity.I have added a cube and made the cube move forward on the terrain. Now I need to move around the cube using head tracking movement.I have referred the below link(Flyer VR movement) .But I am not able to understand the code used in it. https unity3d.com learn tutorials topics virtual reality movement vr Can anybody help me doing this in a simple way to move around the cube by head tracking
|
0 |
Why does Avatar Mask not work as expected? I have 2 layers The base layer, and an upper body layer. On the upper body layer, I have an avatar mask because I only want to affect the upper body. However, this mask doesn't work as expected. Here is what it looks like This is what is looks like when the upper body layer has a weight of 0 And this is with the upper body layer with a weight of 1 and with the Avatar Mask As one can see, the lower body is affected. The avatar mask doesn't seem to have an effect. Is that a bug in Unity, or is there anything I could still check? Thank you!
|
0 |
Can I set multiple animations to run at the same time with Unity's animator (some animated properties would overlap) I am creating a vehicle in Unity and I am currently trying to set up lights for it. I need to be able to press one button to turn on the parking lights. But the parking lights share the same bulb as the turn signals. So when a turn signal is turned on, I need that parking light bulb to now flash, while the others remain on. This is just one example of several I am coming across. Now, I could create an animation for every single scenario, but I believe there should be a simpler way to do this. I thought perhaps using the layers would handle it, but I'm fairly new to animations and I'm not sure I'm understanding them right. I put each animation on a different layer, and then ordered them in a way that made sense to me, and set them to additive. The right turn signal is on top and it works, but the left turn signal right below it does not. Is there something else I can do to make this work? Or a tweak I can do to fix what I have now, something I'm missing maybe? Thanks for the help!
|
0 |
How do I set up the microphone for an Android device in Unity? I'm developing a simple android app that needs to use the microphone. I'm able to load my app on my Android phone using developer mode, but I do not understand how to enable the mic. How can I enable the microphone and use the input? I started with a brand new Unity 2D project. I created a TextMeshPro Text object to display logs and set this reference on the script via the inspector. I have attached the following script to the Main Camera. using UnityEngine using UnityEngine.Android using TMPro public class RequestPermissionScript MonoBehaviour public TextMeshProUGUI logs void Start() if (Permission.HasUserAuthorizedPermission(Permission.Microphone)) The user authorized use of the microphone. logs.text "has authorized" else We do not have permission to use the microphone. Ask for permission or proceed without the functionality enabled. logs.text "has not authorized" Permission.RequestUserPermission(Permission.Microphone) I then Build and Run this as Android and the app is loading on my Android phone attached via USB. I expect a pop up to appear asking for permissions to the mic, but this does not happen and the logs says "has not authorized". What am I missing or doing wrong?
|
0 |
Unity Particle System Shuriken Setting particles in code with random row in texture animation? Good day, I'm attempting to randomly generate a space scene (quite large actually) in Unity through C code mainly. So far, I've gotten stunning results up to what image 2 will show you. However, now I'm looking to expand the look with more random particles. So, I've made a texture atlas of 8 in a vertical row, which works on the random setting if you have an emitter and the particle system is called with PS.Play() Assigning different materials would only work on a per particle system basis(which would be new texture PER cloud, so to speak) which is not what I want. So, my question How can I use the Shuriken Particle System's Texture Sheet Animation functionality through code, without having an "active" particle system? More precisely, I wish to use the 'Random Row' feature of it to assign random textures to each particle. Since I can't share my code (due to policies), here is a bit more info on how I do it I create an array with coordinates for each cloud. Assign a particle system to that cloud. Randomly generate all the particles for the cloud with relative offsets. Use PS.setParticles(particlesArray) Using a Texture Atlas consisting of the letters A to H to test, only B showing on all particles. Using a Texture Atlas consisting of the fog particles to test, only 2nd showing on all particles. Thank you DMGregory for the help, I've tested it multiple times and it works perfectly now, I've also went ahead and tweaked a few of my settings just to get a more "clear" space
|
0 |
How to access the currently touched instance of the Prefab? I have a prefab which is instantiated in the Scene and what I am trying to do is to disable with a touch or timeCounter but sometimes it disables all the instances of the prefab and sometimes 2 or 3 of them. I want to disable particular object which I have touched currently. when i am passing the collider in Destroy(hit.collider) it works perfect but how to handle it null is passed as parameter. Here is my code void Update () blastingTimeCounter Time.deltaTime if (blastingTimeCounter lt 0) DestroySquare (null) for (int i 0 i lt Input.touchCount i ) if (Input.GetTouch (i).phase TouchPhase.Stationary) hit Physics2D.Raycast (Camera.main.ScreenToWorldPoint ( Input.GetTouch (i).position), Vector2.zero) if (hit.collider ! null) DestroySquare (hit.collider) void DestroySquare(Collider2D collider) if(collider null) else collider.gameObject.SetActive (false) blastingTimeCounter blastingTime
|
0 |
How can I change the rotatearound radius in real time when the game is running? using System.Collections using System.Collections.Generic using UnityEngine public class TargetBehaviour MonoBehaviour Add this script to Cube(2) Header("Add your turret") public GameObject Turret to get the position in worldspace to which this gameObject will rotate around. Header("The axis by which it will rotate around") public Vector3 axis by which axis it will rotate. x,y or z. Header("Angle covered per update") public float angle or the speed of rotation. public float upperLimit, lowerLimit, delay upperLimit amp lowerLimit heighest amp lowest height private float height, prevHeight, time height height it is trying to reach(randomly generated) prevHeight stores last value of height delay in radomness Range(0, 50) public float xradius 5 Range(0, 50) public float yradius 5 private void Start() Update is called once per frame void Update() Gets the position of your 'Turret' and rotates this gameObject around it by the 'axis' provided at speed 'angle' in degrees per update transform.RotateAround(Turret.transform.position, axis.normalized, angle) time Time.deltaTime Sets value of 'height' randomly within 'upperLimit' amp 'lowerLimit' after delay if (time gt delay) prevHeight height height Random.Range(lowerLimit, upperLimit) time 0 Mathf.Lerp changes height from 'prevHeight' to 'height' gradually (smooth transition) transform.position new Vector3(transform.position.x, Mathf.Lerp(prevHeight, height, time), transform.position.z) Using the xradius and yradius sliders I want to change the transform.RotateAround radius in real time. UPDATE I added this to the Update if (radius gt 0) var newPos (transform.position Turret.transform.position).normalized radius newPos Turret.transform.position transform.position newPos The problem is now that some times when the radius the distance from the Turret is small for example 20 or less some times the transform is getting right above the turret not sure why. I want it to rotate around the turret at the fixed set distance(radius) but not to be above the turret. Can't figure out why sometimes it's moving right above the turret then after some time it's getting back to the set distance.
|
0 |
Coding style about collisions with geometry Let's say I'm writing 3D Pacman. I have "Dot" objects throughout my maze, that are structured as follows in the Inspector Dot (GameObject) Sphere w Collider When I run into the sphere trigger, I can trivially say "Get me your parent and check if it's a Dot" However, I hate baking in the knowledge that some spheres have parents that are Dot objects. If the trigger were on the Dot itself that problem would solve itself, as I could just call GetComponent(). What's a good programmatic style approach to finding out what logical Game Object actually owns the geometry you've collided with? I could add a Tag of "Dot" to the sphere but that's just a level of confirmation, I still would have to walk up to it's parent and check.
|
0 |
How to set an EditorGUI foreground color for the light Unity skin? Writing an asset management GUI as part of our editor tools, I am in some places colouring LabelFields. Working mostly in the dark Pro skin, this seems to work just fine GUI.color Color.green EditorGUILayout.LabelField("Name", GUILayout.Width(75f)) GUI.color Color.white When switching to the light default skin however, this colouring is no longer visible. The usual GUI.backgroundColor still functions fine there as it does in the dark skin. Is this "foreground" colour something specific to the dark Pro skin? If so, is there perhaps another way to achieve a similar effect?
|
0 |
Rotate a Polygon node in Shader Graph I have a hexagon in the Polygon node I would like to rotate so the pointy side is upwards. Applying the rotation nodes, however, simply changes the color of the hexagon from white to a color in the rainbow. What does the Vector1 of the Polygon output represent and is there a way I can rotate it as if it were a texture?
|
0 |
Unity Shader Graph and GPU Instancing? Unity Version 2019.4.1f1 Render Pipeline URP I created a shader using Unity's ShaderGraph, and i want to apply GPU Instancing on this shader, but there is no way to declare per instance properties inside the shader graph. Is there a way to make GPU Instancing work on shader graphs' materials?
|
0 |
Make a child sprite match the layer ordering of its parent I have my project settings set up to order the sprites' visual layering based on their y position. If I add a sword as a child to my character, the sword won't have the same order as the parent so things can look like Sword gt enemy gt player instead of enemy gt sword gt player (because I want the sword to be in front of the character) I thought of setting the pivot point of the sword sprite so when nested inside the parent sprite, it would be around the same height as the player's pivot point so they would have the same order. I feel like this wouldn't be the best solution because when I will animate the sword to attack, I wont be able to rotate it around the position I want.....unless I make it the child of an empty object? How can I solve this issue?
|
0 |
Remove hidden values within string I tried removing the Unicode Whitespaces in the string using words len .Trim() but still there's still an extra character. Every letter represents the coordinate of where the letter is. As you can see there's an extra coordinate value and it is always located at the end of the string. (dont mind the ' tries') Can you help me Identify what is the extra invisible unicode and what to do in order for it to be removed? private string FisherShuffle(string words) int len words.Length while(len gt 0) float index Mathf.Floor(Random.Range(0f, 1f) len) len var temp words len .Trim() words len words (int)index words (int)index temp return words UPDATE I have found out that the ASCII value is 13. I also have tried using TrimEnd(' n',' n') amp words len .TrimEnd(System.Environment.NewLine.ToCharArray()) to no avail private string FisherShuffle(string words) int len words.Length int index string temp while(len gt 0) index (int) Mathf.Floor(Random.Range(0f, len)) len temp words len .TrimEnd(' n',' r') temp words len .TrimEnd(System.Environment.NewLine.ToCharArray()) words len words index words index temp return words
|
0 |
Civilization Style Borders With Sprites I am making a civilization style game in Unity. The game uses square tiles and has a 2d sprite style. I am currently implementing a border system like in civ4 where a line is drawn around you civilization's borders, but I cannot find a way to create the correct sprites to draw the border. My first thought was to have a sprite corresponding to each neighbor, the sprite would toggle on if the tile it is over is in the bordered area and the corresponding neighbor is not. This would work but It would require 8 (one for each neighbor) sprite renderers per tile and I assume that would be pretty inefficient. I thought of making a separate sprite for each configuration to cut it down to one sprite renderer per tile but that would require 2 8 sprites which just is not feasible. I also thought that maybe I should stick to the first idea but only instantiate or move sprite renderers to where they are needed which would greatly reduce the amount of sprite renderers used at once. This seems like my best option but it seems unnesicarily complicated and still pretty inefficient. I do not know of any simple way to dynamicaly draw sprites to fit a pattern, so it seems I am stuck with one of these solutions. Does anyone know of a better way to handle this?
|
0 |
Blur shader without render textures? Is it possible to append a blur shader to a standard (diffuse) shader ? I am looking for a way to do this as Unity indie doesn't allow render textures.
|
0 |
Using 10 materials for one Model? I made more than 10 robots. all of them had not less than 4 materials, and some had 12 materials. I can't go back and fix this. How this will effect on the game performance later ?
|
0 |
How to handle data for a competitive multiplayer games I am kinda new to Multiplayer Games and I am really wondering how I should handle my data Should each player send and update their data to the database (server) everytime one of their essential variables changes (like health or ingame currencies), or should they save the data as long as the game is running and then update the data all at once at the end of, lets say, each round? I was thinking about using Firebase and Unity and here's a scenario Let's say 2 players connect to a game. Then one of them gets damage and the other one gets gold. Does the data change get sent to the FireBase Database immediatly or should I just update everything when the round ends they disconnect?
|
0 |
Unity3D filling visible camera area with objects I'm developing an isometric tile based game using Unity 3D. I'm using an orthographic camera looking down yaw 45 and pitch 45 . The game has an infinite world, which is loaded from a remote server. Because it is impossible to load everything at once, the game should only load visible areas of world. But I don't know how to determine which tiles should be requested from server in order to fill up all the visible space on the screen. I tried loading tiles by chunks e.g. 16x16 tiles chunk around camera. But this looks hacky to me and sometimes leaves blank edges visible on the screen. Is there better solution to simulate a continuous world on the client side?
|
0 |
Best Practices for Random Enemy Animations? For various animations for NPCs (getting hit with projectiles, shooting, dying) I've been creating 2 4 animations each in blender before exporting. Should I be doing this inside Unity with Animation Controllers instead? Either way what would be the best practices to actually randomizing the animations?
|
0 |
How can I switch between cinemachine free look cameras by script? using System.Collections using System.Collections.Generic using UnityEngine using Cinemachine public class CamerasManager MonoBehaviour public CinemachineFreeLook freeLookCameras public float timeBeforeSwitching Start is called before the first frame update void Start() StartCoroutine(SwitchCameras(timeBeforeSwitching)) Update is called once per frame void Update() IEnumerator SwitchCameras(float TimeBeforeSwitching) yield return new WaitForSeconds(TimeBeforeSwitching) for(int i 0 i lt freeLookCameras.Length i ) freeLookCameras i .en If I have two or more cameras I want that after X seconds start switching between all the cameras in the array by disabling enable the cameras. disable the first enable the second then disable the second enable the third and so on.
|
0 |
How to get time since frame start in Unity for loading purposes I am building a big world (1000 game objects). It takes 2s on the device. I am doing it in the background (the world is hidden until fully loaded). I have figured out that I can maintain the FPS of the active scene by switching to coroutines and making yield return null . The main issue is when to fire yield return null . If I do it too often, then it will slow down the loading. If I do it too rarely, it will reduce FPS on low end devices. My idea is simple to detect how much milliseconds have passed since the start of the frame and fire yield return null just after I have spent for example 12ms (to leave some time to render everything else and maintain something near 60FPS). However, I can not find an efficient way of getting the time since frame start? Unity should have something as the async loading of assets seems to consume just right time to maintain stable FPS.
|
0 |
Load a second app in background and launch behind a loading screen there is a way to preload an application in android from Unity? I mean.. I'm developing a launcher and every click in icon, should be launch a different game.. so, the time between show a loading animation and open the second app, in android, It's posible to make.. when the loading's animation is fadeout and behind the loading screen, the second app is loaded? P D I have to said that, the launcher is a different application from the game that should be launch.
|
0 |
How to cut a desired shape out of a mesh? I want the player to be able to cut a hole through a wall, similar to what's shown in this video I know for the fact that it's really difficult to achieve, so I was wondering how I can cut a shape out of a simple mesh at run time (or even cut a shape out of a 2D sprite).
|
0 |
simple 2d car AI unity I have a top down Car Game. how can I implement AI for the Cars? how the car follow the way points? I want AI cars also rotate itself along the path. I tried this solution using System.Collections using System.Collections.Generic using UnityEngine public class waypoint MonoBehaviour public List lt Transform gt waypoints private Transform currentWaypoint public float speed 5f private float closeEnouth 0.5f int point 0 void Start() currentWaypoint waypoints point Update is called once per frame void Update() Quaternion rotation Quaternion.LookRotation(waypoints point .position transform.position, transform.TransformDirection(Vector3.forward)) transform.rotation new Quaternion(0, 0, rotation.z, rotation.w) float dist Vector3.Distance(waypoints point .position, transform.position) transform.position Vector3.MoveTowards(transform.position, waypoints point .position, Time.deltaTime speed) if (Vector3.Distance(this.transform.position, waypoints point .position) lt closeEnouth) if (point 1 lt waypoints.Count) point and the car moved in the path but it moves reversed and if arrives the final node it stops and corrects its direction and console displays "Look rotation viewing vector is zero" error. Thanks in advance
|
0 |
Voxel clouds rendering in Unity I would like to have realistic voxel clouds in Unity game I found a very promising article on fast fluid simulations, however the the output of the algorithm itself is 3D grid of cloud densities ( 3D texture). My question is how can I render such 3D texture into clouds? My research so far The original article suggest two pass rendering of particles for each voxel, in first pass reading output after each particle(!) is rendered. This approach is both slow and outdated not leveraging modern shader pipeline in addition to being overly complicated. Searching for voxel clouds in Unity suggests using ray marching while the actual implementations does not seem to do any ray marching, but rather using Fractal Brownian Motion to same 2D noise texture. This approach gives decently looking results (with some problems addressed in horizon zero dawn slides), but would not make use of my realistic simulation. The most promising source I could find was this answer, namely last paragraphs. However the answer itself rather vague on actual algorithm and links it provides are either broken or inacessible.
|
0 |
What does pressing CTRL do when editing a sprite sheet? I have a multi sprite sprite sheet. When I have a blue box selected, and I hold CTRL, the box turns green. I have played with it, but cannot figure out what it does. I checked the documentation, but I don't see anything about turning the boxes green. What does holding CTRL when editing a sprite within a multi sprite sprite sheet do?
|
0 |
Can't go above max speed with RigidBody2D.AddForce() I'm having trouble making a character move faster than a certain limit using RigidBody2D.AddForce(). My game is a top down 2D game (constrained to the x y plane). I'm using a float 'MovementSpeed' to scale a normalized vector passed to RigidBody2D.AddForce(), however, when I increase MovementSpeed past 1000, there's almost no noticeable difference in the object's "speed" going from 100 to 1000 is a drastic difference, but there's almost no noticeable difference going from 1000 to 1000000. Here's my WASDMovement() function (called during FixedUpdate() ) private void WASDMovement() Vector3 translationVector Vector3.zero if (Input.GetKey(KeyCode.W)) translationVector new Vector3(0.0f, 1.0f, 0.0f) if (Input.GetKey(KeyCode.A)) translationVector new Vector3( 1.0f, 0.0f, 0.0f) if (Input.GetKey(KeyCode.S)) translationVector new Vector3(0.0f, 1.0f, 0.0f) if (Input.GetKey(KeyCode.D)) translationVector new Vector3(1.0f, 0.0f, 0.0f) translationVector.Normalize() rigidbody2D.AddForce(translationVector MovementSpeed) Here's a video demonstrating my problem to make it easier to see what I'm doing wrong http youtu.be 9kwKvfDOYoo
|
0 |
How to simulate car drivetrain (in Unity)? One of my hobby projects involves cars. Up until now I had a quick and dirty "one class" implementation of engine gearbox wheels, but I thought that this is ugly, and I want to go a bit more realistic. Sadly I couldn't find much on Google (either wrong search terms or there really isn't anything that is what I want). It seems like Setup in scene Four wheelcolliders attached to a big boxcollider. Things that I want in the system Separate classes for engine, clutch, gearbox, differential and wheels (and whatever else does stuff with torque). Throttlecontrol with revlimiter (works!), steering (works too!), brakes (not yet made, but also not very complex and will likely work). First thing I tried Mainly this rotates around how I tell the engine that the wheels are actually using or giving (engine braking) power to the system. so first I created all the classes each with their own updatemethod (not called directly by mainloop, but from a fixedupdate of a controllerclass). updatemethod of engine calculates engine torque from throttle, torque curve (animation curve) and engine friction. This is then used to speed up the virtual crankshaft which has its own inertia. But before speeding up the shaft, I decided to put some feedback torques on the engine torque, so if the wheels can't keep up, the engine can't speed up, or even slows down. Such a feedback torque is added for example by the gearbox, which in turn also has feedback forces from the differential and with that the wheels. The wheels calculate the torque needed to spin up to the speed of the shaft coming out of the gearbox and then it propagates all back to the engine over a few updates. Problem was, the torque feedback didn't really do engine braking, but catapulted it to several million RPM in a split second. Dividing the feedback torque by 1000 did work, but then the car didn't move at all. So this is fail number 1. Fail number 2 Okay screw this, I thought, and tidied up all the stuff. This doesn't use several updatemethod anymore, but recursive updating. Basically I call update on the engine, which in turn then calculates what torque it has available. With that it tells the transmission that it has t torques at r RPMs. The gearbox changes the values according to the current gear and then again puts the values into the differential. The differential SHOULD split the torque between its outputs. To do this I calculate how much torque the output (in this case wheels) would need to speed up to r RPMs. I do this for each output and make a list of it for each output. I also save the sum of these values. With this I can get a value of 0...1 for each output, that determines how much torque each output gets in its updatemethod. Its basically an intelligent differential that gives the output which needs more torque, more torque. I guess modeling a real differential would involve some more complex stuff. Now the torque is at the wheels and gets put into the motorTorque property of the wheelcollider. Up until here it works. If I throttle up and then let go of it the wheels start turning backwards. It's basically another feedbackloop just like with the first try. So also fail And fail 3 Instead of returning the torque that's left, I tried backpropagating the RPMs to the engine instead. So I apply torque, and get RPMs back. But again everything tries to move the car in the opposite direction that I want it to go. Here is where I'm out of ideas. I want a relatively realistic drivetrain, that is modular and can do enginebraking. A bought asset will most probably not solve my problem, and I also want to understand how it works, and not just use it. Does anybody have experience with how to properly model a drivetrain? If I forgot to mention something, please ask.
|
0 |
Armature's bone can't be rotated in Unity when I'm trying to rotate its chest toward its looking direction? I want to rotate my character's chest, so its looking direction will be visualised correctly. But I think that the animation controller doesn't let me. I logged its rotation before and after I set it, and after setting, it's correct, but next frame before I would set it, it's always snapped back. How could I make my character's animation transformed, based on its looking direction? This is the code Debug.Log(Chest.localRotation.eulerAngles) Chest.localRotation Quaternion.Euler(90, 90, 0) Debug.Log(Chest.localRotation.eulerAngles)
|
0 |
How to reset the score to 0 when reloading the game? My scoring system uses DontDestroyOnLoad to persist between scenes public class ScoringSystem MonoBehaviour private int score 0 public void Correct(int number) If correct add score score score number void Start () score 0 void Awake() DontDestroyOnLoad(transform.gameObject) public int GetScore() return score Here is another script that I should include a description about public void iniTag() jawab true Time.timeScale 0 GameObject objek1 GameObject.FindGameObjectWithTag("Benar1") GameObject objek2 GameObject.FindGameObjectWithTag("Benar2") GameObject objek3 GameObject.FindGameObjectWithTag("Benar3") GameObject objek4 GameObject.FindGameObjectWithTag("Benar4") if (objek1.transform.parent.tag "Jawab4" amp amp objek2.transform.parent.tag "Jawab3" amp amp objek3.transform.parent.tag "Jawab2" amp amp objek4.transform.parent.tag "Jawab1") PanelBenar.SetActive(true) buttonNext.SetActive(true) GameObject.Find("QuizManager").SendMessage("Correct", playerScore) void Start () if (GameObject.Find ("QuizManager") ! null) ScoringSystem scoringSystem GameObject.Find ("QuizManager").GetComponent lt ScoringSystem gt () gameObject.GetComponent lt Text gt ().text scoringSystem.GetScore().ToString () else Debug.Log("No Scoring system found. To test scoring system start from the front page scene")
|
0 |
Unity Behavior Designer get gameobject I am trying to create my own action in Behavior Designer. However i cannot seem to get the game object that designer is attached to. if i attempt to do protected Combatant enemyCombatantObject public override void OnAwake() enemyCombatantObject GameObject.GetComponent lt Combatant gt () base.OnAwake() It gives me an error the property or indexer 'Task.GameObject' cannot be used in this context because it lacks the get accessor Can anyone tell me how to get the GameObject that the script is attached to?
|
0 |
How can I unify the collision handling of melee spell attacks in a networked environment? I am trying to figure a good way to create the battle system of a game. The game is fast paced and the gameplay needs to be precise (think hack n slash) What I would like to achieve is a simple and unified system that could manage any type of attacks, that could be tweaked. My first idea is to use physics shape For example an arrow will just be a little capsule moving forward, an explosion would be a growing sphere collider, and melee combat could be done by spawning a box in front of the player. One problem I have with this is that I'd like to have an authoritative server for multiplayer, which means I shouldn't use too much actual physics. So, is there any standard way people program these sort of systems, do you know any good starting point better than just using physics?
|
0 |
How can I make the space craft takeoff landing by code with logic? The code so far using System.Collections using System.Collections.Generic using UnityEngine public class AnimFlyertransportationController MonoBehaviour public Transform transformToMove public GameObject JetFlame public float speed public bool takeOffLand false private Animator animators private void Start() TurnAllAnimtorsOff(transform, false) private void Update() if(takeOffLand) TakeOff() else Land() private void TakeOff() float step speed Time.deltaTime var v3 new Vector3(transformToMove.localPosition.x, 7, transformToMove.localPosition.z) transformToMove.localPosition Vector3.MoveTowards(transformToMove.localPosition, v3, step) private void Land() float step speed Time.deltaTime var v3 new Vector3(transformToMove.localPosition.x, 0, transformToMove.localPosition.z) transformToMove.localPosition Vector3.MoveTowards(transformToMove.localPosition, v3, step) private void TurnAllAnimtorsOff(Transform root, bool onOff) animators root.GetComponentsInChildren lt Animator gt (true) foreach (Animator a in animators) if (onOff) a.enabled true else a.enabled false The problem I need to call the function TurnAllAnimtorsOff but each time only once when taking off and when landing. When taking off it should first turning all animators and flame to true turn them on then taking off and when landing first to land when reaching height target when landing finished then call the function again and turn off all the animators and the flame. I added this flag bool variable takeoffland as helper but now the object is taking off and engine and animators turning on but now it's not landing anymore using System.Collections using System.Collections.Generic using UnityEngine public class AnimFlyertransportationController MonoBehaviour public Transform transformToMove public GameObject JetFlame public float speed public bool takeOffLand false private Animator animators private bool takeoffland false private void Start() TurnAllAnimtorsOff(transform, false) private void Update() if(takeOffLand) if(takeoffland false) TurnAllAnimtorsOff(transform, true) JetFlame.SetActive(true) takeoffland true TakeOff() else Land() private void TakeOff() takeoffland false float step speed Time.deltaTime var v3 new Vector3(transformToMove.localPosition.x, 7, transformToMove.localPosition.z) transformToMove.localPosition Vector3.MoveTowards(transformToMove.localPosition, v3, step) private void Land() float step speed Time.deltaTime var v3 new Vector3(transformToMove.localPosition.x, 0, transformToMove.localPosition.z) transformToMove.localPosition Vector3.MoveTowards(transformToMove.localPosition, v3, step) if(takeoffland) TurnAllAnimtorsOff(transform, true) JetFlame.SetActive(true) private void TurnAllAnimtorsOff(Transform root, bool onOff) animators root.GetComponentsInChildren lt Animator gt (true) foreach (Animator a in animators) if (onOff) a.enabled true else a.enabled false
|
0 |
Stop animation from playing while waiting to destroy object I'm working on functionality in Unity where if a game object's health is zero, it does and the object is destroyed. This works fine as is, I reduce the health to zero, the die animation plays and the game object is destroyed. I want to have the script wait a certain amount of time and then run the destroy method. I thought using WaitForSeconds() would do the trick, and technically, it does, but the death animation continues to play until the object is destroyed. My question is, how do I get the animation to stop playing as the script waits to destroy the object? C void Die() GetComponent lt Animation gt ().CrossFade(die.name) If the current animation time is greater than 90 of the entire animation length, destroy the object. if(GetComponent lt Animation gt () die.name .time gt GetComponent lt Animation gt () die.name .length 0.9) StartCoroutine(RemoveBody()) IEnumerator RemoveBody() yield return new WaitForSeconds(5) Destroy(gameObject)
|
0 |
How to initiate manually an animation in Unity? I have a prefab and I want to control when an animation is initiated. I can't seem to figure out how to do that. I have already created the animation clip, the animator component for the prefab, and the animator controller. The animation works, when I enter play mode in the unity editor (it plays automatically), but I want to control when the animation occurs when providing input (such as pressing on the space bar or clicking on the prefab). How would I go about doing that?
|
0 |
Make objects stack in unity? I have two kinematic rigidbody cubes from the standard 3D objects, I have also enabled contact pairs mode to quot all contact pairs quot , how do I make it so that no matter what angle they collide in they perserve the same angle but just get out of each others space making it look like they're in contact e.g. collided? Here is my attempt at doing that using System.Collections using System.Collections.Generic using UnityEngine public class Physics MonoBehaviour private Collider collider1 private bool grounded false used to determine if the collider hit something so it doesnt keep going down Start is called before the first frame update void Start() collider1 GetComponent lt Collider gt () Update is called once per frame void Update() if (!grounded) if the collider hit something, stop going down collider1.transform.Translate(0f, .1f,0f,Space.World) private void OnCollisionEnter(Collision collision) grounded true the collider hit something if(collider1.transform.position.y ! collider1.bounds.extents.y) if this is true, it means it is at the floor so dont move it transform.position new Vector3(collider1.transform.position.x, collision.collider.bounds.size.y collider1.bounds.extents.y, collider1.transform.position.z) attempts to put the collider on top of whatever it get This works if the cubes are right on top of each other with no angle It also works if one of the cubes collides at a angle to the other cube, when they collide the bottom cube perverse its angle of collision and and the top cube just gets out of the space of the other collider making it look like they have collided What doesn't seem to work is if both cubes collide with each other at a angle, although they preserve their angle of collision, and also get out of each others space, they do not remain in contact with each other which if they did would make it look like they have collided. Instead there is a gap between them, how do I get rid of the gap e.g. make it so that no matter what angle the objects are at they get out of each others space, preserve the angle, and remain in contact with each other to give the illusion that they have collided?
|
0 |
How do I make sprites overlap eachother based on a layering system? In Unity, I am building a 2D puzzle game, however I need to make sure that certain sprites are rendered on top of other sprites when they are above them. Here is an example switch (left) and block (right). I wanted to make sure that the green block appears on top of the green switch when it passes over it, so how do I avoid a situation like this happening?
|
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 |
Unity Player Movement Problem I want to make a little game in Unity, where the player (a ball) jumps up and down and you have to maneuver it through (flappy bird like) obstacles. My problem is, after I added a simple movement script float speed 10f Vector3 move new Vector3(Input.GetAxis ("Horizontal"), Input.GetAxis ("Vertical"), 0) transform.position move speed time.deltatime The ball is stuck and can only be moved a little,before returning to its start position. My question is how i can fix that? I didnt find any solution
|
0 |
NavMesh moving is not smooth I have two car in game one of them is cop that chase player, i put a NavMesh on cop with these values when the cop get close to player (player speed is 10 ) , movement will go jittery and not smooth. Note cop will not collide with player because i have changed stopping distance in script instead of editor. Note 2 this jittery movement is not only in camera its also on scene view. now how i must make movement smoother? where is the problem?
|
0 |
Can UNet do Rigidbody2D prediction? (i.e. using gravity) Having a NetworkTransform with transformSyncMode set to SyncRigidbody2D (as opposite to a plain SyncTransform) I assumed it would try to sync all physics, hence handling gracefully forces, especially gravity. What I got instead, is a very simple linear interpolation, which smooths out the gravity, so that jumping up and down looks incredibly unnatural I would have expected this wish a SyncTransform of course, but, given the name I would have expected SyncRigidbody2D to solve this sort of problem So, am I missing something and might I have some value set wrong, or what?
|
0 |
Causing Update loop with Coroutine Unity Total Noob Alert! lt 7 days with C and Unity My Win Game screen becomes SetActive and my Player is SetActive false when you are standing in a trigger and crouch. That all works fine except you cant see the crouch animation because he is IMMEDIATELY SetActive false. I tried to delay this by creating a coroutine. The problem with that is this is all happening in the Update function (or whatever it's called) because of the getkeydown for crouch. That gets called once per frame so my coroutine is trying to go off once per frame. I tried creating a bool called isCoroutineStarted and set it to false and then set it to true in the Coroutine to break the loop but that didn't work either. Don't know what to do so I reverted it back to before where it doesn't show my crouch animation. Here's my script (It's attached to a Game Object with the trigger) using System.Collections using System.Collections.Generic using UnityEngine public class xxxxxx MonoBehaviour public bool xxx false SerializeField private GameObject youWinUI SerializeField private GameObject player Determines whether or not the player is standing on the xxxxx void OnTriggerEnter2D (Collider2D other) xxx true void OnTriggerExit2D (Collider2D other) xxx false Turns on Win screen and makes player disappear when crouch on xxx void Update () if (Input.GetKeyDown (KeyCode.S) amp amp xxx true) youWinUI.SetActive (true) player.SetActive (false) P.S. ignore the x's no stealsies lol. Also this piece of script works as intended I just want a delay so you can see the crouch animation.
|
0 |
Make my Random.range not repeat same position So I want to make my array Gameobject transform to transform array points position but it will be randomized position when start only without repeating a position so make some script like this public GameObject collectibleAyatGO public Transform transformPoint public List lt int gt TakeList new List lt int gt () private int randomNumber public void RandomTransformPosition() TakeList new List lt int gt (new int transformPoint.Length ) for (int i 0 i lt transformPoint.Length i ) randomNumber Random.Range(0, transformPoint.Length) while (TakeList.Contains(randomNumber)) randomNumber Random.Range(0, transformPoint.Length) TakeList i randomNumber collectibleAyatGO i .transform.position transformPoint TakeList i 1 .position it seem not working or make my unity notresponding maybe due to while loop, Am I doing right here ?
|
0 |
Unity 3D Rotate (smoothly) towards a target I wanted to know if there is a method on which I can rotate an object with an angle given (a float to be precise), I use trigonometry to calculate the angle between the two objects in a (x, z) plane perspective (using y as the height coordinates). This is the code I use to calculate the angle, but I want to know if a float would be anough data (then pass a Vector3 with that angle calculation as the Y parameter, since I want to rotate the Y axis). Makes the player heads to the direction the ball is... public float headOnBall() Vector3 playerPos this.transform.position Vector3 ballPos ball.transform.position float angle float x (playerPos.x ballPos.x) float z (playerPos.z ballPos.z) if(playerPos.z lt ballPos.z playerPos.x lt ballPos.x amp amp playerPos.z lt ballPos.z) angle (Mathf.Atan2(z, x) (Mathf.PI 2)) Mathf.Rad2Deg else angle Mathf.Atan2(z, x) Mathf.Rad2Deg return angle Thanks in advance.
|
0 |
Unity Custom aspect ratio in build I have made a game that was supposed to be for mobile but now I need to build it for PC. I want the aspect ratio to be 2 3 but as you can see on the image that doesn't exist. How do I add a custom aspect ratio for the build?
|
0 |
How do I display the next speaker image in my dialogue? I am working on a dialogue system and while the text part works, the UI for the Dialogue Boxes does not. When I click on the Continue button, I want the script to go down the Elements and use the Image that I have selected there, similar to what the sentences feature does. This is my script using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI using TMPro public class TextDialogueScript MonoBehaviour public TextMeshProUGUI textDisplay public TextMeshProUGUI ContinueDialogue public Image UIDisplay public string sentences public Image CharacterNames public Sprite CharacterDialogueBox public Image CharNames public List lt Image gt DialogueBoxes new List lt Image gt () public List lt Image gt CharacterName new List lt Image gt () private int index private int DBindex public float typingSpeed public GameObject DialogueTrigger public GameObject DialogueEventController public GameObject NormalEeventController Start is called before the first frame update void Start() NormalEeventController.SetActive(true) DialogueEventController.SetActive(false) UIDisplay.enabled false ContinueDialogue.enabled false Update is called once per frame void Update() if(textDisplay.text sentences index ) ContinueDialogue.enabled true public void OnTriggerEnter(Collider other) if(other.CompareTag("Player")) NormalEeventController.SetActive(false) DialogueEventController.SetActive(true) StartCoroutine(Type()) ContinueDialogue.enabled true UIDisplay.enabled true UIDisplay.sprite CharacterDialogueBox DBindex public void OnTriggerStay(Collider other) if (ContinueDialogue true) public void OnTriggerExit(Collider other) NormalEeventController.SetActive(true) DialogueEventController.SetActive(false) ContinueDialogue.enabled false UIDisplay.enabled false IEnumerator Type() foreach(char letter in sentences index .ToCharArray()) textDisplay.text letter yield return new WaitForSeconds(typingSpeed) public void NextSentence() ContinueDialogue.enabled false if(index lt sentences.Length 1) index textDisplay.text "" StartCoroutine(Type()) else textDisplay.text "" if (DBindex lt CharacterDialogueBox.Length 1) DBindex I was using a List that grabbed sprites, but the problem is, it would only use Sprites from the Assets and not the Hierarchy. This is a problem because I have messed with the colours using Unity and played around with the Alpha to get the exact effect I want that cannot be replicated with my image program. (I do not know what the term is for adding on the end of items to add elements that can be expanded. I have been stuck on this dialogue system for a very long time and I am very tired yet excited because I am so close to getting this to work, that it's painful)
|
0 |
(Why) Should I choose Unity 3 or Cocos2d (or something third) for my app? My colleague and me made an HTML 5 iPad game ( http braille.gandzo.com ) and we would like to upgrade it, and our framweork is not enoguh, for what we want. Some of the things we would change are graphics update, animations "effects", multi player, achievements and so on. The game would stay 2d. Now, as far as I understand, both Unity and Cocos would be good for this task, with Unity having the advantage of being multi platform. What I want to know is are there unknown qualites "flaws" to these two programs which would influence my decision (maybe even by choosing something else). Examples that come to mind are "Unity is too complicated has too much unneeded options hoops because it's made with 3d in mind" or "Cocos is significantly more suited for 2d games".
|
0 |
Recursive Unity Coroutine I have a co routine which is heavily reliant on calling itself to get the task done. I have tested it and the code works fine, the problem is that the co routine will return every time that it enters itself recursively. IEnumerator test(arg1, arg2) I want to pause here yield return null I don't want to pause on any of these yield return test(arg1, arg2) yield return test(arg1, arg2) yield return test(arg1, arg2) yield return test(arg1, arg2) In the example above I have a yield return at the top that is hit and pauses the co routine, thats fine. Then there are the calls to itself below which also pause the co routine. How do I avoid pausing the co routine on the recurcive calls?
|
0 |
Rigidbody Ray alternative or optimization I am creating an AI that moves around to certain points, but should interact with ais or objects seen. The ai should find other ai to comunicate or look for objects on the ground. It works with all those solutions with a low number. But when I have 300 ais the fps drops a lot, caused by Physics2D.FixedUpdate or something related with physics. How would you deal with this? I have tried those solutions Solution 1 AI Rigidbody2D Kinematic SphereCollider2D Trigger OnTriggerEnter amp Exit Script. Objects Rigidbody2D Kinematic SphereCollider2D Trigger Solution 2 AI Rigidbody2D Kinematic SphereCollider2D Trigger OnTriggerStay Script executed each 120 frames amp a Coroutine to simulate OnTriggerExit. Objects Rigidbody2D Kinematic SphereCollider2D Trigger Solution 3 AI No RigidBody SphereCollider2D Trigger Cone of Rays executed each 2 second to detect colliders at certain layers. Objects No RigidBody SphereCollider2D Trigger EDIT In solution 1 and 2, all AI have an quot eyes quot children GameObject with a TriggerCircleCollider2D and no RigidBody2D, to detect near AIs and GroundObjects.
|
0 |
Client side prediction buffer size considerations for jitter I am currently having a FPS game with client side prediction. Every 20ms, the client sends it's input to the server. The server buffers 5 ticks worth of input (100ms) and starts consuming the inputs each tick and sends a world snapshot to the client. The client then validates the predictions and corrects the simulations if there is a misprediction. The setup works fine under ideal network conditions. However when the latency suddenly spikes from say 50ms to 400ms, the client's tick packet is delayed which causes the server to eat through all of the available inputs in the buffer and resort to using the previous tick values to perform server simulation. When the client input finally arrives at the server late, the server discards the input because it has already processed the input for that particular tick (using old input values). How do I handle this edge case of latency increasing and decreasing? Sure I could use a larger buffer size for the inputs, but that will cause delays between client state and server state. Using a smaller buffer will cause the server to stall from inputs if there is a jitter that is more than the duration required by the server to process the inputs. I was under an impression that I would need some kind of dynamic buffer size that expands and contracts. However, I am out of ideas to implement something like this. Does anyone have a solution?
|
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.
|
0 |
Make UI Button Image Size Independent of Screen size Unity I have two UI Buttons with image sprites in Panel (inside canvas). I have set their sizes to 40 in the inspector. If I run game in maximize mode, buttons retain constant assigned size of the inspector, instead of adjusting themselves with screen size. I have already added Canvas Scalar component with value Scale with Screen Size. Text fonts are able to adjust with screen size present in same canvas, but button with image does not. Any guide on this? Thanks.
|
0 |
Character not collecting animated coins I am trying to make a simple game where the player jumps and collects animated coins. After collecting all the coins, the scene is supposed to change. For some reason, my character collects the coins but the scene doesn't change. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class Coins MonoBehaviour SerializeField private string newLevel public int coinAmount int coins void OnTriggerEnter2D(Collider2D other) if (other.CompareTag("Player")) coins 1 Destroy(gameObject) addCoins() void addCoins() coins if (coins coinAmount) SceneManager.LoadScene(newLevel) This is a screenshot of the game
|
0 |
Creating a planet out of an existing terrain I am creating a game that I have created a terrain for. I really like the terrain so I am wanting to keep it but I want to have the game take place on a full planet. Avoiding paying 200 for an asset already made, how would I develop something to allow me to "tile" this terrain to make a full planet and to make it round instead of flat? I know this has to be somewhat possible with the expensive assets on the asset store that are for round terrains. I just need to figure out how and I can't find anything online that is much help.
|
0 |
Efficient way to implement a lot of singletons I just came upon programming patterns and learned about singleton. I'm in the process of creating my first game and it contains several managers I wanted to implement singleton on each of the managers,but the only way I can think is copy pasting the singleton pattern on each awake method script attached to each manager. Is there a more efficient way to do it rather than pasting the pattern on each awake method?
|
0 |
Unity Rigidbody2D to act on certain gameobject only I am creating a 2D game and the player object has a rigidbody2D attached to it. The game works fine until the player collides with a power up. The rigidbody physics get all messed up. So I was wondering is there a way so that rigidbody will only act on enemies and be disabled for power ups?
|
0 |
Understanding Physics Materials I have been reading the documentation about Physics materials, and it really seems very incomplete to me. When I try to work with it, I get so many questions... Maybe can someone help me wrap my head around how it works? Why is there a physics material field for the Rigidbody2D, but also another in the BoxCollider2D? Do they work differently, depending on which you put it? What happens if you put different materials, one on the RB and one in the collider with different settings? If a player is standing in a platform, and you want it to bounce, or slide... do you set that on the player? Or in the platform? Update As suggested in the comments, I did some experimenting and this is what I saw When I put contradicting materials in the RigidBody2D and the Collider2D, the one in the collider seems to take precedence. Not sure what is the purpose of the one in the Rigidbody. If both are the same, well, they just behave like one of them alone. The value isn't added
|
0 |
How do I snap the Unity camera to a 2D, tile based map? I have a 2D, tile based map. I want to be able to control the number of visible tiles on the screen vertically and horizontally, regardless of resolution. I want the player to be able to move the camera one tile width at a time until it hits the edge. I do not understand how to manipulate the Unity camera in order to accomplish this. I have read the documentation, and Googled, but there is just something that is not clicking for me. So, let's say I have a 100x100 map. A 32x24 portion of the map is shown at a resolution of 1024x768, each tile has a size of 1x1 Unity unit. The bottom left of the visible area of the map starts at the bottom left of the map (0, 0). The player then clicks the right arrow key and the map moves one tile to the right (1, 0). How do I accomplish this, given that I am using the latest version of Unity in 2D mode?
|
0 |
Unity Adding more functionality to a List Inspector Let's say I have the following code public List lt Armor gt armors new List lt Armor gt new Armor() name "Black set", folder "black set" , new Armor() name "Conquistador", folder "conquistador" , new Armor() name "Crusader", folder "crusader" , new Armor() name "Gothic Plate", folder "gothic plate" , new Armor() name "K.D.", folder "kd" , new Armor() name "Lorica segmentata", folder "lorica segmentata" , new Armor() name "Rusty", folder "rusty" , new Armor() name "Spartan", folder "spartan" This appears in the editor like this While this is acceptable, there are a couple features I am missing Lets take for instance the Sorting Layer list Here there are 2 features that I would like The ability to reorder elements on the editor The ability to add more elements using or Is there any way to add this functionality into my List?
|
0 |
Scale one object to be cover multiple other objects I have placed and aligned several objects next to each other. For the sake of understanding, lets just say I placed 10 cubes next to each other. I snapped them all together (Move V Click amp Drag). The cubes look great so far. Now I want to make a plane in front of the cubes, that has exactly the width of the cubes altogether. Now, I can place a new plane in front of the, no problem. I can snap a single edge to the cube on the most right, also no problem. But now, how can I make the size exactly the same as all the cubes together? Sure, I could eyeball it from top view, an kind of make it about the same size, but chances are, it's a little bit too short or too long. Isn't there a possibility to snap one edge, lock it, and snap another edge making the object scale automatically to the desired width?
|
0 |
How do I move an object towards a moving object? I am trying to make an AI that tries to move towards the player but I don't know how. I tried using Vector2.MoveTowards() but it just mimics my movements instead of moving towards the player. I tried everything i could think of (which was not a lot D) but i couldn't make it move towards and touch the player! Help please D. Also my original code pragma strict var speed float 100 var targetX Transform var targetY Transform var mex Transform var meY Transdorm function Update () var targetX transform.position.x var targetY transform.position.y var meX transform.position.x var meY transform.position.y Vector2.MoveTowards(Vector2(meX, meY), Vector2(targetX, targetY), speed)
|
0 |
How do you deal with transparent fonts that you want to be white? I'm a bit of a total amateur, but I thought I would learn how to make a simple game during quarantine. However, I stumbled into a problem with fonts. I'm thinking about using the free font quot Pixelmania quot to show a score at the top of the screen. But the font is transparent! How do I make the inner part of the font white? Do I have to manually edit the font file myself? Or is there an easier way?
|
0 |
I added a terrain in Unity, but can't see it In Unity I added a terrain through Create rarr 3D Object rarr Terrain. It didn't show up and I can't see it. I tried to press F to focus on it, but I still don't see it. What am I doing wrong? Here is a screenshot
|
0 |
Can't rotate object after using transform.forward I'm using above code to rotate object pointing where it moves transform.forward m Rigidbody.velocity It works fine, however the problem is that I can't rotate this object anymore after set direction. transform.forward m Rigidbody.velocity transform.Rotate(0, 0, m RotateSpeed Time.deltaTime 500) Not Working Code is simple, first rotate the object to point where it goes and then rotate z axis. But when I ran the game, it just shaking little bit and didn't rotate at all. Why it doesn't work even rotating code after the transform.forward? Any advice will very appreciate it.
|
0 |
Why are these unity UI buttons only responding to the top half? I'm instantiating UI objects with buttons on them into a scrollrect. For some reason, all of the buttons will ignore their bottom half with the exception of the last prefab instantiated. Below is a gif to show the problem. I have it set to turn red when the button is highlighted. When the mouse isn't in a highlight position clicking will do nothing so I know it's not just a highlighting issue. Here is the code that I'm using to instantiate the scene. Instantiate the parent UI MyLoadGUI (GameObject)Instantiate(LoadGUI) Get the RectTransform of the scroll rect so I can add each level to the right thing. RectTransform rt MyLoadGUI.GetComponentsInChildren lt RectTransform gt () RectTransform myRt new RectTransform() for (int i 0 i lt rt.Length i ) if (rt i .name "Scroll Panel") myRt rt i break We're going to make 6 fake levels int levelCount 6 int levelSize 88 How tall the levels are int height Mathf.Max(levelSize levelCount, 252) myRt.sizeDelta new Vector2(myRt.sizeDelta.x, height) myRt.anchoredPosition new Vector2(myRt.anchoredPosition.x, height) for (int i 0 i lt levelCount i ) GameObject lsl (GameObject)Instantiate(LoadSingleGUI) RectTransform rect lsl.GetComponent lt RectTransform gt () rect.SetParent(myRt, false) rect.anchoredPosition new Vector2(0, 37 (i levelSize)) Fill in fake details. Doesn't run anything related to the button. lsl.GetComponent lt LoadLevelBar gt ().BuildRandom() So, nothing that should be affecting the button that I can see. I thought that the button was getting resized, but when checking in the scene the button is stretched all the way across the prefab. Any ideas why the button isn't working properly?
|
0 |
Unity Movement Questions I have recently been trying to learn how to make Unity games through Lynda.com using the tutorials provided by Jesse Freeman. But I have one issue, he doesn't explain any of the coding. This bit has me confused. Body2D.AddForce (new Vector2 (forceX, forceY)) 1.) Why is Body2D (this is a variable) separated by AddForce with a .? 2.) Why does a new vector2 have to be created? 3.) My last question isn't quite in the code itself but why must we add a () to methods? (Full Code) using System.Collections using System.Collections.Generic using UnityEngine public class Player MonoBehaviour public float Speed 2.5f public Vector2 MaxVelocity new Vector2 (5, 10) private Rigidbody2D Body2D private SpriteRenderer Renderer2D Use this for initialization void Start () Body2D GetComponent lt Rigidbody2D gt () Renderer2D GetComponent lt SpriteRenderer gt () Update is called once per frame void Update () var absValX Mathf.Abs (Body2D.velocity.x) var forceX 0f var forceY 0f if (Input.GetKey("right")) if (absValX lt MaxVelocity.x) forceX Speed else if (Input.GetKey("left")) if (absValX lt MaxVelocity.x) forceX Speed Body2D.AddForce (new Vector2 (forceX, forceY))
|
0 |
Call code on interrupting Unity animator sub FSM I'm trying to find a way to execute a code when one of two outcomes happens in Unity animator controller When animator's sub FSM finishes or When animator's sub FSM is "interrupted" by a transition originating from "Any state" node at the parent FSM. The concrete setup is next (but that is probably not super important) The parent FSM have a transition from "Any state" to Damaged state and that can "interrupt" an attack sub FSM Parent FSM The attack sub FSM consists of three states that run in succession PreAttack Attack PostAttack Attack sub FSM At the end of the attack sub FSM a method is called. It can be through Animation even at the end of PostAttack animation in the sub FSM, or StateMachineBehaviour.OnStateExit() at the PostAttack state , or StateMachineBehaviour.OnStateMachineExit() at the sub FSM. The problem is that none of these 3 is called when the sub FSM is "interrupted" by the "Any state" transition in the parent. Is there any way to call code when a sub FSM is "interrupted" by "Any state" transition in the parent FSM?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.