Unity3d zooming with orthogonal camera like in Google maps I am implementing 2d orthogonal zoom. As far as I know in Unity3d there are no translations like in OpenGL. Taking this into consideration, I work with camera size camera position (center) real world mouse position I have no issues implementing simple zoom in zoom out operations, combined with camera position changes ( drag'n'drop ) But I have some issues calculating camera zoom shift in this case camera size (4,4) camera position (0,0) real world mouse position (1,0) A double zoom in (2x) is applied, as a result camera size (2,2) camera position (0.5,0) real world mouse position (1,0) User shifts real mouse position to (1.5,0) and applies a double zoom out ( 0.5 ). In this case camera size is again (4,4) camera position ??????? real world mouse position (1.5,0) What should be the camera shift so the mouse doesn't visually move ? What is the formula for calculation in this case ? Thank you in advance. P.S. Any suggestion regarding current method of handling zoom are welcome Update So I resolved this issue with Blue's help. The basic idea about shifting is right. The main reason it didn't work was incorrect zoom factor. Example Initial camera size is 5. User zooms in by 1, camera size is now 4 ( it displays less content on the same 'screen'). User changes mouse position and zooms out by 1. Camera size is 5 again, but the amount of zoom is actually different initially the change was 20 ( 1 5 ) in the second time, the change was 25 ( 1 4 ) My fault was that, when zooming out, I tried to restore position by 20 , not 25 .


How to export an animation from blender to Ethan (third person character) in unity 5 I've made a human animation in blender with the intention of exporting it into unity to add to the animations of the third person character 'Ethan'. Does any one know how I can export the animation into unity for the third person character and make a trigger for the animation?


Objects don't instantiate at mouse position I'm trying to get the player to shoot a projectile at the mouse position, however the projectile is shot in weird directions (http gfycat.com BothFluidHoneyeater). Here is relevant part of my code var shotSpeed 1000 var projectile Rigidbody function Update () var clone Rigidbody if(Input.GetKeyDown(KeyCode.Mouse0)) clone Instantiate(projectile, transform.position, transform.rotation) clone.rigidbody.AddForce(Vector3.forward shotSpeed) What am I doing wrong?


How to reproduce this (parallax?) effect? I'm wondering how to imitate the camera movement like in the gif below. It s from a Android game. This game for example (via GIPHY) Actually, I am not sure if this can be called a parallax effect, but it is the only word I can think of. My code until now using System.Collections using System.Collections.Generic using UnityEngine public class RotateAroundTarget MonoBehaviour public Transform target The object to follow public Transform background public Transform foreground public float speedMod 20.0f Camera speed public float topMargin 0.2f Top rotation margin The position of the target private Vector3 point Point if the camera is rotating to the left private bool toLeft false Use this for initialization void Start () point target.transform.position transform.LookAt (point) Update is called once per frame void Update () The camera is moving to the right until it reaches the top margin, then it changes it movement direction if (!toLeft) transform.RotateAround (point, new Vector3 (0f, 1f, 0f), Time.deltaTime speedMod) rotateBackground (1) rotateForeground ( 1) Debug.Log ("Izquierda") if (transform.rotation.y gt topMargin) toLeft true else transform.RotateAround (point, new Vector3 (0f, 1f, 0f), Time.deltaTime speedMod) rotateBackground ( 1) rotateForeground (1) Debug.Log ("Derecha") if (transform.rotation.y lt topMargin) toLeft false Direction 1 (left) 1 (right) public void rotateBackground(float direction) background.transform.Rotate (new Vector3(0, Time.deltaTime (speedMod 2) direction, 0)) public void rotateForeground(float direction) foreground.transform.Rotate (new Vector3(0, Time.deltaTime (speedMod 2) direction, 0)) But what I obtain in Unity Editor is this Result in Unity Editor (via GIPHY) Any suggestion on how to get this? Any help would be appreciated.


Imported Blender .fbx model appears transparent I exported a model that i made in blender to a .fbx file. I imported it to Unity and, as you can see in the image, one arm of my character appears transparent. I already have the normals pointing in the right direction, so i can't see what's causing this. I even tried to create a new arm from the other one, but the problem persisted. What is causing this?


How can I implement an infinite parallax background like in Slither.io? I am trying to replicate the endless scrolling of slither.io but, I can't figure out how to implement it. Since the players can move to any direction and the background needs to be available during player's displacement. All the parallax background scrolling tutorials show only moving on one axis, either x or y, but my case it could be to any possible direction like an arrow compass. Can some one point me in the right direction about how I can implement this effect? EDIT User can move to any possible direction like an arrow in a compass. Custom Camera Controller that follows the player public class CameraController MonoBehaviour public GameObject Player private Vector3 offset Use this for initialization void Start () offset transform.position Player.transform.position Update is called once per frame void LateUpdate () transform.position Player.transform.position offset


Water drops on camera How can I create water drops on camera something like we see in Ripitude GP, I tried using Unity's default GlassStainedBumpDistort shader though its performance heavy on mobile plus it do not let animate water drops.


How to align a hint arrow to point along a path? I am using CalculatePath and trying to use path.corners in order to give user a hint for path, that where should he lead next. I am using first two instances of Vector3 of path.corners. Lets call those vectors A and B. Let me illustrate this using figure. Now I want to position my arrow above the midpoint of the line from B to A, and orient it so it's pointing along the direction from B to A. When I orient the arrow with LookAt(), it doesn't point in the same direction as the path. Here is an image of my arrow prefab, showing how it's oriented


Hiding UIs behind a custom image shader Is there a way to hide UIs such as text, images etc. behind another transparent image? The problem is that I am using the latest Unity version and these custom shaders have no effect on hiding the UI shaders. The two custom shaders I have applied for testing are Shader quot Custom DepthReserve quot Properties SubShader Tags quot RenderType quot quot Opaque quot quot Queue quot quot Geometry 1 quot LOD 100 Blend Zero One Pass Shader quot Custom InvisibleMask quot SubShader draw after all opaque objects (queue 2001) Tags quot Queue quot quot Geometry 1 quot Pass Blend Zero One keep the image behind it So is there a way to use a transparent image to hide text, images and even gameobjects?


What is an equivalent of Swift's UIScreen.mainScreen().bounds in Unity 2d? Basically, I am from a Swift SpriteKit background where UIScreen.mainScreen().bounds is a CGRect which represents the screen and can be manipulated in various ways like getting the middle of the screen by using var screenCenter CGPointMake(UIScreen.mainScreen().bounds.width 2, UIScreen.mainScreen().bounds.height 2) What is an equivalent of UIScreen.mainScreen().bounds in Unity (C Scripting) that can manipulated to get various positions in a similar manner?


Trying to set up a simple swapping system to swap two game pieces using a button press I am trying to set up a system that will move two objects. This is a puzzle game with a cursor to visualize where the player is. I need to get the position of the cursor's left and right half, send that to a function that will then switch the two blocks when a key is pressed. I have code that will move the cursor around but cannot figure out how to swap two blocks based on the position of the cursor. I do not know if the code that is currently attached to the cursor will be of any help, but I can provide if necessary. I am more or less looking for a general solution that I could apply to swapping two blocks. I do not know if I need to be sending the positions of the cursor to the swap function in order to swap. How would I connect this to the tiles themselves? The code below is located in the board classv2 class. I am not very good with Unity as of yet. Any additional help would be appreciated. void Update() if (Input.GetButtonUp( quot Swap quot )) swapTiles(cursorLeft.transform.position.x, cursorRight.transform.position.x) void swapTiles(float x1, float x2) Game pieces are created and have an x and y number associated with a game board I created. The Game pieces have a move routine. I can't seem to get the pieces to actually swap. public void Move(int destX, int destY, float timeToMove) if (!m isMoving) StartCoroutine(MoveRoutine(new Vector3(destX, destY, 0), timeToMove)) Moves the piece. IEnumerator MoveRoutine(Vector3 destination, float timeToMove) Vector3 startPosition transform.position bool reachedDestination false float elapsedTime 0f m isMoving true while (!reachedDestination) if we are close enough to destination if (Vector3.Distance(transform.position, destination) lt 0.01f) reachedDestination true if(m board ! null) m board.PlaceGamePiece(this, (int)destination.x, (int)destination.y) break track the total running time elapsedTime Time.deltaTime calculate the lerp value float t Mathf.Clamp(elapsedTime timeToMove,0f,1f) switch (interpolation) case InterpType.Linear break case InterpType.EaseOut Mathf.Sin(t Mathf.PI 0.5f) break case InterpType.EaseIn t 1 Mathf.Cos(t Mathf.PI 0.5f) break case InterpType.SmoothStep t t t (3 2 t) break case InterpType.SmootherStep t t t t (t (t 6 15) 10) break move the game piece transform.position Vector3.Lerp(startPosition, destination, t) wait until next frame yield return null m isMoving false


Masking cameras for Voronoi splitscreen I would like to mask a camera to only render to a certain (non square) region of the screen, to be used as an overlay, for splitscreen, or any other application. The goal is obviously to prevent any unnecessary rendering from that camera, so I specified performance, but I'm also happy to hear the easiest to implement option as well. What I'm considering so far Stencil shader on a mesh in front of the camera but my understanding is that doing so would require modifying all shaders on world objects, which isn't ideal. Is there an easier way I'm missing? Transparent mesh with a cutout I could cut out a hole in a mesh and the solid part would block rendering of objects behind it, but I'm not sure how to make that part be transparent so other things can render I'm using Unity 2019 LTS and the built in render pipeline I feel like there must be a simple answer I'm missing but maybe I'm wrong?


When I use rigidbody.move rotation, my player sinks I am trying to implement a simple movement on an object and when I use movePosition from rigid body, the player starts to sink How can I resolve this issue? Below is my code. void Update() Movement() MouseLook() void MouseLook() get X movement of mouse and save as float y get Y movement of mouse and save as float x float xMove Input.GetAxis( quot Mouse Y quot ) mouseSensetivity Time.deltaTime float yMove Input.GetAxis( quot Mouse X quot ) mouseSensetivity Time.deltaTime make vector of that movements Vector3 xLook new Vector3( xMove, 0f, 0f) Vector3 yLook new Vector3(0f, yMove, 0f) apply Y vector to body and rotate it entirely rigidBody.MoveRotation( rigidBody.rotation Quaternion.Euler(yLook)) apply X vector on camera to rotate it. camera.transform.Rotate( xLook) void Movement() Vector3 move new Vector3(Input.GetAxis( quot Horizontal quot ), 0, Input.GetAxis( quot Vertical quot )) charController.Move(move Time.deltaTime WalkSpeed) register x axis movement register y axis movement float xWalk Input.GetAxisRaw( quot Horizontal quot ) float zWalk Input.GetAxisRaw( quot Vertical quot ) Make vectors Vector3 WalkSum (transform.right xWalk transform.forward zWalk).normalized feed this to Move position of rigid body if ( WalkSum ! Vector3.zero) rigidBody.velocity transform.forward WalkSum rigidBody.AddForce( WalkSum WalkSpeed) rigidBody.MovePosition( WalkSum) charController.Move( WalkSum WalkSpeed Time.deltaTime)


