_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 |
Pixel Animation is tearing in Unity I am working on a 2D game and I have created a simple sprite sheet. The sprite sheet represents a medkit. The size of the sprite sheet is 128x16 pixels with 8 different frames that animate the medkit bobbing up and down. I have imported the sprite sheet into Unity as a Sprite with Sprite Mode set to multiple, Generate Mip Maps unchecked, Filter Mode set to Point, and Format set to Truecolor. I have sliced the sprite sheet using the Unity Sprite Editor and added the animation to my scene. After doing so, I am able to see my sprite in my game. However I noticed that the animation of the sprite did not correspond to the sprite sheet. Some pixels seem to be distorted and tearing. I have searched online and couldn't find anyone with the issue I had. As you can see from the gif below, the top of the sprite is tearing. Does anyone know what is causing this issue? Gif of the issue here Sprite sheet used
|
0 |
Unity strange performance impact with moving objects I'm trying to find the solution for 46 hours now and I'd be really happy if someone knows it! I'm using a DOTween library for moving the objects. I also use LeanTween, cause I heard it's faster but none of these work for me in this case. I've used tweening libraries alot, but never faced an issue like this. The bug appeared in my project, so to check it I created a blank one. An empty scene, with a camera and one cube with scale 10,2,10 . Now, I've added a simple script Sequence sequence DOTween.Sequence() sequence.Insert(0f, transform.DOMove(transform.position new Vector3(10f,0f,0f),1f)).SetEase(Ease.Linear) sequence.Insert(1f, transform.DOMove(homePosition,1f)).SetEase(Ease.Linear) sequence.SetDelay(1f) sequence.SetLoops( 1) The script moves the cube continously by 10 units to the right, and back (both in 1 second). There's a noticable jitter. This jitter is strange, cause it does not happen contantly. It choses a time and just freezes the cube in place for a really tiny amount of time which is noticable when you see a smoothly moving object and it freezes for a moment. As you can see, there's a linear interpolation, but I've tried with many (it's even better visible with other interplation types). Now. The profiler is not the case, cause I've tested it on the empty project with one object on the scene. Things I've already tried Turning off occlusion culling Turning off everything I could All the combinations of quality settings LeanTween instead of DoTween The one thing I came up with is the profiler's WaitForTargetFramerate. By definition, when WFTF is huge it means that the app is doing well, cause it finished it's work and waits for the next frame. In my opinion in this case it's the reason of the bug. I have a screenshot of the profiler window (with one cube, one directional light and this script attached to a cube) Now, I'm not 100 sure, but I think that this jitter may happen on these V Sync drops on the screen. Everything is tested on the PC. On Android there's the same thing (a noticable jitter), but I didn't run the profiler. If someone has any idea what may be the cause of this I'd be grateful. I'll put a bounty here as soon as I can, cause I'm really tired! ) DMGregory This is before the 'jump' on the GPU chart and that's on the 'jump' There's no RigidBody or Collider, but on my main project there are box colliders on these floors. I've also tried adding RB with the Interpolation checked. No difference. Josh Hamilton Even if this is a normal behavior, that the frame completed faster there are games on Google Play and AppleStore without any glitches like this. In my main project (where I discovered the issue) the biggest problem is that this lag is happening when I move the camera to follow the player smoothly and the freeze it noticable like anywhere else. Like the entire enviroment was freezing for 1 3 frames.
|
0 |
GraphView Dragging a Blackboard causes it to get stuck offscreen I'm playing around with learning GraphView, and running into some strange problems with the Blackboard component. Here's a very simple repro using UnityEditor.Experimental.GraphView using UnityEngine.UIElements public class MyGraphView GraphView public override Blackboard GetBlackboard() var result new Blackboard(this) COMMENTED OUT BLOCK 1 var c result.capabilities result.capabilities c amp Capabilities.Movable COMMENTED OUT BLOCK 2 result.RegisterCallback lt MouseDownEvent gt (OnMouseDown) result.RegisterCallback lt MouseUpEvent gt (OnMouseUp) result.RegisterCallback lt MouseMoveEvent gt (OnMouseMove) return result public override void ReleaseBlackboard(Blackboard toRelease) toRelease.RemoveFromHierarchy() COMMENTED OUT BLOCK 3 toRelease.UnregisterCallback lt MouseDownEvent gt (OnMouseDown) toRelease.UnregisterCallback lt MouseUpEvent gt (OnMouseUp) toRelease.UnregisterCallback lt MouseMoveEvent gt (OnMouseMove) private static void OnMouseDown(MouseDownEvent e) e.StopImmediatePropagation() private static void OnMouseUp(MouseUpEvent e) e.StopImmediatePropagation() private static void OnMouseMove(MouseMoveEvent e) e.StopImmediatePropagation() using System.Collections.Generic using System.Linq using UnityEditor public class MyGraphEditor GraphViewEditorWindow protected MyGraphView view public override IEnumerable lt GraphView gt graphViews get yield return view private void OnEnable() view new MyGraphView() this.rootVisualElement.Add( view) view.style.height new StyleLength(new Length(100, LengthUnit.Percent)) MenuItem( quot Tools Graph Editor Test quot ) public static void ShowWindow() var graphViewWindow CreateInstance lt MyGraphEditor gt () var graphView graphViewWindow.graphViews.FirstOrDefault() if (graphView ! null) var blackboard graphView.GetBlackboard() graphView.AddElement(blackboard) graphViewWindow.Show() Clicking the new menu item causes the window to open, just a blank editor window with a blank Blackboard. Clicking on the title bar of the Blackboard and attempting to drag it, though, causes it to immediately disappear. Checking in the UIElements Debugger shows that this is because it's somehow gotten its World Bound Y set to 79, so it's disappeared off the top of the window. A bit of checking in the reference source suggests that if the Blackboard was not Movable, it couldn't be dragged around. Not ideal, but a temporary workaround at least. But if you uncomment the code that sets this up, (commented out block 1,) it breaks the editor entirely clicking on the Blackboard causes Unity to stop responding to mouse clicks. Attempting to minimize the damage with the other two commented out blocks has no effect. Anyone have any idea what's going wrong here and how to fix it? What do I need to do to have a Blackboard that can be dragged around properly?
|
0 |
How do I hide the camera object in Unity Editor I have 2019 Unity Editor I have a huge camera object that is blocking all the other objects that I need to move in the scene, I want to hide this object, but I cannot find a hide show menu item anywhere or when I right click on the hierarchy
|
0 |
How can I fix problems caused by "ForceMode2D.Force"? I'm making a 2D platformer with Unity. I used transform.position for movement but it caused some problems like vibration, so I decided to use AddForce.ForceMode2D.Force instead. Since this uses mass for moving the player, it makes the player either so heavy and hard to control (even when the mass is 1) or so quick and fast. I tried changing the mass and speed but I haven't found the setting that makes a smooth movement. Also, the jumping has a problem. The player will be suspended in the air for a few seconds after the jumping. I'm just looking for a way to make AddForcesmoother and solve these problems. Here's my code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.InputSystem public class PlayerController MonoBehaviour SerializeField private float jumpSpeed public float maxSpeed 5f public float maxAcceleration 50f public float maxDeceleration 100f SerializeField private LayerMask ground private PlayerActionControls playerActionControls private Rigidbody2D rb private PolygonCollider2D pol private Animator animator private Vector2 movementInput private void Awake() playerActionControls new PlayerActionControls() rb GetComponent lt Rigidbody2D gt () pol GetComponent lt PolygonCollider2D gt () animator GetComponent lt Animator gt () private void OnEnable() playerActionControls.Enable() private void OnDisable() playerActionControls.Disable() void Start() playerActionControls.Land.Jump.performed ctx gt Jump(ctx.ReadValue lt float gt ()) private void Jump(float val) if (val 1 amp amp IsGrounded()) rb.AddForce(new Vector2(0, jumpSpeed), ForceMode2D.Impulse) private bool IsGrounded() Vector2 topLeftPoint transform.position topLeftPoint.x pol.bounds.extents.x topLeftPoint.y pol.bounds.extents.y Vector2 bottomRightPoint transform.position bottomRightPoint.x pol.bounds.extents.x bottomRightPoint.y pol.bounds.extents.y return Physics2D.OverlapArea(topLeftPoint, bottomRightPoint, ground) void FixedUpdate() Vector2 movementInput playerActionControls.Land.Move.ReadValue lt Vector2 gt () movementInput Vector2.ClampMagnitude(movementInput, 1f) Vector2 desiredVelocity movementInput maxSpeed AccelerateTo(desiredVelocity) var scale transform.localScale if(scale.x rb.velocity.x lt 0) scale.x 1 transform.localScale scale void AccelerateTo(Vector2 DesiredVelocity) var deltaV desiredVelocity rb.velocity var acceleration deltaV Time.deltaTime float limit maxAcceleration if (Vector3.Dot(rb.velocity, desiredVelocity) lt 0f) limit maxDeceleration acceleration Vector2.ClampMagnitude(acceleration, limit) Vector2 force rb.mass acceleration rb.AddForce(force)
|
0 |
Angle between two points I have a character who walks to random points in my room in Unity. The problem is he always faces one direction, I want to write in C a piece of code that will get the direction the character is currently facing and the position of the target, then works out the angle between them to turn the character that amount. I have tried the LookAt function but that makes the character walk in an arc shape towards the target which looks very unnatural as it constantly looks at the target.
|
0 |
Moving large group of units 1 by 1 takes too long, how can I improve this? I use use Unity's own NavMesh AI system and I think it works pretty well. The only problem I have is that when I move large groups of units, they will find a path one by one, but it takes a really long time as you can see in the video https gfycat.com blankhalfdartfrog To set destinations I use this public bool SetDestination(Vector3 point) if (SamplePosition(point)) agent.SetDestination(point) return true return false I know I could wait until they all have pathPending false, but that would mean the entire group moves with a huge delay. Is there some way I can improve or fix this issue? Edit It is quite simple to recreate (if you have some basic knowledge on Unity NavMesh) simply create a "click to move" script that moves a List of units to where you clicked using the code above (just fill the list in Start on each unit). Put down a few obstacles and you're done.
|
0 |
My bullets won't bounce in Unity? I wanted bullets to bounce when they hit walls. However when colliding with a wall, they just jitter about on them. I didn't want to create a new physics material as I want to keep the ball moving at a constant speed and to have them destroy themselves after they have bounced once. Thus, I wrote everything in Code. The constraints for the bullet rigidbody's freezing position is the Y axis while the freezing rotation is X, Y, and Z axis. I also wondered if the initial position the instantiated bullet also had something to do with the speed the bullet travels GameObject bulletObject Instantiate(bulletPrefab) bulletObject.transform.position transform.position (transform.forward 1) Here's the minimum reproducible code using System.Collections using System.Collections.Generic using UnityEngine public class bulletMovement MonoBehaviour private Rigidbody bulletRB private Vector3 lastVelocity, initialVelocity public float bulletSpeed 10f private int bounceCount Start is called before the first frame update private void Start() bulletRB GetComponent lt Rigidbody gt () bounceCount 0 bulletRB.AddForce((transform.forward 1) bulletSpeed) void Update() lastVelocity bulletRB.velocity Update is called once per frame private void OnCollisionEnter(Collision col) if (col.collider.tag quot Walls quot ) bounceCount 1 if (bounceCount lt 2) Bounce(col.contacts 0 .normal) else Destroy(gameObject) private void Bounce(Vector3 normal) var speed lastVelocity.magnitude var direction Vector3.Reflect(lastVelocity.normalized, normal) Debug.Log( quot Out Direction quot direction) bulletRB.velocity direction Mathf.Max(speed, bulletSpeed) lastVelocity bulletRB.velocity is required to be in Update or else the bullet won't move at all.
|
0 |
CrossPlatformInput Prefabs Button handler to move? I am currently trying to put two buttons on my UI that move a character left and right if touched down (Held). I would like to use the cross platform input, and would like the buttons to change the value of the Horizontal axis as my "A" and "D" keys would... And my code for moving my character is as follows private void Update() isGrounded Physics2D.OverlapCircle(groundChecker.position, .15f, groundLayer) float move CrossPlatformInputManager.GetAxis("Horizontal") moveSpeed playerRB.velocity new Vector2(move, playerRB.velocity.y)
|
0 |
SVG textures for 3D game objects in Unity? Is there a way to make textures using vector graphics and use it for 3d models so that textures would be object size independent and won't get blurry?
|
0 |
pause function for x amount of time I've read up on several ways of doing this but can't seem to find one that works for what I need. I have a method that is called and performs some logic, and then I need it to wait for a period of time, then continue with more logic in the same function. I had planned on using a coroutine which is what I did with another part of the game, but I'm running into an issue because the class doesn't directly inherit from Monobehaviour so it can't start a coroutine. I've tried Thread.sleep, but that just makes the game stop, so that isn't what I want. I don't know if there is some way to put a timer in there that will wait and then continue the function or if there is something else that I'm overlooking. Here is the current code public void AssaultRifleShot (GameObject mainBall) if (AmmoRemaining gt 0) if there is ammo remaining, set the main ball to just a normal ball so it can be destroyed on impact and then start coroutine mainBall.GetComponent lt Ball gt ().mainBall false mainBall.GetComponent lt Ball gt ().onBallHitPaddle AssaultRifleShot unsubscribe to event when mainBall is set to false. StartCoroutine(timer, coroutineHost) AmmoRemaining 1 else DestroyPickUp() There are other method calls inside the code for the coroutine, so those would end up going after whatever timer or someting goes in instead of the coroutine.
|
0 |
How does unity size graphics? I'm working on a 2D game. It has tiles. each tile is 50x50 px. I attached script to camera which sets the camera size to screenHeight 2 PixelsPerUnit. Now in the player, as an example i selected 480x320 size. I expected it to show approx 9x6 tiles. However it shows 6tiles horizontally and 4 tiles vertically. Similarly for other sizes, it shows lesser than calculated number of tiles. How does this corelate? Edit i created the tiles in photoshop with 300 dpi. Not sure if that affects anything though.
|
0 |
Footstepper with Vr Unity I have the Footstepper Complete Footstep Solution from the unity store, and i dont get it working with the Vr, I made the footstep material like official documentation said, Then i put the Footstepper Setup in the ovrPlayer object. The problem is that sometimes sound the default fallback, so i think that the colission is not detected as it suppose. Some idea ?
|
0 |
Unity Post process foreground, but leave background as is I am using Unity 2019.3.5f1 and I am using the Universal Render Pipeline (URP). I am trying to use the post processing in URP for the foreground only (in my case, the players), and I want the leave the background (which in my case, is just a quad with a texture), as is. I have tried using the Camera Stack but it wont work for me because the overlay camera can't have post processing effects according to the documentation. The only solution that I could come up with is create the some sort of custom render which Render the background to buffer A. Render the foreground to buffer B, and save the depth. Combine the two using a shader that gets both textures, and the depth texture, and based on the depth, takes buffer A or buffer B. The problem with this I believe is that I cant use it with the post processing for Unity. Any idea what I can do? EDIT I tried another thing in Unity which seem to not be working (might be a bug) I created 3 cameras Foreground Camera, Depth Camera (only render the foreground), and a Background Camera. I set up the Depth camera so it will render to a render texture and, indeed now I have a render texture with the proper depth I need. Now, from here everything went wrong, there seem to be odd things happening when using Unity new Post processing (the built in one) The Foreground Camera is set to Tag MainCamera, and when I enable Post Processing and add an effect, indeed we can see it. (as expected) The Background Camera is essentially a duplicate of the Foreground one, but with Tag Untagged, I use the same options (enabled Post). Now, the expected thing is we see the Background Camera with effects like Foreground, but no When using Volume Mask on my background layer, the Post processing just turns off, no effect at all no matter what (and I have set my background the Background layer). When I disable the Foreground Camera (or remove its tag) and set the Background Camera to MainCamera, still nothing changes, the post still wont work. When I set Volume Mask to Default (or everything), the result is shown ONLY in the scene view, I tried rendering the camera to a RenderTexture but still, you clearly see no effect applied!
|
0 |
Backface culling in Unity I am a Unity noob trying to recreate something I did a long time ago in raw OpenGL. I draw a scene normally glCullFace(GL BACK), and then draw the walls a second time with face culling flipped glCullFace(GL BACK) and a semi transparent alpha to everything. So my question is how to achieve this in Unity? Can I basically set up Unity to draw the scene twice, the second time with the new culling mode, a global alpha and perhaps only drawing meshes that are children of node with a particular tag? Or is there some better or other way to achieve this affect?
|
0 |
How do I create a HUD that appears to occupy 3D space can animate? I'm working with a group to try and make a first person space platformer in Unity, and was wondering if there would be anyway to create a HUD that moves and reacts to player actions, specifically looking around similar to the way the HUD moves in Metroid Prime. I'd also like it appear projected onto the inside of a helmet. I'm not entirely sure what best practice would be in this situation. Should we just attach the GUI elements to transparent objects in 3D space, then parent them to the main camera, essentially building our HUD with actual objects or is there another way that would be more efficient? I'm still very new to game development, but this is something we'd really like to have in our game if at all possible.
|
0 |
Is it possible to use one if statement for each level scene? I'm working on a platform game where you as a player have to collect logs, to keep on all the fires in the level. Each campfire has a timer, which ensures that every x number of seconds the animation of the fire is changed to a numb fire. The timer of a campfire is blocked by the script, when the player has received the fire at 100 . When all fires are 100 you won, if not you lose. Know I use the following if statement to check if the player has won or lose if (Application.loadedLevelName "Level 0") if (campfireAmount allCampfireFull) Do something print ("level 1 complete") Application.LoadLevel (6) if (campfireAmount allCampfireEmpty) Do something print ("level 1 failed") Application.LoadLevel ("GameOver") What I searching for is how I can make this if statement useful for each level, whiteout use for each level scene above if statement. Beside that, what I want is that after each level you get a win scene (if possible a reusable scene) and after clicking in that scene on a button, you should go to the next level scene. Is there a way to load the next level, whiteout set a hard number of the rang list of "Build Settings"?
|
0 |
Is Time.deltaTime framerate dependent? I have a game that calculates your score via Time.deltaTime (the more time the more score). On my PC I get about 1200 points if I just idle the game while on my phone I only get about 400 points. I believe my code must be FPS dependant and that's why my phone is getting a lower score for the same time. Here's the code void Update () time Time.deltaTime score (int)time timerLabel.text score.ToString() Sorry if it's something very obvious. I'm quite new at c . Can't seem to get the solution to work. It just stays at 0 Full Code using UnityEngine using UnityEngine.UI using System.Collections using UnityEngine.SceneManagement public class EndGame MonoBehaviour public Text textWin public Text timerLabel public GameObject retryButton public GameObject points private Vector3 offset private float time private float score void OnTriggerEnter (Collider col) if (col.gameObject.name "Player") setWinText () retryButton.SetActive (true) points.SetActive (false) void setWinText () textWin.text "Final score " score.ToString() void Update () time Time.deltaTime if (time gt 1.0f) score score 1.0f timerLabel.text score.ToString()
|
0 |
Stormy water like Temple Run 2 for Mobile How can I make stormy water like they did in Temple Run 2. I've tried with Unity Water Pro to achieve the same result but when I include it in the project the frame rate crashes to 3 frames per second. Unity Water basic doesn't fulfill the requirements at all. So is there any other way?
|
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 |
Unity WebPlayer WWW GET Requests fail in webplayer only, not in editor My question is about my game requesting data from my server side cloud based storage (I have the option of free public Dropbox or Amazon S3) via GET and the WWW class, and it not working only in the WebPlayer (works fine in the Editor). By not working, I mean that the request is sent successfully, authorized and responded to by the cloud service, but that WWW shows an error in the logs. In the case of using Amazon S3, the Web Player even crashes, otherwise it just fails gracefully and the user is unable to move forward. The Error log left by the webplayer says the following WWW Error Error when creating request. GET request with custom headers is not supported. for URL https my storage.s3.amazonaws.com myDir myFile.json Here's when I use a similar request to a public directory on Dropbox. There is no crash, but the request also fails. WWW Error Failed downloading dl.dropboxusercontent.com u 7782207 spare change weapons 0.json for URL dl.dropboxusercontent.com u 7782207 spare change weapons 0.json Try it for yourself http webroleplay.appspot.com (currently using Dropbox, so not crashing the player) username test1 password t
|
0 |
Separating part of mesh facing upwards I really hope you can help me fix this code List lt Vector3 gt verticesToExport new List lt Vector3 gt () vertices of the triangles facing upwards. List lt int gt trianglesToExport new List lt int gt () new triangle facing upwards. meshToCut is the original mesh, then I just try to replace it with the new data. int triangles meshToCut.triangles Vector3 vertices meshToCut.vertices for (int i 0 i lt triangles.Length i 3) Vector3 corner vertices triangles i Vector3 a vertices triangles i 1 corner Vector3 b vertices triangles i 2 corner float projection Vector3.Dot(Vector3.Cross(b, a), Vector3.down) if (projection gt 0f) verticesToExport.Add(vertices triangles i ) verticesToExport.Add(vertices triangles i 1 ) verticesToExport.Add(vertices triangles i 2 ) trianglesToExport.Add(triangles i ) trianglesToExport.Add(triangles i 1 ) trianglesToExport.Add(triangles i 2 ) meshToCut.SetVertices(verticesToExport) meshToCut.SetTriangles(trianglesToExport, 0) probably I'm doing wrong here! It works great by retrieving the vertices facing up, and I guess the triangles too but when I put it into a mesh filter I believe the triangles are not in order... 1.The model I'm trying to separate the triangles facing upwards. 2. This is what happens if I just take the vertices and triangulate them again. It proves that vertices are alright! 3. The result I get from the code above
|
0 |
How do I share a downloadable WebGL build in Unity? When I make a WebGL build for my project, I get a folder that lets me click a .html to play my game in a browser. Is there a way I can share a folder like this for playtesters? I tried sending a .zip folder to playtesters, but they only got a Unity loading screen that didn't do anything.
|
0 |
Response to form triggers creation of zero or more duplicate scenes I've got two scenes, one with room 1 and one with room 2. In room 1 I've got one table with two 3D assets on top of it. This room also has a door that connects to room 2 through a door but it's closed. Once going near the 3D assets a dialog pops up saying to click "E". This pops up a 2D form one needs to fill. Only after filling both forms I'm able to go into room 2. Now what I would like to do is, depending on the response in the form, one or more duplicate room 2 scenes should be created and dynamically added to the scene. If with scenes isn't possible, what's the way to do such thing? Know about SceneManager.CreateScene but this creates an empty scene, not exactly what I want to.
|
0 |
Why occlusion culling isn't working? I've bought a 3d model from a 3d marketplace. It is a big interior scene. I've imported the single FBX into Unity, added some collider, changed materials (6 7 materials) etc. There are hundreds of child object mesh Despite what my camera is looking, i noticed Unity is rendering 3 400K tris. Why Occlusion Culling isn't working ? Maybe importing a single huge Fbx isn't the right practice ? Thanks This image is my player looking at a black wall... 360K tris rendered !!!!
|
0 |
Why does 'InvalidCastException Specified cast is not valid.' occur for ARKitFaceSubsystem? Why does 'InvalidCastException Specified cast is not valid.' occur for ARKitFaceSubsystem in the snippet below? var faceManager FindObjectOfType lt ARFaceManager gt () if (faceManager ! null) m ARKitFaceSubsystem (ARKitFaceSubsystem)faceManager.subsystem
|
0 |
Make players Rigibody move in direction its going? I have my snowboard character which I am trying to fix the movement for. At the moment, The player is using transform.forward on the rigidbody to move forward. If my player turns around and faces up the hill, it keeps going no matter what. I need a way that my player goes in the direction that the gravity is pushing it, This will also mean my player can ride switch. Also, My player is a capsule not a sphere so it doesnt roll around. I have tried playing around with rigidbody.velocity but nothing seems to want to work. if(Input.GetButton("Jump")) transform.localPosition transform.forward Time.deltaTime force force is the speed of the character This is also Javascript ( yes I know i should use C I'm learning it currently)
|
0 |
A field initializer cannot reference the non static field, method, or property 'CinemachineFreeLook.Variable' engine unity coding language c I am trying to control CinemachineFreeLook maxSpeed from another script in the struct AxisStat public AxisState(float minValue, float maxValue, bool wrap, bool rangeLocked, float maxSpeed, float accelTime, float decelTime, string name, bool invert) It only accepts to type a number, but not a variable. Whenever I create a public float variable and place it in maxSpeed, it keeps sending the error error CS0236 A field initializer cannot reference the non static field, method, or property 'CinemachineFreeLook.rSpeed' Here is the default unity CinemachineFreeLook script code the added code which I declare a float variable quot rSpeed quot at the beginning and added my variable in the AxisStat maxSpeed public class CinemachineFreeLook CinemachineVirtualCameraBase public float rSpeed 300f lt summary gt Object for the camera children to look at (the aim target) lt summary gt Tooltip( quot Object for the camera children to look at (the aim target). quot ) NoSaveDuringPlay public Transform m LookAt null lt summary gt Object for the camera children wants to move with (the body target) lt summary gt Tooltip( quot Object for the camera children wants to move with (the body target). quot ) NoSaveDuringPlay public Transform m Follow null lt summary gt If enabled, this lens setting will apply to all three child rigs, otherwise the child rig lens settings will be used lt summary gt Tooltip( quot If enabled, this lens setting will apply to all three child rigs, otherwise the child rig lens settings will be used quot ) FormerlySerializedAs( quot m UseCommonLensSetting quot ) public bool m CommonLens true lt summary gt Specifies the lens properties of this Virtual Camera. This generally mirrors the Unity Camera's lens settings, and will be used to drive the Unity camera when the vcam is active lt summary gt FormerlySerializedAs( quot m LensAttributes quot ) Tooltip( quot Specifies the lens properties of this Virtual Camera. This generally mirrors the Unity Camera's lens settings, and will be used to drive the Unity camera when the vcam is active quot ) LensSettingsProperty public LensSettings m Lens LensSettings.Default lt summary gt Collection of parameters that influence how this virtual camera transitions from other virtual cameras lt summary gt public TransitionParams m Transitions lt summary gt Legacy support lt summary gt SerializeField HideInInspector FormerlySerializedAs( quot m BlendHint quot ) FormerlySerializedAs( quot m PositionBlending quot ) private BlendHint m LegacyBlendHint lt summary gt The Vertical axis. Value is 0..1. Chooses how to blend the child rigs lt summary gt Header( quot Axis Control quot ) Tooltip( quot The Vertical axis. Value is 0..1. Chooses how to blend the child rigs quot ) AxisStateProperty public AxisState m YAxis new AxisState(0, 1, false, true, 2f, 0.2f, 0.1f, quot Mouse Y quot , false) lt summary gt Controls how automatic recentering of the Y axis is accomplished lt summary gt Tooltip( quot Controls how automatic recentering of the Y axis is accomplished quot ) public AxisState.Recentering m YAxisRecentering new AxisState.Recentering(false, 1, 2) lt summary gt The Horizontal axis. Value is 180...180. This is passed on to the rigs' OrbitalTransposer component lt summary gt Tooltip( quot The Horizontal axis. Value is 180...180. This is passed on to the rigs' OrbitalTransposer component quot ) AxisStateProperty public AxisState m XAxis new AxisState( 180, 180, true, false, rSpeed, 0.1f, 0.1f, quot Mouse X quot , true)
|
0 |
How to implement 3d maneuver gear physics in unity? I am trying to create a attack on titan styled game for a school project. I am not new to programming, but I am new to game development. I couldn't find any resources for this, hence I am posting it here. How do I go about implementing 3d maneuver gear physics from attack on titan anime? What is it? In case you don't know, here's a brief link about 3d maneuver gear. A brief commentary about 3dMG It's basically a grappling hook based system (similar to what you would find in a spiderman game), but it has different components to it, which makes it quite complex to think about. My Approach so far I have seen tutorials on how to use hooks in unity and stuff, but it would be great if someone could give me a general idea as to how to even start with this kind of thing. I would appreciate your answer, even though it is not unity specific. The idea is to have two points on the character, from where we fire the ropes. These ropes could simply be graphics (or unity's RaycastHit). And then we would also need information about the hook "hit point". Once we know that, we just reel in ourselves towards that. However the problem is that I don't know how to use momentum etc to effect the character's movement. Also since it's not just one rope(like a spiderman's game), but two, it's even difficult to think as to how would the movement be if user uses only left hook, or right hook or both. Also there is this gas aspect, which would propel you further and it should also be taken into account, along with momentum that we would carry. So any general idea would be greatly appreciated.
|
0 |
How to rotate a whole Bezier Curve around a given point I am using the code from the question Adding functionality to make individual anchor points of bezier continuous or non continuous to create bezier curves (I added a line renderer). How can I rotate the whole bezier curve (which may contain multiple cubic B zier segments) around a point? Please note that the rotation point could be any point including the one of the curves anchor points or control points.
|
0 |
What is the most appropriate way to achieve synchronous Addressable asset loading? I am transitioning my project from Resources to Addressables. Some parts of my game just aren't worth doing asynchronously, and would just cause more problems but I still want to use Addressables for its other benefits. Anyway, it doesn't offer any synchronous methods in their API. Unity has an official repository with an example for "synchronous addressables" right here https github.com Unity Technologies Addressables Sample blob master Advanced Sync 20Addressables Assets SyncAddressables SyncAddressables.cs Although the code does appear to work in the few tests I've done The code below won't always work, and it doesn't make sense to me anyway. This is the relevant method public static TObject LoadAsset lt TObject gt (object key) if(!s Initialized) throw new Exception("Whoa there friend! We haven't init'd yet!") var op Addressables.LoadAssetAsync lt TObject gt (key) if(!op.IsDone) throw new Exception("Sync LoadAsset failed to load in a sync way! " key) if (op.Result null) var message "Sync LoadAsset has null result " key if (op.OperationException ! null) message " Exception " op.OperationException throw new Exception(message) return op.Result It will throw an exception if the asset didn't manage to load instantly (the !op.isDone part). Sure, that's technically synchronous, but it seems to ignore the elephant in the room if the asset is large I would expect it to need a bit more time (i.e. freeze the game), which is fine for my current needs but instead, the game will just end up crashing because it couldn't load immediately. What is the most appropriate way to achieve synchronous Addressable asset loading?
|
0 |
Unity3D Efficiently loading chunks in an infinite voxel engine I'm developing a voxel engine in C using Unity and I'm currently trying to implement infinite terrain, so I took a look at other Unity voxel engines that have infinite terrain. I've seen three different ways of doing it Using a dictionary to store the chunks and store the block data in another dictionary Using a dictionary to store the chunks and store the block data on every chunk Using a fixed size array and shifting it every time the player moves The engines using approach 1 and 2 were pretty slow at chunk loading. The engines using approach 3 were faster but produced lag every time the player entered a new chunk. I've already tried to implement it using approach 1, but my chunk loading speed got slower by about 10 times, so it was really unplayable. How is it done in efficient or popular voxel engines like Minecraft or VoxelFarm? Do you have experience with voxel rendering and know a better approach? Thanks in advance!
|
0 |
Lag in Destroy() method I have a script that destroys the player object when a collider with that script touches it. The thing is that, even if there is no time specified in the script, it takes couple seconds before it destroys the player. Why does this happen, and how do I get around it? public class DestroyScript MonoBehaviour public GameObject player void OnTriggerEnter(Collision otherObj) if (otherObj.gameObject.tag "Player") Destroy(player)
|
0 |
Generate random position within object I have a plate object which is generated somehow (I don't care how), now I want to put another object within this object on random position. Lets say that I want to put random trees on this plate. How can I achieve this in Unity. I had read for bounds but I don't know how to use it to generate position for the tree.
|
0 |
How do Idle games progress while not active? A hallmark of many idle games is the ability to still progress (or at least regain resources) while the game isn't active. The device can even be off. Initially I figured they just calculated progress off system time next time it was started, but they do not appear fooled by messing with the clock. How do they manage this specific feat?
|
0 |
Is coroutine as good as a delay() function I'm new to Unity and I was learning the usage of coroutines. Is calling a coroutine as good as a delay() function? Does Unity have a delay() function?
|
0 |
Unity Raycasting Error NullReferenceException EDIT I added the if statement if(hitInfo.collider ! null) above the if(hitInfo.collider.CompareTag( quot Player quot )) statement and it seems to work. I'm trying to give my Enemy AI (Red dude) a line of sight via Raycasting. I want it to initiate the Attack() function when it sees the Player (blue dude) whose tag is quot Player quot . I first need to get a quot true quot statement from the RaycastHit2D to write the rest but the game just crashes whenever the Player is out of the ray. When I put the player in range of the enemy model by hand before running the game, it runs okay But when I make something, like jumping, to stay out of the ray, the game crashes and I get the error NullReferenceException Object reference not set to an instance of an object. It shows the line 90 which corresponds to the line if(hitInfo.collider.CompareTag( quot Player quot )) Here is the whole code for my RaycastPlayerDetection() which is called in the Update() function private bool RaycastPlayerDetection() RaycastHit2D hitInfo Physics2D.Raycast(EyeSight.position, transform.right, lineOfSight) Debug.DrawLine(EyeSight.position, hitInfo.point, Color.red) if(hitInfo.collider.CompareTag( quot Player quot )) Debug.Log( quot player has been seen quot ) return true else return false
|
0 |
How can I make it so the baller ball does not keep moving after it bounces? I am pretty new to Unity so how I did it may not be the best way, but when the character jumps it is inconsistent. When I press the up arrow key really quickly and then stop the jump will be further than it is supposed to be and it starts to glide. I want all the jumps to be the same size and the player can't bounce again until it is on the ground. Also if I start playing to quickly within the first second or two the ball jumps really far but if I wait a couple seconds it bounce like normal. Here is my code using UnityEngine using System.Collections public class MovePlayer MonoBehaviour public float distance public float fspeed public float uspeed public float addToDistance bool jumping false PRIVATE private Rigidbody rigidBody void Awake() rigidBody GetComponent lt Rigidbody gt () rigidBody.freezeRotation true void FixedUpdate() if (!jumping) if (Input.GetButtonDown ("up")) rigidBody.AddForce (new Vector3 (0, uspeed, fspeed)) if (Input.GetButtonDown ("down")) rigidBody.AddForce (new Vector3 (0, uspeed, fspeed)) if (Input.GetButtonDown ("right")) rigidBody.AddForce (new Vector3 (fspeed, uspeed, 0)) if (Input.GetButtonDown ("left")) rigidBody.AddForce (new Vector3 ( fspeed, uspeed, 0)) void OnCollisionEnter(Collision other) if (other.gameObject.CompareTag("Ground")) jumping false void OnCollisionExit(Collision other) if (other.gameObject.CompareTag("Ground")) jumping true
|
0 |
How do I properly light characters in a Unity scene? I made a game prototype and want to improve some of rendering the visuals through light baking (which I'm new to). While I was mostly able to do this in my environiments, I'm having issues doing this for my characters in Unity. Previously, they came out with odd ish dark shadows in places as they were affected by light and dull colors. After I begin light baking though and adding Light probes in areas that my characters would be extremely light, especailly on the skin areas. It doesn't look good at all. Alternatively, without using light probes, it looks like this. I'm genuinely confused on how to properly light these characters if I can't get a middle ground of proper lighting. Can anyone help me try to understand this and solve this problem?
|
0 |
Rotate an object on itself, from one random Quaternion to another I have a situation I have a 3D object in the world. let's say a sphere. I have 2 random directionnal vector vector A, and vectorB My question is How to I rotate over time my object, from A to B ? The vector A is important I don't want to simply rotate the forward of the object from current forward to B. I know I can use the function vector3 C Vector3.SmoothDamp(...) in unity to lerp between my 2 vectors A amp B. but then ok, I have vector3 C, how do I apply the rotationof my object to C ? if don't want to do gameObject.transform.forward C I want something like gameObject.transform.rotation SomeQuaternion(C, initial rotation A). or something. Thank you for help ! PS I don't want to parent unparent gameObject or something like that, i want the math answer, using Quaternion.
|
0 |
Unity emission lighting I have created a scene with a blue sphere inside of a white room of planes. The room is being lit by a point light above the roof, and the sphere is emitting a blue light. How do I get the emission from the sphere to contribute to the lighting of the walls without making it static?
|
0 |
Switching between VR and Desktop (VR Controllers are not tracked in Unity Build) I am developing a VR App in Unity3D for HTC Vive Pro (Wireless) everything works well with VR in the usual way. (SteamVR Plugin 2.5.0 (SDK 1.8.19)) Except for some requirement reasons in the same Unity scene, I have to shutdown VR switch to Desktop mode and later at some point enable VR again. The moment, I enable it via script the VR display is ON, the HMD tracking works well but the Vive controllers are not tracked (position amp rotation), I can see the controller model rendered though in the last position when the VR was shut down but I can't get the updated tracking. The issue is only happening in the Unity Build. In the editor, it is working fine now after this change. To fix the issue in the Unity Editor I tried changing the SteamVR ActivateActionSetOnLoad method from Start() to OnEnable() as the error on re enabling was related to controller actions missing, that is now fixed cause of this change. e g private void OnEnable() if (actionSet ! null amp amp activateOnStart) Debug.Log(string.Format(" SteamVR Activating 0 action set.", actionSet.fullPath)) actionSet.Activate(forSources, 0, disableAllOtherActionSets) I am looking for a solution, to fix the issue in the Unity build? Any suggestions are highly appreciated.
|
0 |
Writing a glow shader I'm trying to learn writing shaders. And I've pieced together something that is kinda working. I want to create a transparent glow around a sphere. The problem I have is that I can't seem to alter the transparency of the glow. I tried experimenting with ZWrite off but that doesn't give me the desired results. The red part around the sphere is the glow. But I'm unable to change its alpha. I'd would also like to change the "blurriness" of the glow. How would I do that? EDIT so I did some more tinkering. I've changed the blending to Blend SrcAlpha OneMinusSrcAlpha and enabled ZWrite off. This allows me to change the alpha. The problem with this is that the inside of the object is also colored by the glow. I just want the glow around the circle. not inside. Shader "Custom HoleShader" Properties holeColor ("Color", Color) (1,1,1,1) glowColor ("Glow Color", Color) (1,1,1,1) glowSize ("Glow Size", Range (0.0,5)) 1.0 glowOpacity ("Glow Opacity", Range(0,1)) 1 SubShader Tags "LightMode" "ForwardBase" Pass CGPROGRAM pragma vertex vert pragma fragment frag uniform float4 holeColor uniform float4 glowColor struct appData float4 normal NORMAL float4 vertex POSITION struct v2f float4 pos SV POSITION float4 col COLOR v2f vert (appData v) v2f o o.pos mul(UNITY MATRIX MVP,v.vertex) return o float4 frag(v2f i) COLOR return holeColor ENDCG Tags "LightMode" "ForwardBase" "Queue" "Transparent" "RenderType" "Transparent" Pass ZWrite Off Blend One OneMinusSrcColor Blend SrcAlpha OneMinusSrcAlpha CGPROGRAM pragma vertex vert pragma fragment frag uniform float4 holeColor uniform float4 glowColor uniform float strength uniform float glowSize uniform float glowOpacity struct appData float4 normal NORMAL float4 vertex POSITION struct v2f float4 pos SV POSITION float4 col COLOR float3 viewDirection float3 normalDirection v2f vert (appData v) v2f o float4 pos v.vertex (v.normal glowSize) o.pos mul(UNITY MATRIX MVP,pos) return o float4 frag(v2f i) COLOR return float4( glowColor.rgb, glowOpacity) ENDCG
|
0 |
Add Existing Animation I have several animations that I am using on a GameObject. I switched the folder they were stored in, and they got detached from the gameObject. How can I add the existing animations to my gameObject without having to recreate them? I am not looking to do this programmatically. I just want to undo the damage I have done without having to start over. Ideally, I want a "Load Animation" option from the Animator window in the editor, but that does not appear to exist .
|
0 |
How can I implement UI in Unity using Chromium? I'm looking for an alternative to UI Builder. Ideally I'd like to have basically a Chromium instance atop Unity3D which would have its JS calls somehow land in the C (maybe in the quot Update quot loop it listens to a constant stream of potential calls and the parameters will correspond to function names in my Unity code, I don't know) here's what I found which doesn't quite live up to my expectations Unity WebView doesn't support Windows. 3D WebView for Windows and macOS (Web Browser) requires the UI to be served on an actual live URL and for Unity to access it via that URL and for all interaction to be handled via API, impractical or slow at best. PowerUI HTML CSS is interesting, but was made in 2011. The documentation is all gone. the support for css feature is probably incredibly slim. Embedded Browser looks pretty good, but I'm unsure that it could be bent into a UI system. I want it to frame my game, not to cover it. Coherent Gameface looks probably the best, although the CSS implementation seems a tad lackluster. Also this project was started in 2012, it's probably carrying very old, very slow code. This Unity forum thread may be relevant. Chromium Embedded Framework was a tool used by some assets on the asset store to create chromium UI but it has been removed. If not using these assets, how can I implement my idea of using Chromium as my UI layer?
|
0 |
Make enemy disappear after spawn I have enemies that spawn in different positions but what I want to do is that if you don't kill it after three seconds, the enemy disappears (but the spawning keeps happening of course, the enemy will show up again eventually). I tried using a coroutine but after reading the documentation and watching some tutorials I still don't understand very well how it works so I need some help. Thanks in advance. This is my code so far public class TimedSpawn MonoBehaviour public GameObject spawnee public bool stopSpawning public float spawnTime public float spawnDelay private GameManagerScript GMS void Start () GMS GameObject.Find ("GameManager").GetComponent lt GameManagerScript gt () InvokeRepeating ("SpawnObject", spawnTime, spawnDelay) public void SpawnObject () if (GMS.counterDownDone true) Instantiate (spawnee, transform.position, transform.rotation) if (stopSpawning) CancelInvoke ("SpawnObject")
|
0 |
Ignoring collisions without using physics layers Trying to ignore collisions between certain prefabs, but in this case I don't want to use layers since these are specific object pairs that I want to not collide, and creating a layer for each prefab would complicate the layer matrix more than I want to. What I tried so far public void OnCollisionEnter(Collision collision) if (collision.gameObject.tag "Bullet") Physics.IgnoreCollision(collision.collider, collider) So I tried ignoring the collision in the OnCollisionEnter, but this only worked partially. The objects did go one through the other, but they both slowed down. My guess is that the first frame of the collision, the one that generated the call to OnCollisionEnter, was calculated regardless of the ignore command. Any ideas how I can make all bullets not collide to one another, without putting them in a separate layer?
|
0 |
Unity how to mimic the lighting of a mesh as seen in the editor view I have a camera which shows a "bird's eye view" of a procedurally generated mesh like so Currently in the editor view (right), the terrain looks exactly as I would like it to. However, in game (left) I haven't been able to get it to appear as I would like I was using a directional light above, which was causing the effect where the centre of the mesh appears "shiny". So I looked around at some forum posts and questions on here and decided to try using ambient lighting instead by altering the settings in Window Rendering Light Settings, but this is the result This is the material I'm using (EDIT I'm using a particle shader as the colouration of my mesh is based on altering Mesh.colors. ) I have tried fiddling around with different material types but I couldn't get better results. My question is how do I set up my game to use the same lighting that's being used in the editor? Thanks in advance EDIT Camera settings at runtime as requested EDIT 2 Just to update I have still not managed to fully solve this problem. I ended up using some different colours for my heightmap and tweaking the Metallic and Smoothness properties of the material, and the shininess and non even lighting is somewhat diminished, but it does still exist. If you watch at about 20 seconds into this video, when the mesh is dully coloured, the "circular" lighting effect is still present, which shadows being cast from the centre outwards, and the middle appearing almost blurred and the edges sharp. Later in the video you can see a colourful version of the mesh, where these undesirable lighting effects are barely noticeable (note that I don't always want it to be be in bright colours, hence this is still an issue). I feel like there should be a very simple solution to this. Why can I not get the lighting conditions that I see in the editor in the game view? I am very happy to keep updating here with further progress clarifications, and would love to hear any suggestions anyone has.
|
0 |
Large amounts of strings to be used, but how to store them? This is a question I've been meaning to ask. I have thought about it for a little bit and have a few ideas, but I'm not sure which is most secure, and will give me the most functionality with the most efficiency. For my game (being a story game) I have a plethora of strings that I'm going to need to display. I decided to split up the story into chapters, each chapter being a new scene(This way I could organize the content for the chapter). What I was thinking was that I could write regular text files with the chapter's content, while efficient and practical, this seems highly insecure. Then I thought, why not put it into large string arrays on a separate C file. Well that's more secure, but it's not really practical and it has less efficiency. So I have found pretty much the two extremes here. What would be the best way to deal with large amounts of strings in a secure, efficient, and functional way? Think about a happy medium compared to my two extremes.
|
0 |
Using IPAD's as controllers for a Unity game We are making a Multiplayer game using Unity. The actual game would be run from a PC projected on a screen and the players would be using their respective Ipad as a controller to play the game. I am not sure how difficult this would be to achieve inside Unity but I am assuming that all the game data inside Unity would need to be fed and retrieved from some kind of a server. How would this be possible with Unity because each Ipad would have a separate Unity build and also a separate build for the PC from where the actual game would be running.
|
0 |
How To Deselect (Unfocus) All gameObjects in a Unity Scene View? When I'm done with moving and rotating gameObjects in a Unity scene, I want to deselect everything to not accidentally change it. How? In some applications ESC key does the trick, in others 'D' (deselect) comes to rescue. But I don't know any remedy in Unity. My workaround is that I click somewhere in the Project View (I don't like this approach because it brings up the inspector for that asset).
|
0 |
How could I get composite rigid body into unity I am developing a game, in unity, that has accurate destruction physics and from my understanding unity uses plain old rigid body physics. I was wondering if there was a way to bring composite rigid body physics into unity through a plug in or library or some other way? Thanks, nova edit So composite rigid body physics is almost exact like normal rigid body physics. But the main difference is that in composite rigid body physics all of the assets will not be considered physics based objects until an outside force hits them. For example a building and all of that parts it is made out of will not be processed as physics based objects until say a rocket hits it. This method of composite rigid body physics uses much less memory because it is only processing what is being affect and not everything else.
|
0 |
Why the Vector3.Dot value is 12 when running the game? using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI using UnityEngine.Events using System public class InteractableItem MonoBehaviour public string currentMode private Transform player private InteractableMode currentInteractableMode private string currentDesription private float originDistance private void Awake() player GameObject.Find( quot Player quot ).transform originDistance transform.GetComponent lt InteractableItem gt ().distance public enum InteractableMode Description, Action, ActionWithoutThrow public enum ViewMode FrontView, AllView public ViewMode viewMode ViewMode.AllView public InteractableMode interactableMode InteractableMode.Description public float distance TextArea(1, 10) public string description quot quot public bool IsAnyAction() return interactableMode InteractableMode.ActionWithoutThrow interactableMode InteractableMode.Action public bool IsActionWithoutThrow() return interactableMode InteractableMode.ActionWithoutThrow private void Start() currentMode GetComponent lt InteractableItem gt ().interactableMode.ToString() currentInteractableMode GetComponent lt InteractableItem gt ().interactableMode currentDesription GetComponent lt InteractableItem gt ().description private void Update() var heading transform.position player.transform.position var dot Vector3.Dot(heading, transform.forward) if(viewMode ViewMode.FrontView amp amp dot lt 1) transform.GetComponent lt InteractableItem gt ().distance 0 if (viewMode ViewMode.FrontView amp amp dot gt 1) transform.GetComponent lt InteractableItem gt ().distance originDistance The script is attached to some objects and one of them the ViewMode is set to FrontView and then when running the game first time the dot value is 12 and then it's getting inside and going the line if(viewMode ViewMode.FrontView amp amp dot lt 1) transform.GetComponent lt InteractableItem gt ().distance 0 but it should not set the distance to 0. only if I'm getting close enough to the item then it should see the item from the front and then only if I'm moving the player behind the item the dot should be minus and set the distance to 0 but for some reason the dot is minus 12 when running the game so it's setting the distance to 0 right away.
|
0 |
Free camera navigation and pre defined locations I have an interactive scenery app written in Unity, where users can freely navigate the camera through the scene. What I want to do now, is to let user automatically fly to some quot hotspots quot with a single key stroke, while still allowing the users to navigate manually. I tried Animation, but with it, auto fly and manual navigation are mutually exclusive I have to disable one in order for the other to work. Right now, I'm attempting the fall back solution, where I create some empty game objects with special scripts attached, so that when public script functions are invoked, the game object animates the camera to a pre defined transformation. My question being is there a better solution than my fall back?
|
0 |
Unity Free Inverse Depth Mask? How would it be possible to create an inverse depth mask? In this case, I refer to a depth mask as a shader attached to a mesh that 'pokes a hole' through the current camera layer to let you see the camera render layer one depth down, usually by using ColorMask 0. What I want is for, instead, the mesh to determine what ISN'T cut out, without everything that is NOT seen through the mesh being cut out.
|
0 |
Player must places the object in the preset position I want to know how to do like this video https youtu.be 6gouxqSxeG8 At the minute 3 09, the player can put the street vendor in the predetermined location (with the green arrow show that place). Please tell me some keyword about this or video tutorial about how to implement it in unity 2d. Thanks.
|
0 |
Strange realtime shadows in Unity3D I'm trying to do realtime lighting, and my shadows are acting very strange. When I project a spotlight out from the camera (like a flashlight in a first person game) my shadows show up as 3D skews of the objects, and I can actually clip through them if I move the camera in the right way... if I detach lights from the camera and just have them sit in one position, I don't seem to have this issue (cylinder to the right is just the model Im using for the flashlight... its attached to the camera) All objects have Cast Shadows set to "On" All objects have Receive Shadows checked All objects have Light Probes and Reflection Probes set to "Blend Probes" All objects have Motion Vectors set to "Per Object Motion" All objects have Lightmap Static unchecked All objects have Dynamic Occluded checked All lights have Mode set to "Realtime" All lights have Shadow Type set to "Soft Shadows" All lights have Realtime Shadow Strength set to 1 All lights have Realtime Shadow Resolution set to "Very High Resolution" All lights have Realtime Shadow Bias set to 0 (changing this doesn't seem to effect the issue) All lights have Realtime Shadow Normal Bias set to 0 (changing this doesn't seem to effect the issue) All lights have Realtime Shadow Near Plane set to 0.1 (changing this doesn't seem to effect the issue) All lights have Draw Halo unchecked All lights have Render Mode set to "Auto" All lights have Culling Mask set to "Everything" Camera has Clear Flags set to "Solid Color" Camera has Background set to 000000 Camera has Culling Mask set to "Everything" Camera has Projection set to "Perspective" Camera has Field of View set to 60 Camera has Near Clipping Plane set to 0.3 Camera has Far Clipping Plane set to 1000 Camera has Viewport Rect set to 0, 0, 1, 1 Camera has Depth set to 0 Camera has Rendering Path set to Use Graphics Settings Camera has Occlusion Culling checked Camera has Allow HDR checked Camera has Allow MSAA checked Camera has Allow Dynamic Resolution unchecked Camera has Target Display set to "Display 1" In Player, Rendering Color Space set to "Linear" In Player, all Rendering Auto Graphics APIs checked (win, mac, lin) In Player, Rendering Static Batching checked In Player, Rendering Dynamic Batching checked In Player, Rendering GPU Skinning unchecked In Player, Rendering Graphics Job (Experimental) unchecked In Player, Rendering Lightmap Encoding set to "High Quality" In Graphics, all Built in Shader Settings are set to "Built in shader" In Graphics, Shader Stripping Lightmap Modes is set to "Automatic" In Graphics, Shader Stripping Fog Mode is set to "Automatic" In Graphics, Shader Stripping Instancing Variants is set to "Strip Unused" In Graphics, Preloaded Shaders Size is set to 0 In Lighting, Skybox Material is set to "Default Skybox" In Lighting, Sun Source is set to "None (Light)" In Lighting, Environment Lighting Source is set to "Color" In Lighting, Environment Lighting Ambient Color is set to 000000 In Lighting, Environment Lighting Ambient Mode is set to "Realtime" (and the dropdown box is greyed out, so I can't change it) In Lighting, Environment Reflections Source is set to "Custom" In Lighting, Environment Reflections Cubemap is set to "None (Cubemap)" In Lighting, Environment Reflections Compression is set to "Auto" In Lighting, Environment Reflections Intensity Multiplier is set to 0 In Lighting, Environment Reflections Bounces is set to 1 In Lighting, Realtime Global Illumination is checked In Lighting, Baked Global Illumination is unchecked In Lighting, Fog is unchecked
|
0 |
Unity Diablo style Multiplayer Good time of the day to everyone who is reading this topic. I've been enjoying playing Diablo 3 and decided to try myself in game development (to lure my friends into Diablo 3 and to, ofcourse, practice in game development). I'd like to split the question in to following sections Lobby System (using Unet) Game Server Scene Loading So, lets start with the first part As far as i know, when user decided to play the multiplayer part of the game, he is either creating new game for others to join, or joining an existing game. This process can be observed on the "Joining Creating Game" screen. What i'm actually can't figure out, is that if the game created on the users machine (lets name it local) or the Blizzard server (this will be remote). If it is created on the local machine, how then it is protects itself from cheating. If it is created on the remote machine, does that mean that for every 5 (just any number) players, i will have to start new copy of the game server (probably on the different port) Moving to the second question This requires to run a "headless" version of the game on the server. Is there a possibility to create many different rooms for many players by using only one server instance, or will it require to run separate instance for every 5 players. Also, if player is playing in single player mode, he seems to be also connected to the game server. Looks like the game server is performing all of the necessary calculations and player only sends in the commands for server to process (e.g, move me from 1,0 to 1,1) and after receiving the response, client interpolates the movement received from the server. And finally, the third question Server may have many different scenes, but many players may be situated across many different scenes. There could also be dungeons and other player oriented stuff. So the question is, is it possible to achieve this goal using default Unity functionality.
|
0 |
Is Godot's NavMesh viable for dynamic pathfinding (e.g. avoiding moving enemies)? I am a novice (read low budget) designer looking at moving from Pygame to a real engine, and between Unity and Godot it looks like the latter has a much better 2D engine 1, 2, 3 . I would be happy to support Godot's open source model except that, as far as I can tell, its built in navigation mesh is purely static i.e. it can't update its path to account for dynamic obstacles 4, 5 while Unity's pathfinding system can 6 . So my question is Am I "stuck" with Unity? Or is there functionality that I haven't yet been able to find? Or, alternatively, is GDScript significantly faster than Python such that basic algorithms like fixed grid A would do the job? Edit By "stuck" with Unity I don't mean that it's a bad option or that there aren't good options I mean, 'if I need good pathfinding, do I have to give up on Godot and use what would otherwise be a second choice engine?'
|
0 |
How to tell when animation is finished playing without events in Unity I'm using the newest version of Unity. I have a turn based RPG type of game so everything is very sequential. The actor jumps in front of another actor, plays his melee attack animation, then jumps back. Currently I use events on the animation to tell when the attack animation is complete. The 2 side effects of doing it this way are I have to go into each animation and make an event at the end of them. It would be ideal to NOT have to do this. It would seem I should be able to just check in code if a certain animation is finished playing. The control flow of my attack code becomes awkward. My attack method is a coroutine so I can read it very sequentially and it makes sense. Having this event to tell when the animation is complete ruins that flow. I have to basically make a bool variable and inside my finished event set it, and in my attack function do a while loop after I play the animation checking for that bool variable to change and yielding out until it does. Requiring this event ruins the logical flow of attacks. If I have many animations for whatever reason things get messier. I noticed the Animator component doesn't have an isPlaying() like some other answers suggested. I think those answers were for older version of unity and older just playing animation clips not using the new Animator component. There must be a better way to do this.
|
0 |
How to change player objects when switching scenes? I have a scene for lobby. When player connects to server he gets a lobbyCharacter, which is an empty gameobject with a script on it that create UI element with the players name. In lobby players can select character they want to use. Now when starting game, i would like to switch scene to the game scene when all players are ready. I have been reading the API, documentation, and different stack questions, but i cant seem to find any info on how this should work. On NetworkManager i can do scene schange which will be changed on all clients. But how do i persist data over multiple scenes? And if the lobby characters are destroyied how are the game characters instansiated according to the choises made in lobby? How does the client connection persist between multiple scenes? Do i just manage the character locally and use syncHooks to synchronize over the server? Do i need to create somesort of container gameobject that holds the player connection information and some extra stuff? EDIT Reading the soruce code of mirror i fouind that NetworkManager holds the connection of the client, sort of. So now the issue has come down to replacing the prefab for the connection. I have the following code public void switchScene() GameObject obj NetworkClient.connection.identity.gameObject NetworkServer.ReplacePlayerForConnection(NetworkClient.connection, Instantiate(shipPrefab)) NetworkServer.Destroy(obj) ServerChangeScene(gameScene) This should switch the prefab for connection and then switch scene, but i keep getting error InvalidCastException Specified cast is not valid. Mirror.NetworkIdentity.SetClientOwner (Mirror.NetworkConnection conn) (at Assets Mirror Runtime NetworkIdentity.cs 362) Mirror.NetworkServer.InternalReplacePlayerForConnection (Mirror.NetworkConnection conn, UnityEngine.GameObject player, System.Boolean keepAuthority) (at Assets Mirror Runtime NetworkServer.cs 837) Mirror.NetworkServer.ReplacePlayerForConnection (Mirror.NetworkConnection conn, UnityEngine.GameObject player, System.Boolean keepAuthority) (at Assets Mirror Runtime NetworkServer.cs 697) LobbyManager.switchScene () (at Assets LobbyManager.cs 51) And i dont understand why this is happening. New prefab has networkIdentity and networkTransform. Old prefab only has network transform. Up until this point everything wors, but once i want to switch scenes, it breaks.
|
0 |
Is it possible to make a randomly rotating terrain texture painting brush in Unity? I wanted to make a terrain in unity with a dirt texture painted onto the original grass texture to make a path, but when I tried, the dirt (and grass) looked repetitive and full of patterns. My question is, is there any way I can make a texture's tiles randomly rotate when being applied or painted onto an object?
|
0 |
TextAsset thinks file is 6856 bytes when it is 120123 bytes So I've created a text asset in Unity of a binary file which i'm attempting to read in as a byte array. The result I'm getting is a byte array tht is almost half the size it's supposed to be. The file is a serialized mesh file from here http wiki.unity3d.com index.php?title MeshSerializer2 What I do then is find the file unity created, move it to the assets folder and drag it into a component as a TextAsset. For smaller files it works but larger ones appear to fail to load completely. If I load the same file separately from a C console application using filestream it loads correctly.
|
0 |
How to find a valid point if NavMeshObstacle is blocking path? Is there any way to find the closest valid point to my target if a NavMeshObstacle is blocking my agent's path? This point can be any point along the red line in the image above.
|
0 |
How to circle an uneven object with Camera at a fixed distance? Unity3d. I am trying to move an object with Camera around a fixed terrain (Mountain), while staying an set distance from its edge. I have the camera set to lookAt the mountain, and I want to circle the mountain. I was thinking about sine wave for circular motion but its not an exact circle as I need to move in or out to maintain the fixed distance from the mountains edges. It looks like I might need transform.RotateAround(..), but what about the adjusting to maintain a fixed distance from the edge of the uneven surface while maintaining the circular motion. transform.RotateAround (Vector3.zero, Vector3.up, 20 Time.deltaTime) Update Here is my current script for circling around mountain as first person object function Update () var mountain GameObject mountain GameObject.Find("QuantumCold B") transform.RotateAround(mountain.transform.position, Vector3.up,20 Time.deltaTime) Unfortunately there are two problems 1) The first person object appears to be falling or maybe its the main camera, but in any even there is a game screen looks like its falling below the mountain. 2) it is the mountain that seems to be rotating. Do I need to switch the main camera to be the first person camera. Why does the mountain appear to be rotating?
|
0 |
Switching between world and battle scene with no or minimum loading? I am making a strategy game where the player roams a grid map. When the player encounter enemy on the map he is transferred to a quot battle quot scene where two armies are fighting in turn based battle. Imagine Heroes 3 like game. My question is Should I load the battle scene in additive mode and temporary hide the quot world map quot and when the battle is finished to just show the quot world map quot and hide the quot battle quot scene? Or i should unload the world scene and load the battle scene, and when the battle is over gt unload the battle scene and load the world scene ? I think the 1st approach will give me less loading time between the two scenes, but will require more RAM ? Second approach is standard one, but i will have loading between the scenes ? My idea is to have no or minimal loading between battle and world scenes. What do you guys thing ? Did you know what is the best practice in this case ? By the way, i am using Unity as a engine.
|
0 |
How to create reel slider with mobile controls How can I create a reel slider with mobile game controls so that it looks something like this? The slider is normally non visible, and can be accessed if I slide my finger from the right side of the screen to the left. The slider allows me to switch my current weapon and use items in my inventory. This is my current setup in Unity. I can figure out the inventory portion of the slider, as there are many tutorials out there on an inventory system, and how to make the slider move based on touch, using something similar to a mobile joystick script, but I can't figure out how to make the slider so that it Can quot jump quot from icon to icon (not have the slider be completely fluid prevent it from stopping in between item icons) Detect what item slot the slider is currently on (in the case of the example, the item that will be used is the icon in the center of the screen. Make the icons more transparent the further away it is from the icon in use (I'm guessing that I would have to set the alpha channel value in the color settings of the item to a lower value, but I'm not sure how to detect the icon in use and count how many icons away the other icons are from the one in use.
|
0 |
Unity 2019 depth only camera now overwrites everything We have a pretty traditional camera stacking set up UI camera on top of a everything else camera. The UI camera is set to only clear depth, and only draws the UI layer. The everything else camera is set to clear via skybox and all layers but UI. Only the everything else camera contains a post processing layer component disabling it does seem to make everything work the way it used to. The UI camera has a higher depth than the everything else camera, in case someone suggests otherwise. In 2018 this exact arrangement worked as intended. In 2019, the UI camera's view is the only thing visible. I've found several forum posts on Unity by Unity Technologies about the light weight pipeline breaking this functionality, but we're not using any of the new pipelines. We simply upgraded, and I can't find any indication that we are using the new pipelines. Supposedly everything works normally as long as you don't use the new pipelines, but this is proving false so far. Since this camera arrangement is very common, I can't imagine I am alone!
|
0 |
Why does simply trying to add sound break literally everything So I have a script for an object that when shot explodes and it worked literally perfectly until I tried to add sound at which point it not only didn't play the sound but also stopped exploding, which was pretty rude of it. Here's my code since I have no idea what's wrong (Unity C ) using System using System.Collections using System.Collections.Generic using UnityEngine public class ShootyTarget MonoBehaviour public float health public GameObject destructionPrefab public GameObject explosion public GameObject shockwave public GameObject debris public AudioSource splodeSound void Start() splodeSound gameObject.GetComponent lt AudioSource gt () void FuckingDie() splodeSound.Play() Instantiate(explosion, transform.position, transform.rotation) Destroy(gameObject) Instantiate(shockwave, transform.position, Quaternion.Euler(new Vector3(90, 0, 0))) Instantiate(destructionPrefab, transform.position, transform.rotation) Instantiate(debris, transform.position, transform.rotation) public void takedamage(float amount) health amount if (health lt 0f) FuckingDie()
|
0 |
Unity RTS Multiple Selection Approacah I've recently solved the single selection problem but now I want to do multiple selections. I know I need to find two points with the mouse position to draw a box but it just won't work for me. void Update() if (Input.GetMouseButtonDown(0)) bool dragging true Debug.Log("Multiselect active") MultiSelect(dragging) private void MultiSelect(bool dragging) mouseDownPoint Input.mousePosition if (Input.GetMouseButtonUp(0) amp amp dragging) mouseUpPoint Input.mousePosition Debug.Log("First pos " mouseDownPoint " Second pos " mouseUpPoint) dragging false What is a better way to achieve what I'm trying? If someone can tell me a way that can also detect any units inside the area that'd be nice too.
|
0 |
How to programmatically change sprite sheet sub sprite name I am trying to change the name of the sub sprites of a sprite sheet. I have searched and tried everything I can think of and cannot get it to work, which makes me think it can't be done at this point in time. Let's say I have a sprite sheet that has already been split up into individual sprites inside of Unity. I am attempting to change the sub sprite names programmatically. I tried using AssetDatabase.RenameAsset (...) on the sprite sheet asset, which only changes the sprite sheet name and not sub sprites. I then thought to obtain a sub sprite and attempt to change its name using the below code. if (AssetDatabase.IsSubAsset (subSprite)) AssetDatabase.RenameAsset (AssetDatabase.GetAssetPath (subSprite), "newSprite" i.ToString ()) However, this too only changes the sprite sheet name. I'm not sure where else I can take this to achieve my desired outcome, apart from programmatically copying the original sprite sheet and using that to create a copy. But even then, I still am unable to alter the sub sprite names. I also tried changing subSprite.name, but this just changes the internal name and not the asset name. Any ideas?
|
0 |
Unity How to change editor play stop button positions for dual monitor layout Is it possible to change the play stop buttons positions in editor? I am trying to make a layout for Dual Screen, however the buttons are right in the middle of the two screen. So, it makes it hard to click the buttons.
|
0 |
How to debug fatal signal 11 code 2 in UnityMain? i have searched for the fatal signal caused by Render or GxDriver, FlashMuller in unity forum says it's google play the error 08 03 14 59 47.503 32020 32092 ? A libc Fatal signal 11 (SIGSEGV), code 2, fault addr 0xcbe8dffc in tid 32092 (UnityMain), pid 32020 (com.tuo3.alive) 08 03 14 59 47.533 32121 32121 ? A DEBUG Build fingerprint 'OnePlus OnePlus5T OnePlus5T 8.1.0 OPM1.171019.011 1807181208 user release keys' Revision '0' ABI 'arm' pid 32020, tid 32092, name UnityMain gt gt gt com.tuo3.alive lt lt lt 08 03 14 59 47.544 32121 32121 ? A DEBUG backtrace 00 pc 000575d0 system lib libc.so (je arena tcache fill small 71) 01 pc 00077919 system lib libc.so (je tcache alloc small hard 16) 02 pc 00058fc7 system lib libc.so (je arena palloc 1650) 03 pc 00069bd1 system lib libc.so (imemalign 1164) 04 pc 0006d373 system lib libc.so (je memalign 26) 05 pc 001d6f18 data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so (UnityDefaultAllocator lt LowLevelAllocator gt Allocate(unsigned int, int) 24) 06 pc 001da888 data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so (MemoryManager Allocate(unsigned int, unsigned int, MemLabelId const amp , AllocateOptions, char const , int) 852) 07 pc 001da254 data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so (malloc internal(unsigned int, unsigned int, MemLabelId const amp , AllocateOptions, char const , int) 128) 08 pc 00193bc8 data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so (core StringStorageDefault lt char gt assign(char const , unsigned int) 180) 09 pc 00a350bc data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so ( gnu cxx hashtable lt std pair lt core basic string lt char, core StringStorageDefault lt char gt gt const, ZipCentralDirectory PathDescriptor gt , core basic string lt char, core StringStorageDefault lt char gt gt , gnu cxx hash lt core basic string lt char, core StringStorageDefault lt char gt gt gt , std Select1st lt gnu cxx hash gt , std equal to lt core basic string lt char, core StringStorageDefault lt char gt gt gt , std allocator, lt ZipCentralDirectory 10 pc 00a34adc data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so ( ZZN19ZipCentralDirectory20readCentralDirectoryEvEN3 08 invokeERK15FileSystemEntryR12FileAccessorPKcRKN3zip4CDFDEPv 508) 11 pc 00a38160 data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so (zip CentralDirectory Enumerate(bool ( )(FileSystemEntry const amp , FileAccessor amp , char const , zip CDFD const amp , void ), void ) 804) 12 pc 00a348d0 data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so (ZipCentralDirectory readCentralDirectory() 20) 13 pc 00a26630 data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so (apkAddCentralDirectory 84) 14 pc 00a19074 data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so (Mount(char const ) 84) 15 pc 00a090dc data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so (UnityInitApplication() 216) 16 pc 00a0a660 data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so (UnityPlayerLoop() 264) 17 pc 00a0cc68 data app com.tuo3.alive VZWALBY70nH dSDIQa rKA lib arm libunity.so (nativeRender( JNIEnv , jobject ) 228) 18 pc 000114cb data app com.tuo3.alive VZWALBY70nH dSDIQa rKA oat arm base.odex (offset 0x10000) More discussion 2
|
0 |
Unity rigidbody glitch throu corners No matter how thick the wall is, the player will glitch through. I've tried changing the settings on the rigidbody but nothing have worked. The walls fits together almost perfectly. Why is this happening? I already searched a lot and also found a lot of questions regarding the same problem at "Unity Answers" not a single one of them gets answered. I dont know why, it seems theyr community is almost dead.
|
0 |
Unity camera moving up and down for no reason I have a standard camera in my scene. With standard I mean the camera you get when you click right mouse Camera, with no modification except for the transform position and rotation. Then I attached to the camera this simple script using System.Collections using System.Collections.Generic using UnityEngine public class CameraController MonoBehaviour public GameObject target public Vector3 translationOffset public Vector3 rotationOffset Use this for initialization void Start () Update is called once per frame void Update () transform.position target.transform.position translationOffset transform.LookAt(target.transform) transform.Rotate( rotationOffset) the result I have is this Why my camera is doing that? It may be worth noticing that everything was working fine, but at some point i clicked on "reimport all assets" and it started this weird behaviour. How can I fix? Thanks a lot.
|
0 |
In the Unity Editor, how to push a parent's transform down to its children? I've inherited a Unity scene with quite a deep object hierarchy. Some GameObjects in the hierarchy don't have any geometry of their own, and just exist to group their children and apply a MonoBehaviour to all of their children. Because of the way the scene was authored, some of these objects have arbitrary transforms, which makes it hard to edit the child transforms, to align the children with other objects outside the group. As a one off operation in the editor, I'd like to reset these objects' transforms, without changing the world space positions and orientations of the children. Put another way, I'd like to push the effect of the transform down to the children. What's the easiest way to achieve this in the editor? I've seen a lot of questions from people who want to achieve this in code, to have the effect of detaching the parent and child transforms while keeping the relationship, but that's not what I want. I'm just looking for a one off, manual operation to make my scene file easier to edit.
|
0 |
Unity 5 Animator controls What are their Unity 4 correspondent? I am following a tutorial that is made with Unity 5, but claims to be compatible with Unity 4.6 I am working with the Animator panel, and I was wondering where could I find certain controls on the Unity 4 version. I highlighted them in a red square. Basically stuff that has to do with duration of transitions and checking the transition as not having an exit time.
|
0 |
Rendering Mode transparent is not applying in webgl build I am using this method to convert opaque rendering mode to transparent. item.color new Color(1, 1, 1, value) item.SetFloat( quot Mode quot ,3) item.SetOverrideTag( quot RenderType quot , quot Transparent quot ) item.SetInt( quot SrcBlend quot , (int)UnityEngine.Rendering.BlendMode.One) item.SetInt( quot DstBlend quot , (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha) item.SetInt( quot ZWrite quot , 0) item.DisableKeyword( quot ALPHATEST ON quot ) item.DisableKeyword( quot ALPHABLEND ON quot ) item.EnableKeyword( quot ALPHAPREMULTIPLY ON quot ) item.renderQueue (int)UnityEngine.Rendering.RenderQueue.Transparent This is working fine but not working in my webgl build.
|
0 |
How do you create a grid using a wire frame shader? So I'm having trouble going about creating an 80s neon color grid wire frame, like the examples. How would you go about making the floor into an 80s styled grid floor? I'm just looking for square grids. Here is what I'm currently using Shader "Custom Grid" Properties GridThickness ("Grid Thickness", Float) 0.01 GridSpacingX ("Grid Spacing X", Float) 1.0 GridSpacingY ("Grid Spacing Y", Float) 1.0 GridOffsetX ("Grid Offset X", Float) 0 GridOffsetY ("Grid Offset Y", Float) 0 GridColour ("Grid Colour", Color) (0.5, 1.0, 1.0, 1.0) BaseColour ("Base Colour", Color) (0.0, 0.0, 0.0, 0.0) SubShader Tags "Queue" "Transparent" Pass ZWrite Off Blend SrcAlpha OneMinusSrcAlpha CGPROGRAM Define the vertex and fragment shader functions pragma vertex vert pragma fragment frag Access Shaderlab properties uniform float GridThickness uniform float GridSpacingX uniform float GridSpacingY uniform float GridOffsetX uniform float GridOffsetY uniform float4 GridColour uniform float4 BaseColour Input into the vertex shader struct vertexInput float4 vertex POSITION Output from vertex shader into fragment shader struct vertexOutput float4 pos SV POSITION float4 worldPos TEXCOORD0 VERTEX SHADER vertexOutput vert(vertexInput input) vertexOutput output output.pos mul(UNITY MATRIX MVP, input.vertex) Calculate the world position coordinates to pass to the fragment shader output.worldPos mul(unity ObjectToWorld, input.vertex) return output FRAGMENT SHADER float4 frag(vertexOutput input) COLOR if ( frac((input.worldPos.x GridOffsetX) GridSpacingX) lt ( GridThickness GridSpacingX) frac((input.worldPos.z GridOffsetY) GridSpacingY) lt ( GridThickness GridSpacingY)) return GridColour else return BaseColour ENDCG
|
0 |
Blending between many materials I am storing one material ID per vertex in my meshes. In the shader for the mesh, I have a texture array full of textures that the material ID can refer to. The fragment color is chosen using triplanar texturing. Unlike vertex colors, these material IDs cannot be blended. For example, if a dirt texture had a material ID of 5, and a grass texture had a material ID of 1, fragments in between one vertex with material ID 5 and one with material ID 1 would potentially have a material ID between 2 and 4, which is not ideal. Another flaw with this method is the fact that there would be a hard transition in between materials, as the mix or lerp function in the shader is not used. Is there a way to blend the textures of two neighboring vertices in the fragment shader? I can add additional per vertex data if needed.
|
0 |
Animator from another gameobject keeps disappearing from script on play I am working on a gun script and it worked fine until earlier today when I made a change to the script and it stopped working. I put it back, but for some reason now the animator object attached to the script keeps disappearing. using System.Collections using System.Collections.Generic using UnityEngine public class RifleShooting MonoBehaviour private float NextTimeToFire 0f private int CurrentAmmo private bool IsReloading false Space(10) Header("Floats") public float Damage 10.0f public float Range 100.0f public float ImpactForce 60f public float FireRate 15f public float ReloadTime 1.0f Space(10) Header("Others") Space(5) Space(10) Header("Others") Space(5) public int MaxAmmo 10 public Camera FPSCamera public Animator GunAnimations public ParticleSystem MuzzleFlash public GameObject impactEffect public bool AllowedToShoot true Start is called before the first frame update void Start() GunAnimations GetComponent lt Animator gt () if (CurrentAmmo 1) CurrentAmmo MaxAmmo private void OnEnable() IsReloading false GunAnimations.SetBool("Reloading", false) Update is called once per frame void Update() if (IsReloading) return if (CurrentAmmo lt 0) StartCoroutine(Reload()) return if (AllowedToShoot false) return if (Input.GetButton("Fire1") Input.GetButtonDown("Fire1") amp amp Time.time gt NextTimeToFire) NextTimeToFire Time.time 1f FireRate Shoot() IEnumerator Reload() IsReloading true Debug.Log("Reloading...") GunAnimations.SetBool("Reloading", true) GunAnimations.SetBool("IsShooting", false) yield return new WaitForSeconds(ReloadTime .25f) GunAnimations.SetBool("Reloading", false) yield return new WaitForSeconds(.25f) GunAnimations.SetBool("IsShooting", true) CurrentAmmo MaxAmmo IsReloading false void Shoot() shooting script here Also if it helps here is what I see in the console when I try to fire MissingComponentException There is no 'Animator' attached to the "M4A1" game object, but a script is trying to access it.
|
0 |
Take a screenshot from camera problem I use script below to take a screenshot from camera. It's working fine. However, when I take a screenshot again (pressing k multiple times), its old image is not clear from the memory and it keep drawing over same image over and over again. If object is moving while taking screenshot multiple times, image I will get all frame combine into one image with every frame in the same image. What should I do to fix this problem? using UnityEngine using System.Collections public class HiResScreenShots MonoBehaviour public int resWidth 2550 public int resHeight 3300 private bool takeHiResShot true public static string ScreenShotName(int width, int height) return string.Format(" 0 screenshots screen 1 x 2 3 .png", Application.dataPath, width, height, System.DateTime.Now.ToString("yyyy MM dd HH mm ss")) public void TakeHiResShot() takeHiResShot true void LateUpdate() takeHiResShot Input.GetKeyDown("k") if (takeHiResShot) RenderTexture rt new RenderTexture(resWidth, resHeight, 24) camera.targetTexture rt Texture2D screenShot new Texture2D(resWidth, resHeight, TextureFormat.ARGB32, false) camera.Render() RenderTexture.active rt screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0) camera.targetTexture null RenderTexture.active null JC added to avoid errors Destroy(rt) byte bytes screenShot.EncodeToPNG() string filename ScreenShotName(resWidth, resHeight) System.IO.File.WriteAllBytes(filename, bytes) Debug.Log(string.Format("Took screenshot to 0 ", filename)) takeHiResShot false Debug.Log("Capture!!")
|
0 |
TextField Add in Editor does not display when put under if statement I've been trying to make a custom editor window in Unity and I needed to make an quot add TextField quot button. When I add a TextField directly (without requiring a button), it works. When I put it under if(GUI.Button()) it does not show up. Here's my code private static List lt string gt s new List lt string gt () private void OnGUI() if (GUI.Button( quot quot ) ) s.Add(GUI.TextField(new Rect(0,50,Screen.width,20), quot field quot ))
|
0 |
Unity Depth texture is too pixelated I am trying to combine two cameras together Background camera, Foreground camera. I created 3 cameras in my project, 2 for the background and foreground and one for the foreground depth. I then created a simple shader that combine the first two cameras (they render to render texture as well as the foreground depth), the problem I am having is that because the depth buffer is too pixelated the result looks funny and you clearly see the lines around the foreground (players in my case). I created a depth camera with these properties Notice the Output Texture, I have set the Render texture to This is the result depth texture (zoomed so you can see the pixels) Any idea how I can create that effect maybe using something different then the depth buffer? or can I improve the depth quality? what can I do to reach a good final result?
|
0 |
Rain Effect generation in a Unity VR project I m developing a VR project in Unity Engine and I need to implement a Rain Effect. I have considered the following A VR game must run at least 90 frames per second. The Rain must be detailed. The Rain Drops interact with other objects. These are the approaches I have considered Particles Systems I think it is expensive since there are two cameras rendering the scene and checking collision per particle could be expensive. Image Effect on the canvas I think the result would be unreal, and there would not be interaction with other objects. I have seen examples of rain effect like in Resident Evil 4, Halo Reach, Crysis, FarCry, Project Cars 2 VR and Batman Arkham Knight. A last approach I haven t considered yet is by shading, maybe shading would work for the rain drops in the cameras lens. I would like to know optimal approaches to emulate rain effects without making too much computations. Thanks for your attention.
|
0 |
Unlit Node Shadow Shader Graph How to make unlit node cast shadows? Is is possible with the current state of Shader Graph in LWRP? In this great article Toon Shader OP grabs pass from VertexLit shader. Is something similar achievable with Shader Graph?
|
0 |
Unity Failed to create decoder for ScreenSelector.png My game works fine in the editor, but when I build and run the build the view is zoomed in, my tilemap is missing, and the camera follows a gameobject it should not. How it should look and how it looks I checked the logs and this is the error I am served Failed to create decoder for 'C Users Hamuel The First Documents Jetplatformer Builds Builds Data ScreenSelector.png' 0x80070002 Further Investigation shows that ScreenSelector.png is absent from the path stated in the error. I cannot find anything that says what ScreenSelector.png is, or does. I am using the post processing stack by unity. Any help would be much appreciated!
|
0 |
Animation after enemy spawns right now in my game, four enemies spawn in four spawn points with a delay, but what I want to do is that if you don't kill the enemy after a couple seconds, an animation (it's an animation of a scratch, basically to let the player know it has been attacked) appears. Right now I have a script that display an image (it's an image because I was testing the scripts), but now I want to change the image for the animation but after trying and failing a lot of times I decided to ask here, and hopefully someone can help me. This is the script of the "attack", and it's attached to the enemy prefab public Image TargetImage void Start () TargetImage.enabled false public void spawnAttack() StartCoroutine (playerIsAttacked (5, TargetImage)) public IEnumerator playerIsAttacked (float t, Image im) yield return new WaitForSeconds (t) TargetImage.enabled true and this is in the timed spawn script public class TimedSpawn MonoBehaviour public GameObject spawnee public bool stopSpawning public float spawnTime public float spawnDelay void Start () InvokeRepeating ("SpawnObject", spawnTime, spawnDelay) public void SpawnObject () GameObject newSpawn Instantiate (spawnee, transform.position, transform.rotation) as GameObject newSpawn.GetComponent lt enemyAttack gt ().spawnAttack () if (stopSpawning) CancelInvoke ("SpawnObject")
|
0 |
How to update Unity? I have clicked on check for updates but it says I have latest Unity. But latest is 5.6. How to update it to 5.6?
|
0 |
Character falls through the Platform Effector 2D in Unity. How can I fix it? Character falls through the Platform Effector 2D in Unity. How can I fix it? Here is the demonstration https imgur.com G5YkTxa. I tried changing the Edit Project Settings... Physics 2D Default Contact Offset from the current 0.01 value to the 0.1 value. The result is the same and here is the demonstration of it https imgur.com 3TAOsNY. Here are my settings for the platform Here are my settings for the character's RigidBody 2D Here is what character colliders look like when my character runs https imgur.com CTialU3. I basically run the recorded inside Unity animation of running and move my character with the help of the private void FixedUpdate() ... some code which computes the velocity vector depending on the input (the pressed buttons) characterRigidBody2D.velocity velocityVector I googled for a while now similar issues, but was not able to find a solution. I want to avoid the character falling down randomly during running.
|
0 |
How do I set a scene up for two players? I m finishing a game in Unity, but I have a new requirement make it multiplayer. I will do this by splitting the screen and running two instances. Is there a way to instance a scene twice at the same time, and render them two a different part of the screen? Alternativley, what is the best approach to achieve this?
|
0 |
How to copy the value of a variable from one script to another in Unity? I would need some help with making two floats from two different classes, match their "data". What I want to do here is to make it so when Body.healthb hits a value of 0, Head.health will also hit 0. Any suggestions? I'm barely new to this. The class from which the float comes from public class Body MonoBehaviour public GameObject body public float healthb 50f public void TakeDamageb(float amountb) healthb amountb if (healthb lt 0f) Dieb () Update is called once per frame public void Dieb() Destroy (gameObject) The class it has to reach public class Head MonoBehaviour public static float health 10f public void TakeDamage(float amount) health amount if (health lt 0f) Die () Update is called once per frame public void Die() Destroy (gameObject)
|
0 |
Torque applies to one wheel, but inconsistently to the other wheel I have a GameScript class which is derived by another class WheelScript it is meant to apply torque to a rigidbody in different directions depending upon the key pressed. However the result to this is that one of the rigidbodies rotates fine but the other one doesn't (say the right wheel rotates but the left doesn't turn or even if it does, it doesn't move with the same angular velocity as the first one) Base class public class GameScript MonoBehaviour public static GameScript instance protected float Force protected virtual void Print(GameObject gameObject) print(gameObject.name) protected virtual void MoveForward(Rigidbody rigidBody, int identifier) if(identifier 1) rigidBody.AddRelativeTorque( Vector3.forward Force) else rigidBody.AddRelativeForce( Vector3.forward Force) protected virtual void MoveLeft(Rigidbody rigidBody, int identifier) if (identifier 1) rigidBody.AddRelativeTorque( Vector3.forward Force) else rigidBody.AddRelativeForce( Vector3.forward Force) protected virtual void MoveRight(Rigidbody rigidBody, int identifier) if (identifier 1) rigidBody.AddRelativeTorque(Vector3.forward Force) else rigidBody.AddRelativeForce( Vector3.forward Force) protected virtual void MoveBack(Rigidbody rigidBody, int identifier) if (identifier 1) rigidBody.AddRelativeTorque( Vector3.forward Force) else rigidBody.AddRelativeForce( Vector3.forward Force) Child class public class WheelScript GameScript SerializeField private int identifier Rigidbody body SerializeField float force private void Start() body GetComponent lt Rigidbody gt () Force force void Update() if (Input.GetKey(KeyCode.W)) MoveForward(body, identifier) else if (Input.GetKey(KeyCode.A)) MoveLeft(body, identifier) else if (Input.GetKey(KeyCode.D)) MoveRight(body, identifier) else if (Input.GetKey(KeyCode.S)) MoveBack(body, identifier) and similarly for the other wheel with only difference being that of axis as its axis is (0,0, 1) Hinge Joint for left wheel is visible in this picture Hinge Joint for right wheel is visible here in this picture This is how each wheel is aligned Hinges are attached to the pivot in the opposite direction as marked in the circle Also I think I forgot to mention but the WheelScript is attached to both the wheels (it is the script component for both wheels)
|
0 |
Unity Calculating a rotation based on game time I have a simple script to make an object spin Spin Speed is the speed to rotate the object on each axis (preferably in degrees per second). Local is whether the rotation should be done based on world axes or object axes. Starting Rotation is the initial rotation of the object. Normally I would use Transform.Rotate to do the rotation, but in this case I have to make the rotation a function of time, so you can pass in any time value and it will return what the rotation should be at that time. Here is an example (this doesn't work properly for either world or object axis rotation) private Quaternion getRotation(float time) return Quaternion.Euler(InitialRotation SpinSpeed time) I just need some help figuring out the math behind calculating rotations for both world and object axes. I think that matrices can be used but I honestly don't remember anything about how to use them. Here's an example of using world axes with a SpinSpeed of 180 on the y axis and an initial rotation of 45 on the x axis https i.gyazo.com d7f41b6a88425b5d8b8237cd7ac40878.gif An example of using local axes with the same parameters as above https i.gyazo.com d453b3dd239c9f77b86ce372c499d068.gif
|
0 |
Unity3d Pause RigidBody object, don't stop time Time.timeScale 0 obviously works to stop physics but it's also stoping my Invoke calls. How can I get around this to pause ONLY the game physics? EDIT Temporarily I'm using isKinematic true on all of my rigid body objects via event trigger.
|
0 |
Bug with OnColliderEnter Exit when colliding with multiple objects at almost the same time Unity Version 2017.4.1f1 I currently have a game with a jumping mechanic. I only want the jump to work where you're on ground, so I have planes on top of everything, which, if you are on a plane, then you can jump. This works, however if you are in a position where you are falling and then in quick succession, hit one plane, fall off that plane (like when your centre of mass is hanging off the edge), then land on another plane, at the end of it all, it still thinks you are on the air. Note I don't think this is an error with the velocity of the player, at no point do you go through a collider. So my question is, is there an error in my code (shown below) which I can fix, or should I take another approach towards jumping, thanks. Relevant code below. private bool canJump private Rigidbody rb public float jumpStrength private void OnCollisionEnter(Collision collision) if (collision.collider.CompareTag("Jumpable")) canJump true private void OnCollisionExit(Collision collision) if (collision.collider.CompareTag("Jumpable")) canJump false private void Update() if (canJump amp amp Input.GetKey(Keyode.W)) rb.velocity new Vector3(0, jumpStrength, 0) canJump false Safety measure to ensure consistent jump height Thanks
|
0 |
Lighting changes when loading scene I have a script that changes the levels using Application.LoadLevel (sceneNameToChangeTo) Once a level is loaded using that code when testing with the editor, the lighting changes dramatically. I've checked if something changes in the light or lighting settings, but it doesn't. This is a screen of how the scene looks when I simply press RUN in the scene in the editor Notice the blue tints from the sky etc. This is clearly PBS lighting. Now after I use my code to change the scene to another one and then back to this one, the scene looks like this What am I doing wrong? I am using Unity 5.0.1. This effect does not happen on mobile devices.
|
0 |
My GUI stopped working? Okay I bought this asset online so I would like not to show the whole script. The problem is this asset stopped working when I updated from unity 5.0 to 5.1.2. The script is for a controller GUI interface but it seems to be giving me an error NullReferenceException Object reference not set to an instance of an object UnityEngine.UI.Selectable.Select () on this line of code selectedOject.GetComponent lt Button gt ().Select () so there is a null reference and its no longer recognizing the child objects as buttons is what I'm assuming if you want to have a better look at his set up he has a short video On youtube HERE I would like to continue to use this script and continue updating Unity.
|
0 |
Is it bad practice to store inventory and scores in PlayerPrefs? I'm building a mobile game for a client in Unity. To save time, we started with a template game from the Asset Store that had some of the features that the client wants. The game includes a progression system and shop, so we save the user's scores, progress, in game currency, inventory, etc. We currently have no plans to export the save data. The template game uses PlayerPrefs to store all save data. Is this bad practice? Assuming we don't include a button that calls PlayerPrefs.DeleteAll(), is there any extra risk associated with using PlayerPrefs instead of external files to store the player's data?
|
0 |
see inside but not light from outside I have a top down view of the interior of a house. I want to put a cover on the top so light from outside can't come in and I get more realistic lighting inside but transparent so I can still see inside. No clue how to achieve this in Unity. Any help would be appreciated. Ideally I'd just be able to use Unity's built in cube to make this.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.