_id
int64
0
49
text
stringlengths
71
4.19k
0
Bullet physics C script Is imparting force on rigidbody objects I have recently made the simplest gun and bullet script that I could and it works amazingly, except for one problem that I've found. When I attach it to a game object with a rigid body the force of the bullets move the object back with quit a bit of force. But what I can't seem to figure out is why the bullets are imparting force on the object at all. The bullets do not have a rigid body component. The way my guns work is with two scripts, one which acts as a simple spawning point when a key down event is given and what ever object you give it to spawn. The second script is applied to the bullet itself which causes the bullet to have motion through transform.Translate with a speed variable. The best example I can give of this is when I attached two guns to the default unity jet and when I fired, it had enough force to move the jet back against its thrust speed. I really would appreciate any help with this so I can move on with my project. I will provide the code bellow for the two scripts. Thank you public class Shoot MonoBehaviour public GameObject bullet void Update () if (Input.GetKey (KeyCode.Mouse0)) Instantiate(bullet, transform.position, transform.rotation) public class MoveBullet MonoBehaviour public float speed 1f void Update () transform.Translate (0, 0, speed)
0
In Depth Lockstep Explanation I'm making a multiplayer game built upon a lockstep system and I'd just like a better grasp on the concept. My main question is on how to get every command to simulate at the same time on every client, or rather, on the same points in each client's timeline. I'm using a fixed update of 10 frames per second for simulating every object's position from movement commands (Click and move style) the same way. How do I tell all clients to execute all commands at the same relative time to the first command? Note I'm using Unity3D and a sufficiently accurate physics implementation. I just need to get across every command at the correct time.
0
Animating two characters (like a fighting game) whose animations are tied together? So, say one character grabs another and throws him against a wall. Are these two separate animations that get attached to each character? Or is this really one animation that somehow involves each character model to itself? I'm using the Unity game engine.
0
How to remove a scene after the another one has loaded 2 3I'm having this problem in Unity where I load a new scene, but the original is still overlapping it. How would you remove the original scene?
0
How to know when the cameras change? I'm working on a script that uses raycasting from the camera's perspective to see what the player is looking at. Pretty standard stuff. The only question is, how to reliably find the camera? Everything I've seen says you don't want to use Camera.main in Update() because performance, so instead you should call it once in Start() and cache it in a field. And that's great, as long as you can guarantee that the main camera will never change. But what if it does? What I'd like is to have some sort of OnCameraUpdated event I can subscribe to that will let me know when the main camera has changed, but I don't see anything like that on the Camera class. Is there any good way to find this out without polling for it?
0
Rotating UI element using touch for mobile Unity 2D I want to create the above object that will rotate on z axis following the direction of a finger. Like a dial. I have written the following code and attached it to that element private float rotationRate 3.0f void Update() get the user touch input foreach (Touch touch in Input.touches) Debug.Log("Touching at " touch.position) if (touch.phase TouchPhase.Began) Debug.Log("Touch phase began at " touch.position) else if (touch.phase TouchPhase.Moved) Debug.Log("Touch phase Moved") transform.Rotate(touch.deltaPosition.y rotationRate, touch.deltaPosition.x rotationRate, 0, Space.World) else if (touch.phase TouchPhase.Ended) Debug.Log("Touch phase Ended") But the element does not move at all. Any ideas? EDIT Here is a gif for better understanding
0
How do you set the target location for a navmesh using a GameObject? I am trying to get a GameObject to navigate through a map and get to the exit. I have created a navmesh for the map and given the player GameObject a navmesh agent. The exit is marked with a empty GameObject. Using the unity manual I made this script and atached it to the player function Start () var agent NavMeshAgent GetComponent. lt NavMeshAgent gt () agent.SetDestination(GameObject.Find("exit")) The porblem is that this script gives the error "Assets Scripts enemy.js(4,29) BCE0017 The best overload for the method 'UnityEngine.NavMeshAgent.SetDestination(UnityEngine.Vector3)' is not compatible with the argument list '(UnityEngine.GameObject)'." I think is is because unity wants a vector3 but I have given it a GameObject. How can I get this to work with a game object?
0
Calculating t value to use with Hermite interpolation I'm developing an FPS in Unity using Photon for networking. The Photon provided interpolation is very basic so I decided to roll out my own using the Hermite spline. It works good and is significantly better than the provided interpolation. However, I was wondering what's the correct way to choose the t value. In a perfect world, it should be incremented by deltaTime timeBetweenPositionUpdates. However, that doesn't work since even if the tickRate is set to 10 for example, sometimes the client sends it at 9.5, and then at 10.2 and so on and so forth. This means that we can't have a constant increment rate for the t value since it'll either lag behind or move too fast and we'll run out of buffered frames. What I decided to do is to send the time between frame updates as well and interpolate using that. But, this also isn't perfect by any stretch of the imagination and the receiving client will soon lag very much behind. What I'm doing now is using a multiplier on the t value such that if there is more frames in the buffer than we want to have then it'll speed the interpolation up, and if there's less than how many we want in the buffer then it'll slow the interpolation down. This works pretty well, but it's a hack I believe. Is there a better way, or a proper way to do this?
0
Why does my Unity animator state "finish" before the visible motion does? Example The TopAppearing motion boost the alpha of the sprite from 0 to 1 for total of 2 seconds After TopAppearing state has been finished The TopAppearing's transition settings Question Why is the Top's sprite alpha 235 after the TopAppearing animatior state has been finished?
0
What's the best way to make a game launcher? I am a new game dev, and would like to make a launcher for my games. All my games would be in ONE launcher, and it'd be similar to the Minecraft Launcher. I wanna do it for free too. The main reason I wanna do it is to update my games. I don't have a file server, so the files would be on Google Drive. Thanks!
0
Unity post processing Bloom lags on mobile I made my (first) game today and noticed, that it looked kind of boring, so I decided to add some bloom to my camera and it was looking waaay better. The only problem was the performance, it dropped down from constant 60 fps to like 20 30, I looked it up in the profiler to be sure and yep, it was the post processing, I saw mobile games which had post processing including bloom, but these games never lagged on my phone. My phone has pretty good specs for a phone (Samsung Galaxy M20) so how do I make my post processing performant, are there some special settings I have to make or is it just my phone?
0
Unity test Play mode window problem I tried to find an answer to his problem but i wasn't successful. When i press play to test my game, instead of the play mode going to the Game tab and play the game there, with all the unity tabs and options still on the screen, it goes almost full screen, all of the unity window goes to the game mode and i can't see anything but the game, to see the scene, options, etc.. again i need to stop the play mode. For example, if i want to test triggers in play mode, i can't because all i see is the game window. How can i test the game just in the Game tab? Perhaps i changed some setting. I'm not sure if im explaining my problem correctly. Thank you
0
NullReferenceException Object reference not set to an instance of an object on boolean variable from separate class I'm trying to develop game scenario that able to trigger the alarm with alarm light and siren audio to play. For the testing purpose I set it that to boolean value as "alarmOn" in AlarmLight class. AlarmLight.cs public class AlarmLight MonoBehaviour public float fadeSpeed 2f public float highIntensity 2f public float lowIntensity 0.5f public float changeMargin 0.2f public bool alarmOn false private float targetIntensity public Light light add alarm lights tag as siren void Awake() light.intensity 0f targetIntensity highIntensity void Update() if (alarmOn true) light.intensity Mathf.Lerp(light.intensity, targetIntensity,fadeSpeed Time.deltaTime) ChecktargetIntensity() else light.intensity Mathf.Lerp(light.intensity, 0f, fadeSpeed Time.deltaTime) void ChecktargetIntensity() if (Mathf.Abs(targetIntensity light.intensity) lt changeMargin) if (targetIntensity highIntensity) targetIntensity lowIntensity else targetIntensity highIntensity Then I tried to access that value with LastPlayerSight class and for the testing purpose i was trying to return false as below. alarm.alarmOn (playerPosition ! resetPlayerPosition) Then I tried to play my scene, and I got the error which is the problem with above line of code. This is my LastPlayerSight.cs class public class LastPlayerSight MonoBehaviour public Vector3 playerPosition new Vector3(1000f, 1000f, 1000f) public Vector3 resetPlayerPosition new Vector3(1000f, 1000f, 1000f) public float lightHighIntensity 0.25f public float lightLowIntensity 0f public float fadeSpeed 7f public float musicFadeSpeed 1f directional alarmlight ref private AlarmLight alarm main directional light ref private Light mainLight private AudioSource panicAudio siren audio private AudioSource sirens void Awake() alarm GameObject.FindGameObjectWithTag(Tags.alarms).GetComponent lt AlarmLight gt () mainLight GameObject.FindGameObjectWithTag(Tags.mainLight).GetComponent lt Light gt () GameObject sirenAttachedGameObjects GameObject.FindGameObjectsWithTag(Tags.siren) sirens new AudioSource sirenAttachedGameObjects.Length for(int i 0 i lt sirens.Length i ) sirens i sirenAttachedGameObjects i .GetComponent lt AudioSource gt () void Update() SwitchAlarms() MusicFading() void SwitchAlarms() alarm.alarmOn (playerPosition ! resetPlayerPosition) float newIntensity if(playerPosition ! resetPlayerPosition) newIntensity lightLowIntensity else newIntensity lightHighIntensity mainLight.intensity Mathf.Lerp(mainLight.intensity, newIntensity,fadeSpeed Time.deltaTime) for (int i 0 i lt sirens.Length i ) if (playerPosition ! resetPlayerPosition) sirens i .Play() else sirens i .Stop() void MusicFading() AudioSource audioTemp audio.GetComponent lt AudioSource gt () if (playerPosition ! resetPlayerPosition) audio.GetComponent lt AudioSource gt ().volume Mathf.Lerp(audio.volume, 0f, musicFadeSpeed Time.deltaTime) panicAudio.volume Mathf.Lerp(panicAudio.volume, 0.8f, musicFadeSpeed Time.deltaTime) else panicAudio.volume Mathf.Lerp(panicAudio.volume, 0.0f, musicFadeSpeed Time.deltaTime) I'm beginner of developing such things and can anyone guide me to correct the problem?
0
Build pipleine between 2 points take rotation into account Given a start point and start rotation and end point and end rotation, how can i find a path from start to end, that takes rotation into account and moves only on the axis. I currently have a code that can handle straight line and a L turn. I want it to be able to handle also S or U turn (like on this image), but i cant figure out how to do it. Below is my current code for handling the pipleine building. How do different games handle that? Like satisfactory fluid pipes on vertical mode. Vector3 endPos endPosition Vector3 startPos startPosition Vector3 dir startRotation Vector3.forward Vector3 diff endPos startPos Conveior prev startTarget int dist1 Mathf.RoundToInt(Vector3.Scale(diff, dir).magnitude) BuildStraight(dist1, ref startPos, dir, startRotation, ref prev) Vector3 endDir endRotation Vector3.forward GameObject temp if (dir ! endDir) temp GameObject.Instantiate(turnRight, startPos, Quaternion.AngleAxis(Vector3.Angle(prev.transform.right, endDir), dir) startRotation) else temp GameObject.Instantiate(straight, startPos, startRotation) temp.GetComponent lt RaycastController gt ().dontIgnoreRaycast() temp.transform.Find( quot DirectionGuides quot ).gameObject.SetActive(false) Conveior t temp.GetComponent lt Conveior gt () if (prev ! null) prev.SetNext(t) prev t diff endPos startPos int dist2 Mathf.RoundToInt(Vector3.Scale(diff, endDir).magnitude) startPos endDir BuildStraight(dist2, ref startPos, endDir, endRotation, ref prev) if (endTarget) prev.SetNext(endTarget) private void BuildStraight(int distance, ref Vector3 startPos, Vector3 dir, Quaternion rotation, ref Conveior prev) for (int i 0 i lt distance i , startPos dir) GameObject go GameObject.Instantiate(straight, startPos, rotation) go.GetComponent lt RaycastController gt ().dontIgnoreRaycast() go.transform.Find( quot DirectionGuides quot ).gameObject.SetActive(false) Conveior c go.GetComponent lt Conveior gt () if (prev ! null) prev.SetNext(c) prev c
0
Interpolation UNITY taking longer than expected I'm trying to do multiplayer interpolations with the lidgren network (UDP) but the interpolation is taking longer than expected and the message queue is getting full. It's been a week and I still can't find the issue. Here's an approximate code private void Update() if (networkUpdates.Count gt 0 amp amp CurrentUpdate.Finished) var update networkUpdates.Dequeue() CurrentUpdate NextVesselUpdate NextVesselUpdate update StartupInterpolation() private void StartupInterpolation() CurrentVesselUpdate.NextUpdate NextVesselUpdate StartCoroutine(CurrentVesselUpdate.ApplyUpdate()) In the CurrentVesselUpdate class.... public IEnumerator ApplyUpdate() InterpolationDuration NextUpdate.SentTime SentTime for (float p 0 p lt 1 p (Time.delta InterpolationDuration)) ApplyInterpolations(p) Several lerps here yield return null Finished true ApplyInterpolations(1) Several lerps here
0
Travel over step angle http www.gamasutra.com blogs AdamWinkels 20140220 211306 DevLog 7 Learning How to Walk.php Following the link above I have been able to get my character to move and rotate very smoothly over angled surfaces up to 80 degrees. Anything over that and it begins to clip and wobble when traveling down the surface. The spiders rotation only reaches half of the desired angle. So at 85 degrees it only rotates to 42.5. Going up is a mess, but I have not implemented the fix for that from the link above, so I am less worried about that. Any suggestions? private float RayDuration 0 private float RayAngle 5f private float RayLength Vector2 MovementDirection float OffSetY 5 float OffSetX .5f int GroundMask 1 lt lt 8 void Start() SpiderRect GetComponent lt RectTransform gt () RayLength SpiderRect.rect.height private void TouchHeld(CustomEvent customEvent) if (Input.mousePosition.x gt 400) MovementDirection transform.right else MovementDirection transform.right Vector2 transformUp transform.up Vector2 position transform.position Vector2 rightRayPosition new Vector2(transform.position.x OffSetX, transform.position.y OffSetY) Quaternion rightOffSetAngle Quaternion.AngleAxis( RayAngle, new Vector3(0, 0, 1)) Vector2 rightRayAngle rightOffSetAngle Vector2.down Vector2 leftRayPosition new Vector2(transform.position.x OffSetX, transform.position.y OffSetY) Quaternion leftOffSetAngle Quaternion.AngleAxis(RayAngle, new Vector3(0, 0, 1)) Vector2 leftRayAngle leftOffSetAngle Vector2.down RaycastHit2D rightHit Physics2D.Raycast(rightRayPosition, rightRayAngle, RayLength, GroundMask) RaycastHit2D leftHit Physics2D.Raycast(leftRayPosition, leftRayAngle, RayLength, GroundMask) region move if (rightHit amp amp leftHit) Debug.DrawRay(rightRayPosition, rightRayAngle, Color.red, RayDuration) Debug.DrawRay(rightRayPosition, rightHit.normal, Color.green, RayDuration) Debug.DrawRay(leftRayPosition, leftRayAngle, Color.yellow, RayDuration) Debug.DrawRay(leftRayPosition, leftHit.normal, Color.magenta, RayDuration) Vector2 averagePoint (leftHit.point rightHit.point) 2 Debug.DrawRay(averagePoint, transform.up, Color.cyan, RayDuration) Vector2 averageNormal (leftHit.normal rightHit.normal) 2 Debug.DrawRay(averagePoint, averageNormal, Color.cyan, RayDuration) Quaternion targetRotation Quaternion.FromToRotation(Vector3.up, averageNormal) Quaternion finalRotation Quaternion.RotateTowards(transform.rotation, targetRotation, 10) transform.rotation Quaternion.Euler(0, 0, finalRotation.eulerAngles.z) transform.position Vector2.MoveTowards(transform.position, averagePoint MovementDirection, .15f) else Debug.Log("What")
0
3 hit combo system plays first attack animation every time So the new input system is out, and we're using it for our game. The next hurdle I'm trying to get over is implementing a melee combo ( E E E). Not 100 sure how to get the new system to execute something like that. Right now my trigger isn't resetting. Images of the animator graph at the bottom public class PlayerController MonoBehaviour Rigidbody2D rigidbody SpriteRenderer renderer Animator animator public float fallMultiplier 2.5f public float lowJumpMultiplier 2f PlayerInputActions inputActions Vector2 movementInput public bool inInteractionZone public int attackCount 0 public float attackTimeout 0.5f bool touchingWall private void Awake() HRHEventHub.OnPlayerDeath HRHEventHub OnPlayerDeath inputActions new PlayerInputActions() inputActions.Player.Move.performed ctx gt movementInput ctx.ReadValue lt Vector2 gt () inputActions.Player.Interact.performed InteractPressed private void InteractPressed(InputAction.CallbackContext obj) TODO add attack timeout Check if we are inside a interaction zone if (inInteractionZone) TODO implement return if (attackCount 0 amp amp grounded) attackCount animator.SetTrigger("Attack") animator.SetBool("ATK1", true) else if (attackCount 1 amp amp grounded) attackCount animator.ResetTrigger("Attack") animator.SetTrigger("Attack") else if (attackCount 2 amp amp grounded) attackCount 0 animator.ResetTrigger("Attack") animator.SetTrigger("Attack")
0
Combining cubes Issue in Marching Cubes I was trying to implement the marching cubes and combine every little cube this way I get a cube of vertices depending on their surfaceLevel I look for the ones that are below the surfaceLevel and get the edges that relates to them get a vertice out of the edge using the formula on http paulbourke.net geometry polygonise I put every vertex i created based on the edges on mesh.vertices I make the order on mesh.triangles based of the edge number on triTable i combine everything but i get this Here's my code https pastebin.com jqetCk8r. My guess was that the combine order of every marched little cube is not good. I've got no idea know how to solve this. ps the triTable doesn't show in the pastebin, i copied it from the same link above.
0
Coroutine problem, I don't know what's happening Calling function. private const int deathHangTime 2 private void Die() Debug.Log("1 " Time.time) StartCoroutine(DelayForTime(deathHangTime)) Debug.Log("4 " Time.time) Coroutine IEnumerator DelayForTime(float time) Debug.Log("2 " Time.time) yield return new WaitForSeconds(time) Debug.Log("3 " Time.time) Why doesn't it wait for 2 seconds? Why doesn't it print the 3rd Debug line?
0
Improve appearance of neon LineRenderer at sharp corners I followed the answer given in how to make 2d neon using linerender and get neon effect nicely, but when I draw a line with a tight circle or overlap nearby lines, I get unsightly triangle artifacts and discolouration I'm using this alpha image And I apply this shader on the LineRender Shader quot Trail Neon quot Properties PerRendererData MainTex( quot Sprite Texture quot , 2D) quot white quot Color( quot Tint quot , Color) (1,1,1,1) MainTexture( quot Sprite quot , 2D) quot white quot MaterialToggle PixelSnap( quot Pixel snap quot , Float) 0 SubShader Tags quot Queue quot quot Transparent quot quot IgnoreProjector quot quot True quot quot RenderType quot quot Transparent quot quot PreviewType quot quot Plane quot quot CanUseSpriteAtlas quot quot True quot Cull Off Lighting Off ZWrite Off Blend One OneMinusSrcAlpha Pass CGPROGRAM pragma vertex vert pragma fragment frag pragma target 2.0 pragma multi compile PIXELSNAP ON pragma multi compile ETC1 EXTERNAL ALPHA include quot UnityCG.cginc quot struct appdata t float4 vertex POSITION float4 color COLOR float2 texcoord TEXCOORD0 UNITY VERTEX INPUT INSTANCE ID struct v2f float4 vertex SV POSITION fixed4 color COLOR float2 texcoord TEXCOORD0 UNITY VERTEX OUTPUT STEREO fixed4 Color v2f vert(appdata t IN) v2f OUT UNITY SETUP INSTANCE ID(IN) UNITY INITIALIZE VERTEX OUTPUT STEREO(OUT) OUT.vertex UnityObjectToClipPos(IN.vertex) OUT.texcoord IN.texcoord OUT.color IN.color Color ifdef PIXELSNAP ON OUT.vertex UnityPixelSnap(OUT.vertex) endif return OUT sampler2D MainTexture sampler2D AlphaTex fixed4 SampleSpriteTexture(float2 uv) fixed4 color tex2D( MainTexture, uv) if ETC1 EXTERNAL ALPHA get the color from an external texture (usecase Alpha support for ETC1 on android) color.a tex2D( AlphaTex, uv).r endif ETC1 EXTERNAL ALPHA return color fixed4 frag(v2f IN) SV Target standard sprite shader, only this part is different. takes the sprite in fixed4 s SampleSpriteTexture(IN.texcoord) makes a colored version of the sprite fixed4 c s IN.color makes the grayscale version fixed n (s.g s.r s.b) 3 So, I've scrapped the previous calculation in favor of this I'll leave the previous one in too, just for reference c (c 3 n c.a) c.a Adds the grayscale version on top of the colored version The alpha multiplications give the neon effect feeling c.g (c.g n c.a) c.a c.r (c.r n c.a) c.a c.b (c.b n c.a) c.a You can add c.a multiplications of colors (i.e. turn c.g to c.g c.a) for less color in your effect this saturates the insides a bit too much for my liking return c ENDCG How can I improve the appearance of these corners, so they look smooth?
0
How can I scroll animate up lines reading from a string to ui text? This is the reading lines code if (primaryTarget ! null) var lines primaryTarget.description.Split(' n') text.text quot Item found quot primaryTarget.description else text.text quot quot And this is the script of the description The script is attached to each interactable target(item) using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class InteractableItem MonoBehaviour public enum InteractableMode your custom enumeration Description, Action public InteractableMode interactableMode InteractableMode.Description public float distance private bool action true TextArea(1, 10) public string description quot quot public void ActionOnItem() if(interactableMode InteractableMode.Action amp amp distance lt 5f amp amp action true) action false Depending on the amount of text in the string I want to show it in the ui Text. If there is one line then just show the text or even if there are two lines. but if there is a lot of text then split the lines and scroll the lines smooth up so the first line will be disappear or pushed up and bottom lines will come up. In the screenshot you can see on the left the text that show in the ui text on the right the text of the description. The ui text can't show all the text and I don't want the text to overlap other ui's or objects so the idea is to make the text slowly smooth scrolling up.
0
Create fog (smoke) on Unity3D? I'm creating a game where you are inside a boiler room, the problem is I want to create the fog (smoke) to make this more realistic.
0
Unity 2D Player Shoots at my joystick position Hi I am new to unity and have only a little coding knowledge. Right now I have made my character shoot at my touch position on mobile but when ever I touch the joystick, whick I use to move my character, he shoots there, what should I do to make him not shoot at the joystick when i hold the joystick, any suggestion... heres my code. Shooting code public class Shooting MonoBehaviour public GameObject shot private Transform playerPos void Start() playerPos GetComponent lt Transform gt () void Update() if (Input.GetTouch(0).phase TouchPhase.Began) Instantiate(shot, playerPos.position, Quaternion.identity) else if (Input.GetTouch(1).phase TouchPhase.Began) Instantiate(shot, playerPos.position, Quaternion.identity) else if (Input.GetTouch(2).phase TouchPhase.Began) Instantiate(shot, playerPos.position, Quaternion.identity) Projectile Code public class Projectile MonoBehaviour private Vector2 target public float speed private Shake shake void Start() shake GameObject.FindGameObjectWithTag( quot ScreenShake quot ).GetComponent lt Shake gt () target Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position) target Camera.main.ScreenToWorldPoint(Input.GetTouch(1).position) target Camera.main.ScreenToWorldPoint(Input.GetTouch(2).position) Update is called once per frame void Update() transform.position Vector2.MoveTowards(transform.position, target, speed Time.deltaTime) if(Vector2.Distance(transform.position, target) lt 0.2f) Destroy(gameObject) void OnTriggerEnter2D(Collider2D other) shake.CamShake() Thanks in advance
0
On key press, spawn a collider where my player is facing? I'm trying to create an attack mechanic to my player hero in my 2D Tower Defense game. When I press the Q button I want my hero to do an animation and spawn a temporary collider shaped as a cone at where the hero is looking at. If this collider collides with a GameObject called "Stone" it will decrease its hpValue with a script I made. If there is multiple Stones in the cone I want it to only effect one Stone, chosen either by random or and closest to the hero. How would I go about doing this and how can I detect the direction of where my hero is facing? This is my movement script public float speed Movementspeed Rigidbody2D rbody void Start () rbody GetComponentInChildren lt Rigidbody2D gt () rbody.freezeRotation true void FixedUpdate () Vector2 movement vector new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")) rbody.MovePosition (rbody.position movement vector speed Time.deltaTime) A picture visualising what I mean
0
The camera does not capture movements in z axis I want to make a simple drag and drop card in Unity, where the card pops up a bit towards the screen when the drag begins (lifting effect), and then drops down back on the table when the drag ends. My script looks like this public class Draggable MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler void IBeginDragHandler.OnBeginDrag(PointerEventData eventData) this.transform.position new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z 10) public void OnDrag(PointerEventData eventData) this.transform.position new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10) public void OnEndDrag(PointerEventData eventData) this.transform.position new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z 10) The card is an image, and it is child of the canvas. The render mode for the canvas is Screen Space Overlay. The drag works correctly, but I cannot capture the movements in the z axis. It does capture the movements in the z axis when I change the render mode. However, then the card is too far away in the z axis, and it moves with an offset with respect to the mouse pointer. As far as I understood, I need to do something about realtive distances, but I how can I force the mouse pointer to be on z 0 plane.
0
Why the update function only call once I asked about this question How to efficiently implement a 7 segment display? in previous post. Now I just add an update function to the last part of the code to display the time(I don't bother the exact time at the moment just want to make sure the number change regularly). However,I'm not sure why the update only run once, I checked the answer in this website, mentioned the root cause is gameobject deactivated(Update function only running once) but this is not my case. I tried with void OnMouseDown() Display(DateTime.Now.Second) , the number does change according to my mouse button so I'm not sure what wrong with Update function. In addition, I assigned all the variable but it still pop out message unassigned reference exception, not sure where the problem. using System using UnityEngine public class ClockDigit MonoBehaviour Assuming you number your segments as follows 0 5 1 6 4 2 3 Store a lookup table for which segments should be active when displaying each digit. static readonly bool , SEGMENT IS ACTIVE new bool , true, true, true, true, true, true, false , 0 false, true, true, false, false, false, false , 1 true, true, false, true, true, false, true , 2 true, true, true, true, false, false, true , 3 false, true, true, false, false, true, true , 4 true, false, true, true, false, true, true , 5 true, false, true, true, true, true, true , 6 true, true, true, false, false, false, false , 7 true, true, true, true, true, true, true , 8 true, true, true, true, false, true, true 9 public Color32 activeColour Color.red public Color32 inactiveColour Color.black public SpriteRenderer segments new SpriteRenderer 7 public void Display(int number) var digit number 10 if (digit lt 0) digit 1 for (int i 0 i lt 7 i ) if (SEGMENT IS ACTIVE digit, i ) segments i .color activeColour else segments i .color inactiveColour public void Update() Display(DateTime.Now.Second) I tried this command also, the infinite loop freeze the Unity and FixedUpdate() command also update the frame only one time. void Update() while(true) Display(DateTime.Now.Second)
0
"Overloading" GameObject? I would like to show weapons and health items in an inventory grid. The item can be rotated in the grid, and it occupies a certain region in the grid. Currently I store this information (where the item is located, if it is rotated, etc.) in an additional array. However, this is not elegant and error prone. I would therefore like to ask if it is possible to somehow store this additional information directly in the weapon or health GameObject. Ideally I would like to be able to do something like this Pistol.GridProps.Rotation 90 Pistol.GridProps.Row 5 Pistol.GridProps.Col 3 Is it possible to add something like "GridProps" to all my game objects? Thank you!
0
Why does Unity think my RectTransform has changed? I am working with UI. I want to know when my RectTransform changes its position. I am using transform.hasChanged void Update() if (transform.hasChanged) Debug.Log("Updated Position") transform.hasChanged false However, it thinks it has always changed. "Updated Position" is constantly printing out. If I remove and then readd the component while in play mode, the issue resolves itself. However, I don't want to have to do this, as it is very hacky. I could just throw a bunch of if statements in there to check, but I'd prefer to make use of the build in transform.hasChanged property. How can I check to see if my RectTransform has changed its position efficiently and elegantly?
0
How to create an animation clip that changes whatever color a RawImage has to a certain destination color? I created an animation clip that turns a certain RawImage's color from white to red. I'd like to know how I could change that clip to turn any color that the RawImage might have into red with other words, I don't want to have a specific starting color. Instead the current color shall be used and faded to red.
0
Space to Switch to Hand Tool in Tile Palette? Hi I just download a Utility called Hold Spacebar for Hand (drag) Tool I read the code and I can understand it, but now I wondering how can I modify this to support the same functionality but works in Tile Palette tab, thanks!
0
How to solve conflicting OnValidate() functions I have two OnValidate() functions in two scripts, one attached to the Enemy (EnemyScript) game object and the other to the Enemies(EnemiesScript) game object. In OnValidate() in EnemyScript I have the following void PrepareEnemyType(EnemyType enType) by default hasHibernated false if (!hasHibernated) if (enType EnemyType.Green) gameObject.GetComponent lt SpriteRenderer gt ().sprite Resources.Load lt Sprite gt ("Sprites greenEnemy") else if (enType EnemyType.Red) gameObject.GetComponent lt SpriteRenderer gt ().sprite Resources.Load lt Sprite gt ("Sprites redEnemy") else if (hasHibernated) gameObject.GetComponent lt SpriteRenderer gt ().sprite Resources.Load lt Sprite gt ("Sprites greyEnemy") In OnValidate() in EnemiesScript I have the following for (int i 0 i lt enemies.Length i ) if (!enemies i . hasHibernated) enemies i . hasHibernated true based on the above all the enemies should change sprite to greyEnemy sprite, but that doesn't happen. Before I run the application all of them change to greyEnemy sprite initially, then after I run the application some of them change back to their original sprites, and when I stop running the application they sprites remain the same as when the application was running (different sprites). At this point, the only time that they all become grey again is when I make some other edit to either one of the scripts and save it. Then the above transition repeats. I suspect there could be some conflict with the two OnValidate() functions, not certain though. How can I resolve this?
0
How can I customize scrollbar sensitivity in editor property drawers in Unity3D? A custom property drawer, in my Unity 2017.3 project, has code like this in its OnGUI implementation public void OnGUI(Rect position, SerializedProperty property, GUIContent label) ... EditorGUI.BeginDisabledGroup(maxX 0) scrollX (uint)GUI.HorizontalScrollbar(new Rect(xyPos new Vector2(slHeight, normalizedSize), new Vector2(normalizedSize, slHeight)), scrollX, 1, 0, maxX 1, GUI.skin.horizontalScrollbar) EditorGUI.EndDisabledGroup() EditorGUI.BeginDisabledGroup(maxY 0) scrollY (uint)GUI.VerticalScrollbar(new Rect(xyPos, new Vector2(slHeight, normalizedSize)), scrollY, 1, maxY 1, 0, GUI.skin.verticalScrollbar) EditorGUI.EndDisabledGroup() ... But these scrollbars have a sensitivity of 10 (pressing the up down, or left right, buttons will change the current value by 10 in the respective direction). I need them to have a sensitivity of 1. How can I do it?
0
In Unity, is there a way to Set a new MeshRenderer? Here is what I want to do in Unity for a given GameObject go new GameObject(). I want to create a MeshRenderer, change its properties and only in the end set it as the component of go. For instance MeshRenderer newmeshrenderer (...) do stuff with newmeshrenderer go.AddComponent lt MeshRenderer gt () newmeshrenderer (or) go.GetComponent lt MeshRenderer gt (newmeshrenderer) But both way fail. What is the correct way of setting a MeshRenderer previously created to be the MeshRenderer of an object?
0
How do I make a MoveToward() GameObject jump without Rigidbody, CharacterController or Raycast? I have a prefab that is moving from one point to another thanks to MoveTowards(). Currently, I am having trouble with a functionality where the player can press a button and make the object jump, affecting only the Y coordinate. I tried doing the following before putting the MoveTowards() code down void Start() playerInstance Instantiate(playerPrefab, startPos.position, Quaternion.LookRotation(endPos.position), null) speed Random.Range(2f, 8f) currentPlayerInstancePositionY playerInstance.transform.position.y isGrounded true void Update() if (isGrounded) if (Input.anyKeyDown) playerInstancePositionY jumpForce else playerInstancePositionY currentPlayerInstancePositionY else playerInstancePositionY gravity Time.deltaTime currentPlayerInstancePositionY playerInstancePositionY playerInstance.transform.position Vector3.MoveTowards(playerInstance.transform.position, endPos.position, speed Time.deltaTime) I just used custom gravity to decide when the object falls. But the problem I found was that MoveTowards() takes a Start Position, an End Position and a Float in its method. But it cannot change individual coordinate values. As the only control you have over the object is making it jump, I was wondering if there was another way to implement this since the Y value is not being inserted into the prefab before it is given the MoveTowards() function. I am trying to implement the jump mechanic without any RigidBodies, CharacterControllers or Raycasts. Any help would be appreciated.
0
Best way to create icon for UI , based on 3d model player can use in game I'm trying to figure the best way to create icon (for UI) from my 3d model (object) that player can use in the game. Maybe this is a silly question, but how do you create icon ? Do you create a new scene, place object and use a "shift print" to take screenshots ? Others way ? Thanks
0
Single Letter Alphabet recognition in AR I am developing an AR game with unity where I need to recognize alphabets in runtime. I have tried vuforia but it does not support single letter recognition. OpenCV is an alternative solution, but I don't understand how to detect text in Runtime with OpenCV. I have also tried object recognition, NFT and markerless tracking. But all of these failed because a single letter does not have enough feature to get detected. I am really new in Augmented reality and image processing. Can anyone give me a guideline or plan what I should do? I am using this letter blocks from amazon https www.amazon.ca gp product B0006MU23W ref s9u simh gw i1?ie UTF8 amp pd rd i B0006MU23W amp pd rd r 22ef1e20 b08e 11e7 91cc bbe5f37c0d0f amp pd rd w wCg3M amp pd rd wg NG8Lg amp pf rd m A3DWYIK6Y9EEQB amp pf rd s amp pf rd r TH85A9MZFVDZPD8YYR5P amp pf rd t 36701 amp pf rd p 09a46553 65cf 45b2 8aaa e9bb559981ab amp pf rd i desktop
0
Why should I always consider creating and using object pools instead of instantiating the new object on the fly? I have read about this pattern several times (from a best practices perspective) Memory Allocation Instead of instantiating the new object on the fly, always consider creating and using object pools. It will help to less memory fragmentation and make the garbage collector work less. However, I don t know what it actually means. How can I implement it? For example, I can instantiate a GameObject using the Instantiate method of Unity? Instantiate(prefab, new Vector3(2.0F, 0, 0), Quaternion.identity) Is this use discouraged? What else can it mean?
0
How to check whether an angle lies within a specific negative to positive range? I'm trying to develop a script that detects if an object's angles are tilting too much. I am new to Unity, and I am sure this is not the best way to test an object's angles, but I am trying to learn C so I'd rather figure that out myself. All I want to know is how to check whether a value is between 101 and 101. I have tried this so many different ways, and even though it is working fine for positive integers, the if statement is not applying the moment that my z angle becomes negative. Here is what I have tried so far (maxangle 101, minangle 101) if(Player.transform.rotation.eulerAngles.z gt Mathf.Sign( 101) amp amp Player.transform.rotation.eulerAngles.z lt maxangle), if(Player.transform.rotation.eulerAngles.z gt minangle amp amp Player.transform.rotation.eulerAngles.z lt maxangle)
0
Find grandchildren with specific tag I have an empty object that contains multiple children each containing their own child objects. I want to get a list of all the objects containing a specific tag but i don't know the depth of each child object. The following solution only returns the children that have the tag. foreach (Transform child in city) if (child.CompareTag("Zone")) buildings.Add(child)
0
Mesh does not translate accordingly to WheelCollider So I am trying to implement a car controller script in Unity were the WheelTransform position and rotation is set with every update as the same as the WheelCollider position and rotation, it all works fine except for one thing when translating the WheelTransform, if the car goes slowly, WheelTransform translates as expected, but when the car goes faster, there's a clear offset between the WheelTransform position and the actual position of WheelCollider. Here's the code were WheelTransform position and rotation is set as the same as the WheelCollider position and rotation private void UpdateWheels() UpdateWheelPos(frontLeftWheelCollider, frontLeftWheelTransform) UpdateWheelPos(frontRightWheelCollider, frontRightWheelTransform) UpdateWheelPos(rearLeftWheelCollider, rearLeftWheelTransform) UpdateWheelPos(rearRightWheelCollider, rearRightWheelTransform) private void UpdateWheelPos(WheelCollider wheelCollider, Transform trans) Vector3 pos Quaternion rot wheelCollider.GetWorldPose(out pos, out rot) trans.rotation rot trans.position pos Every single one of the car controller scripts I've found and tried use the same code for this section, I have also tried with 2d sprites without any colliders as WheelTransform but neither the scripts or changing WheelTransform solved the problem. Thanks in advance for the help.
0
Unity3D Smooth rotation for seek steering behavior I am trying to implement Reynolds' seek steering behaviour, but I am having problems on the rotation part. This is what I have void FixedUpdate() get position of current waypoint Vector3 targetPos new Vector3(path currentWaypoint .x, transform.position.y, path currentWaypoint .z) velocity vector towards target Vector3 desiredVelocity targetPos transform.position calculate the steerforce required for the desired velocity based on current velocity Vector3 steerForce desiredVelocity currentVelocity steerForce new Vector3(steerForce.x, 0, steerForce.z) steerForce Vector3.ClampMagnitude(steerForce, maxSteer) create a move vector to be added to agent's current position Then normalize it so it can be scaled according to the agent's max speed Vector3 moveVector steerForce.normalized moveSpeed Time.fixedDeltaTime transform.Translate(moveVector) How would I do it so my agent will be rotated smoothly based only on the code above? I tried rotating based on the current velocity, but the agents is rapidly rotated in one frame towards the target waypoint. I am not working with rigidbodies. Am I doing something wrong? What am I missing? Thanks, Jack
0
How can I load a scene when starting a new game if the loading scene have a Main Camera? The problem is that if I turn the camera on enabled in the editor it will show part of the scene mixed with the main menu scene. And if the loading scene main camera is enabled off I will get error Display 1 No cameras rendering. I have two scenes in the Hierarchy. The first is Main Menu. The main menu have a camera. Now I did that when I click on the button START A NEW GAME It will load another scene using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class NewGame MonoBehaviour public void StartNewGame(int SceneIndex) SceneManager.LoadScene(SceneIndex) In this screenshot you can see in the Inspector I'm calling the method StartNewGame and the index 1. Index 1 present the second scene that should be load The Space Station Now in the scene The Space Station I have also a MainCamera under Player. The MainCamera is turned off in the editor. And I need somehow to switch between the Main Menu scene camera and the The Space Station scene camera. If I will turn on the MainCamera in the inspector I will see some objects of the first scene and the second scene and then the game will start without the main menu and the player will fall down. If I start the game when the MainCamera is turned off I will the Main Menu but then when I click on START A NEW GAME it will show me the message Display 1 No cameras rendering. The last screenshot is of the Build Settings Edit Build Settings... I added the two scenes to the build. The first scene at index 0 is the Main Menu the second scene at index 1 is The Space Station
0
Why I cant change the GUILayout.Button color to green when click on a button? I used a break point and it's getting to the line style.normal.textColor Color.green But not changing the color of the clicked button. And there are no any errors or exceptions. using System.Collections using System.Collections.Generic using System.Diagnostics using System.Linq using UnityEditor using UnityEngine using System.IO public class Manager EditorWindow MenuItem("Tools Manager") static void Manage() EditorWindow.GetWindow lt Manager gt () private void OnGUI() var style new GUIStyle(GUI.skin.button) style.normal.textColor Color.red style.fontSize 18 string assetPaths new string 2 string 0 "Test" string 1 "Test1" foreach (string assetPath in assetPaths) if (assetPath.Contains(".test") var i assetPath.LastIndexOf(" ") var t assetPath.Substring(i 1) if (GUILayout.Button(t, style, GUILayout.Width(1000), GUILayout.Height(50))) style.normal.textColor Color.green
0
Sending position to .net server unity I'm working on a multiplayer game, I created a custom C server using TCPListner. I can't figure out how to send a players position to the server from the client side. I also couldn't figure out how to broadcast the position received from the client side to the rest of the players. Can someone help me with this?
0
Isometric coords to cartesian coords I'm new to the tilemap feature of Unity, and I'm having a hard time with all those coords. I created a new project, added an isometric tilemap and left all values to their default. In the Unity Editor (and in game at runtime as well), the coordinates of the cells are like this This is pretty disturbing to me and it will be to most players (not programmers) too I guess. I would like something like this However, I can't figure out how to do the transformation. I tried this Vector3 currentWorldPos Camera.main.ScreenToWorldPoint(Input.mousePosition) Vector3Int currentCellPos grid.WorldToCell(currentWorldPos) This gives the coordinates as in the Unity Editor except for z currentCellPos.z 0 Set z to 0 so the coordinates of the cell are exactly as in the Unity Editor Vector3 cartesianCellPos new Vector3((2 currentCellPos.y currentCellPos.x) 2, (2 currentCellPos.y currentCellPos.x) 2, 0) Try to transform the Unity coordinates into cartesian coordinates WRONG RESULT But this calculation gives weird results, not what I expect at all. Do you know how I could transform the Unity coordinates shown in the first screenshot into the coordinates shown in the second screenshot?
0
Why is my button script not working? Okay so i'm new to C and i made this script. The goal i have in mind is that when the player is on the button and presses a button ( W in this case ) the button is switched from on to off ( or vice versa). The problem i have is that when the character stands on the button and presses W it doesn't always switch its state and i have no idea why. Any info would be appreciated. using System.Collections using System.Collections.Generic using UnityEngine public class Button MonoBehaviour public bool Pressed false Animator Anim Use this for initialization void Start () Anim GetComponent lt Animator gt () Update is called once per frame void Update () Anim.SetBool ("Pressed", Pressed) void OnTriggerStay2D(Collider2D other) if (Input.GetKey(KeyCode.W)) if (Pressed) Pressed false else Pressed true
0
Why isn't occlusion culling working correctly? Occlusion culling doesn't seem to be behaving the way I was expecting. I've set the yellow wall as static and have baked an occlusion map using the occlusion window in unity. However when visualising the occlusion the red cylinder behind the wall is still visible despite not being seen in the camera preview. Any clue what I'm doing wrong?
0
What happens with associated animation clips when I copy a gameobject in Unity? I have a gameObjectOne that has two animation clips move into the screen and move out of the screen. This gameObjectOne has an animator that checks when each clip has to be played. Now I duplicated this gameObjectOne via the edit menu and named the copy gameObjectTwo, and to my surprise the animator and the animations still work. I expected that the animation clips were associated with gameObjectOne but this is not the case.... The animation clips are not duplicated. There are still only two clips and one animator in the project window. But when I click on gameObjectTwo in the animation window, you can see that there are two animation clips associated with gameObjectTwo as well. So my question is how is this possible? And is there a way to see what is "inside" an animation clip file? If I click in the project window on an .anim file, it doesn't say which gameObject it belongs to.
0
Unity "Convert To Entity" does not work (Render) with "Skinned Mesh Renderer" for Animations I'm trying to make a game with Unity's ECS and Job System. I came across the issue where, Convert To Entity does not support Skinned Mesh Renderer. It does not render the mesh. I need it for animations. On the bright side, Game Object Entity does render Skinned Mesh Renderer. The downside is that, it does not support Physics Shape and Physics Body. Convert To Entity does. I am using Physics Shape and Physics Body for physics. Would anyone mind telling me what options are open to me?
0
Correct the rotation of a car gun? This script for drive a car by arrows. I added a gun above it to aim at target. My issue here is the rotating of my gun effected by my drive when I turn left or right. How to stop the rotation of my gun to be effected by car turns ? using UnityEngine using System.Collections public class RearWheelDrive MonoBehaviour private WheelCollider wheels public float maxAngle 30 public float maxTorque 300 public GameObject wheelShape public Transform target public Transform gun car here we find all the WheelColliders down in the hierarchy public void Start() wheels GetComponentsInChildren lt WheelCollider gt () for (int i 0 i lt wheels.Length i) var wheel wheels i create wheel shapes only when needed if (wheelShape ! null) var ws GameObject.Instantiate (wheelShape) ws.transform.parent wheel.transform public void Update() Gun rotation Vector3 dir target.position gun car.transform.position Quaternion lookr Quaternion.LookRotation(dir) Vector3 rotationy Quaternion.Lerp(gun car.localRotation,lookr, Time.deltaTime 7).eulerAngles gun car.localRotation Quaternion.Euler (0f,rotationy.y,0f) Drive float angle maxAngle Input.GetAxis("Horizontal") float torque maxTorque Input.GetAxis("Vertical") foreach (WheelCollider wheel in wheels) a simple car where front wheels steer while rear ones drive if (wheel.transform.localPosition.z gt 0) wheel.steerAngle angle if (wheel.transform.localPosition.z lt 0) wheel.motorTorque torque update visual wheels if any if (wheelShape) Quaternion q Vector3 p wheel.GetWorldPose (out p, out q) assume that the only child of the wheelcollider is the wheel shape Transform shapeTransform wheel.transform.GetChild (0) shapeTransform.position p shapeTransform.rotation q
0
Change rigidbodys default height from floor? I am new to unity and I have a few questions There is a mesh that has a rigidbody and a box collider that I placed on the scene. I also added a generic terrain to the scene from the 3D objects menu. When I put the mesh at a certain height and it drops I notice that it always stops at Y 0.500000. How do I change this default value? What controls this? For example, does unity have it so that when any other type of collider hits the terraincollider the other collider automatically updates the rigidbody to be 0.50000 above it and this only happens when it hits a terrain collider? If this is the case, Is this causing a collision every frame and adjusting it to 0.50000 every frame so it doesnt fall through? Finally, assuming that the Y 0.50000 value above the ground cannot be changed, if I wanted something to quot hoover quot above the ground, would I always need to take that the maximum amount that I can get to the ground is Y 0.500000?
0
Why players who join late can't see other people data? I want to show the name of the players above their head but I have a problem where people joining late doesn't get other players' name. For example Player 1 joins to the server with the name Peter. Player 2 joins to the server with the name Josh. Peter (Player 1) sees Josh's name perfectly, but when Josh joins Peter's name is not synchronized correctly. My sync code looks something like this SyncVar private string NAME public override void OnStartClient() if(networkPlayerData is null) networkPlayerData BTNetworkController.Controller.playerData NAME BTNetworkController.Controller.playerData.Name SendPlayerNameToServer(NAME) Command private void SendPlayerNameToServer(string name) RpcSetPlayerName(name) ClientRpc void RpcSetPlayerName(string name) gameObject.GetComponentInChildren lt TMP Text gt ().text name So my question is how can I sync data to newly joined players and refresh player names accordingly.
0
How to control which path a unit will take? This might be a really easy solution that I probably just do not know due to lack of experience so thanks for any and all the help. TLDR at bottom of post. I'm still learning Unity C and I am following Brackey's Tower Defense tutorial series while adding my own twist. The tutorials use levels with only 1 available path for units to walk along. However, the game I am currently developing has 3 separate paths that units can walk along. Essentially, the game is similar to the mobile game Clash Royale with 3 lanes except it is also a tower defense. Here is the current layout The different lanes are empty gameObject labeled as Path1 (red), Path2 (blue), and Path3 (green). The nodes laid out in each path are all children objects of their respective path. Each of the parent path objects contain the following script public class Waypoints MonoBehaviour public static Transform points private void Awake() points new Transform transform.childCount for (int i 0 i lt points.Length i ) points i transform.GetChild(i) Now, following the tutorial, I have also successfully added an enemy that contains this EnemyMovement script public class EnemyMovement MonoBehaviour public float speed 10f private Transform target private int waypointIndex 7 void Start() target Waypoints.points 7 void Update() Vector3 dir target.position transform.position transform.Translate(dir.normalized speed Time.deltaTime) if(Vector3.Distance(transform.position, target.position) lt 0.2f) GetNextWaypoint() void GetNextWaypoint() if(waypointIndex lt 0) Destroy(gameObject) return waypointIndex target Waypoints.points waypointIndex Now, as it currently stands, whenever I have an enemy present on the field, it will successfully run down path2 (blue nodes). However, it will ONLY run down path2. I would like to be able to decide which path the enemy will take. Eventually, the enemy's actions will be decided by an Enemy AI. The player will also be able to spawn units and will be able to decide which path the unit will travel. So to reiterate TL DR Following Brackey's Tower Defense tutorial. Currently, enemy will always default to path2. I need to figure out how to have control over which path, out of 3 options, an enemy or friendly unit will take.
0
Increment grid by rotation I'm currently working on a grid for snapping objects side by side. My current script is working fine, but only for game objects which haven't been rotated. Here is an example video of the problem https vid.me jN6D The cube at the right has a rotation of Vector3.zero, the left one has been rotated on the Y axis. As you can see snapping works perfectly for the right one, but at 0 15 you can see that the snapping doesn't work well for the rotated cube, that's because I've currently no idea how I can add the rotation in my current script. Here is a snippet of the most important part of code I'm currently using to calculate the grid Vector3 pivotToPoint hit.point nearestGameObject.transform.position float positionX nearestGameObject.transform.position.x Mathf.Round(pivotToPoint.x nearestGameObject.transform.renderer.bounds.size.x) nearestGameObject.transform.renderer.bounds.size.x float positionZ nearestGameObject.transform.position.z Mathf.Round(pivotToPoint.z nearestGameObject.transform.renderer.bounds.size.z) nearestGameObject.transform.renderer.bounds.size.z Vector3 origin new Vector3(positionX, 0, positionZ) Vector3.up 100 if (Physics.Raycast(origin, Vector3.down, out hit, Mathf.Infinity, layerMask)) previewGameObject.transform.position new Vector3(positionX, hit.point.y, positionZ) previewGameObject.transform.rotation nearestGameObject.transform.rotation Maybe some of you guys have an idea how to solve this, it's driving me crazy. p.s. Here is some guy with a similar problem, but I'm very lost when in comes to adding the solution into my code.
0
Is it efficient to have a only data MonoBehaviours on lots of game objects? I'm working on a voxel based game and this solution would make the implementation of networking and other features a lot more easier, it is less error prone, easier to edit in the Editor, etc. So the question is How bad is it performance wise to have lots of MonoBehaviours in the scene, if they don't implement any of the MonoBehaviour methods? (So they only have primitive data stored in them)
0
Coroutine problem, I don't know what's happening Calling function. private const int deathHangTime 2 private void Die() Debug.Log("1 " Time.time) StartCoroutine(DelayForTime(deathHangTime)) Debug.Log("4 " Time.time) Coroutine IEnumerator DelayForTime(float time) Debug.Log("2 " Time.time) yield return new WaitForSeconds(time) Debug.Log("3 " Time.time) Why doesn't it wait for 2 seconds? Why doesn't it print the 3rd Debug line?
0
Passing properties as arguments such that the resulting class can modify the original I'm really not experienced with c so maybe my whole methodology is wrong but here goes. I'm trying to build a GUI that allows many many parameters to be modified in real time and have a central repository for all those variables. So I am trying to build a wrapper class around the slider so I don't have to explicitly link it to each property in the parameters class manually, and make it easier to add other generic functionalities like events or whatever. So right now I have a UI class that holds the sliders, a slider wrapper class that holds some extra functionality, and a central parameters class. The central class shouldn't have any dependencies of the other two classes. The UI class instantiates the slider wrapper class, and passes a Unity slider object. That part works fine. It also passes the property from the central parameter class to which it should be linked. That's the part I'm stuck on. UI class public class UIParams MonoBehaviour private GeneralParams centralParams reference to central parameters class private Transform mainUI reference to main UI panel private Transform panel1 reference to sub panel private MySlider mySlider1 instance of my slider wrapper class more sliders go here void Start() init centralParams GameObject.FindObjectOfType lt GeneralParams gt () var Panel1 GameObject.Find( quot MainUI quot ).transform.Find( quot Panel1 quot ) sliders mySlider1 new MySlider( Panel1.Find( quot Slider1 quot ).GetComponent lt Slider gt (), pass the actual slider to the wrapper centralParams.Parameter 1) pass the central parameters property to the wrapper more sliders go here Slider wrapper class Code (CSharp) class MySlider private Slider slider object to hold the slider private float sliderValue value of the slider public MySlider(Slider Slider, float CentralParameterProperty) slider Slider reference to Slider slider.onValueChanged.AddListener(delegate update() ) listen for changes to slider, don't want to be checking all the time sliderValue CentralParameterProperty set slider to default value in CentralParams. How do I modify that value??? private void update() sliderValue slider.value how do I change the original value from Central Params without explicitly linking each property manually? Central parameter class Code (CSharp) public class CentralParams MonoBehaviour public Action GeneralUpdateEvent tell other classes when an update has occured SerializeField private float parameter 1 public float Parameter 1 get gt parameter 1 set parameter 1 value GeneralUpdate() more parameters go here void GeneralUpdate() GeneralUpdateEvent?.Invoke() Passing the float CentralParameterProperty into the MySlider instance works to set the default value of the slider. But obviously from that point onwards the slider only modifies the internal variable sliderValue, not the property of the central class. Can I set it up so I pass some object from the UI class into the MySlider on instantiation such that the MySlider instance can both get and set the values of the CentralParams property, without explicitly linking to central class within the MySlider class? Or is this just Wong? Hope that made sense...
0
Respawn not working properly upon scene reload. Why is this? So I made a respawn function and what is supposed to happen is the script it supposed to load a saved checkpoint. However I need to reset the scene (and again this worked just fine last night which was odd...). Essentially the checkpoint waits for a player and then when the player enters the current checkpoint is written to a .txt file. Upon reload or death the scene is restarted, the .txt file is read and grabs the checkpoint. Everything works fine without Scene scene SceneManager.GetActiveScene() SceneManager.LoadScene(scene.name) Reload scene. but I need that in order to "refresh" the scene. CheckPoint Code using UnityEngine using System.Collections public class Checkpoint MonoBehaviour public LevelManager levelManager Empty level manager. Use this for initialization void Start() levelManager FindObjectOfType lt LevelManager gt () Unnneeded void OnTriggerEnter(Collider coll) if (coll.tag "Player") levelManager.currentCheckPoint gameObject lt DISABLE WHEN ES2 is fixed!!! Debug.Log("Activated Checkpoint " transform.position) ES2.Save(gameObject.name, "myFile.txt?tag checkpoint") Saves checkpoint to file. LevelManger Code using UnityEngine using System.Collections using UnityEngine.SceneManagement public class LevelManager MonoBehaviour Tooltip("Note this will also serve as the spawnpoint for the player!") public GameObject currentCheckPoint private GameObject player private int PHP public int RespawnHP Amount of health to give player upon respawn. void Awake () Use this for initialization void Start () player GameObject.FindGameObjectWithTag("Player") Update is called once per frame void Update () PHP GameObject.Find("InventoryManager").GetComponent lt InventoryManager gt ().PlayerHealth if (PHP lt 0) Debug.Log("Player HP has been depleted. Respawning.") RespawnPlayer() if (Input.GetKeyDown("r")) Debug.Log("Restarting level!") RespawnPlayer() public void RespawnPlayer() Scene scene SceneManager.GetActiveScene() SceneManager.LoadScene(scene.name) Reload scene. currentCheckPoint GameObject.Find(ES2.Load lt string gt ("myFile.txt?tag checkpoint")) Load saved checkpoint. Debug.Log("Player Respawning...") player.transform.position currentCheckPoint.transform.position GameObject.Find("InventoryManager").GetComponent lt InventoryManager gt ().PlayerHealth RespawnHP void RestartLevel() ToDo Restart level, and reload last check point. public static void SaveLevel() Saves the current level to file. ES2.Save(SceneManager.GetActiveScene().name, "myFile.txt?tag levelName") Saves level to file. ES2.Save("none", "myFile.txt?tag checkpoint") Overwrite checkpoint? Does anyone have a clue what is wrong? Like I said earlier the problem seems to arise on scene reloading. Response to comment(s) What behaviour are you observing at the moment? Jack Currently what happens is the player enters a checkpoint, the checkpoint is saved to a file, and upon respawn the checkpoint is loaded. After this I get spawned to the checkpoint that was saved but then immediately the level reloads itself and the player is not respawnd at the checkpoint. Here is a video to better demonstrate the issue (it will take a minute or two to finish up processing here as I've just pasted the link).
0
How to get the position of individual characters in TextMeshPro (Unity)? I am making a typing game. There are words falling down what the user have to type, before they can call the OnBecameInvisible() event. When the user types a character I want to apply a force and a torque to it and make it fall down. But to do this I have to instantiate a TextMeshPro GameObject at the position where that letter was located inside that word. But how can I get that position? Just to make things clear
0
Unity (C ) How can I create dialogue to be used in my game? (also critique my system?) I've created my own system for handling dialogue. There's a class for each 'node' or part of dialogue. It contains the following variables identifier (identifiers are unique for each NPC, but not globally, ie "1", "2"), a text variable, a list of strings (which are the option button values), another list of strings (which contains option identifiers), and a string which is used for passing custom functions through. A collection of these Dialogue classes are made, and then stored in a dictionary, with the key of each being the identifier. public string identifier public string text public List lt string gt options public List lt string gt optionIdentifiers public string onCloseFunction public Dialogue(string identifier, string text, List lt string gt options, List lt string gt optionIdentifiers, string onCloseFunction "") this.identifier identifier this.text text this.options options this.optionIdentifiers optionIdentifiers this.onCloseFunction onCloseFunction At the start, the dialogue with identifier 1 will be chosen, and the text displayed, with each of the buttons. If the first option is chosen, that is index 0 in the options list. The index selected is used to get the correct identifier from the identifier list, which will return "2 1". This is then used to find the next dialogue. The system fortunately works, however I'm wondering if I've overcomplicated this, and if there's a simpler way to do this. Building further on this, it isn't easy to sort out the conversations to appear in. I have made the class 'Dialogue' serializable, so the properties are displayed in the unity window. I've made a public array of dialogue, which then is turned into a dictionary with the corresponding key identifiers. public Dialogue dialogueList public DialogueLibrary dialogueLibrary void Awake() Dictionary lt string, Dialogue gt dict new Dictionary lt string, Dialogue gt () for(int i 0 i lt dialogueList.Length i ) Add all dialogue from inspector into dictionary dict.Add(dialogueList i .identifier, dialogueList i ) dialogueLibrary new DialogueLibrary (dict) This allows me to add dialogue as such The biggest problem I have with this, is the fact that it's just... not very nice to deal with. For example, if there were 30 pieces of dialogue, and I wanted to add another between 2 and 3, I would have to either increase every identifier afterwards, or use something like 2a for an identifier. Furthermore, it would be a lot better if I could read the dialogue list from an XML file. What I'm stuck with is how I can create this XML file. I need some software that can simply create the conversations and export them in XML. Honestly I'm not sure how to go about this. Is there any software which exists already which could do something like this, or should I create my own in Visual Studio? I'm not sure how I'd go about creating something like this in visual studio. Ideally the software would be similar to mind maps, where the node of text is the dialogue text, and the connecting arrows have text on, and are equivalent to the options. Identifiers should ideally handle themselves. Can anyone give me any pointers in what direction I should take, and if the direction is creating my own program, could anyone suggest any resources which would help me? I understand this is a long message and I'm asking a lot, but any help, comments or even constructive criticism on my system would be greatly appreciated. Thanks in advance.
0
Maya Unity See through models I've recently modeled my character inside Maya here's an image. The first thing I noticed whilst creating my model is that the models could be seen through source 1, after doing a little research people stated that it was a graphical bug in Maya. However, once imported into Unity the same effect occurs. Therefore, my Question is How can I fix this inside Maya or Unity? To prove that my UV map doesn't contain a low opacity texture see the second image below
0
How to make an event happen only at the first start of the game? I want to know how to make something happen only once like a tutorial in a game which appears only when you first start your game and then when your game got saved to a further point it never appears again even when you close your game and start again. I want to give players some amount of gold when they first got their hands on my game ... but I do not want to give them that again and again whenever they restart the game ... So I want to know how to make something happen only once in a game application.. I hope you get my point ... thanks ..
0
Problem picking up a value, Delegate I'm having trouble passing values that are inside an int function to an onclick delegate. this script causes the object to move in vector3 ( 1 to the left and 1 to the right), these two values are inside the (int value), but I am trying to pass them to a delegate, but when inserting it it is adding different values than being in the script video of the problem private int index, index2 0 SerializeField private Vector3 Myposic1, Myposic2 SerializeField private Button left, right here I change the positions of Myposic1, Myposic2 SerializeField private float time public int slide 0 index between Myposic1, Myposic2. void Update() call() public void previous() slide call() public void next() slide call() void call() if (slide lt 0) slide 0 if (slide gt 1) slide 1 if (slide 0) left.onClick.AddListener(delegate player( 1) ) right.onClick.AddListener(delegate player(1) ) this.transform.position Vector3.Lerp (this.transform.position, Myposic1 index , Time.deltaTime time) if (index Myposic1.Length 1) right.interactable false else right.interactable true if (index 0) left.interactable false else left.interactable true Debug.Log("1") if (slide 1) left.onClick.AddListener(delegate player2( 1) ) right.onClick.AddListener(delegate player2(1) ) this.transform.position Vector3.Lerp (this.transform.position, Myposic2 index2 , Time.deltaTime time) if (index2 Myposic2.Length 1) right.interactable false else right.interactable true if (index2 0) left.interactable false else left.interactable true Debug.Log("2") public void player(int valor) index index valor public void player2(int valor2) index2 index2 valor2
0
Unity Isometric Tilemaps Appear Jagged I had issues using the isometric tilemaps feature in Unity. Whenever I try to place tiles, they don't seem to line up and create this jagged effect. I've tried messing with the anchor points and am a complete beginner at this. Edit My grid component looks like this
0
Unity Creating a Plane from 3 Vectors https docs.unity3d.com ScriptReference Plane ctor.html public Plane(Vector3 a, Vector3 b, Vector3 c) Description Creates a plane. The resulting plane goes through the given three points. The points go around clockwise as you look down on the top surface of the plane. Since there is no Debug.DrawPlane I don't know whether my plane works as expected. Are all 3 Vectors world coordinates? Or are they connected to each other? Can somebody elaborate how this works? Neither can I make any sense of "The points go around clockwise as you look down on the top surface of the plane"
0
How do I check if animation is of Animation Type "Humanoid"? One can set the Rig Animation type of an animation to quot Generic quot , quot Humanoid quot , etc. How could I check by script if an animation rig has been set to type quot Humanoid quot ?
0
Unity 3D engine for Ubuntu? Is there any way to get Unity 3D to run on Ubuntu. I am currently running Ubuntu 12.04 64bit edition. I also have Wine installed.
0
"StrictMode policy violation" warning occurring in my game after upload When I upload my game to my Android device, I get the following warning StrictMode policy violation android.os.strictmode.NonSdkApiUsedViolation Ljava lang invoke MethodHandles Lookup gt lt init gt (Ljava lang Class I)V at android.os.StrictMode.lambda static 1(StrictMode.java 428) at android.os. Lambda StrictMode lu9ekkHJ2HMz0jd3F8K8MnhenxQ.accept(Unknown Source 2) at java.lang.Class.getDeclaredConstructorInternal(Native Method) at java.lang.Class.getConstructor0(Class.java 2325) at java.lang.Class.getDeclaredConstructor(Class.java 2166) at bitter.jnibridge.JNIBridge a. lt init gt (Unknown Source 25) at bitter.jnibridge.JNIBridge.newInterfaceProxy(Unknown Source 8) at com.unity3d.player.UnityPlayer.nativeRender(Native Method) at com.unity3d.player.UnityPlayer.c(Unknown Source 0) at com.unity3d.player.UnityPlayer e 1.handleMessage(Unknown Source 95) at android.os.Handler.dispatchMessage(Handler.java 102) at android.os.Looper.loop(Looper.java 193) at com.unity3d.player.UnityPlayer e.run(Unknown Source 20) What causes this, and how can I resolve it?
0
Colliders stop working when they move I'm trying to make a game where you play basketball as a catapult. Obviously an idea like this leans heavily on the unity physics engine. The cup of the catapult has a bucket on it to keep the ball from falling out. When you hit space, the arm of the catapult spins, which should throw the ball out of the bucket of the catapult. Instead, the ball passes through the cup of the catapult(when it isn't spinning, it acts normally and rolls around the bucket) and then it doesn't fall whatsoever, eve though has gravity is enabled. Here are my physics settings The ball The cup(and also a cup with flipped normals) The Rim of the bucket Here's my ball throwing code public class BallThrower MonoBehaviour private Vector3 axis Start is called before the first frame update void Start() axis transform.position Update is called once per frame void Update() if (Input.GetKey(KeyCode.Space)) if (transform.rotation.z gt 95.4) transform.Rotate(0f, 0f, 5f, Space.Self) What's missing here? Should I make the cup a rigidbody? Let me know if you need more info, Thanks!
0
Why when using Linerenderer it's drawing a line also in scene view? I want to draw lines using the Linerenderer only in the game view window. I'm using Debug.DrawLine but only drawing Red lines but for some reason when the Linerenderer draw a line s one of the Linerender lines is yellow it seems the green linerenderer is getting on the red one in the scene view window. Debug.DrawLine(Input.mousePosition, hit.transform.position, Color.red) Is there a way to avoid it ? So Debug.DrawLine will draw only in sceneview and the Linerenderer will draw only in the game view window ? using System.Collections using System.Collections.Generic using UnityEngine public class RotateObjects MonoBehaviour public GameObject objectsToRotate public float speed 0.1f public Vector3 spinDirection public bool useMouse false public bool automaticSpin false public LineRenderer linerendererPrefab List lt LineRenderer gt lrs new List lt LineRenderer gt () Use this for initialization void Start() for(int i 0 i lt objectsToRotate.Length i ) var lr Instantiate(linerendererPrefab) lrs.Add(lr) Update is called once per frame void Update() if (objectsToRotate.Length gt 0) for (int i 0 i lt objectsToRotate.Length i ) var hits Physics.RaycastAll(Camera.main.ScreenPointToRay(Input.mousePosition), 100.0f) for (int x 0 x lt hits.Length x ) RaycastHit hit hits x if (hit.collider.name objectsToRotate i .name) objectsToRotate i .transform.Rotate(1, 1, 1) Debug.DrawLine(Input.mousePosition, hit.transform.position, Color.red) SpawnLineGenerator(Input.mousePosition, hit.transform.position, false) if(hits.Length 0) SpawnLineGenerator(new Vector3(0,0,0), new Vector3(0,0,0), true) if (useMouse true) if (Input.GetMouseButton(0)) Rotate(i) else Rotate(i) private void Rotate(int i) if (automaticSpin true) objectsToRotate i .transform.Rotate(1, 1, 1) void SpawnLineGenerator(Vector3 start, Vector3 end, bool reset) for(int i 0 i lt lrs.Count i ) if (reset) lrs i .SetPosition(0, start) lrs i .SetPosition(1, end) else lrs i .SetPosition(0, start) lrs i .SetPosition(1, end)
0
I try to recreate a plasma gun from halo into my fps game this is my code public class WeaponTest MonoBehaviour public float weaponHeat public float weaponOverHeat 100f public bool weaponIsOverHeat Start is called before the first frame update void Start() weaponHeat at the start was 0 weaponHeat 0 Update is called once per frame void Update() if (Input.GetButton( quot Fire1 quot ) amp amp !weaponIsOverHeat) if (weaponHeat lt weaponOverHeat) Weapon Shoot() weaponHeat IsHeating() float IsHeating() weaponHeat Random.Range(5f, 10f) return weaponHeat void Weapon Shoot() RaycastHit hit if (Physics.Raycast(playerCam.transform.position, playerCam.transform.forward, out hit, range)) code for damaging the enemy the shoot method was function exactly like what is want but I need the cooldown method I already try a few them but it not work exactly like I want. the I idea was went the left mouse was click the weapon heat will increase and when the left mouse was not been click the weapon heat will decrease until it reach 0. I hope you can help me solve this problem
0
Unity blur on one camera effects the other as well I'm trying to fake a DOF effect for Sprites by using 2 cameras, one for the sharp objects, one for the blurred ones. I have set up the layers like Blur and Sharp accordingly. So I have these 2 cameras, and I use Unity's Blur (optimized) script to blur things, and I have this script on only one camera, the one that is responsible for the blurred render. I have the cameras like Cam 1 Clear flags Don't clear (this is the main, sharp cam) Culling mask sharp layer has no blur effect (or any other post proc effect). Cam 2 Clear flags don't clear (this is the blur cam) culling mask blur Has Blur (optimized). Now, if this blur cam is on the back, meaning its depth is LESS than the main cam's depth, I have a sharp player ground and a blurry background. However, I need a blurry foreground too that should be on top of the player ground. The issue starts when I set the blur camera's depth higher than the main cam's. In this case, everything gets blurred, no matter that the main cam has no blur effect on it. Question is, how to set this up so only the desired layers get the blur?
0
Dot product not working as expected Recently I am learning dot product, While below code works from Unity's documentation, http docs.unity3d.com ScriptReference Vector3.Dot.html public Transform other void Update() if (other) Vector3 forward transform.TransformDirection(Vector3.forward) Vector3 toOther other.position transform.position var dot (Vector3.Dot(forward, toOther) Debug.Log(dot) But it doesn't work when I change direction of "other".It keeps giving same value no matter how much I rotate other unlike when I rotate transform,it does change values. For example, transform is at 0 0 0 and other is at 0 0 10 both has 0 rotation so facing straight in Z axis. The desiire out put I get is negative. Now suppose I change rotation of transform to 180 then the output gets positive as expected. I undo the rotation of trasnform and rotate other to 180 i.e., facing transform, then the output doesn't get change and show negative value only.Which is not correct as other is facing player.. Why is that the case? I am not able to get around it.
0
How to set a directory to download assetbundles from? Hi I'm using unity and I've created an AssetBundle file containing two different sprites. I set it's path to my desktop and I can load my assets. But how to download the AssetBundle from a directory on the web. How can I set a directory for everyone to be able to download the AssetBundle?
0
Unity Editor Scene View does not match built executable I'm trying to make my game resolution independent. I'm using Unity's 4.6 UI, and I've got custom resolutions defined at 1280 x 720, 1600 x 900, and 1920 x 1080. In editor, if I swap between any of these resolutions, the observed scene doesn't change. It looks like this I then build an executable (set to only allow 16x9 resolutions), and run this scene. On 1280 x 720 (as selected from the resolution dialog), I get this While on 1920 x 1080 (as selected from the resolution dialog), I get this Which matches the editor view. (Ignore the character sprites those are in worldspace on a separate camera and aren't relevant to this question). What is it about the executable that causes lower resolutions to be "zoomed in" like this, even if that lower resolution is the Reference Resolution for the Canvas Scaler?
0
How to synchronize damage with attack animation in a RTS game? I have been working on a RTS game in unity and did damage deal through code and a timer but it does not fit with the animations quet well. The damage is dealt in the beginning of the animation and about 4 attacks it fits perfectly and after more 4 attacks the damage is dealt delayed after the animation. My big question is if hitboxes would be a good answer to solve this problem or is it to preformance heavy?
0
How to load an AudioClip at runtime without the WWW class? I am currently pulling a .wav file from an API. I would like to play it at run time. Currently I need to save the .wav file to the persistentDataPath and then use the WWW class to load an audio clip using the file prefix. It works fine but the docs do mention that the WWW class is obsolete. What other options do I have if I want to avoid the obsolete method group? I don't need to save the file to disk, I am simply doing that at the moment because its fairly safe to save it and then read it back out.
0
How to share image in persistentDataPath to facebook feed? I'm trying to share an image taking from CaptureScreenshot() using FB.ShareLink(...) to Facebook. My code is the following (After calling FB.Init(), etc..) string tmpScreenshotPathname "file " currentScreenshotPathname System.Uri contentUri new System.UriBuilder(tmpScreenshotPathname).Uri System.Uri imageUri new System.UriBuilder(tmpScreenshotPathname).Uri FB.ShareLink(contentUri, "Test", "Test desc", imageUri) However, when open the FB share, the page opens for a split second before returning me back to the game. I tried using a normal Uri such as http ........jpg and it works fine, but when I try to use a local Uri, it fails. Is there any way to share the image to the feed without uploading it to the user's Facebook gallery using FB.API? Because there's the case where the user might decide not to share the image to the feed.. but it would have already been uploaded to his gallery from FB.API.
0
When would a mesh collider be better than primitive colliders I have been reading through the Unity Manual and have come across some interesting information about mesh colliders and primitive colliders. It got me wondering if using many primitive colliders would be better than using a mesh collider for say a character object? I was also wondering if there was any information on exactly how inefficient a mesh collider is to say having 20 box or cylinder colliders on a character mesh. I am guessing that the number of polygons on the mesh would be a factor but it would be interesting to see some raw comparisons between how this efficiency scales per polygon (or per 100 polys or some unit of measurement)
0
How to animate a bezier curve over a given duration I have created a bezier curve by adding the following script to an empty game object in the inspector. This draws to complete curve at once when I run the code. How can I animate it over a given period of time, say 2 or 3 seconds? public class BCurve MonoBehaviour LineRenderer lineRenderer public Vector3 point0, point1, point2 int numPoints 50 Vector3 positions new Vector3 50 Use this for initialization void Start () lineRenderer gameObject.AddComponent lt LineRenderer gt () lineRenderer.material new Material (Shader.Find ("Sprites Default")) lineRenderer.startColor lineRenderer.endColor Color.white lineRenderer.startWidth lineRenderer.endWidth 0.1f lineRenderer.positionCount numPoints DrawQuadraticCurve () void DrawQuadraticCurve () for (int i 1 i lt numPoints 1 i ) float t i (float)numPoints positions i 1 CalculateLinearBeziearPoint (t, point0, point1, point2) lineRenderer.SetPositions(positions) Vector3 CalculateLinearBeziearPoint (float t, Vector3 p0, Vector3 p1, Vector3 p2) float u 1 t float tt t t float uu u u Vector3 p uu p0 2 u t p1 tt p2 return p
0
Animation with pivot modification in Mecanim Assume I have two animation cycles Walking Crouching Both assume that the model's pivot is on the same level as the model's feet. Now I also have two animated transitions Get on all fours while walking Climb onto a (table) The first is not too complex. The model walks upright, then gets down on all fours (animation 1) and crouches. Pivot remains on the same level, all fine. What I want However, I can't get my head around the second transition. I want the model to walk up to the table (pivot on ground level) climb onto the table (animation 2) (pivot..?) crouch on the table (pivot on table level, 1 m above ground) What I have The climbing animation (2) assumes pivot to remain on ground level and simply animates the model's climbing up. I built a StateMachineBehaviour which raises the model to the table level as soon as the climbing animation is complete. From then on the pivot is on table level and the crouching can continue. This seems to work fine in a standalone application, however, in multiplayer, where the models' transform and animator state are not necessarily synchronized in the same frame, this prooves problematic. One can clearly see the model jump when the change in the model's position arrives one frame earlier than the switch from climbing to crouching animation. What I tried I thought it might be a better idea to have the pivot move gradually from ground level to table level over the duration of the climbing animation (2), instead of having one instant jump at the end. This way network synchronization would be much more robust because of the relatively small change per frame. Also this approach would much closer resemble the actual thing that's happening in the real world, which is generally a good thing. I tried offsetting the root transformation of the animation clip, and accomodate the modification by adding the negative offset to the root bones. This however did not work, as there seems to be no animatable translations in Mecanim animation clips. So im stuck at this approach. Question Is there a better way? A simpler way? How are you guys tackling this?
0
Isometric ball moving in unity 3d. Ball moving in opposite direction I am making a game in unity 3d. It is a 2.5d game which mean it is in isometric. The game is quite simple. Player drags mouse and a trajectory will be shown just like in angry bird and when player release the mouse the ball will move to the direction. However I am having issue here that once mouse is released the ball moves in exact opposite direction. I am not able to understand what the real issue is. My code is as follows For Ball public class BallScript MonoBehaviour public Rigidbody2D rbg public CircleCollider2D col public Vector3 BallPos get return transform.position void Awake() rbg GetComponent lt Rigidbody2D gt () col GetComponent lt CircleCollider2D gt () public void PushBall(Vector2 force) rbg.AddForce(force,ForceMode2D.Impulse) to enable rigidbody so we can use projectile again public void ActivateRb() rbg.isKinematic false public void DeActivateRb() rbg.velocity Vector3.zero rbg.angularVelocity 0f rbg.isKinematic true The code for my game manager is as follows public class Trajectory MonoBehaviour SerializeField int dotsNumbers SerializeField GameObject dotsParent SerializeField GameObject DotsPrefab SerializeField float dotSpacing Vector2 pos float timeStamp Transform dotsList void Start() hide trajectory in the start Hide() PrepareDots() void PrepareDots() dotsList new Transform dotsNumbers for(int i 0 i lt dotsNumbers i ) dotsList i Instantiate(DotsPrefab,null).transform dotsList i .parent dotsParent.transform public void UpdateDots(Vector3 ballPos,Vector2 forceApplied) timeStamp dotSpacing for(int i 0 i lt dotsNumbers i ) pos.x (ballPos.x forceApplied.x timeStamp) pos.y (ballPos.y forceApplied.y timeStamp) (Physics2D.gravity.magnitude timeStamp timeStamp) 2f dotsList i .position pos timeStamp dotSpacing public void Show() dotsParent.SetActive(true) public void Hide() dotsParent.SetActive(false) Here is the code for gamemanager using singleton pattern Camera cam public BallScript ball public Trajectory trajectory public static GameManagerScript Instance void Awake() if(Instance null) Instance this SerializeField float pushForce 4f bool isDragging false Vector2 startPoint Vector2 endPoint Vector2 direction Vector2 force float distance void Start() cam Camera.main ball.DeActivateRb() void Update() if(Input.GetMouseButtonDown(0)) isDragging true OnDragStart() if(Input.GetMouseButtonUp(0)) isDragging false OnDragEnd() if(isDragging) OnDrag() void OnDragStart() ball.DeActivateRb() startPoint cam.ScreenToWorldPoint(Input.mousePosition) trajectory.Show() void OnDrag() endPoint cam.ScreenToWorldPoint(Input.mousePosition) distance Vector2.Distance(startPoint,endPoint) direction (endPoint startPoint).normalized force direction distance pushForce trajectory.UpdateDots(ball.BallPos,force) void OnDragEnd() ball.ActivateRb() ball.PushBall(force) trajectory.Hide() The ball moves in exact opposite direction where I wish to send it by dragging. Is it because of the isometric issue or I am missing something?P.S have applied negative force as well as in case and have also made change in direction formula rbg.AddForce( force,ForceMode2D.Impulse) direction (startPoint endPoint).normalized
0
Removing FMOD from a Unity WebGL project causes an error about not being able to copy fmod register static plugins.cpp When I imported the FMOD plugin into a Unity WebGL project, then removed it afterwards, I wasn't able to build it due to errors about trying to copy an FMOD file fmod register static plugins.cpp Restarting the editor, reimporting everything, deleting Library Temp folders did not help. Neither did deleting the FMod folder.
0
How to connect a skeleton to an animator at the parent I have two different meshes with similar armatures. And the parent contains the Animator Component with a universal avatar and animation controller. The animations doesn't apply when the bones are not the imminent child of the Animator. Is there a way to get this working?
0
Is it better to create a scene in blender or in unity? First of all, I am really new to all of this. This is my first time so its really confusing me if it's better to create a scene and then import it into Unity or is it better to just create objects like chracters, chairs in blender and scenes in Unity? I just want to recreate a scene of my school and include it in my final project as a Unity game where it will have no function other than walking around and some jumping and fighting? Because my project is not based on the game, it will just help it.
0
Delay for seconds when key is held down? Hello I am very new to Unity and am trying to make a shooting game in which when the space key is pressed down the gun charges then shoots. I want it to wait for 0.3 seconds before the gun fires off because I want an effect to happen with a particle system(I confused animation with effect in the first post). Also the problem the script has is that the bullet would not fire at all when the space is pressed. Here is the scripts I wrote void Start() StartCoroutine("Shoot",0.3f) IEnumerator Shoot() yield return new WaitForSeconds (0.3f) Bam () void Bam() transform.Translate (0, 0, 12) void Update () if (Input.GetKey (KeyCode.Space)) Shoot()
0
Keep track of VoxelData NPC in parallel Level Background I'm tring to make a First Person Shooter Game in a Voxel World (Finit Size) with Unity3d. The Player has some kind of a Base that he has to protect against Enemy units. There are also one or more enemy Bases that the Player has to destroy, but in a different Level Map. The Game has multiple Levels that are connected through predefined Ports. So the Player and other Units can travel from Level to Level. There are a couple of Levels to explore. (Maybe there could be infinit Levels in the future.) At game start I create a LevelManager and all Levels as Children of them. They can spawn an manage the Units and Voxel Blocks independently. One ChunkManager renders always the current Level where the Player is in. He creates multiple Chunks which itself generate the Mesh from the current Voxel Data of the Level. This works all very well and I'm also able to travel between the Levels. (This runs all in one Scene.) At the moment I try to implement some kind of a Worm unit. They spawn from time to time anywhere in each level and can move randomly around and modify the Voxel World by eating the Blocks away... type of random enviroment event. Problem The problem I can't solve is how to simulate all the Worms in parallel Levels? And the Blocks they have eaten? Same problem would occur for the enemy bases if they grow and build new defences and so on. Because when the Player enter a Level there should be some differences since his last visit. My attempt All my Units and Buildings have already separated logic and rendering components. So they can work properly even when not rendered by the ChunkManager. Its working for maybe 3 Levels and a handfull of worms but if I increase the amount of Levels it gets starting to go laggy (4 10FPS). So this would not be the right way to go or is it and my code is crap? Has someone any suggestions for me how I can solve this? Edit I disable now all none active Levels and reactivate always the current Level where the Player is in. So I can better manage the objects that realy need computation time. The problem I get now is how can I simulate the progress in a Level since start? Example for the worm unit. He would have moved across the Level and left a path of removed voxels. Should I made a seperate method to calculate the path that would be made or the last X minutes or should I just call the Update method multipletimes to match the missed calls since last X minutes? This should then be made by all Objects that can modify the Level or produce something.
0
How to detect speed on collision The problem with OnCollisionEnter2d is that it only gets called when there is a collision but what I wanted is to get the current speed of object at the moment of impact until the object stops moving. So that I if the object stops moving after impact I will call another function. void OnCollisionEnter2d(Collision2D collision) Debug.Log(speed) problem this will only give the speed at the moment of impact if(speed lt 0) blah blah I also tried putting speed variable on the Update() void Update() var currentVelocity player rb.velocity speed currentVelocity.magnitude
0
Capsule getting stuck on edge of block I'm making a first person game and when I jump and my character gets close to the top of the wall, the vertical movement stops, jitters, or suddenly snaps to the top of the wall. Video Here is my character controller code, based on this tutorial using UnityEngine RequireComponent(typeof(CharacterController)) public class PlayerController MonoBehaviour private InputManager inputManager private CharacterController controller private Vector3 playerVelocity private bool groundedPlayer SerializeField private float playerSpeed 2.0f SerializeField private float jumpHeight 1.0f SerializeField private float gravityValue 9.81f private Transform cameraTransform private void Start() controller GetComponent lt CharacterController gt () inputManager InputManager.Instance cameraTransform Camera.main.transform void Update() groundedPlayer controller.isGrounded if (groundedPlayer amp amp playerVelocity.y lt 0) playerVelocity.y 0f Vector2 movement inputManager.GetPlayerMovement() Vector3 move new Vector3(movement.x, 0f, movement.y) move cameraTransform.forward move.z cameraTransform.right move.x move.y 0f controller.Move(move Time.deltaTime playerSpeed) Changes the height position of the player.. if (inputManager.PlayerJumpsThisFrame() amp amp groundedPlayer) playerVelocity.y Mathf.Sqrt(jumpHeight 3.0f gravityValue) playerVelocity.y gravityValue Time.deltaTime controller.Move(playerVelocity Time.deltaTime) I also tried using other solutions by changing the physics material of the level and player, neither worked.
0
How to change pre splash image for iOS? When I launched my game on my iPad, the screen first displayed a faulty splash image with a black lower half momentarily, before displaying the normal splash image. No matter what I tried, I couldn't get rid of this faulty 'pre splash image'. I have tried the following Entered my Plus package serial number and updated my seat in Unity. Deleted and left all splash images blank in Unity. Checked all the LaunchScreen XXX.png images in Xcode. Checked the files referenced by Images.xcassets in Xcode. Changed all the above images to a completely black image. Still, the old faulty picture would appear. Cleared all the data and installation files on my iPad. Deleted General Launch Images Source. I wonder where Xcode kept the faulty image. I am using Unity 5.5.1 and Xcode 9.2. Could someone please help?
0
How can I flip a coin? I am working in unity and have flattened out a cylinder object to make a coin for a 3d coin flipping game, but I am not sure how to get the coin to flip when the player swipes across it and allow for a double flip if the player swipes over it a second time while in mid air. here is what I have tried using System.Collections using System.Collections.Generic using UnityEngine public class CoinFlip MonoBehaviour private Vector3 start private void Start() start gameObject.transform.position void Update() transform.position transform.right Mathf.Sin(Time.time 0.45f) 0.025f void OnEnable() gameObject.transform.position start
0
Force change prefab source I have a prefab A and i use it in scene A (as gameobject A). Then i to save that scene A as scene B and also renamed the gameobject A to gameobject B. Then inside unity (in project window ) , i duplicated the prefab asset A to prefab B. Fyi, i'm using .blend (blender file) as the prefabs. in scene B, i want the gameobject B which refers to prefab A , to switch its prefab's source to prefab B. This way , i have 2 different scenes which has independent gameobjects which refer to unique prefab. So i can modify prefab A and will affect scene A but not scene B. Ussually, i can drag the gameobject to project window and choose create 'new original prefab' option, but this method can't be used, since i want both prefab as .blend file (so i can modify them directly using blender). What i did so far, is to drag prefab B to scene B, which then i have to manually redo all the setting which has been done in scene A . I want to avoid this tedious process. Does anyone have any idea ?
0
Prefab disables its script when a clone is instantiated A clone of a cube is spawned when it is destroyed, however the clones disable the script in the editor (example http gfycat.com SnarlingScornfulEgg). Used the exact same script for a different kind of 'enemy' and it worked as intended. Relevant part of script function Start () health 100 function Update () if(health lt 0) Dead() function OnCollisionEnter (col Collision) if(col.gameObject.tag "Bullet") health 25 function Dead () Destroy(gameObject) var posx Random.Range( 50, 50) var posz Random.Range( 50, 50) Instantiate(enemyl, Vector3(posx, 0.5, posz), transform.rotation) Is there something I'm missing? EDIT The clone takes damage but doesn't die like the original when its health is lt 0.
0
Instantiated object not tracking collision I have an issue, and I'm not sure why it's happening. I have a prefab that I've built in a colour changing game. It has the following Four 2D objects that if they collide with the player (2D collider attached to all), they cause the player to die. One 2D object that if the player strikes, it generates a duplicate of itself with the Instantiate function. All 2D objects are created The four objects that cause the player to die are being created as normal and continue to cause the player to die. However, the object that instantiates the prefab and increments the score can no longer be collided with. The player appears to pass behind it. I'm pasting my code below. I would really appreciate if anyone can offer advice on this void Update () if (Input.GetButtonDown("Jump") Input.GetMouseButtonDown(0)) thing.velocity Vector2.up bounciness scoreText.text score.ToString() private void OnTriggerEnter2D(Collider2D collision) if (collision.tag "plusScore") score Destroy(collision.gameObject) Instantiate(barrier, new Vector2(transform.position.x, transform.position.y 7f), transform.rotation) return if(collision.tag ! currentColour) Debug.Log("You DIED!") SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex) score 0
0
How to scale our multiplayer support, similar to Among Us We are a small team with the goal of creating our first multiplayer game, and we want to support multiplayer that can rapidly scale up as Among Us has successfully done. We don't have a huge budget and we are struggling to find an appropriate way to implement multiplayer, including peer to peer (although it would be exhausting to combat cheating and make a smooth experience). Our game has no more, no less than 50 players in a very tight space. As an example, we're looking at the indie game Among Us. They went from such a small game with barely any players, to maintaining well over 3 million CCU (concurrent users). How can we achieve similar scalability?
0
How to avoid enemies overlapping each other when chasing player in Unity? I am trying to get enemies to chase player but without them overlapping each other when they get closer to the player. So far what I have is that I check for the distance between current enemy and the another enemy in a list and if their distance is less than 2 then update their position away from each other. But when I do that, the enemies instantly move away rather than smoothly moving away from each other. What can I do to improve this? Here is my script for chasing player public void ChasePlayer() foreach (GameObject enemy in enemies) if (enemy ! null) float currentDistance Vector3.Distance(transform.position, enemy.transform.position) if (currentDistance lt 2.0f) Vector3 dist transform.position enemy.transform.position transform.position dist if (lantern.transform.GetChild(0).gameObject.GetComponent lt Light gt ().enabled) gameObject.GetComponent lt MeshRenderer gt ().enabled true gameObject.GetComponent lt Collider gt ().enabled true transform.LookAt(player.transform) transform.position transform.forward speed Time.deltaTime else gameObject.GetComponent lt MeshRenderer gt ().enabled false gameObject.GetComponent lt Collider gt ().enabled false
0
Unity3d Find out if current animator animation is playing? I need to call a function immediately after animator animation finished playing, I know I could solve this by adding an event to my animation, but I try it without. How can I find out if the current animator animation is playing? On normal legacy animations I solved it by writing a coroutine public static IEnumerator playAndWaitForAnim(Animation anim, string clipName, Action callback) anim.Play(clipName) Wait until Animation is done Playing while (anim.IsPlaying(clipName)) yield return null Done playing. Do something below! callback() Which I use like this StartCoroutine(AnimationHelper.playAndWaitForAnim( myAnimation, "ToSettings", () gt Debug.Log ("Finished playing") )) But how does this work with mecanim animator animations?
0
How can I insert random numbers in specific place in text of UI Text? I have a Canvas with Text and a Panel. I want that it will show random numbers between 3 and 10 between the almost and hours Hello my friend, It's about time to wakeup. You were sleeping for almost...hours. My name is NAVI and i'm your navigation helper in the game. Sometimes when running the game I was sleeping for almost 5 hours and sometimes when running the game I was sleeping for almost 3 hours. For example Hello my friend, It's about time to wakeup. You were sleeping for almost 5 hours. My name is NAVI and i'm your navigation helper in the game. Instead the 3 dots to add a random number.
0
Limiting interaction between certain RigidBodies I'm developing a 2D game in Unity and have been tasked with building a particular feature I'm not sure how to accomplish with Unity's physics engine. To simplify, a bunch of objects of type X and O are filled into a pit XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX XXoXXXoXXXoX Both objects have Rigidbody2Ds and colliders. Objects of type X have normal gravity and should settle into place. Objects of type O have inverse gravity and should float. However, O should not be able to push X, and X should not be able to push O. Another way of looking at it is that O should only be able to move upward, and X should only be able to move downward. If we remove some of the Xs directly above an O, the O should float upwards as the Xs fall downwards until the Xs settle on top of the O and everything stops moving XXXXXXXXXXXX XX XXXXXXXXX XX XXXXXXXXX gt XXXXXXXXXXXX XX XXXXXXXXX gt XXoXXXXXXXXX XXoXXXoXXXoX XX XXXoXXXoX (In the actual game Xs and Os can be different sizes their movement is continuous and they are not constrained into rows or columns). The Os should be able to support the weight of any arbitrary number of Xs without sinking. XXXXXXXXXXXX XXXXXXXXXXXX XooooooooooX X X Lastly, the Os should be able to float diagonally if there is a space available XXXX XXXXXXX XXX XX XXXXX XX gt XXXXX XXXX XXXX XXXX gt XXXXoXXXXXXX XXXo XXXXXXX XXXX XXXXXXX I can't solve this problem simply by adjusting the mass of the Xs or Os since the number of Xs on top of an O may vary. I can't use the built in RigidBody constraints since they don't allow you to disable only one direction along an axis (e.g. saying an object can move upward but not downward). What's the proper way to handle this? I could do something like this void FixedUpdate() if (movementDirection Direction.UP) if (transform.position.y lt lastYCoordinate) Vector3 position transform.position position.y lastYCoordinate transform.position position lastYCoordinate transform.position.y but that feels hacky to me and I suspect it will keep the objects from sleeping. Are there better solutions here?
0
unity input event consumed by image raycast target that is "under" a sprite with a 2D collider I am having a hard time getting my UI to work. Basically I have a canvas with a UI image A that is the size of the screen. This image has raycast enabled and if effectively receiving inputs. Not in the canvas I have a sprite B that have a 2D collider attached to it. No matter what I try, the UI image is always consuming the input event when I click on the sprite. When I disable the image A , the sprite B gets the events, so the setup looks right (camera with Physic2D raycaster for the sprite B, layerMask set to the layer of the sprite B, canvas with Graphic raycaster for the image A, no blocking object, no mask). What do I need to do so that the sprite B gets the input event BEFORE the image A and consume it? EDIT Those two elements are part of the UI and must be interactable at all time. I use a sprite for the second element as it is dragged from the UI inside the game and I don't want to make it an image. The image A is a big cancel button with opacity 0 on the whole screen that must be active at all time. I just want to know if the Collider of sprite B can intercept the input before the image A. If it isn't possible, I'll create an Image B instead of the sprite B and destroy it to create a Sprite with the same texture when the is interacted with.