walking up down slowed by z coordinate layering I am making a 2D topdown sprite game. I got myself a controller script that handles input and makes the character move attack etc. I eventually added objects you could walk in front of or behind, like trees, houses, and flowers, so naturally I needed a script to handle that. This answer gave me two solutions one using sprite renderer sorting layers and the other by altering the z coordinate of objects. The former solution worked but was finicky, and the last one worked just fine. However, now I am noticing a bug. I have two scenes and if you die, you respawn to the first scene. The bug only occurs if I die and respawn or if I go all the way back to scene 1 e.g. scene 1 gt scene 2 gt scene 1 (I have pathways that lead between scenes with triggers). The bug is that walking up or down is significantly slower than walking right or left and if I uncheck my Z Layer script on the player, the speed goes back to match the left right movement. This bug doesn't happen in any other scenario, if I start the game in either scene it is fine, but whenever I respawn or go all the way back to scene 1, the up down movement is slowed. It seems to me the extra work of changing the Z Coordinate is causing the slowness but it is odd that it only occurs on looping back to scene 1, or respawning (which puts you back to scene 1, as well). I am not creating additional players each time he dies, or saving any data between loads yet. Is there any idea on what could fix this or what is causing this without having to go deep into all my scripts? EDIT Here is my Z Layer script. It is attached to my Player. using System.Collections using System.Collections.Generic using UnityEngine public class ZLayer MonoBehaviour sets the Z coordinate of a sprite to its Y. if the camera settings are reversed, youll need to multiply by 1, float initial Vector3 temp void Awake () SetPosition() note since Update is called every frame, you must disable the scripts that on static objects e.g. trees, walls etc, (disabled scripts dont get their updates called for moving objects keep it ticked. (note this is why we used start and not awake too. void Update() SetPosition () void SetPosition () temp transform.position temp.z transform.position.y transform.position temp For reference, here is the code that moves my player void Move(float h, float v) movement.Set (h, v) normalize movement vector and make it proportional to speed per second movement movement.normalized speed Time.deltaTime move the player to the current position temp new Vector2 (transform.position.x, transform.position.y) temp2 temp movement playerRigid.MovePosition (temp2) Move(h,v) is called in Update() if a boolean walking is true, and h and v are the horizontal and vertical inputs obtained from Input.GetAxisRaw. A key part I want to reiterate is that it works fine on start, it only slows up down movement when I respawn or get back to scene 1 from scene 2. Doing one scene transition seems to work fine, but 2 gt 1 gt 2 or 1 gt 2 gt 1 bugs out.


According to Collision Change Rotation of Car Basically I want to give rotation to player car as per collision occur with wall. Following image gives you over all idea. I have following code that giving me correct collision reflection but its in position form not for rotation. void OnCollisionEnter2D (Collision2D other) ContactPoint2D contact other.contacts 0 Vector3 reflectedVelocity Vector3.Reflect (direction, contact.normal) direction reflectedVelocity Quaternion reflectedRot Quaternion.FromToRotation (transform.up, contact.normal) transform.rotation reflectedRot What I have to do for getting correct collision rotation for car? As well smooth turn for car on same rotation so car start moving on that way. Please give me some help for this.


How can I prevent seams when attempting to create a skybox for Unity5? After following the documentation for how to create a skybox, seams are appearing around all sides of my 6 textures (sorry for faintness of image) There are no active lights in my scene. What am I doing wrong and how can I prevent this? Any skybox creation methodology suggestions would be much appreciated.


What is the package lock.json file for in Unity? My project contains this file Packages packages lock.json And I'm curious about what it's for. It has a bunch of json about my packages in it, but it's not clear to me what goes in the lock file vrs the normal packages file.


How to store variable inside an array unity? I was wondering how I can store these anims inside an array, because, the start function will be fired one time. I would like to be able to call these Animators more then one time. public Animator anim0 public Animator anim25 public Animator anim50 public Animator anim75 public Animator anim100 void Start () anim0 GameObject.FindGameObjectWithTag("Campfire0").GetComponent lt Animator gt () anim25 GameObject.FindGameObjectWithTag("Campfire25").GetComponent lt Animator gt () anim50 GameObject.FindGameObjectWithTag("Campfire50").GetComponent lt Animator gt () anim75 GameObject.FindGameObjectWithTag("Campfire75").GetComponent lt Animator gt () anim100 GameObject.FindGameObjectWithTag("Campfire100").GetComponent lt Animator gt ()


Capture High Resolution Screen Shot for Unity Game I'm working on a mobile game. We need some HD screen shot to use in our press kit. I'd like to know, how do we capture HD screen shot of games inside unity's editor. Resolution must support printing quality of banners that we would use to showcase our game in local game expo.


Dynamic Aspect Ratio in Unity (for Anti Aliasing) I am using HDRP with 1920x1080 resolution. The anti aliasing works very well if the screen resolution increases and it works really bad if the screen resolution is lower than 1920x1080. Why does this happen? Is there a way to overcome this?


(Unity 5) Force child object to be perpendicular to the ground? As i mentioned in the header, i want my MainCamera child object to stay perpendicular to the ground, any ideas?)


Issue Implementing Ads with Vungle I'm trying to implement ads on Unity for my program with Vungle, I followed the implementation guide at https support.vungle.com hc en us articles 360003455452 reference sample app 0 3 But the ads aren't displaying at all. I get a debug.log that seems to indicate the ad was called, but no ad displays, even if I build and run the program. I contacted support, but they haven't been super helpful. They told me to wait a little longer before calling the ad, I put it on a coroutine with a 10 second delay and still no ad. Here's my script for reference, using System.Collections using System.Collections.Generic using UnityEngine public class VungleAds MonoBehaviour string appID string iosAppID quot ios app id quot string androidAppID quot android app id quot string windowsAppID quot 5fbfc6bc1136b9069f63f0bf quot void Awake() appID windowsAppID Vungle.init(appID) private void Start() StartCoroutine(ShowBanner()) Vungle.loadBanner(appID, Vungle.VungleBannerSize.VungleAdSizeBanner, Vungle.VungleBannerPosition.BottomCenter) IEnumerator ShowBanner() yield return new WaitForSeconds(3) if (Vungle.isAdvertAvailable(appID)) Vungle.showBanner(appID) else print( quot No ad quot ) StartCoroutine(ShowBanner()) It's just printing quot No ad. quot repeatedly. Does anyone have any experience with Vungle ads? I have been trying to figure this out for like a week haha. Thanks


Can't open scripts in Unity 2019.2.11.f1 version I'm using Visual Studio 2017, Unity Hub to 2.1.3 and just created a project using Unity's 2019.2.11.f1 version. Once trying to open a script in Unity, it doesn't open and then I'm forced to use Task Manager to End Unity's task because can't even close it normally due to not being able to interact with the screen. No errors or warnings, VS doesn't open, can't interact with Unity anymore. This doesn't block me from working, it just isn't as convenient as before.


Why would a property be returning null? I'm working on learning how pass data from one script to the other in Unity and I'm getting a little confused. I have two scripts, PlayerData and CreateCharacter. PlayerData is used to pass persistent data from one scene to another, so it's not going to be attached to any GameObject or Transform. CreateCharacter, however, is attached to a button which gets the information from user input. Here are the two scripts PlayerData public class PlayerData private string playerName public string PlayerName get return playerName set playerName value CreateCharacter public class CreateCharacter MonoBehaviour public InputField playerName public PlayerData playerData new PlayerData() public void AddStats() public void SubtractStats() public void CreateCharacterOnClick() playerData.PlayerName playerName.text Debug.Log(playerData.PlayerName) What's happening is, when I click the button I'm getting a null reference error on playerData.PlayerName but if I just log playerData I actually get the object to return. What I'm trying to see is that the character name(playerName) is logged when the button is clicked. Can anyone explain to me what I'm doing wrong and how to fix it?


Loading a heavy scene behind some loading screen in unity Is there a way to load a heavy built scene behind a loading screen in unity to not make the game look like stuck loading the scene rather show the player some loading bar that would help the player think some background process is happening. any sites or vidoes that describe about this would be a great help! Thanks!


Render Texture shows opposite view of camera when rendered? I am using render texture (cube) to render what camera sees into it. However, the render texture shows me opposite side of cameras view (flipped) instead of what camera sees. Any solution for this? void Update() renderTexture.isPowerOfTwo true Graphics.SetRenderTarget(renderTexture, 0, CubemapFace.PositiveZ) renderTexture.dimension TextureDimension.Cube camera.RenderToCubemap(renderTexture, 63) What camera sees What Render Texture shows What happens when I rotate Render Texture manually by hand 180 degrees So, instead of rotating per hand, what I want is for the render texture to be rotated via code so that what is in camera view is shown exactly the same in render texture view.


Flipped vertical button element on Canvas not reacting I have a small refresh arrow circle that I wanted to use for an indicator in which direction the tile gets rotated on click. After I rotated it by 180 under the rect Transform rotation Y to spin the opposite direction, it does not react anymore for OnClick events. Probably since we are technically clicking on the backside of the image. The non rotated version works, changing the rotation from 180 to 0 works as well. Is there any way to get a flipped image working without duplicating the source image and flip it before assigning it to the button? The scene is a simple screen space camera, one canvas with 2 buttons (having the same image source), one button has 180 under Y Rotation and the default EventSystem.


