_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | Unity Method count exceed the limit of 64K I just got an issue related to a 64k method in Unity so that's why I'm unable to build my project. It shows method limitation exceed the limit of 64k method count. So can anyone here help me out to resolve this issue? |
0 | Can a Component.gameObject be null in Unity? Can a Component.gameObject be null in Unity? If it can what can cause it to be null? The context for the question is a NullReferenceException I got from the users, which specifies only method, but not line in which it occurred. So, I suspect that there may were conditions which cause Component.gameObject to be null. |
0 | Instantiating problems I'm beginner here, I'm trying to instantiate a single object every specific duration, either form the left of the screen or from the the right, at the same time I want this object to move to the other side of the screen So the troubles I'm facing here are sometimes 2 objects are being instantiated at the same time. the objects move in the direction that are defined in the first if statement (both objects on the left and the right move in one direction) the part where I instantiate objects is in the script(smallFishes) that's attached to an empty gameobject is void Start () timer gameObject.AddComponent lt Timer gt () width 2f timer.Duration 3 timer.Run() left Resources.Load("Left") as GameObject right Resources.Load("Right") as GameObject void Update () if (timer.Finished) lr Random.Range(1, 3) if (lr 1) var generetx 8.8f width 2 Instantiate(left, new Vector2(generetx, Random.Range( 4.8f,4.8f)), Quaternion.identity) else var generetx 8.8f width 2 Instantiate(right, new Vector2(generetx, Random.Range( 4.8f, 4.8f)), Quaternion.identity) timer.Duration 3 timer.Run() public int state get return lr the part where I make the object move from the script that's attached to the object prefab void Start () small gameObject.AddComponent lt smallFishes gt () rb2d gameObject.GetComponent lt Rigidbody2D gt () void Update() var fishes GameObject.FindGameObjectsWithTag("small") if (fishes! null) if (small.state 1) moveright new Vector2(4 Time.deltaTime, 0) rb2d.AddForce(moveright, ForceMode2D.Impulse) else moveleft new Vector2( 4 Time.deltaTime, 0) rb2d.AddForce(moveleft, ForceMode2D.Impulse) Thanks in advance. |
0 | How can I render 3D objects and particle systems in front of a Screen Space Overlay Camera? I am using Unity 2019 with the Universal Render Pipeline. I have a canvas that is using Screen Space Overlay render mode. I cannot change my render mode to Screen Space Camera, because it is not currently supported by the Universal Render Pipeline. How can I have a particle system, or any other 3D objects, render on top of my canvas? |
0 | How to combine the camera that follows the player and the camera shake effect in Unity? I need to combine both camera that follows the player and the camera shake effect in the same moment. The problem is in that, if I make the shake effect for the camera, then the camera doesn't follow the player and if I make the camera follow the player, then the shake effect doesn't appear. The basic idea of my script is next Vector3 originalPos GameObject targetPlayer bool canShake void OnEnable() originalPos camTransform.localPosition void Update() Camera shakes if (CanShake) transform.localPosition originalPos Random.insideUnitSphere shakeAmount Camera follows the player else transform.position new Vector3(targetPlayer.transform.position.x, transform.position.y, transform.position.z Does anyone have ideas how to combine these two things (camera shake effect and camera that follows the player) at the same moment? |
0 | Export Spriter animations to Unity I want to use bone animations in my 2D game for Unity (5.0 beta). I am trying Spriter. Apparently, it has no official Unity support. There was some guy, back in 2014, who posted a plugin to convert Spriter files to Unity prefabs here http brashmonkey.com forum index.php? topic 3365 spriter for unity 43 updated integrated . However, the plugin does not seem to work (perhaps it is because I am using 5.0 beta). There are deprecated lines, like AnimationUtility.SetAnimationType(animClip, ModelImporterAnimationType.Generic) Or UnityEditor.Animations.AnimatorController.AddAnimationClipToController(controller, animationClip) If you remove them, of course it won't be able to properly export your files. So my question is is there a reasonable to use Spriter animations in Unity? I know I could just export to a spritesheet, but I was hoping to use bones for super fluid animations (I have several characters so I don't really want to make lots of spritesheets). Or perhaps there is a better bone based solution for 2D animation in Unity? |
0 | Spawn point not working on unity I have two GameObjects set down. One is named Spawn Point, and it is set at the beginning of my level, and Death Point, set down at about 0, 40,0. My code tries to see if the character is below the Death Point area and moves the player to the spawn point. I feel that the answer is so simple, that I could look it up, but I looked it up, and I didn't see it. using System.Collections using System.Collections.Generic using UnityEngine public class death MonoBehaviour public GameObject spawnPoint public GameObject deathPoint Start is called before the first frame update Update is called once per frame void Update() Vector3 playerPos transform.position if(playerPos.y lt deathPoint.transform.position.y) transform.position spawnPoint.transform.position A big thank you in adavance. |
0 | Why do built versions of my multiplayer game act different than the version I run in the editor? (Unity Mirror) When loading saved data from a client's PC, it act's different to how my game, running in the editor works. Saved data is only being loaded on the version being played in the editor. Without any specifics, could anyone explain some differences between the editor version of a game and the built version because I was under the impression that they were the exact same. |
0 | Bullet spread changes depending on the camera direction I'm working on an FPS game. I want to make a little bit of difference in shooting direction, only on the horizontal axis. To do this, I wrote this code Temp Shake Horizontal.x Random.Range( 0.1f, 0.1f) if (Physics.Raycast(the camera.position, the camera.forward Temp Shake Horizontal, out BulletDecal Hit, Mathf.Infinity)) Quaternion HitRot Quaternion.FromToRotation(Vector3.forward, BulletDecal Hit.normal) decals Objs decal Index .transform.position BulletDecal Hit.point decals Objs decal Index .transform.rotation HitRot But I don't know why, when I rotate the camera, the result is changing! Here is what it looks like when I face in one direction (this is the intended result) But when I rotate the camera about 90 degrees to the left or right, the result is no horizontal variation the bullets all line up in a vertical column. Why does this happen, and how can I solve this issue? I want the result to always be like the first picture, with random variation side to side. |
0 | Double vision with Google Cardboard in Unity I am working on a VR app. I have a terrain and some cube placed in the terrain.Even I have added the Reticle to point at the cube and display some message when the user gaze at the cube. I have set the distortion to "None". The problem I am facing here is,when I run the app the cubes and the pointer(reticle) is seeing as double in the scene.What will be the reason for it.Can anybody help me out please. |
0 | Run a method once per iteration without adding a component to a game object in Unity I want to run a function once per main loop iterator but I don't want to add this as a script to a game object in my scene. This is something that should always run no matter what scene and making people include it into every scene on a game object would cause issues because I'll people will forget. Is there any hooks into the main loop where I can tell unity to run this function once per loop for the entire game not just per scene? |
0 | Raycast drawing and hitting limited to inside cylinder I'm trying to get a very basic "radar" system to work. Right now, I'm not even scanning, just looking at a known target location. using System.Collections using System.Collections.Generic using UnityEngine public class RadarScript MonoBehaviour public GameObject radar public GameObject target private bool found false void Update () Vector3 lookLocation target.transform.position radar.transform.position RaycastHit hitInfo if (found false) Ray ray new Ray (radar.transform.position, lookLocation) Debug.DrawRay (ray.origin, ray.direction, Color.red) if (Physics.Raycast (ray, out hitInfo, 10000.0f, 0)) if (hitInfo.collider.tag "Target") printHitInfo (hitInfo) found true private void printHitInfo(RaycastHit hit) Debug.Log ("TARGET FOUND!") Debug.Log ("Distance " hit.distance) So, here's the result can be seen here https gfycat.com FloweryBraveCockroach There's 2 problems here. The Debug.DrawRay call is only drawing the ray inside the cylinder (radar). The target is never being hit. What's going wrong here ? |
0 | How does unity size graphics? I'm working on a 2D game. It has tiles. each tile is 50x50 px. I attached script to camera which sets the camera size to screenHeight 2 PixelsPerUnit. Now in the player, as an example i selected 480x320 size. I expected it to show approx 9x6 tiles. However it shows 6tiles horizontally and 4 tiles vertically. Similarly for other sizes, it shows lesser than calculated number of tiles. How does this corelate? Edit i created the tiles in photoshop with 300 dpi. Not sure if that affects anything though. |
0 | Unable to move GameObject? This simulates a GameObject swinging between two positions. I am unable to manually move a GameObject on the Y axis using the Unity editor (in scene view) when the following script is attached and running, it's like a solid animation Vector3 min, max void Update() min wall1.position new Vector3(4,0,0) max wall2.position new Vector3(4,0,0) transform.position Vector3.Lerp (min, max, (Mathf.Sin(2 Time.time) 1.0f) 2.0f) |
0 | Find the current player instance from multiple scripts I have the following code used by multiple classes (e.g. Enemy, Scenary, EnemyProjectile etc.) in my game, which seems intrinsically wrong. What are some ways I could write this code once and use it from multiple places? GameObject go GameObject.Find( quot Player quot ) if (go null) Debug.Log( quot Failed to find Player go quot ) else player go.GetComponent lt Player gt () if ( player null) Debug.Log( quot Failed to find player component quot ) I usually have this code in an Awake function but sometimes I do it in a collision event, e.g. for EnemyProjectile grabbing a player handle would often not be required and thus a wasted lookup. Player is a private variable in the class definition of each class. |
0 | Start Broadcast Unity Network Discovery I am using the unity NetworkDiscovery component, and I am wondering how I can auto start broadcasting when the server starts, instead of the client having to click on the gui Initialize Broadcast Start Broadcasting. I would like to be able to put some C in my start host function so that the user does not have to do anything. |
0 | Client side prediction buffer size considerations for jitter I am currently having a FPS game with client side prediction. Every 20ms, the client sends it's input to the server. The server buffers 5 ticks worth of input (100ms) and starts consuming the inputs each tick and sends a world snapshot to the client. The client then validates the predictions and corrects the simulations if there is a misprediction. The setup works fine under ideal network conditions. However when the latency suddenly spikes from say 50ms to 400ms, the client's tick packet is delayed which causes the server to eat through all of the available inputs in the buffer and resort to using the previous tick values to perform server simulation. When the client input finally arrives at the server late, the server discards the input because it has already processed the input for that particular tick (using old input values). How do I handle this edge case of latency increasing and decreasing? Sure I could use a larger buffer size for the inputs, but that will cause delays between client state and server state. Using a smaller buffer will cause the server to stall from inputs if there is a jitter that is more than the duration required by the server to process the inputs. I was under an impression that I would need some kind of dynamic buffer size that expands and contracts. However, I am out of ideas to implement something like this. Does anyone have a solution? |
0 | Unity WebGL audio not looping when started with playdelayed() I have an audioSource in which loop is set to true. I am starting it playing by calling playdelayed() In the editor its plays fine. In a webgl build it does not loop. It just plays once. Also in firefox it does not start playing at the correct time, it is a good fraction of a second off. public override void MatchStarted() Intro.Play() Loop.PlayDelayed(Intro.clip.length) PlayScheduled has exactly the same effect. public override void MatchStarted() Intro.Play() Loop.PlayScheduled(AudioSettings.dspTime Intro.clip.length) Play(ulong) has the same effect public override void MatchStarted() Intro.Play() Loop.Play((ulong)(44100 Intro.clip.length)) I'm posting this here seeking workarounds. Any suggestions? As you can see from my code, my use case is a piece of music with an intro and a loop. ... ps. I have seen some posts saying that if the bitrate is not 44.1 KHz this can cause looping issues on WebGl. The audio file in question is set to override the bitrate to 44.1 in its import settings. |
0 | Unity Player Movement Problem I want to make a little game in Unity, where the player (a ball) jumps up and down and you have to maneuver it through (flappy bird like) obstacles. My problem is, after I added a simple movement script float speed 10f Vector3 move new Vector3(Input.GetAxis ("Horizontal"), Input.GetAxis ("Vertical"), 0) transform.position move speed time.deltatime The ball is stuck and can only be moved a little,before returning to its start position. My question is how i can fix that? I didnt find any solution |
0 | Make Render Texture distorted blurry? I have created a function that clicks images in real time and these images are copied to render texture that is created. I am looking for a way to blur distort half fade out the render textures. Is there a way to achieve this? Graphics.Blit(Texture2D, renderTexture) |
0 | Unity object stuck where it shouldn't Here's the thing. I am making a 3D top down game about cars on the road. Right now I have different colored cuboids representing cars. They are position locked in Y and rotation locked on all three axis (axises? Sorry, English isn't my first language). The cuboid in question is controlled with the following code using UnityEngine using System.Collections System.Serializable public class Boundary public float xMin, xMax, zMin, zMax public class PlayerController MonoBehaviour public float speed public Boundary boundary void FixedUpdate () float moveHorizontal Input.GetAxis("Horizontal") float moveVertical Input.GetAxis("Vertical") Vector3 movement new Vector3 (moveHorizontal, 0.0f, moveVertical) GetComponent lt Rigidbody gt ().velocity movement speed GetComponent lt Rigidbody gt ().position new Vector3 ( Mathf.Clamp (GetComponent lt Rigidbody gt ().position.x, boundary.xMin, boundary.xMax), 0.0f, Mathf.Clamp (GetComponent lt Rigidbody gt ().position.z, boundary.zMin, boundary.zMax) ) It's pretty simple, almost unchanged code from the Unity tutorial. Boundaries are set as 8, 8 on X and 13, 13 on Z. The cuboid spawns at 0, 0.55 (It's 1 height, I gave it some clearance), 13. I move it forward with the WASD and it just gets stuck at 0.15 Z. Just dies there and can't move anywhere. I'm very new to Unity, so I expect it to be some rookie mistake. Can someone help me out? Thank you. |
0 | 3D Object in 2D Unity Project Is there a way to bring 3D objects into a 2D project that is using the 2D Universal pipeline for rendering light? I have some 3D objects I want to bring in to the project I'm working on, but they just get imported as pure white. Is there a way to import 3D models into a 2D game, and keep the 2D pipeline for lighting? I'l tried a few different shaders, but if they're not pure white they're pink. I would like them to have shading as a 3D object, and still interact with light and rotate on all axis if possible. If it's impossible to use a 3D object, if there was a way to at least have a 2D sprite taken from a 3D object, but still react to light as if it were 3D, that'd work too I suppose. This is what it looks like, https i.stack.imgur.com HJeIN.jpg I've also tried adding 3D lights as well, but to no avail. I'm guessing the issue is because of my 2D lighting renderer, and for the record, this is what this tree looks like in a 3D project. https i.stack.imgur.com nKCyd.jpg I have since attached a custom shader graph to it that I made, it looks okay, but it still doesn't receive shading at all... Thanks in advance. |
0 | Unity Google VR SDK Main Camera showing Game Objects Behind Left and Right Cameras I'm trying to get a basic VR app up and running on iOS with the Unity Google VR SDK and I've run into a strange issue where my game objects are appearing behind the left and right camera views in cardboard view. In the HeadsetDemo app that is provided along with the SDK, there's just a black background but in my app that background is the default grey blue skybox color and renders any game objects that I have in my scene. Does anyone know how to hide game objects from that main camera? |
0 | In Unity, why does DrawProceduralNow work in OnRenderObject but DrawProcedural does not? In Unity, if I call DrawProcedural (or one of its variants) from Update() it works fine, but if I make the exact same call from OnRenderObject() it draws nothing. (It also doesn't work from OnPreRender or OnPostRender). HOWEVER, DrawProceduralNow() works fine from all of these functions. Why is that so? Is it documented somewhere? What can I do to make DrawProcedural and variants work in OnRenderObject? What is different about DrawProceduralNow that makes it work? (Yes, I have tried using material.SetPass(0) in the DrawProcedural version and it still renders nothing. I understand that the OnRender functions are called later in the frame and some graphics state is different at that point, but it seems like DrawProcedural is exactly the kind of thing we should be doing in OnRenderObject. I feel like there is some fundamental thing about the Unity rendering pipeline that I am misunderstanding that would clarify all this. (Tested in 2019 LTS and 2020.2.3) For example C public class TestRender MonoBehaviour public Material material private ComputeBuffer vertexBuffer private GraphicsBuffer indexBuffer private ComputeBuffer paramsBuffer private Bounds bounds void Start () material new Material(material) Copy geometry from MeshFilter (you can just use a cube for testing) Mesh mesh GetComponent lt MeshFilter gt ().sharedMesh vertexBuffer new ComputeBuffer(mesh.vertices.Length, Marshal.SizeOf lt Vector3 gt ()) indexBuffer new GraphicsBuffer(GraphicsBuffer.Target.Index, mesh.triangles.Length, Marshal.SizeOf lt int gt ()) vertexBuffer.SetData(mesh.vertices) indexBuffer.SetData(mesh.triangles) paramsBuffer new ComputeBuffer(5, sizeof(int), ComputeBufferType.IndirectArguments) paramsBuffer.SetData(new int mesh.triangles.Length, 1, 0, 0, 0 ) material.SetBuffer( quot VertexBuffer quot , vertexBuffer) bounds new Bounds(transform.position, new Vector3(5, 5, 5)) private void Update() This works! Graphics.DrawProcedural(material, bounds, MeshTopology.Triangles, indexBuffer, indexBuffer.count) So does this! material.SetPass(0) Graphics.DrawProceduralNow(MeshTopology.Triangles, indexBuffer, indexBuffer.count) private void OnRenderObject() This does NOT work Graphics.DrawProcedural(material, bounds, MeshTopology.Triangles, indexBuffer, indexBuffer.count) But this does! material.SetPass(0) Graphics.DrawProceduralNow(MeshTopology.Triangles, indexBuffer, indexBuffer.count) Simple shader Shader quot Test Render quot SubShader Pass CGPROGRAM include quot UnityCG.cginc quot pragma target 4.5 pragma vertex vertex shader pragma fragment fragment shader StructuredBuffer lt float3 gt VertexBuffer struct v2f float4 pos SV POSITION v2f vertex shader (uint id SV VertexID, uint inst SV InstanceID) v2f o float4 vertex position float4( VertexBuffer id ,1.0f) o.pos UnityObjectToClipPos(vertex position) return o fixed4 fragment shader (v2f i) SV Target fixed4 final fixed4(0, 0, 1, 1) return final ENDCG |
0 | Why does changing Texture of Particle System using Material Property Block changes texture, but Particle System is still emitting old texture? I try the code in Start, checking in Editor shows new texture, but Particle System still emits old texture. The script works for SpriteRenderer, but not ParticleSystem. I tried to Play Stop emission no difference. ParticleSystemRenderer renderer gameObject.GetComponent lt ParticleSystemRenderer gt () MaterialPropertyBlock materialPropertyBlock new MaterialPropertyBlock() renderer.GetPropertyBlock(materialPropertyBlock) materialPropertyBlock.SetTexture(" MainTex", texture) renderer.SetPropertyBlock(materialPropertyBlock) |
0 | How to instantiate a prefab only when something is hit, and for some seconds? How do I instantiate a prefab only when something is hit for a few seconds? I mean, I just need to activate the particle system when something is hit. Now it always runs, even before I hit something. I need it to activate the particle system when something is hit and for 2 3 seconds. This is what I do now public void Shot() Destroy(gameObject) Instantiate(effect, transform.position, transform.rotation) |
0 | How can I mass duplicate or "paint" Unity objects? Let's say I have a basic map with a single box on it. I want to make many, many more of these cubes, so they can cover a large portion of the map, like this Each box needs to be exactly one unit away from the adjacent boxes, so there is no overlap. My idea was to clone the first box so the entire blue map is covered, then manually delete some of them to make the path. In other software, there are ways to clone duplicate large numbers of objects so that they fill an area, or follow a certain set of transformations. I cannot figure out how to do this in Unity. I have tried manually duplicating the box and setting its location (so I have two properly positioned boxes), then selected both of those and duplicating (so I have four boxes total), duplicating those, etc, but as soon as I select multiple boxes, I can't type in a location without all the selected boxes going there (so if I type a y location of 12, every single selected box will be crammed on top of each other on y 12). |
0 | Problem in multiplayer game lobby trying to pass map name to MasterServer.RegisterHost I'm working on an online multiplayer game, so I have lobby where users can see the hosts list. Every host in the hosts list has some information like "host user name" and "map name". I'm using this code to register the host and load "host user name" public void something() var useNet !Network.HavePublicAddress () Network.InitializeServer (6, 25000, useNet) MasterServer.RegisterHost ("roomname", hostUserName , "unity") public void btn Refresh() MasterServer.RequestHostList ("roomname") data MasterServer.PollHostList () for (int i 0 i lt data.Length i ) ButtonRoom i .gameObject.SetActive(true) TextNameRoom i .text data i .gameName I also need "map name", exactly like "host user name", so I added another value to MasterServer.RegisterHost() like this public void something() var useNet !Network.HavePublicAddress () Network.InitializeServer (6, 25000, useNet) MasterServer.RegisterHost ("roomname", hostUserName, mapName, "unity") but now I have an error that RegisterHost() can't have 4 arguments No overload for method RegisterHost takes 4 arguments What other way could I pass the map name? Thank you. |
0 | Varibles Initialized in Awake are null in other script's Start I have a component gameState Attached to one gameobject called GameState public class gameState MonoBehaviour public Context stateMachine private void Awake() PlayerGameobject p GameObject.Find("Player").GetComponent lt PlayerGameobject gt () stateMachine new Context(new Playing(), p) On another gameObject I have this component public class PlayerGameobject MonoBehaviour void Start() gameState GameObject.Find("GameState").GetComponent lt gameState gt () When I try to use gameState within PlayerGameobject's Update method I find that stateMachine is null. if (gameState.stateMachine.CurrentState "Playing") null why is statemachine null? I initialized it in awake which should run before start. gameState is not null and other public variables assigned in Editor are not null. |
0 | OnMouseClick not detected I created "main script" and in Start() created simple cube GameObject cube GameObject.CreatePrimitive(PrimitiveType.Cube) cube.transform.localScale new Vector3 (1,2,1) cube.GetComponent lt Renderer gt ().material.color new Color(0,0,255) cube.AddComponent lt CubeScript gt () and then in CubeScript I have empty Start() and Update() but in onMouseDown() just Debug.Log("click detected") and I can never see log despite clicking on cube.. Any advice? did I missed something? |
0 | KeyCode dictionary in Unity I found a strange problem while programming keyboard input in Unity (v5.3.5). public class AvatarInputMapperUnityContext MonoBehaviour private AvatarController avatarController public KeyCode JumpKey KeyCode.Space public KeyCode LeftKey KeyCode.A public KeyCode RightKey KeyCode.D public KeyCode UpKey KeyCode.W public KeyCode DownKey KeyCode.S private Dictionary lt KeyCode, WeaponTags gt ShotKeys void Awake () avatarController GetComponent lt AvatarController gt () ShotKeys.Add(KeyCode.I, WeaponTags.Pistol) ShotKeys.Add(KeyCode.O, WeaponTags.Shotgun) void Update () if (Input.GetKeyDown(JumpKey)) avatarController.JumpSignal() Now, when the ShotKeys.Add... lines are commented out everything works fine. But when I uncomment them, the program never reaches the avatarController.JumpSignal() line, and none of the other directional keys (w,a,s,d) work. What can be the reason? |
0 | What is the best practice for handling touch events on different GameObjects in Unity2D? First of all I want to describe what I have in my scene. 1. Joystick. 2. Main character that has link to joystick and handles touch events from joystick. 2. Buttons. 3. Other GameObjects that must handle touch events. But that's not all. When player is touching any part of screen (except of the above objects) main character must start fighting. The problem is in that I cant correctly handle all touch events on these game objects. When the player is touching to the joystick the main character starts moving but before this he is performing a single fight action. Can anyone give me some ideas how to correctly handle touch events on different gameobjects? Perhaps my question is confusing, I am sorry for this. |
0 | Different kind of stamina problem I have an object that I interact with physics via using UnityEngine using System.Collections public class PhysicsBall MonoBehaviour public float speed private Rigidbody rb void Start () rb GetComponent lt Rigidbody gt () Update is called once per frame void FixedUpdate () float moveHorizontal Input.GetAxis ("Horizontal") float moveVertical Input.GetAxis ("Vertical") Vector3 movement new Vector3 (moveHorizontal, 0, moveVertical) rb.AddForce (movement speed) However, now I want to add a "stamina" bar, so if the user holds any of the movement keys which affect the rb, the stamina bar starts depleting. Once empty, the user can no longer affect the rb with the movement buttons. I've tried viewing some of the classic stamina bar sprint options but they don't use the rigidbody physics like I am doing, so I wonder if anyone knows how I do it in my example? |
0 | Gameobject with Canvas child (Unwanted inspector behavior) When I try to focus (by double clicking or pressing f) on gameobjects in my scene which have a Canvas as a child, the scene view zooms out to show the Canvas. I would like to be able to see the gameobjects themselves when focusing on them. Is there a way to do this? |
0 | Predicted trajectory becomes less accurate in a side on collision In my 2D billiards game, I have it so that when the user clicks and drags with their mouse, a Physics2D.CircleCast is projected from the cueball to wherever the mouse is. If the circle happens to hit the red ball, a line is rendered from the red ball's position to the direction of the normal of the collision. So it's supposed to predict where the red ball will go when it gets hit by the cueball. If you look at the first gif below, you'll see that it works if the red ball gets hit at its center (or close to it). The red ball ends up moving more or less along the predicted line. However, if you look at this second gif, you'll see that if the red ball gets hit closer to its edge, the predicted line is much less accurate. Why is this and how can I fix it? This is the prediction code I use if (Input.GetMouseButton(0) amp amp cueBall) Vector2 mousePos cam.ScreenToWorldPoint(Input.mousePosition) var direction (mousePos (Vector2)cueBall.position).normalized var hit Physics2D.CircleCast(cueBall.position, radius, direction, Mathf.Infinity) if (hit) lineMain.Draw(cueBall.position, hit.point) ghostBall.SetPosition(hit.point (direction radius)) lineTarget.Draw(hit.point, hit.point hit.normal) This is the predicted trajectory. |
0 | Runtime Issues on 144Hz Monitors I've recently finished my first ever Unity game. The game runs okay in my end but two of my friends had issues with the game. They both have 144hz monitors and the issues are solved when they lower the refresh rate to 60Hz. The problems are that any object who has a velocity depending on Time.deltatime, it gets halved. Is there a way to fix this on code so that nobody has to reduce their refresh rate when playing? Here is an example code of a snowball projectile's behaviour. The snowball usually stays alive for 3f seconds and that allows him to go across the whole screen but in 144hz runtime, the snowball goes really slow and it does not last enough to even get across the half of the screen. using System.Collections using System.Collections.Generic using UnityEngine public class Snowball MonoBehaviour SerializeField private float speed 20f SerializeField private Rigidbody2D rb SerializeField private GameObject impactEffect Start is called before the first frame update void Start() Destroy(gameObject, 3f) void Update() rb.velocity transform.right speed Time.deltaTime 75 void OnTriggerEnter2D(Collider2D hitInfo) if(hitInfo.CompareTag( quot Player quot ) hitInfo.CompareTag( quot Enemy quot )) Destroy(gameObject) Instantiate(impactEffect, transform.position, transform.rotation) Here is my game if anyone is interested in further examination itch.io link |
0 | Trapping Asserts in Visual Studio I'm writing a 2D game with some fairly complex off screen logic, with plenty of room for bugs. My usual habit is to write code with a lot of Asserts in it. When an Assert gets hit I drop into the debugger, have a look around, find and fix the bug. Works for me. Problem is how to get Unity Asserts to call into the Visual Studio debugger. So far they just seem to get generate a log message in the Editor Console, and then Unity carries right on as if they didn't matter. What use is that? There is an 'experimental' option in the Unity VS settings, but it doesn't seem to do anything (good or bad). Any suggestions? I can think of a couple of really hackish things to try, but surely there must be a right way? After further experimentation Enabling Assert.raiseExceptions (only) makes Unity grind to a halt (instead of carrying on regardless) but otherwise no change. No trap into VS. Enabling the experimental Exceptions mode (only) causes Unity to crash with a bug check on the first assert failure. Doing 1 2 is the same as 1 only. This is VS 2015 in case it matters. |
0 | How to make progress bar in EditorWindow with Threading in Unity? I need to make a progress bar in EditorWindow. To do this, I perform the function of calculations in threads Thread thread new Thread ( worker.Work) thread.Start () The class itself emitting calculations looks like this for me (Worker.cs) using System.Collections using System.Collections.Generic using UnityEngine using System using System.Threading public class Worker private bool cancelled false public void Cancel() cancelled true public void Work() for (int i 0 i lt 100 i ) if( cancelled) break Thread.Sleep(50) Debug.Log("i " i) ProcessChanged(i) WorkCompleted( cancelled) public event Action lt int gt ProcessChanged public event Action lt bool gt WorkCompleted The PlacementObjects EditorWindow (PlacementObjects.cs) class looks like this using System.Collections using System.Collections.Generic using UnityEngine using UnityEditor using UnityEngine.UI using System.IO using System.Linq using System using System.Text.RegularExpressions using UnityEditor.IMGUI.Controls using UnityEngine.Profiling using Newtonsoft.Json using System.Threading public class PlacementObjects EditorWindow private Worker worker bool pressedbool false float scaleSlider 0 float scaleMinSlider 0 float scaleMaxSlider 100 MenuItem("Window PlacementObjects") static void Init() windowPlacementObj (PlacementObjects)EditorWindow.GetWindow(typeof(PlacementObjects)) windowPlacementObj.titleContent new GUIContent(" terrain") ... void OnGUI() DrawFooter() void DrawFooter() GUILayout.BeginArea(FooterSection) GUILayout.BeginVertical() if (!pressedbool) GUILayout.Label(" json") GUILayout.BeginHorizontal() stringTextFieldURLjsonfile GUILayout.TextField(stringTextFieldURLjsonfile) if (GUILayout.Button(" ...", GUILayout.Width(100))) stringTextFieldURLjsonfile EditorUtility.OpenFilePanel(" json", "", "json") GUILayout.EndHorizontal() if (GUILayout.Button(" ")) worker new Worker() worker.ProcessChanged worker ProcessChanged worker.WorkCompleted worker WorkCompleted pressedbool true ProcessJSONPlaceONmap() Thread thread new Thread( worker.Work) thread.Start() else if (GUILayout.Button(" ")) pressedbool false scaleSlider EditorGUI.IntSlider(new Rect(3, 20, position.width 6, 15), scaleSlider " ", Mathf.RoundToInt(scaleSlider), scaleMinSlider, scaleMaxSlider) EditorGUI.ProgressBar(new Rect(3, 45, position.width 6, 20), scaleSlider scaleMaxSlider, scaleSlider " ") Repaint() GUILayout.EndVertical() GUILayout.EndArea() private void worker WorkCompleted(bool cancelled) Action action () gt string messeg cancelled ? " " " !" Debug.Log("messeg " messeg) pressedbool true if (InvokeRequired) Invoke(action) else action() private void worker ProcessChanged(int progress) Action action () gt scaleSlider progress if (InvokeRequired) Invoke(action) else action() action() This code does not update the progress bar. Found an example of Asynchronous tasks methods But here it is not clear how to call StartCoroutine (LoadingRoutine ()) from EditorWindow. |
0 | Unity parallel vectors and cross product, how to compare vectors I read this post explaining a method to understand if the angle between 2 given vectors and the normal to the plane described by them, is clockwise or anticlockwise public static AngleDir GetAngleDirection(Vector3 beginDir, Vector3 endDir, Vector3 upDir) Vector3 cross Vector3.Cross(beginDir, endDir) float dot Vector3.Dot(cross, upDir) if (dot gt 0.0f) return AngleDir.CLOCK else if (dot lt 0.0f) return AngleDir.ANTICLOCK return AngleDir.PARALLEL After having used it a little bit, I think it's wrong. If I supply the same vector as input (beginDir equal to endDir), the cross product is zero, but the dot product is a little bit more than zero. I think that to fix that I can simply check if the cross product is zero, means that the 2 vectors are parallel, but my code doesn't work. I tried the following solution Vector3 cross Vector3.Cross(beginDir, endDir) if (cross Vector.zero) return AngleDir.PARALLEL And it doesn't work because comparison between Vector.zero and cross is always different from zero (even if cross is actually 0.0f, 0.0f, 0.0f ). I tried also this Vector3 cross Vector3.Cross(beginDir, endDir) if (cross.magnitude 0.0f) return AngleDir.PARALLEL it also fails because magnitude is slightly more than zero. So my question is given 2 Vector3 in Unity, how to compare them? I need the elegant equivalent version of this if (beginDir.x endDir.x amp amp beginDir.y endDir.y amp amp beginDir.z endDir.z) return true |
0 | Unity Casting shadows of anima2d characters I want to cast shadows of animated 2d character on a level like this The only thing here I want is dynamic shadows for anima2d character as animation progresses.Is there a way of achieving shadows with anima2D characters? |
0 | Lighting, shader and GI is messing up the materials in Unity3D Hello Guys I am not very sound with Unity3D Lightmapping. Currently I have a set of low poly items in my scene. Textures on my models are getting washed out. They totally look absurd. here is a picture of expected (Right) vs current result (left) |
0 | Creating a static 2D background at runtime I'm using unity for a 2D game. We have a lot of props for grass, plants, flowers, etc that are static and always in the background. I'd like to optimize the background and reduce the drawcalls as much as possible by making a big image with the final result of the background. The idea would be to draw on a texture all the elements in the background, and then use this texture as the background. This way a single element has to be drawn. How can I create these background texture at runtime, so it is generated as soon as the scene is loaded? |
0 | (Unity) Serializing Data with Custom Object Stored by Reference I have a custom class that I serialize deserialize to from file(s), and is not guaranteed to be identical each time the game runs (in this example, a language pack. it's possible to fix a typo manually). As a result, I do not use UnityEngine.Object on it, and deserialize it each load. However, some classes that implement UnityEngine.Object (Monobehavior), have references to it. these references must persist (so that the language stays the same each load) As per the Unity Scripting page, https docs.unity3d.com Manual script Serialization.html, this can cause undesired behavior "If you store a reference to an instance of a custom class in several different fields, they become separate objects when serialized. Then, when Unity deserializes the fields, they contain different distinct objects with identical data." Naturally, I'd prefer this not be the case. again from Unity documentation linked above When you need to serialize a complex object graph with references, do not let Unity automatically serialize the objects. Instead, use ISerializationCallbackReceiver interface to serialize them manually. I know how to implement the interface. How do I preserve the reference? (Disclaimer not an expert in serialization, so if it's a simple fix, I'm sorry. Unity documentation doesn't provide an example for references). |
0 | How to raycast from a UI element How do I raycast from a UI object? I have tried Ray ray Camera cam Transform obj UI object ray cam.ViewportPointToRay(obj.position) AND ray new Ray(obj.position, obj.forward) Neither of these seem to work. |
0 | Difference between 2 quaternions I need to patch an animation during LateUpdate. I'm rotating the "chest" bone according to the mouse delta. This is to mimic aiming a pistol. During this aiming, the "neck" bone should stay relatively still. As changing the chest bone's location rotation yaw automatically changes the "neck" bone's local yaw rotation, I store the chest bone's rotation BEFORE I apply a new rotation to it. Then I calculate the difference between the old and the new rotation. Then I apply this rotation yaw difference to the neck bone. The inspector gives me nice values to work with. When I inspect the rotation values by script, I get reprensations that I can not easily work with. Here is an example While the Inspector shows "15.4", the localEulerAngle shows "344.6". If I use "344.6", the neck rotation goes Berzerk of course. How should this be solved? For completeness, here is the entire void private void pHandle LateUpdate Aim() Vector3 nOldChestRotation Chest.localRotation.eulerAngles Fade old input before capturing new, so we don't dull the freshest data. float yawBlend Mathf.Pow(1.0f Aim yawInputFalloff, referenceFramerate Time.deltaTime) A Lerp toward zero is just the same as a multiplication by the blend factor. Chest yawRate yawBlend Accelerate by mouse movement over the past frame. (May need adjustment for display resolution). Chest yawRate Input.GetAxis("Mouse X") float yawDelta Chest yawSpeed Chest yawRate Time.deltaTime float offCenterYaw Chest currentYaw Chest yawCenter float fDesiredChestYaw Chest currentYaw yawDelta float fHeroRotation 0f if (fDesiredChestYaw gt Chest rotateRange) fHeroRotation fDesiredChestYaw Chest rotateRange we don't rotate the chest beyond the allowed "Chest rotateRange", so simply act like the user didn't move the mouse Chest yawRate 0 yawDelta Chest yawSpeed Chest yawRate Time.deltaTime else if (fDesiredChestYaw lt Chest rotateRange) fHeroRotation (Chest rotateRange fDesiredChestYaw) Chest yawRate 0 yawDelta Chest yawSpeed Chest yawRate Time.deltaTime If we're moving away from the center, slow down as we approach the edge. if (yawDelta offCenterYaw gt 0) float extremityYaw offCenterYaw Aim yawMaxRange yawDelta 1.0f extremityYaw extremityYaw this.transform.Rotate(0, fHeroRotation, 0) Ensure we never overshoot the allowed range. Chest currentYaw Mathf.Clamp(Chest currentYaw yawDelta, Chest yawCenter Aim yawMaxRange, Chest yawCenter Aim yawMaxRange) Vector3 nNewChestRotation new Vector3(Chest.localEulerAngles.x, Chest currentYaw, Chest.localEulerAngles.z) Chest.localRotation Quaternion.Euler(nNewChestRotation) float fChestRotationDifference nNewChestRotation.y nOldChestRotation.y the neck should not rotate with the chest. So I first counter rotate it against the new chest rotation, then rotate it a little towards the chest rotation Neck.transform.localRotation Quaternion.Euler(0, Aim NeckYaw fChestRotationDifference (fChestRotationDifference 0.5f), 0) |
0 | Moving a dynamically spawned object I would like to create an object dynamically when the player presses Q and use this object in Instantiate and in transform.Translate. The problem is that the translation must be outside the if that checks for the Q press, but it applies to the cube that I created inside the if. using System.Collections using System.Collections.Generic using UnityEngine public class instancier new object MonoBehaviour public float moveSpeed 5f void Update () if (Input.GetKeyDown (KeyCode.Q)) GameObject objet new GameObject ("objet") GameObject cube new GameObject ("cube") cube Instantiate( objet, new Vector3(1, 2, 3), Quaternion.identity ) cube.transform.Translate( Time.deltaTime moveSpeed, 0, Time.deltaTime moveSpeed, Space.Self ) |
0 | Making a 2D gun spin from recoil when it shoots I am trying to clone the game quot Flip the Gun quot as an exercise. Here is the behaviour I have so far. And here is the code I am using if (Input.GetKeyDown(KeyCode.Space)) rigidbody2D.AddForceAtPosition( transform.position recoilPoint.transform.position recoilForce, recoilPoint.position, ForceMode2D.Impulse ) As you can see in the video, the gun is moving too fast and rotating too fast. It seems out of control. I am not sure if the way of adding force to the gun is correct or not. Thank DMGregory for editing the question for me. I am new to this family so that helped a lot. ) |
0 | We are asked not to use "Set Native Size" it's been around 2.5 weeks since we were tasked to build a 2d mobile game. The game heavely uses canvas and we have lots of images. Our designer uses Figma to design the game and I export images from it. If you have ever used Figma or Sketch, you may know that their mobile phone frame width and height is quite different than the physical device. For example, iPhone Pro Max frame in Figma has 896x414 but the physical device 2688 1242. So all the screens and the images in design is scaled down to look good in Figma's 896x414 frame. Another important thing I think worth to mention is that we set our Canvas Scaler's reference resolution to 1920x1080 as shown in the image below. So the thing is, there is also a guy, who is much more experienced in Unity, told us that we should export images from Figma with 2x scale. He says that images will look blurry if we export them in 1x. On top of that, he told us not to use Image component's Set Native Size property, because the image has twice the size shown in Figma. Instead we should scale down the images ourselves MANUALLY with eye decision (not sure if that phrase exists). So I am confused and not sure if that method is correct. What is a common practice in such situations? Do people not use Set Native Size? What would be a correct way of exporting images from Figma to a 1920x1080 canvas? P.S. As I am new to Unity, I may not be able to explain the situation correctly, if there is some extra information you need, feel free to ask in the comments. |
0 | Find the coordinates between two points based on third You can see two points in this picture. Points are surrounded by collider which is set to trigger. Points can either be Vector3 or Vector2, shouldn't make any difference. I need to get the coords on gray line if mouse enters the trigger, at the exact point where mouse and gray line form 90 degree angle. Gray line is just an straight line between 2 points. All the data left point coords right point coords mouse coords Is it possible with the data I have and how? |
0 | How do I get this effect in Unity3D? Here is a mockup of a main menu screen I'm trying to put together in Unity. I'm clueless as to how I should go about creating the blue glow on the left of my menu options. Can somebody point me in the right direction? |
0 | accelerometer not working unity why is the cube moving when I use a controller, but not with the accelerometer? void Update () text.text "X " Input.acceleration.x " Z " Input.acceleration.z transform.position new Vector3(10 Input.acceleration.y, 0, 10 Input.acceleration.z) transform.Translate(Input.acceleration.x, 0, Input.acceleration.z) transform.position new Vector3(10 Input.GetAxis("Horizontal"), 0, 10 Input.GetAxis("Vertical")) transform.Translate(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")) (I'm on a Xperia Z3 compact by the way) |
0 | Why doesn't Array.Copy to mesh.verticies work in Unity? I am rebuilding a mesh but something seems odd that I have to create a temp array just to hold the verticies rather than copy an array. I'm not using list because this is used frequently and I do not want to resize list and instead just use height index boundary to prevent additional garbage collection from resizing lists. Doesn't work and results in no mesh showing Mesh mesh new Mesh() copy myVerticiesArray to mesh.verticies. myVerticiesArray length has null values above verticiesIndexHeight but array copy height set in Array.Copy() Array.Copy(myVerticiesArray, mesh.vertices, verticiesIndexHeight) ... code to set UVs etc omitted mesh.Optimize() mesh.RecalculateNormals() mesh.RecalculateBounds() this.GetComponent lt MeshFilter gt ().mesh mesh Also doesn't work and results in no mesh showing Mesh mesh new Mesh() loop through built verticies array to mesh.verticies of correct size because myVerticiesArray length has null values above verticiesIndexHeight mesh.verticies new Vector3 verticiesIndexHeight for(int i 0 i lt verticiesIndexHeight i ) mesh.verticies i myVerticiesArray i ... code to set UVs etc omitted mesh.Optimize() mesh.RecalculateNormals() mesh.RecalculateBounds() this.GetComponent lt MeshFilter gt ().mesh mesh Works and renders mesh Mesh mesh new Mesh() Vector3 tempVerticiesArray new Vector3 verticiesIndexHeight copy built verticies array to temp array of correct size because myVerticiesArray length has null values above verticiesIndexHeight Array.Copy(myVerticiesArray, tempVerticiesArray, verticiesIndexHeight) mesh.verticies tempVerticiesArray ... code to set UVs etc omitted mesh.Optimize() mesh.RecalculateNormals() mesh.RecalculateBounds() this.GetComponent lt MeshFilter gt ().mesh mesh |
0 | How to Properly Type My Curve's Formula I'm creating an RPG game (using C in Unity API) that uses a leveling system. I went to the Desomos Online Graphing Calculator and created the following curve representing the levels based on experience https www.desmos.com calculator bsvkba4qg1. Note that the Y intercept is at approximately (0, 1). My Character class has the following fields representing the experience curve from above public float experience get set public int level get float level experience 120 level 1.123f level Mathf.Log(level) level 20 return Mathf.FloorToInt(level) However, when the game begins and experience defaults to 0 as floats do, level returns 2. When experience is 100, level returns 13. Clearly there is some error on my part. Have I entered my formula wrong? If so, how can I fix it, and if not, what else might be the problem? |
0 | How can I destroy particles on collision with specific a GameObject? I wrote a script to manage my Particle System emission. The starting lifespan is set to infinite so that the particle never dies until it reaches a specific collider. I didn't find any method to destroy a specific particle in the Unity Manual. How can I do this? Here's the code (updated to show the partial fix) using UnityEngine using System.Collections.Generic public class PlayerDamage MonoBehaviour private ParticleSystem ps public List lt ParticleCollisionEvent gt collisionEvents public int attackValue 1 Range(0.0f, 100f) public int maxParticles public float particleLife public bool neverDies public float particleSpeed 8.0F void Start() ps GetComponent lt ParticleSystem gt () collisionEvents new List lt ParticleCollisionEvent gt () var collision ps.collision collision.enabled true collision.type ParticleSystemCollisionType.World collision.mode ParticleSystemCollisionMode.Collision3D void OnParticleCollision(GameObject other) int numCollisionEvents ps.GetCollisionEvents(other, collisionEvents) Rigidbody rb other.GetComponent lt Rigidbody gt () int i 0 while (i lt numCollisionEvents) if (rb.CompareTag( quot Enemy quot )) BaseHealth baseHealth other.GetComponent lt BaseHealth gt () if (baseHealth ! null) Vector3 pos collisionEvents i .intersection Vector3 force collisionEvents i .velocity 10 rb.AddForce(force) baseHealth.TakeDamage(attackValue) i void Update() var collision ps.collision collision.maxKillSpeed particleSpeed Debug.Log( quot Particles Alive Count quot GetAliveParticles()) ps.Emit(maxParticles) var main ps.main main.maxParticles Mathf.RoundToInt(maxParticles) main.startLifetime particleLife if (neverDies) particleLife float.PositiveInfinity else particleLife 5f int GetAliveParticles() ParticleSystem.Particle particles new ParticleSystem.Particle ps.particleCount return ps.GetParticles(particles) |
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 | Problems with BlendOp Max I'm trying to write a shader that doesn't blend additively etc etc. I'd like to take whichever of the source or destination colours is brighter and use that and BlendOp Max seemed like the tool for the job. However, as you can see below, the shadow of one light seems to be occluding the other, which doesn't match up with how I understand BlendOp Max is supposed to work Unity Docs NVidia OpenGL Could anyone clarify where I'm going wrong or provide an alternative? Interestingly, Blend One One is working fine, however, BlendOp Add (along with all the other BlendOps apart from the 'logical' ones) are creating the same issue. Update Shader Code Shader "Lantern Flat Pullup" Properties LitTex ("Lit (RGB)", 2D) "white" UnlitTex ("Unlit (RGB)", 2D) "white" Pullup ("Pull up Point", Range(0,1)) 0.7 BlendSize ("Blend Size", Float) 0.3 SubShader Pass Tags "LightMode" "ForwardBase" LOD 200 CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" uniform sampler2D UnlitTex uniform float4 UnlitTex ST uniform sampler2D LitTex uniform float4 LitTex ST uniform float Pullup uniform float BlendSize uniform float4 LightColor0 struct VI float4 vertex POSITION float4 tex TEXCOORD0 struct V2F float4 pos SV POSITION float4 tex TEXCOORD0 float4 posWorld TEXCOORD1 V2F vert(VI v) V2F o o.pos mul(UNITY MATRIX MVP, v.vertex) o.tex v.tex o.posWorld mul( Object2World, v.vertex) return o float4 frag(V2F i) COLOR float3 flatReflection LightColor0.xyz (1 length( WorldSpaceLightPos0.xyz i.posWorld.xyz)) return lerp( tex2D( UnlitTex, i.tex.xy UnlitTex ST.xy UnlitTex ST.zw), tex2D( LitTex, i.tex.xy LitTex ST.xy LitTex ST.zw), clamp((length(flatReflection) Pullup BlendSize) (2 BlendSize), 0, 1) ) ENDCG Pass Tags "LightMode" "ForwardAdd" Blend One One BlendOp Max LOD 200 CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" uniform sampler2D UnlitTex uniform float4 UnlitTex ST uniform sampler2D LitTex uniform float4 LitTex ST uniform float Pullup uniform float BlendSize uniform float4 LightColor0 struct VI float4 vertex POSITION float4 tex TEXCOORD0 struct V2F float4 pos SV POSITION float4 tex TEXCOORD0 float4 posWorld TEXCOORD1 V2F vert(VI v) V2F o o.pos mul(UNITY MATRIX MVP, v.vertex) o.tex v.tex o.posWorld mul( Object2World, v.vertex) return o float4 frag(V2F i) COLOR float3 flatReflection LightColor0.xyz (1 length( WorldSpaceLightPos0.xyz i.posWorld.xyz)) return lerp( float4(0,0,0,1), tex2D( LitTex, i.tex.xy LitTex ST.xy LitTex ST.zw), clamp((length(flatReflection) Pullup BlendSize) (2 BlendSize), 0, 1) ) ENDCG FallBack "Diffuse" Update 2 The same plane and lights rendered using Unity's standard shader, for illustrative purposes. |
0 | How to customize a character with new objects (clothes, body parts) in a 3D game? how do we customize a character in a game by adding, for example, a different clothing? The character has an armature, made in Blender, if I add a new object with the game engine, I would have to copy the position for each frame, and the orientation? Or is there a technique to make the model in Blender with different meshes, find the meshes in the .dae file (for scenekit, but it might be the same for fbx for unity), and replace it with a new object, and the orientation will be automatically copied? Has anyone had some experience with this? Thanks |
0 | Unity custom inspector How to serialize scene objects in ScriptableObject? I am writing a custom inspector for the artist in our team to design some simple animations (without using mecanim). The basic setup is the following Animations are saved as ScriptableObjects. There is a class AnimationBase that inherits from ScriptableObject and different Animation classes that inherit from AnimationBase. There is an AnimationSystem script that stores the animations for one gameobject. Animations can be added dynamically for different events (I got multiple MyAnimation to store those per event type). It also stores a string with the name of a ScriptableObject AnimationList. That ScriptableObject stores the filenames for all the used animations in lists of strings for the different animation event types. Now I have an animation "EnableAnimation" (inheriting from AnimationBase and therefore a ScriptableObject) that should enable a gameobject. If I select a gameobject from the assets, the reference is saved in the EnableAnimation asset as expected. But when I select a gameobject from the scene, the EnableAnimation assets shows "Type mismatch" instead. I think the problem is that I use a EnableAnimation asset but want to store information in the scene. Is it possible to store the ScriptableObject in the scene instead? Other things to take into account for solving the problem The custom inspector should work for prefabs, prefab instances and normal gameobjects. If possible prefab instances should be allowed to use the same animations as the prefab but change some values per scene. I have a prefab "A" that has an AnimationSystem component and a child gamobject "B". With the default inspector I can select B as an gameobject in a script and apply that change to the prefab. If I select a different gameobject in the scene and try to apply, the prefab does not save the reference. If possible, this behaviour should be used too. Thank you for your help! |
0 | Check if is object in camera field and not covered by other object I know how to check if object is in camera view but how I can check if that object is cover by something elese? In my case I want to turn on or off some effect when I look at light. At this moment my code is straight forward, I have created interface for lightable object with method public bool isVisibleByCam(Camera cam) if (GeometryUtility.TestPlanesAABB(GeometryUtility.CalculateFrustumPlanes(cam), gameObject.GetComponent lt Collider gt ().bounds)) return true return false I hope there is better way than checking every object in camera view and comparing distnace between camera. |
0 | Unity UNET, problems spawning and then destroying that instantiated prefab I am very new to networking, and have ran into an issue, read below. I have multiplayer system setup, where players can spawn, they can pick up weapons and drop them, there is an object representing a pickup with network identity component attached and local player authority enable, the player can come up to it and press "E", which will destroy the pickup object, then the player can press I to to "drop" that weapon, which instantiates it infront of the player, now this is what should happen, and it works on single player, but when there's 2 players, for second player(client only) it doesn't work as it should. I have 1 script weapon manager and another small, Pickup (on pickup object child with trigger). Below is the code and according description of my attempt so far Below is PickUp script (on 1st child of pickup object with trigger enabled) private void OnTriggerStay(Collider other) if (other.CompareTag("Player")) if (Input.GetKeyDown(KeyCode.E)) Call pickup function on player, passing the weapon id and parent gameobject other.GetComponent lt WeaponManager gt ().PickUpWeapon(weaponID, transform.parent.gameObject) Below is WeaponManager script (on player) public void PickUpWeapon(int id, GameObject go) CmdDestroyObj(go) ... (other code, not relevent) Command void CmdDestroyObj(GameObject obj) RpcDestroyObj(obj) ClientRpc void RpcDestroyObj(GameObject obj) HERE obj is NULL (!!ERROR!!) Destroy(obj) Above in RpcDestroyObj() obj is null void Update() if(isLocalPlayer) if (Input.GetKeyDown(KeyCode.I)) if (slots currentActiveSlot ! null) CmdDropWeapon() Then here's CmdDropWeapon() function Command void CmdDropWeapon() RpcDropWeapon() Here's RpcDropWeapon() function ClientRpc void RpcDropWeapon() GameObject drop (GameObject)Instantiate(drops currentGun.GetComponent lt WeaponStats gt ().id , transform.position transform.forward, Quaternion.identity) drop.GetComponent lt Rigidbody gt ().AddForce(transform.forward 25000f Time.deltaTime) CmdDestroyWeaponHeld() Destroy currently held weapon (don't pay attention, not relevent to current problem currentGun null if (isLocalPlayer) GetComponent lt PlayerSetup gt ().playerUIInstance.GetComponent lt PlayerUI gt ().SetInventorySlotFill(currentActiveSlot, 1) emptyHanded true On single player (so host amp client), everything works besides destroying the pickup prefab that is Instantiated. On multiplayer, second player (client only), can pick up and drop weapons as well as the originally spawned weapon is destroyed, but destroying the newly instantiated (so after player drops it) pickup object doesn't work. (In the console there are no errors when UnityEditor is the Lan host server, when 2 players are playing and I try picking up and dropping weapons several times from client side) Why is this not working? I would appreciate any help assistance in getting this right and sync over network for all players. My guess is that, rpc function Instantiates the drop prefab but it's kind of different on all clients, so the server or another client doesn't have exactly the same object in the scene which means it will not find it and return null. Let me know if you need any additional information. Thanks a lot in advance! |
0 | Using collision.contacts to determine if on a floor I'm trying to make my own first person character (because I get lost in the sea that is Unity's FP character script), and am trying to make it so it detects when it is standing on a floor. I tried using a playerController, but I've found rigidbody is just more malleable. Anyways, so I think how you'd do it is finding the direction of the contact, and if it isn't straight down, then to keep onGround as false. I'm just not entirely sure the scripting behind this, and several searches have turned up nothing. Several offered using mutliple colliders, but I would prefer to keep the number of objects, colliders or otherwise, at a minimum, considering there will be a large number of them in the scene as is. I also want something that's easily manipulable so that I can add extra features like climbing up a wall or the like, and I think that measuring the angle to the center is about as simple and easily manipulated as it gets. |
0 | Unintended window opening when pressing Unity's "Submit" button I've been working on a top down 2D game for a while now, and yesterday I found a strange bug that I just can't explain to myself whatsoever. I have a loot window for looting enemies, as well as a character panel to equip gear see stats. I realized that after I open and close a loot window, if I press the space button (used for attacking, not for opening any windows) while holding A LeftArrow or W UpArrow it opens the character panel. Once this happens, I can press space to open close the character panel. Went to the character panels OpenClose() function (all it does is set the canvas group alpha to 0 and block raycast to false and vice versa) which is being called unintentionally, put a debug.log inside to verify if it really was being called, and yes, it is. I look up all references to see where I used it, but I only use it in a single place in the project that is behind an if statement looking for they keycode C (NOT space). I added a debug.log for the Input.inputstring to see if somehow a magic C button press is ending up in that function, but no. If I press C to open the window, the debug log pops up, if I press space, the inputstring appears to be empty, so the if statement to get to the only place in the code referencing that function cannot be met. Removed the space button from my Player entirely, the behaviour still persists. Added another debug.log with stackTrace.GetFrame(1).GetMethod().Name to show who is actually running this function, but it turns out that if I run it and press C, it says it's being opened by the update function in the UIManager (as expected). If I run it the strange, unintended way, it says it is being run by the EventSystems Invoke function. Coupled with the fact that the behaviour persists despite the space button being removed from the player, I realized that it's Unity's built in "Submit" button being pressed. Strange behaviour It appears to call the submit function on the OpenClose button for the character panel, but only under the circumstance that I closed a loot window and haven't clicked the mouse anywhere yet afterwards. If I deactivate the button that holds the character panels OpenClose function, the behaviour stops. The button shouldn't be pressed though, because it is on a canvas group with alpha 0 block raycast false, just like all the other buttons with the identical function that work fine. The loot window has no idea about the character panel either, and all the windows are properly wired to their own OpenClose function. Upon further inspection, the window only starts showing up if, after closing a loot window, i press A LeftArrow Space or W UpArrow Space. This is getting more and more confusing for me. So basically my issue is how do I figure out why this function is being called? It feels as if closing the loot window somehow "caches" the OpenClose button for the character panel onto the submit button, but only until I click elsewhere on the screen. Did you guys have any experience with a similar situation? Could you share some pointers on how to debug this? What is the "submit" button usually used for, and what would make it only work in combination with the left top directional buttons? I've spent about 4 hours on this now and don't know how to get any further. |
0 | Unity C How to make 3D objects move in the grid? I want to move and deploy 3D objects in the grid, like bakery 2(Storm8 Studios). How do you make a grid like that? For example, make a 5x5 grid and move it to a touchdrag. I'd like you to give me some advice. Pictures for reference https lh3.googleusercontent.com Kwp9i9ExRboeQCtM65sztw3tqEL9R76zZzB9U6j5vs98ueF9ksOU3huMdZqv4KPDZ2E w2590 h1430 |
0 | GameObject remains null for some reason The idea is to access the function BlockWasDestroyed() from Combo class. Instead of var combo gameObject.GetComponent(Combo) I've also tried with var combo GetComponent(Combo) var combo Combo gameObject.GetComponent(Combo) var combo Combo GetComponent(Combo) But the console keeps telling it's null. However it could work when the function was static, but thing is now that function is calling another function, and so the errors happen once again. Here's my code so far Brick.js pragma strict public class Brick extends MonoBehaviour function OnCollisionEnter(col Collision) if(col.gameObject.name quot Ball quot ) var ballb gameObject.GetComponent(BouncingBall) var combo gameObject.GetComponent(Combo) combo.BlockWasDestroyed() ballb.velocityZ ballb.velocityZ 1 Score.score 20 Destroy(this.gameObject) |
0 | Combining cylindrical Billboarding and aligning with velocity (unity) I'm trying to make a custom GPU particle solution on Unity to fullfill some needs on my project, using compute shaders and custom shader Graphics.DrawProceduralNow() to draw them. While I managed to make the system, I'm struggling making the particles cylindrical billboards and align them to their velocity axis as I'm not really used to work with matrices. I achieved to make both effect working individually (using usefull ressources on the forum) but I can't manage to combine the two rotations without obtaining wrong results v2f vert(uint id SV VertexID, uint inst SV InstanceID) v2f o Vertex position float3 q quad id float3 newPos q particles inst .size SizeMul PARTICLE DIRECTION float3 particleDirection normalize(particles inst .velocity) float3x3 rotMatrix float3 xaxis cross(float3(0,0,1), particleDirection) xaxis normalize(xaxis) float3 zaxis cross(xaxis, particleDirection) zaxis normalize(zaxis) Matrix for particle direction rotMatrix 0 .xyz float3(xaxis.x, particleDirection.x, zaxis.x) rotMatrix 1 .xyz float3(xaxis.y, particleDirection.y, zaxis.y) rotMatrix 2 .xyz float3(xaxis.z, particleDirection.z, zaxis.z) newPos mul(rotMatrix, newPos) CYLINDRICAL BILLBOARDING Distance between the camera and the center float3 dist WorldSpaceCameraPos particles inst .position With atan the tree inverts when the camera has the same z position float angle atan2(dist.x, dist.z) float cosinus cos(angle) float sinus sin(angle) Matrix for billboarding rotMatrix 0 .xyz float3(cosinus, 0, sinus) rotMatrix 1 .xyz float3(0, 1, 0) rotMatrix 2 .xyz float3( sinus, 0, cosinus) newPos mul(rotMatrix, newPos) newPos particles inst .position o.pos mul(UNITY MATRIX VP, float4(newPos.xyz,1)) o.uv q 0.5f o.col particles inst .alive particles inst .color return o Another way to say it is i would like Y to point toward the velocity direction and then rotate the quad around it's new Y axis to make the billboard point at best toward camera. Any help would be much appreciated and any other approach for cylindrical billboarding that would work once quad is aligned to velocity vector would be welcomed too. Have a good day! |
0 | Skewed 3d model when moving device around with Unity and Vuforia I am having trouble with the orientation of a 3d model that is larger (think queen sized bed) than the target image(a4 size bond paper). The model appears to be slanted in a way that looks totally unrealistic especially when moving the device around. Is there a way to keep the model horizontally aligned with the real world floor? I have already enabled Extended Tracking but the behavior is still present. I have also set the world center to Specific Target and set Device Camera focus mode to FOCUS MODE CONTINUOUSAUTO. Thank you. |
0 | Getting the edge cells in a list of cells on a 2d grid, and knowing which neighbor is missing I create a quot circle quot on my 2d grid using this code public List lt Cell gt GetSurroundingCellsCircle(Coord originCoord, int distance) List lt Cell gt matches new List lt Cell gt () int EX distance coord.x int EY distance coord.z int SQ distance distance for (int x coord.x distance x lt EX x ) for (int z coord.z distance z lt EY z ) int c x coord.x int d z coord.z if ((c c d d) lt SQ) Cell cell GetCell(new Coord(x, z)) if (cell ! null) matches.Add(cell) return matches This code works fine and returns a list of cells that together create a circle shape. Now I want to get all the edge cells of this circle, and not only that, but I also need to know which side of the edge cell that has no neighbor, so I know where to draw the line. I want a result that looks like this red line I wrote this code that would work for a square (it just finds the max min of X Z and draws a sphere there, but as you can see in my image, its missing the quot rounding quot cells int maxX 0, maxZ 0, minX 0, minZ 0 for (int i 0 i lt cells.Count i ) int cX cells i .coord.x int cZ cells i .coord.z if (i 0) minX cX minZ cZ else if (cX lt minX) minX cX if (cZ lt minZ) minZ cZ if (cX gt maxX) maxX cX if (cZ gt maxZ) maxZ cZ for (int i 0 i lt cells.Count i ) int cX cells i .coord.x int cZ cells i .coord.z if (cX maxX cZ maxZ cX minX cZ minZ) Gizmos.DrawSphere( new Vector3((cells i .coord.x GridBase.WORLD CELL SIZE) GridBase.WORLD CELL OFFSET, 1, (cells i .coord.z GridBase.WORLD CELL SIZE) GridBase.WORLD CELL OFFSET), 1) |
0 | Unity Extending native components I was wondering if it was possible to use the existing native components inside Unity to extend them, and create my own. For instance, if I wanted to create a component called Hurtbox, could I maybe do something like this? class Hurtbox BoxCollider2D ... That would allow me to use the existing logic of the component and enhance it for my purposes. Currently I have a separated BoxCollider2D and a Hurtbox components. The latter uses the former, but I thought if I managed to combine them both in a single one, it would be more elegant. Is it doable? How? |
0 | How do I get line numbers in a unity headless server's stack trace? For some reason Unity 5 doesn't allow me to do a developement build of a headless server, and this is quite a problem when debugging, since I get stack traces without line numbers, such as NullReferenceException Object reference not set to an instance of an object at ClientServer.Update () 0x00000 in lt filename unknown gt 0 Trying the xvfb trick to run a pseudo headless server, which doesn't prevent enabling debugging symbols, doesn't work (it crashes mono for some reason). I'm really at a loss on how to debug an headless server is there something I'm missing? |
0 | Resizing the camera view in Phaser 3 just like in Unity I started to work in Phaser 3 with a previous background in programming in Unity and I can't figure out how to zoom the camera view. In Unity, I can change this value, to resize the camera view Then, everything in its view becomes bigger or smaller and it does not affect GUI elements, and the camera still fills up the full game window. In Phaser I was trying to use those methods this.cameras.main.setSize(width,height) it just resizes the camera making it smaller, and everything outside the camera becomes black this.cameras.main.setViewport(x,y,width,height) just as above, but x and y ads padding this.cameras.main.setZoom(3) the closest effect I want to achieve, but it zooms to the center of the scene, scales GUI elements and messes the camera bounds I made an illustrative picture which can explain my problems better So how can I change the size of the main camera, to fit the game window and not scale the GUI, keeping the camera bounds at the same time? |
0 | How to playlay multiple Particle Systems when colliding with multiple obstacles using object pooling? I have two types of particle, one for each player Player 1 (Red Particle) Player 2 (Blue Particle) When player 1 collides with an obstacle then I want to play the red particle system, and when player 2 collides with an obstacle then I want to play the blue particle system. Code TouchControll.cs public GameObject PlayersPartical void OnTriggerEnter2D(Collider2D other) here my player collided with obstacle foreach (Transform child in transform) if (child.tag "point") GameObject partical Instantiate(twopartical Random.Range(0,1) , transform.position, transform.rotation) ParticleSystem heal partical.GetComponent lt ParticleSystem gt () heal.Play() GameObject partical Instantiate(PlayersPartical, transform.position, transform.rotation) ParticleSystem heal partical.GetComponent lt ParticleSystem gt () heal.Play() ObjectPooler.Instance.SpawnFromPool("redandbluepartical", transform.position, Quaternion.identity) ObjectPooler.cs public static ObjectPooler Instance public void Awake() Instance this System.Serializable public class Pool public string tag public GameObject prefab1 public GameObject prefab2 public int size public List lt Pool gt pools public Dictionary lt string, Queue lt GameObject gt gt pooldictionary which gameobject you should be pool void Start () pooldictionary new Dictionary lt string, Queue lt GameObject gt gt () foreach(Pool pool in pools) add a pool in list Queue lt GameObject gt objectpool new Queue lt GameObject gt () for(int i 0 i lt pool.size i ) GameObject obj Instantiate(pool.prefab1) GameObject obj1 Instantiate(pool.prefab2) obj.SetActive(false) obj1.SetActive(false) objectpool.Enqueue(obj) pooldictionary.Add(pool.tag, objectpool) public GameObject SpawnFromPool(string tag,Vector3 position,Quaternion rotation) two tag red and blue partical if(!pooldictionary.ContainsKey(tag)) Debug.Log("doesnot exist" tag) return null GameObject objecttospawn pooldictionary tag .Dequeue() here how to call my trigger objecttospawn.SetActive(true) objecttospawn.transform.position position pos objecttospawn.transform.rotation rotation rotation pooldictionary tag .Enqueue(objecttospawn) return objecttospawn Image1 Image2 How do I call these particles? |
0 | How to avoid game starting before start button is clicked? I've made a game with a Title Screen (Canvas), and a Start Button attached to the Title Screen. Points, GameOver, Restart, and even the Start Button sort of works, but it's possible to play the game before the user presses start. Is there a way to make the GameObjects only appear after the button is clicked? I've tried to move and change the "public void StartGame()", but I can't get it right. This is my first game ever, so hope the code provided is relevant. Enemy.cs void Start() enemyRb GetComponent lt Rigidbody gt () gameManager GameObject.Find("GameManager").GetComponent lt GameManager gt () player GameObject.Find("Player") GameManager.cs public void StartGame() powerup.transform.rotation) score 0 UpdateScore(0) isGameActive true titleScreen.gameObject.SetActive(false) void Update() enemyCount FindObjectsOfType lt Enemy gt ().Length if (enemyCount 0) roundNumber SpawnEnemyIntruders(roundNumber) Instantiate(powerup, GenerateSpawnPosition(), powerup.transform.rotation) void SpawnEnemyIntruders(int enemiesToSpawn) for (int i 0 i lt enemiesToSpawn i ) int enemyIndex Random.Range(0, enemies.Length) Instantiate(enemies enemyIndex , GenerateSpawnPosition(), enemies enemyIndex .gameObject.transform.rotation) public void GameOver() restartButton.gameObject.SetActive(true) gameOverText.gameObject.SetActive(true) isGameActive false PlayerController.cs void Start() playerRb GetComponent lt Rigidbody gt () playerAudio GetComponent lt AudioSource gt () StartButton.cs void Start() button GetComponent lt Button gt () gameManager GameObject.Find("GameManager").GetComponent lt GameManager gt () button.onClick.AddListener(StartThis) |
0 | How to make a long highway in unity? I'm planning to make a long highway for a Racer game. What is the best way to do it ? Do you make it in a single scene which I think is difficult to manage ? Or do you make multiple scenes or anything else ? |
0 | unbelievable strange problem in unity android build texture and frame Suddenly the texture quality of Unity Android Build and the frame of the game was greatly degraded. See the picture A and B. In image A the center lines on the road are sharper, but B is blurred. I want my game to look like A, not B. What is surprising is that you can roll back the project to the point where it worked and then run the apk build again. In the above picture, A is a screenshot of a normal time. I have installed apk backed up at that point. B is a screenshot of when I built A after I rolled back the Unity project at the build time. Both are the same project, but the build output is different. (Of course not good ...) Of course I did not touch Unity, Java, Android SDK etc at the same time. Of course, there is no configuration change on the testing phone as well. It's just like this all of a sudden. I even reinstalled the PC this morning. I still have this problem. Even if you build on a separate PC, you're having the same problem. I build a project at another pc, mac book pro, but problem is still there. Of cause, I factory reset my test phone, but problem still there. Test phone is Samsung Galaxy S4. build environment is Windows 10, Unity 2017. |
0 | A collider defined as intersection of two colliders I'm working in unity and I have the following problem Suppose you have an object that's very similar to say the intersection of say the corner of a cube and a ball, and you want a nice collider for this object. First option is to simply use the mesh collider option but this is apparently not very efficient, and if for example the sphere is very smooth, there might be a lot of polygons and that could be a problem. Second, you could just fill the object with various simple colliders. However, both of the above options seem unnecessarily complicated it would seem natural to me to somehow work with both colliders the sphere collider and the cube collider. To determine if the object is touching something, the requirement is that both the cube and sphere collider are touching something, not just one of them. I don't know how the actual collision checks work, but I would expect that say in the second option I wrote above (placing a few small colliders inside the object), a collision check sees if any of the colliders is touching a collider of some other object so there is an option for "union" type of collision check (see if any of the colliders are touching something). Similarly, I would expect there would be an option of checking whether both the colliders are touching something, but I'm not aware of it. Either way, I would appreciate ideas on how to implement a good collider for this problem, and whether there's a way to implement it by the way I described, using the "intersection" of two colliders. |
0 | How to determine size of art assets for Unity UI? Previously when I made games, I used ui assets from the asset store. Working with those assets was easy as the backgrounds were plain. However, I'm now working on a game where custom graphics are used for UI. So, I need to specify size of backgrounds,icons etc to the art team. I understand how aspect ratio works with regards to unity camera, but having trouble understanding the relation between camera size and Canvas. For example, for a camera size of 4.6, an image size of 517X920 will cover the whole screen in 9 16 aspect. However, the same image is considerably larger when used as UI image under the Canvas. Can someone please help me understand how Canvas deals with image sizes? |
0 | How can I add solid collideable borders to the viewport regardless of the resolution? I'm making a game in Unity. In my game I have a sphere, what I need is for the sphere to rebound against the edges of the viewport. For that I used a few Gameobjects with 2D box colliders. The problem is that when game resolution changes, the edges of the camera are extended or reduced, and empty gameobjects are not on the edge. How can I make gameobjects which always stay on the edge of the viewport? Is this the correct way to make it bounce at the edges? |
0 | Improving the look of a character with solid parts inside a translucent jello exterior So my problem is a bit hard to explain. I have a character made out of a jello shell, with an internal skeleton. So let me introduce you to ma boi quot Chonker McJello quot The problem is, that I want a rich green slightly transparent jello, without loosing too much details and quot whiteness quot on the internal skeleton. If I turn the transparency or saturation of the jello down, the jello looks ugly, if I put the jello as I want, the Skeleton looses too much details turns green. I have thought of different approaches, but do not really know how to achieve the effect I want. Single sided emission Is there a way to make the jello glow internally and light the skeleton up? The emission should only come from the backfaces. Doing something with the render layers, like rendering the skeleton with transparency on top of the jello again, to make it appear quot less affected quot by it's color Everything I have in mind sounds easy but is propably pretty complicated and I don't have a lot of experience with shadergraphs and unity's hdrp. If you have any idea how to achieve the desired effect (maybe not in the way I thought) I would really appreciate your help! Thanks a lot! |
0 | Animator.Play() only works the first time I am creating a game in Unity 3d that is using an animation to move an object. For some reason the animation only works the first time it is accessed and from then on it acts as if it is not being called even though I have debugged and I see that it is being called. Here is the code I use to call the animation if (anim null) foreach (Transform component in myObject.transform) anim components.GetComponent lt Animator gt () anim.Play("Flip Forward") anim.enabled true As you can see I have an animator connected to myObject that I access in order to plan an animation. "Flip Forward" is one of the animations I have created. |
0 | SetIKHintPosition and SetIKHintPositionWeight seems to have no impact I have recently been exploring Unity's inverse kinematics, to further polish the interaction between our rigged avatars and props. I have made a sample project, using PuppetMaster's basic humanoid for the model, rig, and idle animation, but without Final IK meaning this is Unity's inverse kinematics. Inside our OnAnimatorIK method, we set the right elbow's SetIKHintPosition and SetIKHintPositionWeight like we did with the hand IK animator.SetIKHintPosition(avatarIKHint, hintPosition) animator.SetIKHintPositionWeight(avatarIKHint, hintBlendValue) animator.SetIKPosition(sourceIKGoal, targetPosition) animator.SetIKPositionWeight(sourceIKGoal, blendValue) You can see the left and right hand correctly move to where we set it. However, it seems like the right elbow is ignoring the hint position entirely. You can see the white debug line connecting the elbow to the hint position in the picture above. It seems like the elbow ONLY bends if it absolutely must for the hand to reach the target position, regardless of where the hint is set, and the weight value given. I have fiddled with this on and off for days and still haven't found a solution. Others have asked the same question here and on other sites, but no one has posted an answer. |
0 | How do I set horizonal Field of View by code as in Inspector? I have a camera that I have set to RenderType Base Projection Perspective FOV Axis Horizontal Field of View 75 Physical Camera False Clipping Planes Near 0.3, Far 1000 If I set Field of View values during gameplay in the Inspector, it works as expected. For example, I type 75, and the camera behaves as I think it should. I'm comparing with Resident Evil 4. It has a camera cheat, and if I select FOV 75 in this cheat, the Resident Evil 4 camera behaves like my Unity game camera. However, when I set the camera.fieldOfView to a 75 by code, the Inspector shows 104, and the code does not look as it looks when I type 75 in the Inspector. camera.fieldOfView however returns 75. What is going on here, and how do I fix it? Thank you! |
0 | How does input work when exporting to Android? I know I must add Android sdk , but my question is this If I make a game that works with the mouse, for example a puzzle game, then I output my game to Android, do I have to rewrite it to work with the touch screen? |
0 | Convert Canvas Space point to local space of a rotated rect? I got a quite tricky problem I have my mouse position and my rectangle position in canvas space(screen space but with adjusted scaling). Now I want my mouse position converted to local space of the rectangle. Problem is, the rectangle can be rotated. Without rotation its quite simple and works nicely. Heres a graphic for better demonstration Edit3 Got it finally working. I messed up with a minus in the calculation instead of using a . Also the hierarchy of the image in unity was incorrect. Lastly I had to change the rotation from CCW to CW(Thanks unity for using CCW in your UI...). This is my final solution Code Unity C var mapRect MapContentTransform.rect Canvas Space Map Center var mapPositionCenter CanvasRectTransform.InverseTransformPoint(MapContentTransform.position) mapPositionCenter.x CanvasRectTransform.rect.width 2.0f mapPositionCenter.y CanvasRectTransform.rect.height 2.0f Mouse Position in Canvas Space Vector2 mousePositionCanvasSpace CalculateScreenspacePositionCanvasSpace(new Vector2(Input.mousePosition.x, Input.mousePosition.y)) Rotation angle of the Map in Radians float theta (MapContentTransform.eulerAngles.z 360.0f) Mathf.Deg2Rad var rotatedX ((mousePositionCanvasSpace.x mapPositionCenter.x) Mathf.Cos(theta) (mousePositionCanvasSpace.y mapPositionCenter.y) Mathf.Sin(theta)) mapRect.width 2.0f var rotatedY ((mousePositionCanvasSpace.y mapPositionCenter.y) Mathf.Cos(theta) (mousePositionCanvasSpace.x mapPositionCenter.x) Mathf.Sin(theta)) mapRect.height 2.0f Thank you Kyy13! |
0 | What is the AssetBundle dropdown in the inspector for? I know what an AssetBundle is alright. But what is the dropdown at the bottom right for? Apparently you can choose an asset bundle for this asset to belong to. So what? What happens when you choose one? Does Unity build an AssetBundle for you? Where? |
0 | Player moves in a jerky way when riding on a moving platform I have a moving platform script that travels between three positions. This works fine. I have a script that holds the player to a platform, and this works fine too. But when I parent my platform that holds my player to an object with the moving platform script, the player's movement is jerky and uneven. Here are the scripts I'm using using System.Collections using System.Collections.Generic using UnityEngine public class MovingMultipalPoint MonoBehaviour public Vector3 pointB public Vector3 pointC public float Second 5.0f public float Speed 3.0f public float HoldSecond 5.0f IEnumerator Start() Vector3 pointA transform.position while (true) yield return new WaitForSeconds(Second) yield return StartCoroutine(MoveObject(transform, pointA, pointB, Speed)) yield return new WaitForSeconds(Second) yield return StartCoroutine(MoveObject(transform, pointB, pointC, Speed)) yield return new WaitForSeconds(Second) yield return StartCoroutine(MoveObject(transform, pointC, pointB, Speed)) yield return new WaitForSeconds(Second) yield return StartCoroutine(MoveObject(transform, pointB, pointA, Speed)) IEnumerator MoveObject(Transform thisTransform, Vector3 startPos, Vector3 endPos, float time) float i 0.0f float rate 1.0f time while (i lt 1.0f) i Time.deltaTime rate newRotation Quaternion.Euler(0, 90, 0) transform.rotation Quaternion.Slerp(transform.rotation, newRotation, 20 Time.deltaTime) thisTransform.position Vector3.Lerp(startPos, endPos, i) yield return null This script holds the player to the platform. using System.Collections using System.Collections.Generic using UnityEngine public class HoldPlayer MonoBehaviour private GameObject target null private Vector3 offset void Start() target null void OnTriggerStay(Collider col) target col.gameObject offset target.transform.position transform.position void OnTriggerExit(Collider col) target null void LateUpdate() if (target ! null) target.transform.position transform.position offset (1st Image) Here is how the moving platform is configured in the Inspector (2nd Image) And the holding script Also here recorded video of issue Any ideas how I can keep the movement smooth in this case? |
0 | Load single texture atlas for multiple sprite Recently, I am developing sudoku game. For this, I have created multiple grid 9x9,12x12 and 15x15. For this numbers are repeated so multiple sprite renderer are created and it load same number texture multiple time. So I want single number loaded single time only no repetition texture occur in graphical memory. Because of this problem I am facing following problem that I already posted. Android Device Screen Flicker I want suggestions to overcome this problem from your side. |
0 | Turning a 2D character to face left or right So far I know of the following ways to turn a 2D character to face the other direction (in my case the char can only walk left or right) Mirror the right walk animation and use that as a separate state in the animation controller. Simply set a 180 rotation on the game object that hold all of my characters parts when he turns the other way. Create a transition animation by blending (I don't know if it's called exactly like this) the left oriented sprite and the right one. Orient the sprite based on its movement direction using this code void OrientChar() Vector3 moveDirection gameObject.transform.position origPos if(moveDirection ! Vector3.zero) float angle Mathf.Atan2(moveDirection.y, moveDirection.x) Mathf.Rad2Deg gameObject.transform.rotation Quaternion.AngleAxis(angle, Vector3.forward) 1 and 2 will create a rather abrupt change and might not look smooth. How do I make them or is it possible to make them smooth? For number 3 I have a very basic idea on how to do it. Can I do it directly Unity? |
0 | How can I programmatically change a sprite's pivot without it affecting a game objects current position and rotation? Because of the complexity of positions, I am using the centre pivot for my game objects sprite. Can I possibly change the pivot without it affecting the game objects current position and rotation? or in other words, can I change the pivot while the sprite remains unchanged visibly? I would preferably like to do this using c script. |
0 | How to find the participation id corresponding to a sender id I am creating a real time multiplayer game in unity 3d using Google Play Game Services. In my function where I deal with the positioning of players based on information that is sent from other players, I get a sender id. The sender id is a long string of characters that does not match any participation ids. My participation ids are just strings such as "Player 1234." I keep the participation ids in an array so I can reference them and compare them to the sender of the information that I am receiving so I know which player it is from. If the sender id and participation id are two different things, how do I make the connection between the two? Here is a link to the tutorial I have been following for Google play services in unity https www.raywenderlich.com 87042 creating cross platform multi player game unity part 2 |
0 | Fragment shader coordinates Displacing pixels and texCoord problems I'm trying to create a shader that creates a displacement on an object, slicing horizontally the sprite. These is an example of the atlas I'm using and the effect I'm trying to achieve I tried to achieve this creating a fragment shader, that would read the Y coordinate of the texcoord, and depending on the height, displace it horizontally. But I found two main problems 1) If my atlas had more rows of sprites, I can't really tell at what height I'm drawing the sprite in the fragment shader. Since values of texcoord go from 0 to 1 relative to the atlas being use, the more rows I have, the smaller values should I choose to create the horizontal cut. Is there any way to know the position inside the drawn? 2) The problem is similar to the previous point. When displacing the pixels horizontally, if the displacement is too big, I end up sampling the sprite next to the one being rendered. The idea is for it to loop back the the begining of the sprite. If I had the width of the sprite, I could tell how to do so, but using texcoord alone is just not posible. How can I do this? |
0 | Why can't I use the operator ' ' with Vector3s? I am trying to get a rectangle to move between two positions which I refer to as positionA and positionB. Both are of type Vector3. The rectangle moves just fine. However, when it reaches positionB it does not move in the opposite direction, like it should. I went back into the code to take a look. I came to the conclusion that as the object moved, the if statements in the code missed the frame in which the rects position was equal to positionB. I decided to modify the code to reverse direction if the rects position is greater than or equal to positionB. My code is not too long, so I will display it below using UnityEngine using System.Collections public class Rectangle MonoBehaviour private Vector3 positionA new Vector3( 0.97f, 4.28f) Start position private Vector3 positionB new Vector3(11.87f, 4.28f) End position private Transform rect tfm private bool atPosA false, atPosB false public Vector2 speed new Vector2(1f, 0f) private void Start() rect tfm gameObject.GetComponent lt Transform gt () rect tfm.position positionA atPosA true private void Update() NOTE Infinite loops can cause Unity to crash Move() private void Move() if ( atPosA) rect tfm.Translate(speed Time.deltaTime) if ( rect tfm.position positionB) atPosA false atPosB true if ( atPosB) rect tfm.Translate( speed Time.deltaTime) if ( rect tfm.position positionA) atPosA true atPosB false When I changed it, however, it warned me of the following error message Operator cannot be applied to operands of type Vector3 and Vector3. This confuses me for two reasons first, both values are of the same data type. Second, using the comparison operator( ) on the two values works without error. Why can't I use the operator gt with Vector3s? |
0 | How to tilt an object(2D) after collision and the rotate continuously I am having trouble rotating and object after collision. The object only transforms to the given angle of rotation once and stops. I would like to achieve in a way that after it has collided with the player object it rotates continuously till its killed after exiting the screen. The OnCollisionEnter2D(Collision2D collision) can't achieve this. How can I achieve it using the FixedUpdate function? Here is the code namespace Assets.scripts public class Barmovementscript MonoBehaviour public float Tilt private void FixedUpdate() upon collision the object rotates in a clockwise direction. void OnCollisionEnter2D(Collision2D collision) if (collision.collider.tag "Player") Tilt Time.deltaTime 10 gameObject.transform.rotation Quaternion.Euler(0, 0, Tilt) |
0 | Animation works, but Unity doesn't realize it I have an animation which plays once, and it played once just fine. I want to Invoke a method as soon as the animation finishes. I have been researching and experimenting for over an hour now, but without the result I want. I try to get the animation from the Animator, but Unity says my animation is not attached. The thing is, I don't care if it's attached...I just want to know how long it is, not actually do anything with it. How can I achieve this? Here is the code which results in the error CODE using UnityEngine using System.Collections RequireComponent(typeof(PolygonCollider2D)) RequireComponent(typeof(Animator)) public class Construction MonoBehaviour Use this for initialization void Start() Invoke("EnableObstacleState", GetComponent lt Animator gt ().animation.clip.length) private void EnableObstacleState() GetComponent lt PolygonCollider2D gt ().enabled true ERROR MissingComponentException There is no 'Animation' attached to the "Barricade(Clone)" game object, but a script is trying to access it. You probably need to add a Animation to the game object "Barricade(Clone)". Or your script needs to check if the component is attached before using it. Construction.Start () (at Assets Scripts Construction.cs 11) |
0 | How to Create a Blast of Liquid in Unity I am making a small cartoon ish fighting game, and one of the weapons is a Hot Coffee Sprayer, which is a shotgun style weapon. How do I create a thick blast of dark liquid to come from it, with a solid appearance like the repulsion gel in Portal 2? If its too complex, just tell me how make the gun launch a handful individual drops at once rather than a horizontal wall of coffee. I am not amazing in Unity or C but I learn easily and I understand the fundamentals of programming very well. I'm skilled in Python. |
0 | Random.range giving me the same value at the same time I created a random direction in x and y axis at where to move, then my problem is when I tried to randomize it sometimes I get the same value at the same time on both x and y axis. How do I not let this happen, I only want one axis to have a value, not both? ERROR HOW I WANT IT TO HAPPEN CODE public Vector2 randomDirection void Awake() void Update() randomDirection new Vector2(Random.Range( 1, 2), Random.Range( 1, 2)) |
0 | Help with modifying a geometry grass shader to allow removing areas? So I have this geometry grass shader from a roystan tutorial I followed but it applies the grass effect to the entire mesh at once. I need to find a way to only apply grass to set areas much like how the unity painting vegetation tools work. I had an idea of using a quot guiding quot texture that the shader would follow which would only apply grass onto set areas on the texture e.g areas that are green but I'm not sure how to implement it. I would appreciate any advice! |
0 | Scene dark when perspective camera is far from scenery I can't find anything about this subject in the docs or forums to know if this is normal behavior There seems to be a direct correlation between how close to the scenery my camera gets and how brightly lit the scene is. My camera is able to move up to 200 units from Vector3.zero. Here are two shots of the same piece of scenery one close up, one far away The camera is set to perspective, using deferred rendering. Things I've tried Turning off post processing Using auto expose in post processing Changing to orthographic (removes the issue, scene is uniformly bright at any distance) Changing the FOV Changing global lighting to use color rather than skybox Putting some lights at altitude This may be normal behavior amp I just havent noticed before. Can anyone confirm? Is there some way to prevent this happening? I don't want to use an orthographic camera but I do want the scene to be evenly bright at any distance from the camera. |
0 | Function Not Storing New Value of Variables? I'm currently building a small scope RPG and running into an issue with modifying variables. My goal is to alter my character's stats when I run a procedure to change their equipment. My code is as follows public class Player MonoBehaviour Base stat variables public static int PAtk 12 public static int PDef 6 Battle exclusive stats. Will have equipment added onto them. public static int Attack PAtk public static int Defense PDef Equipment variables. public string weapon public string armor private void Awake() Get equipment EquipWeapon( quot Bronze Sword quot ) EquipArmor( quot Bronze Armor quot ) void EquipWeapon(string WeaponName) weapon WeaponName EquipmentManager.GetComponent lt Equipment gt ().EquipStatIncrease(PAtk, Attack, PDef, Defense, WeaponName) void EquipArmor(string ArmorName) armor ArmorName EquipmentManager.GetComponent lt Equipment gt ().EquipStatIncrease(PAtk, Attack, PDef, Defense, ArmorName) public class Equipment MonoBehaviour Create dictionary to give each weapon a key ID. This will be used for calling items in another array. Dictionary lt string, int gt WeaponDictionary new Dictionary lt string, int gt () Create weapon array for stats. public int , WeaponStats Start is called before the first frame update void Awake() Declare weapon IDs WeaponDictionary.Add( quot Bronze Sword quot , 0) WeaponDictionary.Add( quot Bronze Armor quot , 1) Declare stat array Table ID, Atk, Def WeaponStats new int , 0,4,0 , 1,0,4 public void EquipStatIncrease(int BaseAtk, int BattleAtk, int BaseDef, int BattleDef, string Equipment) BattleAtk BaseAtk WeaponStats WeaponDictionary Equipment , 1 Debug.Log(BattleAtk quot Battle Power quot ) BattleDef BaseDef WeaponStats WeaponDictionary Equipment , 2 Debug.Log(BattleDef quot Battle Defense quot ) The general gist of it is once EquipWeapon or EquipArmor is ran, the equipment variables in the Player class will be updated. Afterwards, another function in the Equipment class will be ran with variables from the Player class passed over, in order to be modified by the WeaponStats array. The Debug logs in EquipStatIncrease show me that I am getting the desired results. However, the Attack parameter that is being placed into the function is not being permanently modified. During the first execution of the EquipStatIncrease method, I will get a result of 16 BattleAtk and 6 BattleDef, due to the weapon being equipped. However, once it's run a second time to equip the armor, I'm shown a result of 12 BattleAtk and 10 BattleDef, even though BattleAtk should have stayed at 16. This leads me to believe that the variables I'm trying to transform are not being modified, and I'm not sure what to do about this. In the EquipStatIncrease parameters, BattleAtk gives the message Parameter 'BattleAtk' can be removed if it is not part of a shipped public API its initial value is never used However, I don't know what action to take to resolve this. I'm aware of being able to use an int function instead of void, but unless I'm missing something, that only works if I'm trying to change one variable. If I want to have an equipment object that affects 2 different stats at once(ex. a weapon that increases BattleAtk and BattleDef), then I don't see how an int function would work. |
0 | How do I get parabolic movement in Unity using Rigidbody2d? EDIT It was the Animator after all. Apply Root Motion basically nullifies any physics based work. I "know" this answer but I can't figure out what can possibly be wrong. My code is in FixedUpdate(). My Rigidbody2D has a Gravity Scale of 4 and a Mass of 1. For whatever reason a Gravity Scale of 1 just isn't strong enough to keep it from floating away. In the pictures below the little cubes should be marking each frame. Using the below code I get a jagged leap movement. The object shoots upwards and falls like a feather. if(Game.inputManager.GetKey("Jump").KeyPressed()) yForce 1000f this.rigidbody2D.AddForce(Vector2.up yForce) And using another suggestion I distribute the force over a second of time. if(Game.inputManager.GetKey("Jump").KeyPressed()) addForceTimer 1 yForce 1000f addForceTimer Time.deltaTime if(addForceTimer gt 0) this.rigidbody2D.AddForce(Vector2.up yForce Time.deltaTime 4) And I get a more desirable but still just as wrong movement where there is no hang at the top of the jump. From what I thought I knew neither of these should be happening at all. The object shouldn't be falling at a constant speed like it is. Does anybody have any suggestions? The character is animated if that can possibly have some sort of effect but I don't imagine it would. |
0 | How do I fix missing anti aliasing in the Unity scene view and game? Both the editor and the game seem to lack anti aliasing even though quality is set to Ultra. I chose the quot 3D quot project template when I created the project, so I am using the build in render pipeline. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.