Clamping the camera isn't so smooth when moving the camera around. Is there a way to make the clamping smoother? using System.Collections using System.Collections.Generic using UnityEngine using Cinemachine public class CamerasManager MonoBehaviour public CinemachineFreeLook playerCameraCloseLook public CinemachineFreeLook playerCameraGameplayLook public float timeBeforeSwitching public float clampMin public float clampMax public float pitch public float speed private float brainBlendTime Start is called before the first frame update void Start() brainBlendTime Camera.main.GetComponent lt CinemachineBrain gt ().m DefaultBlend.m Time StartCoroutine(SwitchCameras(timeBeforeSwitching)) Update is called once per frame void LateUpdate() if (playerCameraGameplayLook ! null) pitch speed Input.GetAxis( quot Mouse Y quot ) pitch Mathf.Clamp(pitch, clampMin, clampMax) playerCameraGameplayLook.GetRig(1).GetCinemachineComponent lt CinemachineComposer gt ().m TrackedObjectOffset.y pitch IEnumerator SwitchCameras(float TimeBeforeSwitching) yield return new WaitForSeconds(TimeBeforeSwitching) playerCameraCloseLook.enabled false playerCameraGameplayLook.enabled true PlayerLockManager.PlayerLockState(false) StartCoroutine(BlendTime()) IEnumerator BlendTime() yield return new WaitForSeconds(brainBlendTime) PlayerLockManager.PlayerLockState(true) I can look around up down left right using Cinemachine CinemachineFreeLook but when using the clamping in this script and then when moving the camera around with the mouse it looks like the camera is a bit stuttering jittering. Without the clamping, in the LateUpdate the camera will work fine but then I can't move the camera up down left right only to the left and right. The reason I'm trying to do the clamping on my own is that in the FreeLookCamera in the Axis Control gt Y Axis if I set the speed to 100 or 300 when I move the camera up and down it will also zoom in out on the player and I don't want that zooming but there is no option to remove disable the zooming.


How should I deal with different enemy types? I'm making simple space shooter game for Android in Unity. I want to have different types of enemies (different weapon, stats, movement schemes) and I'm not sure how to do it. I'm quite new to objective programming and I don't really know what classes should I create. I guess I could just make a prefab for every enemy since there won't be many types, but that is not what I'm looking for. I have some ideas First of all I'd write an BaseEnemy class and enemy type subclasses that inherit from it. My first idea is to create those without MonoBehaviour. Then I'd have to make an EnemyScript with MonoBehaviour that I'd add to enemy game object. It'd have a specific subclass object inside, which will set every variable. BaseEnemy would just have undeclared variables and in subclass I'd set particular values. But I'm not sure how to deal with different movement schemes then. I wouldn't be able to put move() function in subclass since it wouldn't have MonoBehaviour, so I'd have to find another way. I might put in EnemyScript every possible scheme and then use correct one depending on some type value, but it doesn't seem like a proper way, does it? The second idea is to just make a MonoBehaviour BaseEnemy class. Then while creating enemy game object I'd just add correct subclass script (aaand... I'm not sure how to do it ) Could you tell me which one is a better way? Maybe neither of those?


Unity Rotate Object Around Local X Axis , then Local Y Axis, then Local Z Axis (like a turtle) I am having trouble getting my unity gameobject to rotate in the manner I would like. I would like my gameobject to act kind of like a turtle from a drawing program, where I could input a Vector3 like (10, 25, 5) and then it would rotate around its x axis by 10 degrees. Then rotate around it's Y axis by 25 degrees, and then rotate around it's z axis by 5 degrees. Here's a picture example (rotations not exact) The problem is that the axes (the green, blue, and red gizmos you see when you have an object selected) change direction as the "turtle" goes through the Vector3. It seems like transform.Rotate(new Vector3(10,25, 5), Space.Self) should be what I'm looking for. But it doesn't give me the result I would like! It still seems to rotate around it's start up, right, and forward vectors. public Vector3 rotation Quaternion zero new Quaternion(0,0,0,1) void Update() transform.rotation zero transform.Rotate(rotation, Space.Self) I have also tried doing some things with Quaternions to get the desired result, but I can't figure out exactly what is need. If anyone has any advise it would be greatly appreciated!


GUI.Button inside GUI.Window not responding I am trying to do some GUI work with unity but am having some issues. I call a window with this code fortuneRect GUI.Window(0, fortuneRect, fortuneWindow, "Your future") and inside the window I have a button if(GUI.Button(new Rect(10, 10, 150, 20), "save fortune")) Debug.Log("save fortune button press") writeToFile("Button pressed!", "fortune.txt") Debug.Log("After save fortune button press") but the button doesn't fire any of its events on click. I tried commenting out the writeToFile but even with only Debugs in the body it doesn't fire.


How to test for BoxCollider2D intersection in Unity? I have a Player object with a BoxCollider2D component and a Ladder object also with a BoxCollider2D component. Each object has a script, and in each script, I set up references to the box colliders in the normal way. public BoxCollider2D box collider void Start () box collider GetComponent lt BoxCollider2D gt () My player script is called "PlayerController", so that's the class defined in the script. In my Ladder's script I have the following void Update () GameObject player GameObject.Find("Player") PlayerController player controller player.GetComponent lt PlayerController gt () if (player controller.box collider.bounds.Intersects (box collider.bounds)) Debug.Log ("collision") else Debug.Log ("no collision") This script invariably returns "no collision" and I'm not sure why. Any ideas?


Wrong Second position of LineRenderer I'm drawing some kind of bullet trace effect with LineRenderer in my 2D Game Project with Unity. At some position, setting position of LineRender result weird In the above screenshot, you can see two types of lines are exists. Pure red lines are result of Debug.DrawRay which is only renders in Scene view, not actual game play, and another lines which has yellow to red gradient are actual line renders I want to draw. I used exactly same code for rendering both two, Debug.DrawRay() and LineRenderer.SetPosition(), but as you can see only DrawRay works as I expected and LineRenderers are cutted and pointing wrong direction. Here's the code I'm trying void Fire() Vector3 shootDirection m ShootPoint.right RaycastHit2D hit Physics2D.Raycast(m ShootPoint.position, shootDirection, m Range) Debug.DrawRay(m ShootPoint.position, shootDirection.normalized m Range, Color.red, 20) On Hit, set end position where it hits if (hit) CreateBulletTrace(m ShootPoint.position, hit.point) Otherwise, render straight until it's range else CreateBulletTrace(m ShootPoint.position, shootDirection.normalized m Range) void CreateBulletTrace(Vector3 startPos, Vector3 endPos) GameObject bulletTraceObj Instantiate(m BulletTraceLineRendererPrefab) LineRenderer bulletTraceLineRenderer bulletTraceObj.GetComponent lt LineRenderer gt () bulletTraceLineRenderer.useWorldSpace true bulletTraceLineRenderer.SetPosition(0, startPos) bulletTraceLineRenderer.SetPosition(1, endPos) Destroy(bulletTraceObj, 0.1f) Note that LineRenderer checked use world space to true. What am I missing? Using Unity 2019.1.0f2.


Why is my TextMesh always on top? I have a 2 d game that I am making, using 3 d assets, including TextMeshes for text. I have decided that in some instances, I would like to have the TextMesh appear behind objects in the foreground. The below is one such example. It seems that the TextMesh is always in front. I have tried a number of things to get the text between the map and object layers, with no success. These include Moving the text between the map and object. Changing the SortingLayers and SortingOrder. The map, objects, and labels are on 3 different layers, with the Objects being the highest layer, the map the lowest, and default and label in between. Using a perspective camera, not orthographic. Any ideas as to what else could be going on? Thanks! How can I make the TextMesh appear that isn't on the top layer? Thanks!


How to make Unity game moddable with scripting in a friendly way? I am building a game in Unity using C and visual studio. I want to make it possible for users to write code in some scripting (for modding purposes) without necessarily opening the source. What are my best options? I'd prefer well supported and battle tested options that integrate well with Unity and visual studio, but I am willing to do a fair amount of work myself as long as it makes scripting as seamless as possible for future modders.


Calculating the bounding box of a game object based on its children 2D game with Unity. Have a parent game object, with several children objects scattered all over the scene. I want to calculate the bounding rectangle of the parent game object. Let the black dots be the children objects. The red rectangle is the bounding box. I am not really interested in the position I only want the dimensions of such box. Of course, the bounding box should also consider the bounding boxes of the children... and so on. How can I achieve this? I heard that Renderer has a bounds property... but my parent object doesn't have a renderer. And when I put one, the value is 0 anyway.


Button not clickable if it's under a Content Size Fitter Horizontal Layout Group in Unity? I'd like to make a Tooltip System Tutorial System. I'm using the Content Size Fitter and Horizontal Layout Group components to have a dynamic text bubble.. Also I'd like to attach a button to it, so when the tooltip appears, the game pauses, and then when the player clicks the button, it closes the tutorial text, resuming the flow of the game. But for some reason the click doesn't reach the component. Not even the animation happen, like something is blocking my button from being clicked. Hierarchy uiTutorialText Has a CanvasGroup to fade the whole structure. Interactable true, BlocksRaycast false TutorialText Has an Image (background) RaycastTarget false Has a Content Size Fitter and a Horizontal Layout Group And Text and Button are just simple plain Text and Button objects, and the Button's Interactable is true. I also tried making the Button a child of Text, and then translating it sideways, so the button doesn't share screen space with the tooltip. But it's not clickable this way as well. As soon as I move the Button out of the hierarchy, like directly under the canvas, it works.


Unity Grid Shader line Color First of all I'm sorry if my question is a odd thing to ask, but i'm new to Shader things and don't know how to handle this stuffs. I have a shader that draws grid on a ground plane and it works just fine. But i wanna do one thing more. Currently the color of the grid lines are all in same color. I want to set the main grid line's color differently. for example, like this one and this is what i have now for example, every 4x4 or 2x2 the line color should be something like red blue etc. I'm adding my shader's code below. plz somebody help me figure this out. Shader quot Unlit Grid quot Properties GridColour( quot Grid Colour quot , color) (1, 1, 1, 1) BaseColour( quot Base Colour quot , color) (1, 1, 1, 0) GridSpacing( quot Grid Spacing quot , float) 0.1 LineThickness( quot Line Thickness quot , float) 1 SubShader Tags quot RenderType quot quot Transparent quot quot Queue quot quot Transparent quot LOD 100 Blend SrcAlpha OneMinusSrcAlpha ZWrite Off Pass CGPROGRAM pragma vertex vert pragma fragment frag include quot UnityCG.cginc quot struct appdata float4 vertex POSITION struct v2f float2 uv TEXCOORD0 float4 vertex SV POSITION fixed4 GridColour fixed4 BaseColour float GridSpacing float LineThickness v2f vert(appdata v) v2f o o.vertex UnityObjectToClipPos(v.vertex) o.uv mul(unity ObjectToWorld, v.vertex).xz GridSpacing return o fixed4 frag(v2f i) SV Target float2 wrapped frac(i.uv) 0.5f float2 range abs(wrapped) float2 speeds Euclidean norm gives slightly more even thickness on diagonals float4 deltas float4(ddx(i.uv), ddy(i.uv)) speeds sqrt(float2( dot(deltas.xz, deltas.xz), dot(deltas.yw, deltas.yw) )) Cheaper Manhattan norm in fwidth slightly exaggerates thickness of diagonals speeds fwidth(i.uv) float2 pixelRange range speeds float lineWeight saturate(min(pixelRange.x, pixelRange.y) LineThickness) return lerp( GridColour, BaseColour, lineWeight) ENDCG


How to stop switching between paths to a moving target? I've noticed after implementing A pathfinding into my game, that there is exploitable unrealistic behavior that goes on when the player moves between two nodes that alter the path of the AI trying to reach them. I have made a few images to demonstrate this problem. This image above shows how the pathfinding in my game would behave if the player stood on the opposite side of a wall than my AI. If the player doesn't move it will take this single path to reach them. Assume that the red icon is the AI (enemy) and the blue icon is the target (player). Now, if the player in this image above moves along the white arrows up and down, and the AI is constantly finding the optimal path to the player (ignore the performance costs of doing that), then the AI will also get stuck moving up and down because the optimal path will constantly shift between going above the wall and going under the wall. Is there a way to modify a standard A implementation to remedy this? I will include my pathfinding code for clarity, but it's pretty much a standard top down implementation. The "Node" object is a node on my grid, and the grid is an object that holds a list of nodes, with a few functions to find a node from a world point. public class Pathfinding MonoBehaviour public Transform seeker, target AstarGrid grid void Awake() grid GetComponent lt AstarGrid gt () public List lt Node gt FindPath(Vector3 startPos, Vector3 targetPos) Node startNode grid.NodeFromWorldPoint(startPos) Node targetNode grid.NodeFromWorldPoint(targetPos) List lt Node gt openSet new List lt Node gt () HashSet lt Node gt closedSet new HashSet lt Node gt () openSet.Add(startNode) while (openSet.Count gt 0) Node node openSet 0 for (int i 1 i lt openSet.Count i ) if (openSet i .fCost lt node.fCost openSet i .fCost node.fCost) if (openSet i .hCost lt node.hCost) node openSet i openSet.Remove(node) closedSet.Add(node) if (node targetNode) return RetracePath(startNode, targetNode) foreach (Node neighbour in grid.GetNeighbours(node)) if (!neighbour.walkable closedSet.Contains(neighbour)) continue int newCostToNeighbour node.gCost GetDistance(node, neighbour) if (newCostToNeighbour lt neighbour.gCost !openSet.Contains(neighbour)) neighbour.gCost newCostToNeighbour neighbour.hCost GetDistance(neighbour, targetNode) neighbour.parent node if (!openSet.Contains(neighbour)) openSet.Add(neighbour) return null


How to fix stretched splash image in Unity? I'm trying to add my own splash on my Unity project. However, when I implement it, the splash is stretched vertically, real bad. Here is the screenshot While the original splash is I'm not altering the settings for the sprite that much How to fix that problem? I'm using a 1080x1080 PNG file for the splash and Unity 5.5.0f for building the application. Altering the resolution of the PNG results no luck. Am I missing something important here? EDIT Sorry for the late mention, but I've made the border on the sprite editor. Still no luck.


Blur just one object in Unity I've recently encountered a problem where I needed to blur an object that is inside another object. I've tried several methods to fix this but none of them works properly. In the screenshot below, renders have to happen in order so that the shape is preserved but the middle portion is blurred. My current setup is this 3 Cameras each rendering different objects (one object per camera), the white one below is actually a depth mask and only the camera that renders it is clearing the depth mask. The others aren't clearing anything. When I apply a blur mask on the camera that has the middle portion (Object in the blurmask layer), everything else gets blurred too (there's a background off screen which shouldn't get blurred, that's the reason for Vuforia tag). How do I solve this? Frankly, I'm absolutely stumped at this point and willing to try anything (comments are welcome too). This is what I have right now (The longer cylinder had a depth shader in its material which clears any 3D object parts behind it)


Could not establish connection with local server process when opening or making Unity project Whenever i try to either create or open a Unity project, I get faced with this error. Does Unity need a proxy server, because I dont have one. (If so, how do I get one?) And apparently I need to add some environment variables, (HTTP PROXY, HTTPS PROXY and UNITY NOPROXY localhost,127.0.0.1) what values do i add to these? Unity Package Manager Diagnostics (v0.1.5) Ran 7 checks 1 succeeded 6 failed UPM registry reachable (FAIL) Make an HTTP request to the UPM package registry Connection error. This could be because a proxy is misconfigured. Ping UPM registry (FAIL) Measure the latency of the UPM package registry API No successful pings could be made in 0.062 seconds (30 failed) Ping UPM download (FAIL) Measure the latency of the UPM package download endpoint No successful pings could be made in 0.039 seconds (30 failed) UPM registry download speed (FAIL) Test the Internet connection using the UPM package registry Connection error. This could be because a proxy is misconfigured. Speedtest.net (FAIL) Test the Internet connection using Speedtest.net Connection error. This could be because a proxy is misconfigured. HTTP proxy environment variables (PASS) Detect whether proxy related environment variables are set (HTTP PROXY, HTTPS PROXY, ALL PROXY, NO PROXY, UNITY PROXYSERVER, UNITY NOPROXY) Proxy support has been configured through the following environment variables HTTPS PROXY C Program Files Unity Hub Unity Hub.exe HTTP PROXY C Program Files Unity Hub Unity Hub.exe UNITY NOPROXY C Program Files Unity Hub Unity Hub.exe UPM health check (FAIL) Start the UPM process and call its health endpoint Server started but did not respond to health requests Error Invalid protocol c How do I fix this?


Unity 3D How to stop reset 2D sprite animation after releasing key? Im following a tutorial to create animations with a 2D sprite character. But i put in my own. Which has 8 animation positions. For some reason when my guy walks around,then stop, the walkings animation continues to play out then resets to idles. I need the animation to reset as soon as i release the key. Im using Animator if you are wondering. EDITED Original video with all the keys for each animations. Youtube video Second video with only 2 keys per animation, it was a test. Second Video Here Code Snipet! using UnityEngine using System.Collections public class PlayerMovement MonoBehaviour public float speed private Animator animator private Rigidbody2D rigidbody2D Use this for initialization void Start () animator GetComponent lt Animator gt () rigidbody2D GetComponent lt Rigidbody2D gt () Update is called once per frame void Update () CheckDirection() void CheckDirection() if (Input.GetKey (KeyCode.A)) WalkAnimation( 1,0,true) else if (Input.GetKey (KeyCode.D)) WalkAnimation(1,0,true) else if (Input.GetKey (KeyCode.W)) WalkAnimation(0,1,true) else if (Input.GetKey (KeyCode.S)) WalkAnimation(0, 1,true) else animator.SetBool("Walking", false) void FixedUpdate () Move() void Move() float dirX animator.GetFloat("VelX") float dirY animator.GetFloat("VelY") bool walking animator.GetBool("Walking") if (walking) rigidbody2D.velocity new Vector2(dirX,dirY) speed else rigidbody2D.velocity Vector2.zero void WalkAnimation (float x, float y, bool walking) animator.SetFloat("VelX", x) animator.SetFloat("VelY", y) animator.SetBool("Walking", walking)


How to make sure that a GameObject which gets a certain tag first, is allowed to do something first? I have created a trigger zone to make sure that only one gameobject should pass through the trigger zone at once. Other gameobjects approaching the trigger zone are made to stop just outside the trigger zone if there is already a gameobject in the trigger zone. I could get things working up until here. Now, I need to make sure that the gameobject that got to the trigger zone first and started to wait first is allowed to pass first while others wait and then the second gameobject is allowed to pass and so on. I am stuck at this part.


Insert 3d text to the front face of a cube GameObject I want to add a text to a cube in Unity. I have a cube which has a 3d text as a child. I am using the below UnityScript to write on the 3d text var countdown int 200 function Update() GetComponent(TextMesh).text countdown.ToString() I am trying to write show the text to the front face(or very close) of the cube but I am failing. EDIT My difficulty is to make the text appear in the front side face of the cube, like it is written on it. Attaching the text or the script to any object is not an issue My last failed try was to use the below lines var tm gameObject.AddComponent(TextMesh) tm.text countdown.ToString() Any ideas?


Why is my texture array getting only the last link index? Here's my code SerializeField GameObject uitex new GameObject 3 void GetTextureFromServer() string dealer img "" for (int i 0 i lt PlayInfo.Instance.gametablelist.Count i ) dealer img PlayInfo.Instance.gametablelist i .dlrimage dealer img "," Debug.Log("HERE ARE THE LINKS " dealer img) string links dealer img.Split(',') for (int j 0 j lt links.Length 1 j ) Debug.Log("HERE ARE THE NEW LINKS " links j ) new BestHTTP.HTTPRequest(new System.Uri(" amazonaws.com resources " "dealer pic " links j ), (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res) gt for (int k 0 k lt uitex.Length k ) var tex new Texture2D(20, 20) tex.LoadImage(res.Data) uitex k .GetComponent lt UITexture gt ().mainTexture tex ).Send() The problem with this code is that it's only getting the last index of my links. What could be the problem on my iteration? Here's an approach that works that shows what the expected behavior is for (int i 0 i lt tzPlayInfo.Instance.bc gametablelist.Count i ) dealer img tzPlayInfo.Instance.bc gametablelist i .dlrimage dealer img "," string newLinks dealer img.Split(',') new BestHTTP.HTTPRequest(new System.Uri(" .amazonaws.com resources " "dealer pic " newLinks 0 ), (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res) gt var tex new Texture2D(20, 20) tex.LoadImage(res.Data) uitex 0 .GetComponent lt UITexture gt ().mainTexture tex ).Send() new BestHTTP.HTTPRequest(new System.Uri(" .amazonaws.com resources " "dealer pic " newLinks 1 ), (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res) gt var tex new Texture2D(20, 20) tex.LoadImage(res.Data) uitex 1 .GetComponent lt UITexture gt ().mainTexture tex ).Send() new BestHTTP.HTTPRequest(new System.Uri(" .amazonaws.com resources " "dealer pic " newLinks 2 ), (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res) gt var tex new Texture2D(20, 20) tex.LoadImage(res.Data) uitex 2 .GetComponent lt UITexture gt ().mainTexture tex ).Send() new BestHTTP.HTTPRequest(new System.Uri(" .amazonaws.com resources " "dealer pic " newLinks 3 ), (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res) gt var tex new Texture2D(20, 20) tex.LoadImage(res.Data) uitex 3 .GetComponent lt UITexture gt ().mainTexture tex ).Send() It's working perfectly, but now the problem is that it is not very clean code.


Move enemies over the network without sending their positions I am trying to move enemies on two clients without sharing their positions. I use this startingPosition GetRandomDir() Random.Range(1f, 10f) To have the same movement on clients and server, I set the same seed to get the same directions with Unity Random. I set it with the system datetime now ticks on server and clients Random.InitState(newTicks) I am getting the same movements on the server and on the clients until a enemy starts looking for a player and chasing that player. When this happens, the enemy on one client is not at the same position on the other client. One enemy is targeting a player on one client, but on the other client he hasn't targeted that player yet. The enemy keeps wandering creating a different position on one client than on the server or other clients for example. Is there a better way to synchronize the enemy movement ? My idea was not to send the positions of the enemies from the server to the clients but rather have the clients move their enemies themselves. I would also like to know what to search for on Google to get help with this problem networking ai movement doesn't help, synchronize movement over the network without sending position does not return the results I would like either. What I think is strange and I don't understand is that the same code is executed on both the client and the server. The players and the enemies are at the same positions. Yet the enemy will choose to chase a player on the server and not to chase a player on the client. Resulting on the client to view the enemy at a different position than the position of the enemy on the server.


Lerp rotation is offset I am trying to get an object to slowly look at another object, that is, rotate slowly so its forward points towards the target position. Here is my code using UnityEngine public class LookAtTheDamnThing MonoBehaviour public Transform target public float speed void FixedUpdate() AimAtTarget() public void AimAtTarget() Vector3 direction target.position transform.position Quaternion toRotation Quaternion.FromToRotation(transform.forward, direction) transform.rotation Quaternion.Lerp(transform.rotation, toRotation, speed Time.time) Vector3 fwd this.transform.TransformDirection(Vector3.forward) Debug.DrawRay(this.transform.position, fwd 50, Color.green) This results in the object looking kind of towards the target but never actually looking at it. I cannot for the life of me see my mistake. Can anyone help me?


How can I attach a ball to something? I'm using Unity 2017 and am writing a game wherein you shoot a ball, and when said ball hit something (a cube for example), I want it to remain in that position that it hit. I tried this but it didn't work ball.transform.localPosition gameObject.transform.localPosition Something like this picture


Referencing Tilemap inside Grid Prefab I have a prefab of a grid which contains 3 different tilemaps Main, Foreground, amp Background I want to reference the tilemaps inside a script of the prefab but can't figure out how to do that... I just need to edit the tiles in the tilemaps located inside the prefab.


How to join two cubes? If I want to make a character (in Blender) made of cubes, to export it to unity later, should I leave these cubes and all the other body parts as separate objects, or join them all into one mesh? And, If I should join them is it a good idea to leave the cubes elements inside of each other? Or I should remove them, add some loops and connect the vertexes? In the last case it will be difficult to keep the cubes surfaces flat, because of the vertex shifting during joining.


Splitting a prefab into two These hands are in a single prefab. I want to split this into two so that I can make bones for each of them separately and use them with leap motion. How can make each of these hands as a single prefab? Also, I'm using Unity 2018.


How do I make a quake style camera tilt in Unity? I want to make a retro styled game with a modern look to it, and to do so I wish to make a quake styled camera tilt. By that I mean when moving sideways the FPS Camera tilts a little bit, and the returns to default when letting go of the key. I have little to no scripting knowledge. https www.youtube.com watch?v scSea v7JHA Notice how in the video when moving to the side the camera tilts a little bit.


World Space canvas rendering in front of line mesh I'm attempting to attach a pointer to my steamvr controller to simplify world interactions. I'm very new to unity, but found a nice volumetric line asset (VolumetricLines) that aesthetically is exactly what I want. However, it seems to be rendering behind my canvas, as you can see here The canvas is set to world space with the event camera set to the VR camera, and renders properly for all world objects except this line. The line also renders properly with all objects except this canvas. What exactly is the mechanic that causes the line to render behind the canvas, when it renders in front of other game objects, and what could I do to fix the render order?


How to go back to the old input system? I have tried using Unity's new input system, but it's incredibly hard to learn, the documentation is poor, and the old system is much easier to work with. I would like to revert my project back to the old system, but I am unsure how to do that. How do i disable the package and reconfigure my project so it will accept code using the old system?


How to destroy particles system after its work is over How can i stop particle system after player get destroyed


Unity Mask shows black content in world space canvas (Vuforia) So I've built my scroll rect, like this reference tells me to do http docs.unity3d.com Manual script ScrollRect.html Scroll View (Rect Transform with scroll rect attached) Viewport (Image Mask attached) Content (Image attached) In scene view it looks like I want it to look like, but in play mode it looks like this, which is the correct shape, but obviously not the correct content Update My Canvas Update The Image is getting displayed normally, when I disable the mask. Update The source of this problem seems to lie in Vuforia (Image Object Tracking library) since Vuforia appends a ClippingMask to the cameras


is there any method to simply ignore some files in unity build? as im trying to build my new app on unity android specially when i want to use gradle, there is always some conflict with manifest or libraries and ..... for debug and problem exploration i need to ignore some folders to check for those bugs instead of need to move them somewhere else. i just thought about git branching but it can cause lots of branches and maybe not efficient


Unity how to check if object is fully covered by another objects (2d) I am creating an educational game for kids , and in one of the levels player must to paint animals , like in color book, so I created scene where 2 object , already colorful lion and white lion (white is above) and script, which is instantiating circle sprite masks in players touch position , how can I check if white lion is fully covered by masks and not visiable . P. S. If you have better idea for painting (like painting with brush) and checking , please say.


How to make Unity ground mix up with sky I'm building up a scene with Unity, I want the plane to extend far enough and mixed up with sky like the picture showing bellow The only way I can think off in unity is by creating two plane with 90 degree with each other to simulate this scene, I tried to set solid color for the sky but still there is clear gap between the ground plane and the sky, how do you manage to extend the ground far enough and mixed up with sky?


How do I position a mesh just outside the camera view? I want to slide in an object into view, coming from the right of the screen. In order to achieve this, I need to position the object next to the camera view, so that it is still not visible, but close enough for a quick slide in. For example, placing the object at X 1000000 (so that it is surely outside the camera view) for safety wouldn't work as it couldn't slide in quickly enough. For a reasonable slide, I would need to have it really close next to the camera view. How could I calculate the object's position for that? Thank you. Edit Here is the script that I'm now using and which I'm still having problems with using System.Collections using System.Collections.Generic using UnityEngine public class NewBehaviourScript MonoBehaviour void Update() float fDist Mathf.Abs(Camera.main.transform.position.z this.transform.position.z) Bounds b BoundsFromTransform(this.transform) this.transform.position GetPointLeftOfCamera(Camera.main, fDist, b.size.magnitude 2) public static Bounds BoundsFromTransform(Transform uTransform) Bounds bounds new Bounds(uTransform.position, Vector3.zero) foreach (Renderer renderer in uTransform.GetComponentsInChildren lt Renderer gt ()) bounds.Encapsulate(renderer.bounds) Vector3 nOff bounds.center uTransform.position return new Bounds(nOff, bounds.size) public static Vector3 GetPointLeftOfCamera(Camera camera, float distance, float goDiameter) 1. var ray camera.ScreenPointToRay(new Vector3(0, camera.pixelHeight 2f, 0)) 2. var borderPoint ray.GetPoint(distance) 3. var leftPlane GeometryUtility.CalculateFrustumPlanes(camera) 0 var frustumLeft leftPlane.normal 4. var halfDiameter goDiameter 2f return borderPoint frustumLeft halfDiameter public static Vector3 GetPointRightOfCamera(Camera camera, float distance, float goDiameter) var ray camera.ScreenPointToRay(new Vector3(camera.pixelWidth 1, camera.pixelHeight 2f, 0)) var borderPoint ray.GetPoint(distance) var rightPlane GeometryUtility.CalculateFrustumPlanes(camera) 1 var frustumRight rightPlane.normal var halfDiameter goDiameter 2f return borderPoint frustumRight halfDiameter


Deployed Android APK file size was more tha expected when developed in Unity I developed a game, and build it as an Android APK file. I was not using any assets, only a UI panel and a UI Button. I thought the APK file woul be 3 MB, but it was 18MB. On the Google Play store, there are many good games using good graphics that have a small size. Some are only 5MB or 6MB. I want to know why I am getting such a large APK file. How do I reduce the size of my APK file?


Why is an empty Unity Iphone Build over 700 Megs? Is this Normal? So after 2 weeks of slaving over my first game I was finally done! I was entirely ecstatic....until I saw its file size. 770 Megabytes For a simple numbers game, that was way too much and I created an empty unity project as a test and that was also over 700 megs Why is an empty Iphone project this large?


Normal mapping for Android and iOS I'm making a mobile game for Android and iOS on Unity. At the moment I am researching and designing the technical aspects of the game. Since it is not plausible to use highly detailed models for mobile platforms, should normal mapped models be used instead? Thus I have couple of questions about normal mapping. Are normal mapped models much more costly to make, in other words, do they take a lot longer to create? And are they much more expensive to render? At least there are no additional draw calls, but of course the shader is more complex.


Unity 4.6 New GUI Issue with GIT I am using Unity 4.6 new UI. I have my project setup on bit bucket (using GIT). It was working fine but when I cloned the project on another macbook. All the unity new UI scripts went missing. Is there any workaround for this issue ? I am using same unity version on both macbooks. Editor Settings screenshot attached Ref of inspector where scripts went missing. Editor Settings


Flipped camera with Google VR I just imported latest Google VR SDK into Unity and made a simple scene that has only Main Camera, plane, and single zombie just standing there with T Pose. In Main Camera, I added GvrPointerPhysicsRayer component, and it has GvrReticlePointer as child object. Running in Unity Editor seems fine but when I build and run, whole world is just flipped. I can't find any related issues about this anywhere, and struggle with this almost a day. Why camera flipped and how do I fix it? What am I missing? Using Unity 2019.1.0f2 and gvr unity sdk 1.200. Any advice will very appreciate it. P.S. I saw the warning message in project settings default orientation Virtual Reality Support is enabled. Upon entering VR mode, landscape left orientation will be the default orientation unless only landscape right is available. This message never disappear whatever default orientation selected.


Is wireframe effect possible without geometry shader? I am trying to write a shader that highlight the edge between each pair of vertices, much like the UCLA Wireframe Shader. All implementations I came across require geometry shader support. I am wondering if this is possible with just vertex and fragment shaders? (Of course, I can use texture to workaround it but I am trying to avoid create custom textures for each model that I need this effect. On the other hand, I could just use geometry shader but it presents quite a problem when porting to iOS, which lacks support.)


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!


Unity Restrict movement inside a gameobject (2D) I've been sort of trying my own thing but it's super buggy so I'd like to see what other people have done to create moveable spaces. In essence, I just want to restrict my character's movement to inside of a sprite. So one of my sprites is the character and another one of my sprites is a box I want to make it so my character can't leave the box. I've been modifying transform.position on mouse click in order to move my character, but now I'm not sure if this was the smartest idea.


How to force Landscape Mode Unity3D Android Game? I am developing a small side project on Unity that will ultimately be for Android but I cannot figure out how to force landscape on the device and when I have tried it out the game just goes all over the place! I am using Unity Canvas and have spent a long time with binding position points etc. but I cannot work it out! Could someone please tell me how to force the phone into landscape mode?


Sending message to all players in room from Photon server? I need to send a message to all players in the room from a Photon server. Sending the message from a player would introduce too much latency so I need the server to collect data and distribute messages at a rate of 16 s without a player's influence. Is there a way to do this?


Unity3D Automatic Mipmap I'm using Unity3D. I'm working advanced topics. For example Mipmap. How I can automatic mipmap (use camera distance) for textures? Thank you.


HDR mode in windows makes build version of Unity game look washed out I've got a 2D Unity game I've been working on. The development computer is hooked up to a TV that supports HDR. If I turn on the "Play HDR Games and Apps" switch in windows then run the build version of my game the colors all appear overly bright and washed out. It looks fine in the editor though and looks fine when the windows HDR mode is turned off. Is there a setting in Unity that can stop this problem?


Detect Mouse Enter on An oval shape image in unity I have an image that is attached to a panel and I want to detect On Pointer Enter and exit. The event is working fine but currently, it is working on the full image while I want to detect this event on an inner oval shape. Actual the remaing are of the image is transparent.


How to apply forces to character with gamepad in Unity? I've been following Brackey's tutorial on this, see the excerpt from my code below. In his tutorial it only teaches quot transform.Translate quot , how do I use this gamepad input system tool to add forces to the character to make them move instead? So I can have jump physics, and when they're in space they'll keep the momentum. NewControls controls Vector2 move Vector2 rotate private void Awake() controls new NewControls() controls.Gameplay.Jump.performed ctx gt Jump() controls.Gameplay.Walk.performed ctx gt move ctx.ReadValue lt Vector2 gt () controls.Gameplay.Walk.canceled ctx gt move Vector2.zero controls.Gameplay.Rotate.performed ctx gt rotate ctx.ReadValue lt Vector2 gt () controls.Gameplay.Rotate.canceled ctx gt rotate Vector2.zero private void Update() Vector2 m new Vector2(move.y, move.x) Time.deltaTime transform.Translate(m, Space.Self) Vector2 r new Vector2(rotate.y, rotate.x) 100f Time.deltaTime transform.Rotate(r, Space.Self) To move with rigidbody controls, you have to use things like forward or left but I want one joystick to control the forward, backwards, and side to side movements. I don t know how to use the joystick input for moving in all those directions. The tutorials have them as separate arrow keys does anyone have some sample code, or a tutorial to point me to, or just some explanation? it would be much appreciated.


Blurry background sprite, other sprites fine Why is the background blurry, but all the other sprites fine? The background sprite has the same settings as the others. It's on the same Z position (0). It happened after I made some changes to the original image, just deleting some colours on it, not changing it's dimensions. It's coming from a sprite sheet of 11 images. All the images are blurred in the same way Details The camera is set orthographic. The camera size is set to 95. The camera is at 0,0, 10 . The background sprite is at 0,0,0 . The sprites are all at Z 0 The sprite is W 256, H 174. Anti aliasing is disabled in the project.


How to avoid an applied force from effecting one particular Rigidbody2D I am creating a 2D side scroller car race game with zombies. In this game, I set up a feature through which the player can shoot the zombies from the car, as well. The problem is that when I apply force to shoot the bullet towards the right, the car also gets effected by that force, i.e it just moves a lot in reaction to the bullet shot. I don't want this behavior. I want the car to remain calm and just shoot. Is there any way to exclude one particular rigidbody, i.e the rigidbody attached to the car, from applying the force the bullet rigidbody is using?


How do I point with my straight line the point that moves in the figure "infinite" "8"? I need a help for my project. Given a straight line "a" "b" I have "a" point anchored and "b" can move. I need to make sure that the "b" point of the straight line always points to the "c" point, taking into consideration that "a" is anchored. I can not use the LookAt () because I need to be able to use the mouse too.


How to write depth texture and read values from it I am new in Unity and specializing in another field. But now I have to rapidly study it for a new project. I will be very thankful if anyone explain me how to read values of the depth buffer. I wrote a shader, which creates depth image Shader quot Custom MyDepthShader quot Properties MainTex ( quot Texture quot , 2D) quot white quot SubShader No culling or depth Cull Off ZWrite Off ZTest Always Pass CGPROGRAM pragma vertex vert compile function vert as vertex shader pragma fragment frag compile function frag as fragment shader include quot UnityCG.cginc quot struct appdata float4 vertex POSITION float2 uv TEXCOORD0 struct v2f float2 uv TEXCOORD0 float4 vertex SV POSITION v2f vert (appdata v) v2f o o.vertex UnityObjectToClipPos(v.vertex) o.uv v.uv return o sampler2D MainTex sampler2D CameraDepthTexture fixed4 frag (v2f i) SV Target float depth tex2D( CameraDepthTexture, i.uv).r depth Linear01Depth(depth) depth depth ProjectionParams.z return depth ENDCG Now I need to get depth information into a texture and save float values of this texture to for example txt file for further processing. I didn't found yet answer to this question after two days of googling and reading guides. For testing this shader I am using OnImageRender(RT src, RT dst, material).


Another try. List don't remove properly I hve that script public void ActivateCard(Card card) Debug.Log( quot Activating card quot card.CardsData) if (card.CardsData.creatureName ! string.Empty) Summon(card) else CastSpell(card) if ( hand.Cards.Contains(card)) hand.Cards.Remove(card) Debug.Log( quot Card quot card.CardsData.cardName quot deleted quot ) Debug.Log( quot now we have(cards) quot hand.Cards.Count) hand.TakingCards(0) And I expect that card will be removed from the list. But it allways remove only FIRST element in there. Here's what I have(card can't be the same in one list) ADDICTION It's not a full code, but it's all we need I think. Here's how this method calls I public class InputClass void Update if (targetSet) if (Input.touches 0 .phase TouchPhase.Ended) Cancel(true) void Cancel(bool isDone) actCard.Cancel(isDone) II class ActCard public void Cancel(bool isDone) if (isDone) activator.ActivateCard( card) III class CardActivator public void ActivateCard(Card card) Debug.Log( quot Activating card quot card.CardsData) if (card.CardsData.creatureName ! string.Empty) Summon(card) else CastSpell(card) if ( hand.Cards.Contains(card)) hand.Cards.Remove(card) Debug.Log( quot Card quot card.CardsData.cardName quot deleted quot ) Debug.Log( quot now we have(cards) quot hand.Cards.Count) IV public class Hand List lt Card gt hand new List lt Card gt () public List lt Card gt Cards get return hand set hand value


Unity Sharing values between functions invoked by buttons and the rest of the script Ok so, here is the problem. I am doing a multiplayer 2D game using UNET. I have a script that kind of helps a player select an avatar to play with. The avatars are listed as a scrollview of buttons. These buttons invoke the function setAvatar(int id) that sets a player's avatar passing in an ID as argument. The function just sets the player's avatar using ID as index in a list of avatars. Now the problem is this player is a prefab which is instantiated at the start of the playscene for Player A and Player B. So the setAvatar(int sprid) function assumes I am referring to the prefab whenever I use "gameObject" So, I decided to store the local gameObject in a temporary variable. Here's the full code, public class Player2DController NetworkBehaviour Attached to player prefab public float moveForce 2 Rigidbody2D myBody Transform mainCamera Shooting shscript int i public Transform joystick GameObject temp public Sprite spr void Start () if (!isLocalPlayer) Destroy (this) return temp gameObject storing local gameobject in temp joystick GameObject.Find ("MobileJoystick").transform shscript GetComponent lt Shooting gt () mainCamera Camera.main.transform RotateCamera () myBody GetComponent lt Rigidbody2D gt () if (isClient) i 1 if (isServer) i 1 public void RotateCamera() if (isClient) mainCamera.rotation Quaternion.Euler (new Vector3 (0f, 0f, 180f)) if (isServer) mainCamera.rotation Quaternion.Euler (new Vector3 (0f, 0f, 0f)) void FixedUpdate () if (PauseMenu.isOn) return Vector2 moveVec new Vector2(CrossPlatformInputManager.GetAxis("Horizontal"),CrossPlatformInputManager.GetAxis("Vertical")) moveForce myBody.AddForce (moveVec i) if (CrossPlatformInputManager.GetButton("Shoot")) shscript.CmdFire () public void setAvatar(int id) called through the buttons in the avatar list temp.GetComponent lt SpriteRenderer gt ().sprite spr id null pointer exception This code doesn't work. I get a null pointer exception on temp variable saying it is not assigned. But how can this be? I clearly assign it to active gameObject in Start() method. The only reason I can think of why this is happening is that since the button acts on the player prefab, it creates a separate instance of the script for the player prefab that doesn't get executed. So, when it invokes setAvatar(), it has a temp which is not initialized. So that's the whole problem. Since this didn't work, I tried renaming the players as clientPlayer and serverPlayer and then accessing them using GameObject.Find(name).GetComponent lt SpriteRenderer gt ().sprite. But this had no effect and no errors. I have no idea why. So any ideas on how to go about this?


how to sync clients and local avoidance in mobile RTS game? I have been making mobile RTS game in Unity look like Clash Royale similarly. Unfortunately, I faced to two big problems. First is two phones(clients) to be synchronized each other in game state. And second is "path finding" or "local avoidance"(collision check). To solve the path finding issue, I have searched about "Flow Field". Should I do consider on 3 layer map(cost field, integration field, flow field) to apply "Flow field"? If I do apply "flow field" to my game, can I have a liberty from the problem of Sync two clients? Thank you in advance.


How can I change existing hierarchy in Unity regarding animations? I made a bunch of animations in Unity. Now I need to adjust the hierarchy. For example My animator used to change things in this tree, where the head, legs, and arms were animated Player gt Torso gt Head gt Arms gt Legs Now I added another layer in my hierarchy so that it is Player gt Body gt Torso gt Head gt Arms gt Legs And it cannot find the existing animation, since the hierarchy path is different. How can I insert the body in my animation hierarchy so that I can keep my new hierarchy without having to redo all of the animation?


Multiple SpriteSheets break batching The problem I can't fit all my 2d animation sprites for all units and environment in 1 spritesheet. Everything batches fine until I use two spritesheets... I noticed the following all units from spritesheet A batch fine until something needs to be rendered fom spritesheet B. so lets say from back to camera 50units tree 50 units camera will result in 3 drawcalls... Not that bad but if you have unit tree unit tree unit tree ... like it's probably most of the time... this wil result in 100 drawcalls even though you have only two spritesheets... How can you solve this? Or better, how can i use two spritesheets and have only two drawcalls even though the sprites are at different distances to the camera Hope this image helps to understand the problem 1 the trees are on spritesheet B and batch fine 2 the batching is broken as the unitsprite sits on spritesheet A and is put in between the trees...


Is there a difference between using one large mesh with 100k polygons and using 1000 meshes with 100 polygons each? I'm planning on creating a first person shooter for mobile. Now I know that fps games usually have a lot of meshes in the scene (trees, buildings, terrains, etc.). So I've been looking at a lot of Unity optimization tips. One thing I've noticed is that they always say "If you have a lot of objects in your scene, then each mesh must have low polygon count". But how exactly does this help? If I have a lot of houses in my scene and I ensure that each house has very few polygons, wouldn't the total number of polygons in my scene be affecting the performance anyways? Or will my scene be rendered differently now that I've broken up the total polygon count into multiple parts?


Art style for a character that has frequent visual changes during gameplay I'm creating a game with a bodybuilding fitness theme. The camera will almost always be focused on an inclined front view of a character who will be evolving very frequently during the game as the player 'levels up' the musculature of each part of the character such as arms, legs, chest, etc. I've been doing some research trying to figure out the most economical yet effective way to incorporate this visual mechanic of letting individual parts of a character independently increase in size and detail and have come up somewhat short, most likely due to my complete lack of experience when it comes to art (my experience is mostly in programming). I was thinking 2D would be best for this game, however maybe this one character should be in 3D? Would a low poly style fit these requirements, or should I look towards something akin to sprites or hand drawings? The games interactivity will be purely through menus so that doesn't need to be taken into account when dealing with the problem of this character. I would like this character to have some animations, of course, however I'm not sure if that fits the scope of this single question.


Positions are the same but appear in different locations I have a procedurally generated tile that is a part of a turn based hex tile game. When I try to have the tile instantiate a prefab that is the placeholder for a unit, I used the tile's transform.position as the position part of GameObject.Instantiate(Object, Location, Rotation). Unfortunately, this is the result A similar thing happens no matter which tile I use. More information I tried placing a cube on where the hex is, supposedly. Its transform is very different. So what it appears to be is that the tile is being placed in the wrong place, not the cube. Further experimentation shows that the cube is appearing at exactly half the hex's apparent transform (I added a multiplier of 2 to the cube's position and it appeared in the right spot). I still have no idea why.


Transform.Rotate is jumping around Why is the parent that contains 4 children jumping around and then settling into a position instead of rotating once by 90 deg? I can't seem to get it to rotate a single time as expected. using UnityEngine public class rotateparent MonoBehaviour public Vector3 rotationPoint void Update() if (Input.GetMouseButton(0)) transform.Rotate(new Vector3(0, 0, 1), 90) Object jumping when mouse clicked


2D Animation based on Time.deltaTime has problems when the game performs long operations I animate my 2D sprite using the Update() method float timer 0.0f float delayPerFrame 0.04f void Update() timer Time.deltaTime if (timer gt delayPerFrame) timer 0 Logic to display the next frame As you can see, it is pretty simple every 0.04 seconds the next frame will be set. But sometimes, my game needs to do some exhausting processing (like loading large scenes and whatnot), which causes a tiny little lag in the game. When this happens, my sprite begins with a wild, fast animation. Then eventually it resumes at a normal pace. I imagine this is because the lag caused the Time.deltaTime value to skyrocket for a period of time. I am also under the impression that Update() is called too often during such period (although that shouldn't matter). I don't want to use existing animation features of Unity. My game is already built under this particular piece of logic, so I'd like to fix it. Using FixedUpdate() doesn't help. I can also confirm that Time.deltaTime does indeed peak at the beginning. Note that this occurs only after doing an exhaustive operation. If you spawn a sprite of these in the middle of the game, everything will go smoothly. But if you spawn them immediately after doing something like loading a large scene, then they will have some sort of boost at the beginning.


How can I resize a game object using single drag handle? Really need your help. I'm trying to create a custom controller for my app to allow users to resize and rotate game objects using a single drag object. I was able to create the code to create the visuals and to rotate it but I'm stuck on how to resize the game object. To position the drag handle at the start, I'm getting the bounds of the target object and taking the bounds.extents.magnitude to determine the y position. So I was hoping the behavior would be such that when you drag the handle closer to the center of the target object it shrinks the bounds.extents.magnitude based on the new handle position and then becomes bigger if you go further away from the center of the target object. Here is where I am now using System.Collections using System.Collections.Generic using UnityEngine public class CircleMaker MonoBehaviour public float lineWidth .1f private int segments 360 private LineRenderer line private float radius private Renderer boundsSource private Bounds bounds public GameObject dragHandle public GameObject target private int pointCount private Vector3 points public int angle 0 public float zPosition 8.0f public bool isDraggingHandle false void Start() line GetComponent lt LineRenderer gt () boundsSource target.GetComponent lt Renderer gt () bounds boundsSource.bounds line.useWorldSpace true line.startWidth lineWidth line.endWidth lineWidth line.positionCount segments 1 line.receiveShadows false line.shadowCastingMode UnityEngine.Rendering.ShadowCastingMode.Off pointCount segments 1 points new Vector3 pointCount float r bounds.extents.magnitude float d2r Mathf.Deg2Rad (target.transform.localEulerAngles.x 360f segments) dragHandle.transform.position new Vector3(Mathf.Sin(d2r) r, Mathf.Cos(d2r) r, zPosition) target.transform.position DrawCircle() void Update() if (isDraggingHandle) rotate object based on drag handle location Vector3 direction target.transform.position dragHandle.transform.position int sign (direction.x gt 0) ? 1 1 float offset (sign gt 0) ? 0 360 float angle Vector2.Angle(Vector2.down, direction) sign offset target.transform.rotation Quaternion.Euler(0, 0, angle) if (target.GetComponent lt DragAndDrop gt ().isDragging true) dragHandle.transform.parent target.transform else dragHandle.transform.parent null DrawCircle() draw circle around target gameobject based on bounds.extents void DrawCircle() radius bounds.extents.magnitude target.transform.localScale.x for (int i 0 i lt pointCount i ) float rad Mathf.Deg2Rad (i 360f segments) points i new Vector3(Mathf.Sin(rad) radius, Mathf.Cos(rad) radius, zPosition) target.transform.position line.SetPositions(points)


How to Stop TextMeshPro Truncate from Removing Next Line? Unity 2020.3.1f1 In updating from Unity 2019 to 2020, it appears the TextMeshPro (TMP Text) is behaving differently. The code for TMP stayed the same upon updating Unity, so I presume Unity itself must be doing something differently. Nevertheless, I also updated the TMP package and it did not resolve the issue. The Issue I have two lines of text in one text box. I want the overflow to be truncated, but to keep the second line in existence. Example Input This is the really long text on the first line that I want cut but still have this line show. In short, I want it to read as follows when using the quot truncate quot option like it used to work before This is the really long text still have this line show. Instead, the second line disappears and it acts as if I have only that first line (centered vertically). This is the really long text So how do I get this functionality back? Is it possible?


Text Based Tutorials for Unity3d I hope this is the right place to ask this. I'm very new to Unity but not to programming. I also have some basic game programming experience. I'm searching for text based versions of the videos from unity3d.com learn tutorials. These tutorials are very good, but I end up forwarding videos a lot to get key screenshots and code snippets. Is there any text pdf html .doc .rtf (i'm very open) version or similar resource to learn unity? Again, those tutorials are amazing and I'd hope to find something of similar quality, but I know that if I have to skim through tens of hours of video I'll end up frustrated. I get that the long hard way is probably the most robust one for deeper understanding, but I was hoping to hack a quick project. EDIT If this can make it a relevant question, then I am currently looking at the "Roll a Ball Tutorial". Really, any other text tutorial would be very welcome


How to stop my particle systems from being frustum culled Please could somebody advise on whether it is possible to control the culling of particle systems in Unity? I am referring to the entire system, not individual particles. In my use case, I am modifying the vertex transformation to get the quot distant object effect quot . When the camera thinks it is not viewing something it will cull it (frustum culling). For most game objects you can get around this by inflating the size of the bounds to make the camera think it is within its frustum and therefore not get culled. However, particle systems are not a single object, they are many particles and I can t see a way of manipulating the total bounds of the system. Any ideas?


Render object with different shader depending on the camera I have an object with a custom shader. When it is being rendered by cameraA, then I want it to render a particular way (ex red). When it is rendered by another cameraB, I want it to render a different way (ex green). Is there some way I can tell what is the current camera rendering in the shader? Or perhaps I can toggle a boolean value in my shader between rendering of each camera? Where would I do this (OnPostRender() maybe?).


Should larger Unity Projects use Visual Studio I've worked with several engines and I'm most comfortable with a mature engine, world editor and C codebase. I'm now looking at Unity as a side project and have mostly been working in Javascript. Has anyone done a large scale project with Unity and does it require Visual Studio or is sticking to the Javascript approach best? Are there any big pitfalls with large scale Unity projects or with working with Visual Studio? Most the stuff I've seen has been focused at smaller Indies or people with little experience. I should have phrased this as an external IDE, Visual Studio is just my IDE of choice


Global fog does not work with deferred rendering in Unity When I set deferred rendering the global fog from the Unity Standard Assets does not work, there is no fog at all. With forward rendering the global fog works. How do I add fog with deferred rendering?


Raycast implementation in order to optimizate collision detection I want to know if a gameobject (a plane) is facing another one to prevent collisions. Right now I have an array that contains all planes in the scene and, for each one, compare position in order to detect if is facing it or not. The number of planes is small, but I want to increase it and this method is a little... Mean. I was thinking to implement a raycast to detect if the gameobject has another one in front of it. Is it worth? Will it be less expensive? I think that raycast it's very expensive. In addition, I think that I will have to run three raycasts for every plane. Obviously this is not executed every frame, but every two seconds.


Mirror problems after building game in unity Hi I am facing a weird problem in unity when I build a particular scene. Here is the screenshot of how the mirror looks when I play the game from inside the unity editor And here is how it looks once I build this scene and then play it The quality settings at Edit Project Settings Quality are these And the player settings at File Build Settings Player Settings are these So how do I fix this? What do I need to change or is there any other entity?


how to put elements around circle with equal distance? I know circle formula and know how to draw it. but I want put 4 points on it with equal distance from each other. how can I do that? I work with unity.


Why is transform.up behaving differently for different functions? Can anyone please explain to me what i'm doing wrong here? As I see it the raycast is the only one using transform.up correctly, though why not Debug.DrawLine() and lineRenderer.SetPosition(1, transform.up maximumBeamLength) using UnityEngine RequireComponent(typeof(LineRenderer)) public class LaserBeam MonoBehaviour SerializeField private float maximumBeamLength 5f private LineRenderer lineRenderer private void Start() lineRenderer GetComponent lt LineRenderer gt () void Update() lineRenderer.SetPosition(0, transform.position) RaycastHit2D hit Physics2D.Raycast(transform.position, transform.up) Debug.DrawLine(transform.position, transform.up maximumBeamLength, Color.blue) Debug.DrawLine(transform.position, transform.up , Color.red) if (hit.collider) lineRenderer.SetPosition(1, new Vector3(hit.point.x, hit.point.y, transform.position.z)) else lineRenderer.SetPosition(1, transform.up maximumBeamLength)


Refresh UI after changing source code I was trying following things. GameManager bool gameHasEnded false public GameObject completeLevelUI public void CompleteLevel() completeLevelUI.SetActive(true) public void EndGame() if(gameHasEnded false) gameHasEnded true Invoke( quot Restart quot ,2f) void Restart() SceneManager.LoadScene(SceneManager.GetActiveScene().name) EndTrigger public GameManager gameManager void OnTriggerEnter() gameManager.CompleteLevel() I get a log in the console quot END quot . Earlier I was using Console.Log( quot END quot ) on CompleteLevel(), but I changed that source code. The old code seems to be working and not the new one. It's like Unity couldn't refresh that source code. (And I am sure that I have successfully saved the C file.) using System.Collections using System.Collections.Generic using UnityEngine public class PlayerCollision MonoBehaviour public PlayerMovement movement void OnCollisionEnter(Collision collisionInfo) Debug.Log(collisionInfo.collider.name) if (collisionInfo.collider.tag quot obstacle quot ) movement.enabled false FindObjectOfType lt GameManager gt ().EndGame()


Animated textures for models How to write a shader? Was watching some Rocket League and notice there was animated decals and wheels. . I would like to implement something similar to the effects in the image above. How would I go about writing a Unity Shader to do the wheel effect? I don't know much about Shaders, but can I edit the standard Unity Shader to do the animation effect?


Not able to change Rigidbody 2d gravity scale I have been trying to change the gravity scale of my Rigidbody2d when I click on it. By default it is by 0 and when I click on it, it should change to 1, so that it falls down. I have a square with a boxcollider2d and a Rigidbody2d and a square with just a box collider. public bool gravity false public bool m isRunning false public SpriteRenderer m spriteRenderer private Rigidbody2D rb private void Update() if (gravity) rb.gravityScale 1 private void Start() m spriteRenderer this.GetComponent lt SpriteRenderer gt () rb GetComponent lt Rigidbody2D gt () private IEnumerator Changecolor() yield return new WaitForSeconds(1) int random Random.Range(1, 4) if (random 1) m spriteRenderer.color Color.blue else if (random 2) m spriteRenderer.color Color.red else if (random 3) m spriteRenderer.color Color.green else m spriteRenderer.color Color.yellow this.StartCoroutine("Changecolor", 3f) private void OnMouseDown() gravity true m isRunning !m isRunning if (m isRunning) StartCoroutine("Changecolor", 3f) else StopCoroutine("Changecolor")


Get all images from peristent data path and save them to a Texture2D array So i managed to make a working script that downloads images from firebase in this situation and saves them to Application.persistentDataPath. Now what i would like help in doing is getting all those images quot jpg quot and assigning them to a Texture2D array for later use. So far i have mananged to open one of those images by name and assign it to a single texture. public Texture2D image private void Awake() string dirname quot levelNature quot string path Application.persistentDataPath quot quot dirname quot quot quot nameofImage.jpg quot LoadSprite(fileName) private void LoadSprite(string path) if (string.IsNullOrEmpty(path)) Debug.Log( quot null or empty quot ) if (File.Exists(path)) byte bytes File.ReadAllBytes(path) Texture2D texture new Texture2D(1024, 1024, TextureFormat.RGB24, false) texture.LoadImage(bytes) image texture Debug.Log( quot success quot ) With just one image i can assign it to a texture but since later on in the gameplay i'm using a texture2d array to assign those images to the gameplay , which now are set through the inspector , i would like to load all images in a particular folder to a Texture2D array which later on i will be using to show each image index in a specific level. I did try it out like this but it isn't successful. public Texture2D source var fileNames Directory.GetFiles(Application.persistentDataPath quot quot dirname quot quot quot .jpg quot ) source new Texture2D fileNames.Length int index 0 foreach (var fileName in fileNames) source index LoadSprite(fileName) i get the error here that it cant convert void to texture2D index Hopefully once all images are loaded i could see in that array in the inspector all the images and then use that for the rest of the game. Thank you!


How to restrict movement of Leap Motion hand object I have a quot Hand quot GameObject controlled by a Leap Motion Controller. The Hand despite having RigidBody and Box Collider just seemingly moves with no regards to physics (transform translate movement I suppose). So it clips through other Rigidbody objects. I'm trying to pseudo introduce physics to it. I created a second GameObject quot HandClone quot (with Rigidbody and Box Collider) that copies the first Hand position but moves with actual physics. HandClone script private void FixedUpdate() rb.MovePosition(targetTransform.position) rb.MoveRotation(targetTransform.rotation) Now HandClone goes where Hand goes, and HandClone is successfully bumping into other objects. However, when HandClone gets stopped by something, Hand still keeps moving past HandClone and clips into the other objects, like before. Now I am thinking that the way to solve this is to constrict Hand's movements to the bounds of HandClone so that finally Hand will stop clipping through objects. But how can this be achieved, would that even work, and is there a better way? Will movement streamed from Leap Motion Controller even respond to scripts like that? Edit I've now decided to hide Hand and place HandClone where Hand was. But my script for HandClone to copy Hand's movements is making HandClone fly all over the place. Here's the script using System.Collections using System.Collections.Generic using UnityEngine public class clone1 MonoBehaviour private Rigidbody rb public GameObject target void Start() rb this.GetComponent lt Rigidbody gt () Update is called once per frame void Update() private void FixedUpdate() Vector3 newRotation new Vector3(target.transform.eulerAngles.x 8.5f, target.transform.eulerAngles.y 172.78f, target.transform.eulerAngles.z 94.02f) rb.MoveRotation(Quaternion.Euler(newRotation)) The reason why I am adding those float numbers is because when the game isn't playing, those numbers are what make HandClone sit in the correct position, so I thought it would help with alignment in playmode. But HandClone is just flying everywhere regardless. Any advice with making the HandClone stay attached to the avatar's wrist would help.


Unity SOAP wsdl problem i'm trying to using a SOAP service from my game but the problem is that after using wsdl.exe for generete the connector Unity inform me that System.Web namespace doesn't exist. How can I use the wsdl? There is some workaround without writing a lot of code? Many thanks


Sprite with transparency Create box collider (ignoring transparent area) I have a sprite which has a transparent area in it. The non transparent area is a free form graphic (red). I would like to create a box collider around it (yellow), but ignoring the transparent area. Some notes to the image above Left This is what happens, if I apply a PolygonCollider2D. The yellow line represents the area covered by the PolygonCollider2D. This is not what I want. Middle This is what happens, if I apply a BoxCollider2D. The yellow line represents the area covered by the BoxCollider2D. This is also not what I want, as it includes the transparent area of the sprite. Right This is what I want Have a BoxCollider2D outside my free form graphic. Here's how I currently load my sprite data into the game during runtime My sprites are located in the Assets Resources SceneData ... folder structure of my project. The graphics are stored as .png files. When loading a level, I load the required graphics as sprites like this var sprite Resources.Load lt Sprite gt ("SceneData AfternoonAtTheBeach DragAndDrop Graphics Level1 ElephantWithIceCream") "ElephantWithIceCream" is the .png file (Resource.Load wants me to refer to this file without file extension) After that, I create a new game object and attach a SpriteRenderer component to it. The sprite is assigned to the SpriteRenderer by setting the sprite attribute of the SpriteRenderer component. My first thought on how to solve my problem was to do something like this Create a PolygonCollider2D and try to convert it into a BoxCollider2D. But I was not able to find code examples on how to do this. After that, I thought of trying it to do like this Create a PolygonCollider2D and try to extract some useful information out of it (such as bounds, center, extents, etc...). Delete the PolygonCollider2D and create a BoxCollider2D. Use the previously extracted info to create the BoxCollider2D. But I fail doing so. I am also a bit confused as sometimes they refer to world space or local space. Does anyone have a working recipe for doing something like this? I do not really understand how to work with center, bounds and extents. If there is any better way of doing this, I am highly interested. Thanks a lot for your help!


Stop 2D platformer character from sliding down slope I'm making a 2D platformer game with the default Unity 2D physics. I am implementing slopes, but my player slips down the slope because of the physics. Here is the code I use for the player movement MoveInput Input.GetAxisRaw( quot Horizontal quot ) rbd2.velocity new Vector2(MoveInput speed, rbd2.velocity.y) rotacion de personaje if (MoveInput gt 0) transform.localScale new Vector3(1f, transform.localScale.y, transform.localScale.z) if (MoveInput lt 0) transform.localScale new Vector3( 1f, transform.localScale.y, transform.localScale.z)


When importing Mixamo animated characters into Unity, they come without avatar? I'm using Unity 2019.3.3f1. I create the character in Adobe Fuse. I uploaded it to Mixamo and choose an animation. I then downloaded the fbx for unity file. When imported into Unity, it is visible that the file has no avatar or animator component. How can I fix this? Is it a Unity version issue?


Are the prefabs stored in RAM or in the Hard disk? (Unity3D) I have many prefabs objects (65 MB) in an Unity3D project. My game use 100 different levels with combinations of the prefab objects. What is better create 100 scenes or create only one scene where the prefab objects are placed with data from a XML?. Each Scene load your own prefab objects? Are the prefab objects loaded in the RAM when the scene is loaded or are stored in the hard disk and then loaded in the RAM when come in the scene?


Possible to yield a coroutine when it is taking too long to run? Suppose I have a function that raycasts from (0,0,0) to every object in the scene. Sometimes the scene contains just a couple objects and sometimes it contains several hundred. Is it possible to setup the raycasting function in a way that ensures a good framerate? For example, within the "for" loop that shoots the rays could I somehow evaluate how much time has passed since the loop started and "yield return null" if the time in seconds is greater than the target time of each frame?