Programmatically creating new tags in Unity I'm writing a custom editor script to add tags programmatically. I got the error of IndexOutOfRangeException Array index is out of range from the lines below SerializedObject tagManager new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings TagManager.asset") 0 ) SerializedProperty tagsProp tagManager.FindProperty("tags") These are my codes SerializedObject tagManager new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings TagManager.asset") 0 ) SerializedProperty tagsProp tagManager.FindProperty("tags") Adding a Tag string s "Instantiated" First check if it is not already present bool found false for (int i 0 i lt tagsProp.arraySize i ) SerializedProperty t tagsProp.GetArrayElementAtIndex(i) if (t.stringValue.Equals(s)) found true break if not found, add it if (!found) tagsProp.InsertArrayElementAtIndex(0) SerializedProperty n tagsProp.GetArrayElementAtIndex(0) n.stringValue s Latest Update Error IndexOutOfRangeException Array index is out of range is solved by resolving file location in my original script. I apologized for that. Fixed Added a line in the script to update the properties if (!found) tagsProp.InsertArrayElementAtIndex(0) SerializedProperty n tagsProp.GetArrayElementAtIndex(0) n.stringValue s tagManager.ApplyModifiedPropertiesWithoutUndo()


Random.range giving me the same value at the same time I created a random direction in x and y axis at where to move, then my problem is when I tried to randomize it sometimes I get the same value at the same time on both x and y axis. How do I not let this happen, I only want one axis to have a value, not both? ERROR HOW I WANT IT TO HAPPEN CODE public Vector2 randomDirection void Awake() void Update() randomDirection new Vector2(Random.Range( 1, 2), Random.Range( 1, 2))


Static variable not holding its value I am creating a real time multiplayer game in Unity 3d. When a game ends I set a static boolean value called "waitingToEndGame" to true. In Update() it waits a few seconds before moving to a new scene like this if (waitingToEndGame) waitTime Time.deltaTime if (waitTime gt 5f) showGameScores false waitingToEndGame false if (type "Multiplayer") MultiplayerController.Instance.LeaveGame() GameObject levelManager GameObject.Find("Level Manager") levelManager.GetComponent lt LevelManager gt ().LoadLevel("MainMenu") DisableAllMovingObjects() My problem is that even though I am setting the boolean value to true it acts as if it doesn't change and it doesn't make it into the code above to move to the main menu. I even had debug statements printing here as well and they seem to just suddenly stop.


Enlarge screen space Texture by set pixel amount I have a texture shown over the screen using screen space UV's. The Texture is 495x,596x, Screen size is 888,500, but can change. The Texture has a Tile of (3.469775f,1.392644f) to correct for distortion from being stretched to the Screen's size, and has repeat set to Clamped. So basically, I'm showing a Texture of an arbitrary size on screen and using Tile and Offset in the shader to correct for distortion and keep the texture at its original aspect ratio. Now my problem is I want to Zoom in and out by a set pixel amount in Screen space. So lets say I need the texture to increase in width by 10 pixels in screen space. What is a formula I can use to recalculate the Tile and Offset so that the texture stays at the same aspect it was but increases by the amount I want it zoomed? I've been trying things like 1 Pixel (1f Camera.main.pixelWidth). So to zoom by 10 pixels I would go something like Tile.x (10f (1f Camera.main.pixelWidth)) But this doesn't seem quite right, I'm not seeing it increase the Texture by the right number of pixels... My current function is something like this, but for Zoom 5f, it's only enlarging by about 2px. AspectRatio Tiling in the Material and WidthOffset HeightOffset is just the Offset. public void ZoomOverlay(float ZoomAmount) AspectRatio.x ZoomAmount (AspectRatio.x (float)Camera.main.pixelWidth) AspectRatio.y (ZoomAmount (AspectRatio.x (float)Camera.main.pixelHeight)) 2f WidthOffset ((ZoomAmount 2f) (AspectRatio.x (float)Camera.main.pixelWidth)) HeightOffset ((ZoomAmount (AspectRatio.x (float)Camera.main.pixelWidth)) 2f) AspectRatio.x


How can I find and get all enabled cameras and switch between them? I have 5 cameras in the scene. In the Inspector I added to the cameras array 3 cameras. In the script I store this cameras using storedCameras array. In cameras array there are 5 cameras. I added a flag allCameras to change between the stored cameras mode and all cameras mode. And I'm using the G key to switch between the cameras either the stored or the all cameras. But when I press on G I see in the Inspector that each press on G remove one camera from the array cameras in the end I left with one camera. And the idea is to press G and switch between the cameras either if it's on stored cameras mode or all cameras mode depending on the flag. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class SwitchCameras MonoBehaviour Header("Cameras Init") public Camera cameras public Vector3 originalPosition HideInInspector public Vector3 currentCameraOriginalPosition, currentCameraPosition public bool allCameras false private Camera storedCameras Space(5) Header("Cameras Switch") public string currentCameraName public Vector3 lastCameraPosition private int currentCamera 0 void Start() storedCameras cameras if (allCameras true) cameras new Camera Camera.allCameras.Length cameras Camera.allCameras lastCameraPosition new Vector3 cameras.Length if (cameras.Length gt 1) originalPosition new Vector3 cameras.Length for (int i 0 i lt cameras.Length i ) originalPosition i cameras i .transform.position if (cameras.Length 1) Debug.LogError("Need more then 1 camera for switching..") else Debug.Log("Found " cameras.Length " cameras") for (int i 0 i lt cameras.Length i ) cameras i .enabled false cameras 0 .enabled true currentCameraName cameras 0 .name currentCameraOriginalPosition originalPosition 0 void LateUpdate() if (allCameras true) cameras new Camera Camera.allCameras.Length cameras Camera.allCameras else cameras new Camera storedCameras.Length cameras storedCameras if (Input.GetKeyDown(KeyCode.G)) cameras currentCamera .enabled false if ( currentCamera cameras.Length) currentCamera 0 cameras currentCamera .enabled true currentCameraName cameras currentCamera .name currentCameraOriginalPosition originalPosition currentCamera lastCameraPosition currentCamera cameras currentCamera .transform.position currentCameraPosition lastCameraPosition currentCamera


game object disappears when I add OnTriggerEnter script I'm setting up collision detection for my enemy objects and projectile. When I add the detect collision script below, my enemy object just disappears. Projectile has the same detect collision script and also disappears. I get this error code NullReferenceException Object reference not set to an instance of an object MoveForward.Start () (at Assets Scripts MoveForward.cs 16) This is a copy of my prefab settings for enemy object I'd appreciate any advice. Thank you Detect Collision Script using System.Collections.Generic using UnityEngine public class DetectCollision MonoBehaviour Start is called before the first frame update void Start() Update is called once per frame void Update() private void OnTriggerEnter(Collider other) Destroy(gameObject) Destroy(other.gameObject) Move Forward Script using System.Collections using System.Collections.Generic using UnityEngine public class MoveForward MonoBehaviour public float speed 20f public GameObject Trump public GameObject Player private Rigidbody enemyRb Start is called before the first frame update void Start() enemyRb GetComponent lt Rigidbody gt () Player GameObject.Find( quot Player quot ) this.transform.LookAt(Player.transform) Update is called once per frame void Update() transform.Translate(Vector3.forward Time.deltaTime speed)


Unity character customization parts I'm relatively new to unity, started a couple weeks ago and so far I managed to setup a character with multiple parts, like hair, head, and body. Here's how it looks like I also managed to import some animation thanks to https www.mixamo.com and everything works perfectly well for now... Now, I'm struggling with the quot change quot part mecanism. I'd like to swap the quot nude quot body mesh part, to an quot armor quot mesh or any other body mesh. Problem is, when I change the model in the SkinnedMeshRenderer it tells me the following with this result I did some reseach about this error message, and it actually makes sense, the given mesh doesn't have any bone setup, bone weights or such. I would like to know if it's possible to use quot common quot skeleton for every models and assign it throught code?


GraphicRaycaster performance OnClick Let's say I have two Canvases BackgroundCanvas and UICanvas. Now, on BackgroundCanvas I have multiple moving, not clickable objects so I removed the GraphicRaycaster ( 69 to performance). On the UICanvas, all the objects are on the UI layer. I also have some additional layers somewhere else. Now, if I change the GraphicRaycaster's (on UICanvas) blocking mask to UI only, would it improve performance if there are other objects on the Default and other layers? Or would it still ray all these objects on other layers? How does this really work? I'm asking cause I don't see any performance impact while switching these Blocking Masks, but after disabling the entire component I do (but the input is not working S).


Does transparency work with SSS in Unity's HDRP Lit shader? I am using Unity's HDRP Lit shader in Shader Graph (all are version 4.8.0 preview) on Unity 2018.3.0b12. I am trying to use both transparency and subsurface scattering on the material. However, it appears that the visual appearance loses SSS when transparency is introduced. Example The cube on the left has transparency enabled, and has no visible SSS. The cube on the right has the same SSS settings as the left cube, however the right cube has no transparency enabled. I need transparency to fade in the cube depending on its position, like this And here is my master node If anyone has an alternative solution that sidesteps this potential limitation, I am all ears. Cheers!


How To Use Unity With C ? In the C Visual Studio installer, there is an option Game Development With Unity. However, after selecting that, I didn't find any changes to regular Visual Studio. So I looked it up, and found no results regarding C . How can I use Unity with Visual Studio for C ?


'Edit Collider' exits after every adjustment When I click the Edit Collider button I can see the collider's region and the handles to adjust it. After every adjustment (with the mouse) the collider outline disappears as Edit Collider finishes. It's frustrating to use, having to reclick Edit Collider after every drag click. How do I stop Edit Collider mode from exiting after every change and only exit if I click the button, or press some commit key?


Add buttons into List when mouse is HoldDown? I have three buttons in my menu. What I need to do is when I click on first button it becomes the first element in my list. Now, when I keep mouse button down and move it to the second button it becomes the second second element in my list. The same with the third button. public List lt GameObject gt UI Button List new List lt GameObject gt (3) void Update() if (Input.GetMouseButtonDown(0)) if (UI Button List 0 null) UI Button List 0 EventSystem.current.currentSelectedGameObject.gameObject if (UI Button List 0 ! null amp amp UI Button List 1 null) UI Button List 1 EventSystem.current.currentSelectedGameObject.gameObject if (UI Button List 0 ! null amp amp UI Button List 1 ! null amp amp UI Button List 2 null) UI Button List 2 EventSystem.current.currentSelectedGameObject.gameObject end if


how to detect Unity UNET errors? I'm working on a simple multiplayer online game. and I use UNET and Networkmanager. In my game I have some rooms and players that they can join to this rooms by connecting to specific server.exe file that I runned on a dedicated server. My problem is when I use port 7777 for first server, if I run another server, then this error Appear Cannot open socket on ip ,and port 7777 For now I solved this issue by building servers with specific ports. for example in server1.exe I used port 7777 by default. and server2.exe , 7778 and same for other servers . But I want to do this automatically. I mean when the server recognize port 7777 is busy , then increase port number. I want to know can I use try catch for this kind of errors ? because I used try catch but it's not work. I don't know how to use it. this is part of my code try StartServer() catch(Exception ex) networkPort then change port number and run server again I just looking for a way that my servers run by choosing right port automatically.


How do I stop rotation after colliding with a specific object? How do I stop rotation after colliding with a specific object? I want player to stop rotating when they collide with walls. I am using Unity, with C .


How can I reduce the size of bundled Unity DLLs on Android? I have created a simple project (I am a Unity beginner) for Android but the apk size is around 18 MB! I checked the documentation. One way to decrease the apk size is to check the editor log. Then I discovered that imported DLLs have a size of 3.9MB. I only used UnityEngine and Collision packages. So how can I avoid to import the other big DLLs?


How to make a string from the words of a file in Unity? I have .txt file containing all the English words separated by line breaks. I want to turn them to a string so I can easily pick a random one from them. The way I would do that in normal C is the File.ReadAllLines(path) function in the System.IO namespace. But, I don't think that I can use System.IO with Unity so the alternative that I could come up with is the TextAsset class which I can use to reference an imported text asset and get its text property as a string. But, if I have a giant string how can I simply split it up into individual words and store them as a string ?


"Your license does not cover Android Publishing" error I recently installed Unity 2017.1.0f3. I imported a project from an older version of Unity it worked perfectly and allowed me to build for Android. I logged in to the Asset Store through the tab in the Unity editor, now I can no longer build for Android. This is the error I receive I created my Unity account before Android was free. Is there a way to update my account to allow me to build with Android again?


Intantiating objects across multiple container pages I have this script here that generates buttons based on an array and a serialized grid transform public void InitializeUI() LevelItem levelItemsArray LevelSystemManager.Instance.LevelData.levelItemArray for (int i 0 i lt levelItemsArray.Length i ) if (i n 0) sets it to 15 LevelButtonScript levelButton Instantiate(levelBtnPrefab, levelBtnGridHolder) levelButton.SetLevelButton(levelItemsArray i , i, i LevelSystemManager.Instance.LevelData.lastUnlockedLevel) var page GameObject.FindObjectOfType lt UI.Pagination.PagedRect gt () page.AddPageUsingTemplate() Now what I'm trying to do is make that array instantiate a new page (calling the page.AddPageUsingTemplate() function which is from another script) once for every 15 items of the array. I have 75 levels and want to instantiate the buttons on a new game object which has a grid layout group, so it would be 15 buttons on each grid with 5 pages grids in total. I do indeed get 5 pages when I run this code, but since the transform is only set to the first one the buttons don't get placed on the other pages. How can I place buttons after the first 15 on the following pages?


Gamemaker vs Unity2d Speed of Development I know coding, so programming is not a problem Money is not a problem at all, I can get both GameMaker Master Collection and Unity Pro I want to make a 2d game. So which one is better for speed of development? On which one would I be able to finish my project earlier?


How to set up bloom in Unity Last time I used image effects in Unity it was back when 3.0 was released and for bloom you used the object's alpha to indicate whether it should glow or not. Now in 4.2 I couldn't grasp how to apply the image effect properly. It seemed to put the whole scene to glow and alpha did not affect it. There was no help from the Unity docs which are pretty much just spec sheets for the effects and no proper tutorials around. This leads to couple of questions How do you create something like the screenshots in the Bloom page in the docs? Only the car windows and metal parts glow, but no glow on the concrete. How do you make a light source like the second image on the above link? I tried different shaders and lights on a gameobject but none of them produced anything like that. What does the HDR checkbox in the camera actually do?


How can I make object to follow first person character and the camera without making the object child? using System.Collections using System.Collections.Generic using UnityEngine public class ObjectFollowCamera MonoBehaviour public Transform cameraToFollow public Transform objectToFollow public float distanceFromCamera private void Update() objectToFollow.position new Vector3(cameraToFollow.position.x,cameraToFollow.position.y,cameraToFollow.position.z distanceFromCamera) This script is attached to a empty GameObject. The objectToFollow will move once i'm moving the Player with the keys. But when i'm rotating the camera of the player around the objectToFollow is not moving. The Player have attached to it Character Controller , First Person Controller , Rigidbody And the Camera is child of the Player.


Unity wall jump issue I've got a very annoying problem that I have been stuck on for a few days and I can't figure it out. It is for a wall jump. I basically want my wall jump to have a bit of force away from to wall to make it look and feel better than just jumping up straight. The problem is, when i add a force on the x axis, it does not register when i am also holding the arrow towards the wall. If I am not holding down the walking button, then press jump...then the x force works. I have a feeling that the horizontal axis force is competing with the opposite force that i want to add to the player when he hits the jump button... Walking code private void ApplyMovement() if (isGrounded) myRigidbody.velocity new Vector2(movementSpeed movementInputDirection, myRigidbody.velocity.y) else if (!isGrounded amp amp !isWallSliding amp amp movementInputDirection ! 0) Vector2 forceToAdd new Vector2(movementForceInAir movementInputDirection, 0) myRigidbody.AddForce(forceToAdd) if (Mathf.Abs(myRigidbody.velocity.x) gt movementSpeed) myRigidbody.velocity new Vector2(movementSpeed movementInputDirection, myRigidbody.velocity.y) else if (!isGrounded amp amp !isWallSliding amp amp movementInputDirection 0) myRigidbody.velocity new Vector2(myRigidbody.velocity.x airDragMultiplier, myRigidbody.velocity.y) if (isWallSliding) if (myRigidbody.velocity.y lt wallSlideSpeed) myRigidbody.velocity new Vector2(myRigidbody.velocity.x, wallSlideSpeed) Jump code private void Jump() if (canJump amp amp !isWallSliding) myRigidbody.velocity new Vector2(myRigidbody.velocity.x, jumpForce) numberOfJumpsLeft else if ((isWallSliding isTouchingWall) amp amp !isGrounded amp amp canJump) isWallSliding false numberOfJumpsLeft Vector2 forceToAdd new Vector2(wallPushForce facingDirection, wallJumpForce wallJumpDirection.y) myRigidbody.AddForce(forceToAdd, ForceMode2D.Impulse) Where I call The code void Update() CheckInput() private void FixedUpdate() ApplyMovement() private void CheckInput() movementInputDirection CrossPlatformInputManager.GetAxisRaw("Horizontal") if (Input.GetButtonDown("Jump")) Jump() if (Input.GetButtonUp("Jump")) myRigidbody.velocity new Vector2(myRigidbody.velocity.x, myRigidbody.velocity.y variableJumpHeightMultiplier) Any help would be much appreciated. Thanks in advance


Why use Time.deltaTime in Lerping functions? To my understanding, a Lerp function interpolates between two values (a and b) using a third value (t) between 0 and 1. At t 0, the value a is returned, at t 1, the value b is returned. At 0.5 the value halfway between a and b is returned. (The following picture is a smoothstep, usually a cubic interpolation) I have been browsing the forums and on this answer I found the following line of code transform.rotation Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime) I thought to myself, "what a fool, he has no idea" but since it had 40 upvotes I gave it a try and sure enough, it worked! float t Time.deltaTime transform.rotation Quaternion.Slerp(transform.rotation, toRotation, t) Debug.Log(t) I got random values between 0.01 and 0.02 for t. Shouldn't the function interpolate accordingly? Why do these values stack? What is it about lerp that I do not understand?


Child transform's position not updated as parent moves I have a parent game object Object1. It has a child, which is simply an empty game object called ReferencePoint. ReferencePoint can be any arbitrary point on Object1 itself. I have another game object Object2. It has a public field called RotationReference, of type Transform. In the inspector, the ReferencePoint on Object1 is assigned to the RotationReference field on Object2. As Object1 moves, I expect ReferencePoint to change its position as well. Object2 is supposed to change its rotation to face its RotationReference in this case, the ReferencePoint on Object1 public override void Rotate() Vector3 relativeRotationReferencePosition this.RotationReference.position this.transform.position this.transform.rotation Quaternion.LookRotation(relativeRotationReferencePosition) However, I noticed that Object2 is not rotating at all, even when Object1 is moving. When I step through the call stack multiple times, I discover that this.RotationReference.position always has the same value, even though Object1 is moving. What am I missing here?


Why does Unity Eventsystem lag on first touch? Hi I am making a very simple simple platformer game for android devices. I am using Unity's event system for player movement. The problem is when I touched the button first time there is a lag (hiccup) after then everything is ok. I have profiled my game there is a spike in EventSystem Update method. here is the simplified code, using System.Collections using System.Collections.Generic using UnityEngine RequireComponent (typeof(Rigidbody2D)) RequireComponent (typeof(BoxCollider2D)) public class PlayerController MonoBehaviour public float movementSpeed 5f public float jumpForce 5f public float distanceToGround 0.2f public LayerMask staticCollider public playerState state private Rigidbody2D rBody public Transform leftmost public Transform rightmost Collider2D platforms new Collider2D 2 public int hrInput 0 Use this for initialization void Start ( ) rBody GetComponent lt Rigidbody2D gt () FixedUpdate is framerate independent, and therefore completely unrelated to your framerate void FixedUpdate () state.grounded isGrounded () if (hrInput gt 0) MOVE RIGHT () else if (hrInput lt 0) MOVE LEFT () else STOP MOVE () public bool isGrounded() print ("ground") if (Physics2D.OverlapAreaNonAlloc (leftmost.position, rightmost.position, platforms, staticCollider) gt 0) return true else return false public void setHrInput (int h ) print (h) hrInput h public void JUMP() if(state.grounded) state.onAir true rBody.AddForce(Vector2.up jumpForce, ForceMode2D.Impulse) rBody.velocity Vector2.up jumpForce public void MOVE LEFT() rBody.velocity new Vector2 ( 1 movementSpeed Time.deltaTime, rBody.velocity.y) public void MOVE RIGHT() rBody.velocity new Vector2(1 movementSpeed Time.deltaTime, rBody.velocity.y) public void STOP MOVE() rBody.velocity new Vector2(0,rBody.velocity.y) end Here is the profiler Image. Please help me to fix this issue.


Changing Pixels Per Unit First off, excuse my ignorance. I am just getting started in game dev. and ran into a little issue. So I had these weird rippling lines going across my screen, and saw in a couple forums that this means I don't have what is called a quot pixel perfect quot game. To fix this, I am supposed to change the pixels per unit of each sprite down to 1. Currently I had it on 32 because that is my sprite size and I am a complete noob. Now, I change it down to one but it completely destroyed my game. Everything that is generated on my map grid is sucked into the center in this giant orb of sprites (I procedurally generate my map off a grid of 1 0s). I am guessing there is just a setting or some such thing that I am missing. Any ideas? Also would be happy with an alternative to remove the rippling lines.


Euler (right handed) to Quaternion (left handed) conversion in Unity I'm having trouble figuring out the proper conversions from Euler angles to Quaternions. The Eulers come from BVH files, which use a right handed coordinate system (Y is up, Z is forward) and can have any rotation order specified. The Quaternions are in Unity, which is left handed (Y is up, Z is back). I'm composing the Quaternions from three AngleAxis rotations, but messing up the order somewhere. So far I can't find understandable and generalized information for doing these types of conversions. public enum AxisOrder XYZ, XZY, YXZ, YZX, ZXY, ZYX, None public Quaternion EulerToQuat(Vector3 eulerAngles, AxisOrder rotationOrder) I've tried various combinations of axis angles here, but would like to understand what's wrong rather than brute force every combination var xRot Quaternion.AngleAxis(eulerAngles.x, Vector3.left) var yRot Quaternion.AngleAxis(eulerAngles.y, Vector3.down) var zRot Quaternion.AngleAxis(eulerAngles.z, Vector3.back) switch (rotationOrder) case AxisOrder.XYZ return (xRot yRot) zRot case AxisOrder.XZY return (xRot zRot) yRot case AxisOrder.YXZ return (yRot xRot) zRot case AxisOrder.YZX return (yRot zRot) xRot case AxisOrder.ZXY return (zRot xRot) yRot case AxisOrder.ZYX return (zRot yRot) xRot return Quaternion.identity ...and converting translation data like so (I believe this is working) public static Vector3 BvhToUnityTranslation(float xPos, float yPos, float zPos) return new Vector3(xPos, yPos, zPos) If anyone can help me better understand how to conceptualize coordinate system conversions, and where I'm going wrong, I'd greatly appreciate it.


Combining lots of small polygons to one (some) big poly(s) I am looking for algorithm to merge lots of relatively small 2d polygons to one or some big polygons. In case two small polygons are touching or overlapping, they should be merged to one polygon. My big goal is to sufficiently decrease amount of points lines required to describe collider. Resulting collider can include some polygons, btw. Could you propose an algorithm or library to do this? (Finally I will implement solution in C for Unity3d). P.S. Here is one picture of task I need to solve. Look this http epsiloncool.ru i E20160624 224050.png Green lines is a colliders. I need to merge them all to get one collider (or some)


How can I add a delay for each moving object? The waypoints script using System.Collections using System.Collections.Generic using System.Linq using UnityEngine public class Waypoints MonoBehaviour public Transform objectToMovePrefab public int numberOfObjectsToMove 1 with this approach, you use GameObjects to represent your waypoints (they can be empty if you want the waypoint to be invisible) SerializeField private List lt Transform gt waypoints private void Start() for (int i 0 i lt numberOfObjectsToMove i ) var parent GameObject.Find( quot Moving Object Parent quot ) var objectToMove Instantiate(objectToMovePrefab, parent.transform) objectToMove.name quot Platfrom quot public int Count gt waypoints.Count public Vector3 GetWaypoint(int index) return waypoints index .position Then in the editor I added this script to the prefab using System.Collections using System.Collections.Generic using UnityEngine public class WaypointsFollower MonoBehaviour SerializeField private Waypoints waypoints SerializeField private float speed 5f SerializeField private bool goBack false SerializeField private float delay private float startTime private int waypointIndex 0 private void Start() startTime Time.time delay waypoints GameObject.Find( quot Waypoints quot ).GetComponent lt Waypoints gt () void Update() if (Time.time lt startTime) return Vector3 waypoint waypoints.GetWaypoint(waypointIndex) movement float distance speed Time.deltaTime transform.position Vector3.MoveTowards(transform.position, waypoint, distance) check if we've reached the waypoint float threshold .1f how close is considered having reached the waypoint if (Vector3.Distance(transform.position, waypoint) lt threshold) wraps back to 0 when we reach last waypoint if (goBack) waypointIndex (waypointIndex 1) waypoints.Count else if (waypointIndex ! waypoints.Count 1) waypointIndex waypointIndex 1 The delay is working but it's delaying all the WaypointsFollower's so they move at the same time after the delay. I want that even if all the Followers have the same delay value for example 3 so the first one will start moving after 3 seconds then the next follower will start moving after another 3 seconds and so on and not that they all delay for 3 seconds and move together but to make delay so there will be spaces between the followers when they are moving.


Raycast Movement on a sphere so I'm working on a mobile game where I have touch input from a Asset from the asset store. It all works perfectly fine, except for one thing I want to implement a "drag and drop" feature so when I pick up an Item it should follow to the position of my finger. But because the playground is a sphere, I have to do the movement with a Raycast. So my plan is that the item should follow the Raycasts position. My current attempt looks like this public void DragTo(float screenX, float screenY) if (draggingObject null) return Debug.Log("Dragging") Converts the screen space to world space Vector3 mousePosFar new Vector3(screenX, screenY, Camera.main.farClipPlane) Vector3 mousePosNear new Vector3(screenX, screenY, Camera.main.nearClipPlane) Vector3 mousePosF mainCam.ScreenToWorldPoint(mousePosFar) Vector3 mousePosN mainCam.ScreenToWorldPoint(mousePosNear) shoots an ray to the world space RaycastHit hit if (Physics.Raycast(mousePosN, mousePosF mousePosN, out hit)) float step speed Time.deltaTime draggingObject.GetComponent lt Rigidbody gt ().MovePosition(hit.point) I already have tried the following options draggingObject.GetComponent lt Rigidbody gt ().MovePosition(hit.point) draggingObject.GetComponent lt Rigidbody gt ().MovePosition(hit.normal) draggingObject.transform.position hit.point draggingObject.transform.position normal They all work, but they all have really buggy and strange behaviors. Also when I dont freeze the z. axis on the Rigidbody the item just "flies" up on the z axis, until it reaches the camera. Then it teleportes again down and it all starts again. So its flying up on the ray. So if you have any Ideas why this happens let me know. Any help is appreciated. (Also dont forget that its all happens on a sphere) UPDATE It works now. When the dragging began i changed the layer from the object to "Ignore Raycast" and when it end changed it back to "Default".


I want to test the Animator component of a gameobject using nunit, but I am having issues I made a Blender 3D model with animations. Then I used the Animator Controller, and attached it to the model. The Animator Controller has a few Boolean parameter variables like isWaving, isDoing, and isIdle and more variables like that. If, say, a non idle action is true, then the animation of my model transitions to the next one. I am into test driven development, but I have never done it with Unity. I tried writing the following code to test my project SetUp public void SetUp() Crystal GameObject.FindGameObjectWithTag("CrystalModel") CrystalScript Crystal.GetComponent lt CrystalChanPlayer gt () CrystalAnimator Crystal.GetComponent lt Animator gt () unity game animator Test public void ifSetAnimationIstodoThenToDoAnimationIsPlayed() CrystalScript.setAnimationStrategy("todo") set strategy CrystalScript.playAnimation() sets todo boolean to true and idle to false first debug output Debug.LogError("todo is " CrystalAnimator.GetBool("isDoing") " idle is " CrystalAnimator.GetBool("isIdle")) second output Debug.LogError("current state is " CrystalAnimator.GetCurrentAnimatorStateInfo(0).IsName("idle")) Assert.True(CrystalAnimator.GetCurrentAnimatorStateInfo(0).IsName("todoAnimation")) I received the following output "todo is true and idle is false" "true" I think this is because Unity isn't really running, and my Animator doesn't get to update based on the variable changes. The first output assures me that todo is set to true and idle is false, hence the Animator should transition that animation to the todoAnimation. Yet, I can't seem to show that, in my tests. Is there any way to test the Animator class? Are there any design patterns I can use?


Unity 2D Tap to shoot at mouse position on android device Hello everyone i am really stuck at the moment and would appreciate any help if possible. I have my game where i move the player up and down with 2 buttons on the bottom left of screenshot. I also have a button over the entire screen for tap to shoot and this moves the weapon to my finger position where i have tapped and it shoots towards that position using mouse.position. Now the problem is when i am on my android device and i am moving up and down but when i also tap to shoot the gun it moves towards my up and down buttons and this is not what i want. i want to be able to move with my finger and also shoot towards the second finger. Any ideas would be greatly appreciated. Here is my Tap to shoot button code! public void ShootButton() timer 0 Face true if finger presses Shootbutton then activate this Vector3 difference Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.position subtracting the position of the player from the mouse position. difference.Normalize() normalizing the vector meaning all the sum of the vector will be to 1. float rotZ Mathf.Atan2(difference.y, difference.x) Mathf.Rad2Deg find the angle in degree. WeaponTrans.transform.rotation Quaternion.Euler(0f, 0f, rotZ rotationOffset) if (reloading false) if (fireRate 0) Shoot() else if (Time.time gt timeToFire) timeToFire Time.time 1 fireRate Shoot()


Unity Items not being removed from list So I finally perfected my RTS multiple movement. The situation is that the game objects are added into a list in a script bound to the camera called UnitController they are added from a unit client script MultiselectClient, this client accesses the UnitController class and adds itself the gameObject into the list. Each time I do the drag select I want it to clear the list first before adding any more. But for some reason, it doesn't work? This is in my UnitController (below) void MultiSelect(RaycastHit hit) Debug.Log(SelectedUnits) if (SelectedUnits.Count gt 0) Debug.Log("Moving group to " hit.point) foreach(GameObject gameObject in SelectedUnits) gameObject.GetComponent lt NavMeshAgent gt ().SetDestination(hit.point) This is in my client (below) public bool Selected false void Update() if (Input.GetMouseButton(0)) Vector3 camPos Camera.main.WorldToScreenPoint(transform.position) camPos.y Screen.height camPos.y if inside the cameras drag selection area then mark player as selected Selected UnitController.selection.Contains(camPos) Debug.Log("Selected") if(selected) addTo() void addTo() UnitController.SelectedUnits.Remove(gameObject) I have also tried .clear() which also hasnt worked. if (!UnitController.SelectedUnits.Contains(gameObject)) UnitController.SelectedUnits.Add(gameObject) Debug.Log("Added to list " UnitController.SelectedUnits) else Debug.Log("Im already in that list.")


Recenter User Orientation on X and Y axis on with Oculus GO and Unity I am working on an Oculus GO App for patients in a doctors chair. They'll be using Oculus GO Headsets while sitting, lying, or something in between. So what I am trying to do is to recenter the HMD orientation when the HMD is mounted. But since the patients position can be seated or lying horizontally, I will need to recenter the rotation on all three axis, or at least X and Y. Unity provides UnityEngine.XR.InputTracking.Recenter() But that will only recenter the Y Axis. Oculus Integration provides OVRManager.display.RecenterPose() But under the hood its just using the Unity InputTracking.Recenter() again. So how can I recenter my whole scene or the player on y axis as well? If you go to Oculus GO main menue and push the recenter button on your controller, it does exactly what I want. However I can't find a way to do the same thing in my Unity application. Thanks in advance!


How can I prevent pixel artifacts on programatically generated textures? In the game I'm developing, rooms can be of various sizes, which means I need to vary the size of the floor texture appropriately. The way I've solved this problem is to generate a Texture2D programatically, and set each pixel to be transparent (or not) as appropriate appropriately. I get something like this Where, if you look at the top left, you'll clearly see the pixel artifacts from the floor texture against the dark blue background. When I run into this with static textures, the fix is simple. Set the Texture's wrapmode to clamp instead of repeat. But when I try to do that programatically... (and change nothing else!) I get this I'm not quite sure what's happening, or why setting the wrapMode changes the results so markedly. Anyway I can avoid the pixel artifacts? I suppose it's possible to add an extra border around the generated texture (so that all edges can be transparent), but that doesn't seem a particularly clean solution. Code is here void DebugFloorTextureMerge() sizeVector makes up the rectangle circumscribing the room's parallelagram Vector2 sizeVector new Vector2(roomBounds.topRight.x roomBounds.bottomLeft.x, roomBounds.topLeft.y roomBounds.bottomLeft.y) get the texture of the filled sprite Texture2D patternTexture (Texture2D) floorTexture.image make a new texture of the size of the room. Texture2D fillTexture new Texture2D( (int) sizeVector.x, (int) sizeVector.y, TextureFormat.ARGB32, false) COMMENTING THIS LINE OUT MAKES THE TEXTURE WORK WITH ARTIFACTS fillTexture.wrapMode TextureWrapMode.Clamp LEAVING IT IN MAKES THE FOLLOWING CODE WORTHLESS int patternX 0, patternY 0 Vector2 pointVector Color transparent new Color(0,0,0,0) for(int x 0 x lt sizeVector.x x ) for(int y 0 y lt sizeVector.y y ) pointVector new Vector2(x,y) if(roomBounds.Contains(pointVector)) get the next pixel fillTexture.SetPixel(x,y, patternTexture.GetPixel(patternX, patternY)) else pixel was not in the room, so set it to transparent. fillTexture.SetPixel(x,y, transparent) resultx x resulty y increment the pattern counter and reset if necessary. if you only increment this when Contains is true, you'll warp the texture patternY if(patternY gt floorTexture.fillSize.y) patternY 0 increment the pattern counter and reset if necessary. also reset y, so the pattern will line up properly. patternY 0 patternX if(patternX gt floorTexture.fillSize.x) patternX 0 set the PixelChanges. fillTexture.Apply()


Trying to trigger dialogue when the space bar is clicked, and two objects are colliding I'm getting a NullReferenceException on OnTriggerStay. I've been going crazy trying to figure out why. I have tried to cut this down to only the relevent information. I got this code through a tutorial https www.youtube.com watch?time continue 48 amp v nRzoTzeyxU (just for credits). using System.Collections using System.Collections.Generic using UnityEngine RequireComponent(typeof(Rigidbody)) public class MainCharacter MonoBehaviour public int limbs public float speed public Vector3 jump public float jumpForce Rigidbody2D rb public float fire start time Time.time Animator animator public DialogueManager dialogueManager Checking if we are grounded public bool isGrounded public LayerMask groundLayers private SpriteRenderer myRenderer public Sprite LimbSprites void Start() dialogueManager gameObject.GetComponent lt DialogueManager gt () public void OnTriggerStay2D(Collider2D collision) if (Input.GetKey(KeyCode.Space)) Dialogue dialogue collision.GetComponent lt Dialogue gt () dialogueManager.StartDialogue(dialogue) Here is my dialogue manager using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class DialogueManager MonoBehaviour public Text nameText public Text dialogueText public Animator animator private Queue lt string gt sentences Use this for initialization void Start () sentences new Queue lt string gt () public void StartDialogue (Dialogue dialogue) animator.SetBool("IsOpen", true) nameText.text dialogue.name sentences.Clear() foreach (string sentence in dialogue.sentences) sentences.Enqueue(sentence) DisplayNextSentence() public void DisplayNextSentence() if (sentences.Count 0) EndDialogue() return string sentence sentences.Dequeue() dialogueText.text sentence void EndDialogue() animator.SetBool("IsOpen", false) Here is DialogueTrigger using System.Collections using System.Collections.Generic using UnityEngine public class DialogueTrigger MonoBehaviour public Dialogue dialogue public void TriggerDialogue () FindObjectOfType lt DialogueManager gt ().StartDialogue(dialogue) Here is Dialogue using System.Collections using System.Collections.Generic using UnityEngine System.Serializable public class Dialogue MonoBehaviour public string name TextArea(3, 10) public string sentences


Move relative to screen I use top down 60 degree tilted camera and want move always visually straight directions relative to screen (up, down, left, right). When object is near screen edges it starts moving diagonally (visually) probably because of camera tilt. I tried with WorldToViewportPoint ViewportPointToRay but it doesnt work exactly because even when there is no input, conversion to viewport and back to world same value sometimes gives slighltly offset from start position. float delta Time.deltaTime float h Input.GetAxisRaw("Horizontal") float v Input.GetAxisRaw("Vertical") Vector3 view MainCamera.WorldToViewportPoint(transform.position) view.x (h gt 0) ? 1 (h lt 0) ? 0 view.x view.y (v gt 0) ? 1 (v lt 0) ? 0 view.y Ray ray MainCamera.ViewportPointToRay(view) RaycastHit hit Physics.Raycast(ray, out hit, Mathf.Infinity, 1 lt lt 15) 15 ground plane layer Vector3 world new Vector3(hit.point.x, transform.position.y, hit.point.z) Vector3 dir (world transform.position).normalized transform.position dir Speed delta


Unity how to position items into a Scroll View? I'm trying to add items (prefab) into a Scroll View but either if I simply add items without set positions and trying to setting position it not work. Case 1 without setting position Result All items overlapping Case 2 forcing positions (like commented row code below) Result Items not overlapped but X position take the same value (that not is 0) for (int i 0 i lt rows.Length i ) GameObject newObj Instantiate(MyRowPrefab) newObj.transform.SetParent(ScrollViewObject.transform, false) newObj.transform.localPosition new Vector3(0, ( 1 ((i rowHeight))), 0) If i decomment this line, X isn't set to zero... why ?


Unity Animation parameters are not being set I have the following animation controller with two parameters of walkingSpeed and Jump. I have the following code which should change the values animator.SetFloat("walkingSpeed",0.9f) animator.SetBool("Jump",true) and animator is the correctly referenced animator object. However the values that the parameters are set to do not appear to change in the animator window, nor do they appear to impact what is happening on the screen. However they do seem to impact the values obtained when doing the following animator.GetFloat("walkingSpeed") The animator consists of the shown blend tree, which works correctly and is always active, however due to the values not being changed it does not blends, and always acts as if the value with which it blends (walkingSpeed is 0). What is going on?


Why do I get this error with FB.LogInWithPublishPermissions? I don't know what's wrong. I know that FB.Login is already deprecated. I don't know what syntax to use. public class FBholder MonoBehaviour void Awake() FB.Init (SetInit, OnHideUnity) private void SetInit() Debug.Log ("FB Init Done") if (FB.IsLoggedIn) Debug.Log ("FB Logged in") else FBlogin () private void OnHideUnity(bool isGameShown) if (!isGameShown) Time.timeScale 0 else Time.timeScale 1 void FBlogin() FB.LogInWithPublishPermissions ("user about me, user birthday", AuthCallback) void AuthCallback(ILoginResult result) if (FB.IsLoggedIn) Debug.Log ("FB Logged in worked") else Debug.Log ("FB Logged in failed") and I'm getting this error Assets FBholder.cs(40,6) error CS1502 The best overloaded method match for Facebook.Unity.FB.LogInWithPublishPermissions(System.Collections.Generic.IEnumerable, Facebook.Unity.FacebookDelegate)' has some invalid arguments and this Assets FBholder.cs(40,35) error CS1503 Argument 1' cannot convertstring' expression to type System.Collections.Generic.IEnumerable'


how can i fix my code in order to get rid of the error that says that the object I want to instantiate is null? using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class replicate MonoBehaviour public void replicateCube(InputField T) int H int.Parse(T.text) for (int i 0 i lt H i ) GameObject prefab Resources.Load("Cube") as GameObject GameObject go Instantiate(prefab) as GameObject go.transform.position new Vector3(0, i 5, 0)


Sprite editor "minimum size" feature alternative in Unity 5 As you know , unity has been removed its minimum size feature in sprite editor multiple auto slice mode. In some pics Unity discovers a lot of tiny rubbish sprites for example as 4x3 or 10x5 pixels. Is there anyway to set minimum size for good auto slicing in Unity 5?


Help with the calculation of the usage of my speed stat I am working on a freeroam, action RPG (before you read further, I am not noobish to programming, plus have friends to help with actual content rather than the base code). Anyway, I am trying in Skills to the game. I decided the movement based skills and animations should be a priority, so I began integrating it in. The animations work fine, but alas my movement skill Athleticism is making the character move unrealistically fast at a higher skill. The skill ranged from 1 to 100. After realising I should do some calculations to make you go from normal to Sonic the Hedgehog, I am using this formula currently (Athleticism Mathf.Sqrt(Athleticism)) 0.05f runMod This has helped, but it still looks weird. I need some help to make a formula that makes that the skill doesn't have such of a linear effect on the movement. EDIT Trying to be specific. The player moves, currently about 0.05 walking units per second at Athleticism 10, which is nice. However, the movement rate at Athleticism 100 cranks up to 0.15 units, which is a little too fast. I am aiming for 0.1 instead.


How to rotate an object to a specific transform? I am working on a car racing game and there are some times when the car rotates and ends up on its roof. On those situations I want the car to respawn on the same location. What can I do to rotate it so the car ends up on its wheels?


Tile set showing grid with lighting Hi so I have this tile set generated procedurally at the start of the scene. When I activate the point light in the middle of the screen I keep getting this grid in the game view, i tried changing the size of the tiles but no luck if I change them before pressing play in the game view. But if I do it at run time from the inspector the bug goes away , hiding the square of the tile that I have moved...for that tile in particular even just moving it a bit solves it. This happens in edit and game mode ,and the grid is made of loads of sprites put together. The import settings of these sprites is dont generate mip maps, no compression. And each of the tiles have the default shader sprite diffuse. I deactivated gizmos but no luck either Any idea what can this be ? anything related with baking the light or something? thank you for your help!


How to override the NetworkManager in Unet properly? I need some customization on the NetworkManager Class for my game I'm working on. I've read, that it's pretty common to override stuff from the NetworkManager. So I've implemented the NetworkManager as CustomNetworkManager class like this using UnityEngine.Networking public class CustomNetworkManager NetworkManager I hope I'm right, that I don't have to implement a method to get all the functionality from the base class? I duplicated my NetworkManager Object, which basically was just the NetworkManager with another CustomNetworking Script. Then I replaced the old NetworkManager with my new CustomNetworkManager and changed the references in the other script accordingly. So my old GameObject looks like this And this is my new GameObject The old GameObject works (I just have to change the NetworkManager type in my CustomNetworking class) But the new GameObject with the custom implementation is getting the following error NullReferenceException Object reference not set to an instance of an object CustomNetworking.EnableMatchmaker () (at Assets CustomNetworking.cs 27) The CustomNetworking class with the error looks like this using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Networking using UnityEngine.Networking.Match using UnityEngine.Networking.Types public class CustomNetworking MonoBehaviour public CustomNetworkManager manager public MatchInfo currentMatch Use this for initialization void Start() manager GetComponent lt CustomNetworkManager gt () public void EnableMatchmaker() manager.StartMatchMaker() This is the first call which is made and where the error occurs public void CreateMatchmakerMatch() manager.StartMatchMaker() manager.matchMaker.CreateMatch( manager.matchName, manager.matchSize, true, "", "", "", 0, 0, manager.OnMatchCreate) public void FindMatchmakerMatch() manager.matchMaker.ListMatches(0, 20, "", false, 0, 0, manager.OnMatchList) if (manager.matches ! null) for (int i 0 i lt manager.matches.Count i ) var match manager.matches i manager.matchName match.name manager.matchMaker.JoinMatch(match.networkId, "", "", "", 0, 0, manager.OnMatchJoined) public void DestroyMatchmakerMatch() manager.client.Disconnect() manager.matchMaker.DropConnection(manager.matchInfo.networkId, manager.matchInfo.nodeId, 0, manager.OnDropConnection) manager.matchMaker.DestroyMatch(manager.matchInfo.networkId, 0, manager.OnDestroyMatch) manager.StopMatchMaker() public void StartMatchmakerMatch() manager.StartClient() manager.ServerChangeScene("MainScene") I think I did some failure with implementing the overwritten NetworkManager, hopefully someone can help me with this issue.


Stuck on walls or sliding on top dilemma I'm making a 2.5D platformer game. I earlier had problem with my character getting stuck on walls when holding the forward button. I solved this problem by adding a physics material with zero friction to my colliders on the wall. So now when hitting a wall the character slides down, which is correct. My walls consits of 1 unit cubes tiled together, and box colliders are generated and merged at runtime. Now I've created a ladder and by pressing a button the player will rotate 180 degrees, and I also add some force along the y and z axis var force transform.forward Vector3.up force.y JumpOffForceY force.z JumpOffForceZ rigidBody.AddForce(force, ForceMode.Impulse) Now when the player lands on the top of the wall, which has the same box collider, and physics material, the player slides very jerky for a long time before coming to a halt. I understand why this happens, I've been trying to find a solution. One solution I'm thinking of is to change my algorithm that creates the box colliders and divide them so there is one box collider on the top with higher friction, and one for the walls with zero friction. Before I delve into that, is that a good solution? Or is there any other way? Have a nice day!


Should I be concerned that my microtransaction based game will often be hacked? I used to play Diablo II, both online and offline. The game was so easily hackable offline that one could download a program called Hero Editor and, using a nice, comfortable interface, change their character in many ways. However, it was harder to hack the online portion of the game, and many that did were caught. Thus some of the game s content was restricted to online play, doubling up as a way to promote people playing together. Now I m making a mobile TD using Unity, targeting the iOS, Android, and perhaps PC Mac Linux platforms initially. Players would slowly earn some rare currency during play that can be used for permanently unlocking exciting (but non essential) extras, or they can just pay for them. I m concerned that if I allow this gradual unlocking to happen offline (without a server to confirm the accrual of said currency), then it ll be as easily hacked as Diablo II s offline mode and that many people would simply resort to doing that instead of either playing it through or paying for it. However, I m also reluctant to force online play, as the mobile environment has significantly lower network stability and this is a relatively long game to be playing in such conditions, so drop out is very likely. So my question is how concerned should I be about the mobile game getting hacked for the purpose of acquiring these unlocks without going through the correct methods? Is it so easy that your average user could do it, like they could for Diablo II, having the potential to significantly damage the game s bottom line? Or is it difficult such that only a small percentage of people who are interested enough would bother to try, so I can focus on providing the best UX for all players without worrying about these hackers? Brownies for anybody who can summarise how it may actually be hacked!


Unity Free Inverse Depth Mask? How would it be possible to create an inverse depth mask? In this case, I refer to a depth mask as a shader attached to a mesh that 'pokes a hole' through the current camera layer to let you see the camera render layer one depth down, usually by using ColorMask 0. What I want is for, instead, the mesh to determine what ISN'T cut out, without everything that is NOT seen through the mesh being cut out.


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 can I turn a Unity game into an MRAID compliant playable ad? I need to create a mini game, one really simple scene, and export it as a playable that comply with the MRAID requirements. Basically, I can export a WebGL. The question is which adaptations the code needs to have (if any) in order to become compatible with MRAID. I saw the Luna tool that claims to solve this issue and export the scene on its own engine, to avoid any future adaptations, but honestly, I don't really understand what they're doing differently, if their engine still converts to JS and HTML5. It seems really blurry at the moment and I can't find concrete, coherent answers. All I'm getting from the company that approached my to get it done is quot it needs to be MRAID compatible quot . Does anyone have any experience and can shed some light on this subject? Thanks in advance, Omer


Can Unity support use textures that are not square? I have been told by another highly skilled Unity artist that Unity cannot efficiently handle non square images. Since that doesn't sound right to me, I wanted to get a second or third confirmation to that claim. Having worked in the game development industry for almost 15 years, I have always understood that best practice was keeping in powers of two, but that if the UV map called for it, a 1024x512 map was acceptable, rather than using a 1024x1024 map with 1024x512 pixels of wasted UV space. Granted, that was best practice on game engines other than Unity. Can anyone confirm that in Unity's case, it is better (best practice) to have a 1024x1024 image containing UV islands occupying 1024x512 pixels, rather than using a 1024x512 image map to exactly accommodate the UVs? Which platforms can use non square images and which ones cannot with the Unity engine? I am particularly interested in whether or not this limitation affects PC builds.


Unity Serialize IConvertible variable How can i Serialize IConvertible variable to show up in the inspector? As it now, i can only see the string name. But not the value. E.g adding CStat item.AddCStats("description", "This a long ranged boosted weapon.") item.AddCStats("attack", 10) item.AddCStats("speed", 50f) item.AddCStats("unique", true) System.Serializable public class Item ISerializationCallbackReceiver SerializeField public int id 0 SerializeField public int amount 1 SerializeField public List lt CStats gt cstats new List lt CStats gt () public Dictionary lt name, IConvertible gt cstatsDictionary new Dictionary lt name, IConvertible gt () public Item(int id, int amount) this.id id this.amount amount public void AddCStats lt T gt (string name, T value) where T IConvertible if (!cstatsDictionary.TryGetValue(name, out )) cstatsDictionary.Add(name, value) else cstatsDictionary name value for (int i 0 i lt cstats.Count i ) if cstats i .name name) cstats i .value value return cstats.Add(new CStats(name, value)) public T GetCStat lt T gt (string name) where T IConvertible return cstatsDictionary.TryGetValue(name, out IConvertible value) ? ConvertToType lt T gt (value) default public void OnAfterDeserialize() cstatsDictionary new Dictionary lt string, IConvertible gt () for (int i 0 i lt cstats.Count i ) cstatsDictionary.Add(cstats i .name, cstats i .value) public void OnBeforeSerialize() private T ConvertToType lt T gt (IConvertible value) where T IConvertible return (T)value.ToType(typeof(T), null) System.Serializable public class CStats SerializeField public string name String.empty SerializeField public IConvertible value null public CStats(string name, IConvertible value) this.name name this.value value


How do you render planets without distortion? I've recently been working on a little spaceship flying sim in Unity and want to add planets. Up till now, I've been hand modeling them in Blender. But I want to have a way to generate large planets with heightmaps. While researching the topic, I found this video about a voxel planet game and its tech, Here. In the video, they describe a way to render a planet with low distortion. They also relate it to how No Man's Sky does it. My question is, Are there other methods of rendering planets that have zero distortion? I would prefer if the answers wouldn't be Unity3D specific since i'm considering switching to Monogame or DirectX. Thanks in advance! Edit. I've been asked to describe the distortion. The distortion is what happens when a cube gets mapped to a sphere. The video suggests a method of using shader warping when on the ground but using the method of squishing a cube to a sphere when in space. This method causes a noticeable warp when going from space to ground because it switches rendering methods. My question is if there is a way to prevent that warp and provide a truly seamless transition from space to ground. One more edit, I have found another video on a seamless planet engine called Outerra here It seems to have no warping when leaving the atmosphere. It can be seen at 0 50 and at2 22 in this video.


How to create rotating mode selection knob on multimeter I want to create something looks similar to this for electrical and electronic troubleshooting simulationw. I need to know how to program the drag interaction that and rotates the knob to select the mode of operation. I checked several videos including this one, but this is not what I'm looking for. I am hoping to drag and rotate the knob in a circle. I also need to know how to set the operating mode based on rotation. For instance, if the knob is pointing at 0 5 degrees (after drag and release), the knob position is set to 0, and the device is in off mode if it is at 85 95 degrees then angle 90 degrees, and the device is set to resistance measurement mode.


How do I set meshCollider.cookingOptions to MeshColliderCookingOptions.Everything in code? I'm procedurally generating some meshes for a project, and I need to add colliders to them. The meshes are generating fine, but after setting the shared mesh in the mesh collider, I need to be able to set the cookingOptions to Everything. In the inspector, I can do this fine and the colliders work correctly. Since I am generating these at runtime, I can't really do this after making a build. How do I go about doing this? Works Correctly Does not Work Correctly


Unity open UI from ScriptableObject I have a Canvas that has multiple UI Panels in it for an inventory, crafting, etc. To open these panels I currently have a monobehaviour class on the Canvas with methods like OpenInventory(), etc. For every item within the inventory I use ScriptableObjects. However, some items open the crafting panel when right clicking, I created a class that extends the Item class and added a method to it that gets added to the inventory slot and gets called when right clicking that item. Because the monobehaviour on the Canvas is an instance, I can't access it from a ScriptableObject. Long story short, is there a way to open a UI panel from a ScriptableObject? If not, what would be the best way to fix this issue?


An invisible object that deletes anything behind it? I am using augmented reality to put a 3D object on top of a "camera detected" object. The 3D object can be though of as leaves that go above the real world object but also fall in front behind on the sides of it. The leaves are not uniform so they appear as arcs which let more of the "camera detected" object be seen in some parts and less in others. Because of this I want to only show the leaves that would normally be seen if there was a real 3D object (instead of the camera detected one) in that place. But since the camera detected one is just a background image part of the leaves on the side or behind are seen when the object is rotated. I was thinking it might be possible to use an "invisible" object that moves and rotates the same way as the "camera detected" one so it behaves as a placeholder for depth testing but is not actually rendered. Is this possible? May I have some pointers on how to achieve this? Thank you


FBX animation works in 3DSMax but not with Assimp I have an FBX file that represent a plane with an animation of the gear opening. In my editor 3DSMax or in the Unity editor, the file and animation seem good, but when I use Open 3D Model(the official viewer of Assimp) or when I call the FBX file simply in an application, to see what the file will look like with the use of Assimp, I got some issues. The object seems normal at the beginning, but when I try to launch the animation, all my animated elements are going crazy. Here's what it looks like Here's my FBX FILE Do you have experience something similar ? Does it come from my file or a parameter in Assimp ? I am beginning to think that there is a problem with how Assimp handles pivot points, looks like objects are rotating using a different pivot point in Unity open3mod.


How to set "useGravity" for Rigidbody to entities in Unity For the position you can use this Inject private ComponentDataFromEntity lt Position gt position But cant use it for Rigidbody. How to access the parameters for Rigidbody for entities?


Setting a texture's "Max Size" while ensuring that its dimensions are still multiples of 4 A version of my game has several large textures with dimensions that are multiples of 4 so that Crunch compression can kick in. A ported version of my game, for platforms that have very limited RAM restrictions, will need us to limit the quot Max Size quot of our textures to 512 or 256, etc. There are some cases in which a Crunch friendly texture, when resized by Unity's quot Max Size quot parameter, will actually end up with dimensions that aren't multiples of 4. 944x800 would end up as 512x434, if we select quot 512 quot , which isn't good for Crunch. The naive solution in my mind is to write a simple script tool that resizes pads all my textures by a couple of pixels in such a way that Unity's resize will end up in a Crunch friendly way. However, I'd rather do that as a last recourse if possible. Is there a more standard way to approach this situation of mine?


Unity UNET, problems spawning and then destroying that instantiated prefab I am very new to networking, and have ran into an issue, read below. I have multiplayer system setup, where players can spawn, they can pick up weapons and drop them, there is an object representing a pickup with network identity component attached and local player authority enable, the player can come up to it and press "E", which will destroy the pickup object, then the player can press I to to "drop" that weapon, which instantiates it infront of the player, now this is what should happen, and it works on single player, but when there's 2 players, for second player(client only) it doesn't work as it should. I have 1 script weapon manager and another small, Pickup (on pickup object child with trigger). Below is the code and according description of my attempt so far Below is PickUp script (on 1st child of pickup object with trigger enabled) private void OnTriggerStay(Collider other) if (other.CompareTag("Player")) if (Input.GetKeyDown(KeyCode.E)) Call pickup function on player, passing the weapon id and parent gameobject other.GetComponent lt WeaponManager gt ().PickUpWeapon(weaponID, transform.parent.gameObject) Below is WeaponManager script (on player) public void PickUpWeapon(int id, GameObject go) CmdDestroyObj(go) ... (other code, not relevent) Command void CmdDestroyObj(GameObject obj) RpcDestroyObj(obj) ClientRpc void RpcDestroyObj(GameObject obj) HERE obj is NULL (!!ERROR!!) Destroy(obj) Above in RpcDestroyObj() obj is null void Update() if(isLocalPlayer) if (Input.GetKeyDown(KeyCode.I)) if (slots currentActiveSlot ! null) CmdDropWeapon() Then here's CmdDropWeapon() function Command void CmdDropWeapon() RpcDropWeapon() Here's RpcDropWeapon() function ClientRpc void RpcDropWeapon() GameObject drop (GameObject)Instantiate(drops currentGun.GetComponent lt WeaponStats gt ().id , transform.position transform.forward, Quaternion.identity) drop.GetComponent lt Rigidbody gt ().AddForce(transform.forward 25000f Time.deltaTime) CmdDestroyWeaponHeld() Destroy currently held weapon (don't pay attention, not relevent to current problem currentGun null if (isLocalPlayer) GetComponent lt PlayerSetup gt ().playerUIInstance.GetComponent lt PlayerUI gt ().SetInventorySlotFill(currentActiveSlot, 1) emptyHanded true On single player (so host amp client), everything works besides destroying the pickup prefab that is Instantiated. On multiplayer, second player (client only), can pick up and drop weapons as well as the originally spawned weapon is destroyed, but destroying the newly instantiated (so after player drops it) pickup object doesn't work. (In the console there are no errors when UnityEditor is the Lan host server, when 2 players are playing and I try picking up and dropping weapons several times from client side) Why is this not working? I would appreciate any help assistance in getting this right and sync over network for all players. My guess is that, rpc function Instantiates the drop prefab but it's kind of different on all clients, so the server or another client doesn't have exactly the same object in the scene which means it will not find it and return null. Let me know if you need any additional information. Thanks a lot in advance!


Why does my terrain turn white when I get close to it? When I zoom in on my terrain it goes white The further in I zoom, the greater the whiteness becomes. Is this normal? Is this to speed up rendering or something? Can I turn it off? I'm also getting these error messages in the console over and over again rc.right ! m GfxWindow GetWidth() rc.bottom ! m GfxWindow GetHeight() and GUI Window tries to begin rendering while something else has not finished rendering! Either you have a recursive OnGUI rendering, or previous OnGUI did not clean up properly. Does this bear any correlation on the issue? Update I create virtual desktops to flit between using the program Deskpot. Turning this program off and restarting has stopped the above errors appearing in the console. However, I still get white terrain when I zoom in. Not a single error message. I've restarted my computer to no avail. I have an Asus NVidia GeForce GTX 760 2GB DDR5 Direct CU II OC Edition Graphics Card. Any known issues? Update I don't think it's fog...


I can not proceed to my room menu using photon in unity when i use PhotonNetwork.JoinRoom() I have a TextMeshProUGUI called EnterRoomName and I am trying to enter the name of the room that I'm supposed to enter, but it's not working. This is my function public void JoinRoom() PhotonNetwork.JoinRoom(EnterRoomName .text) MenuManager.Instance.OpenMenu( quot loading quot )


Multiple Sprite animation layers overlayed in Unity Animator I have an animator with two layers, an axe layer and a body layer. I would like to animate the two in sync with each other. They are both 64x64 sprite animations, frame by frame bitmaps. The problem I'm having is I can't figure out how to alpha blend the layers. The axe either plays and the player body becomes invisible, or the axe isn't visible. I have a bunch of states like this which each return to an idle state. And link to an animation. I'd post a screenshot but I'm not allowed. The axe layer is set to sync so the state machine looks the same, and I set the motion to the axe animations rather than the character body animations.


Unity, tell matched players to go pick characters (Matchmaking) I need to tell all the players in the match to go to some method that'd take them to character pick. The thing is that the pick happens inside the menu scene after the level get's preloaded (ascyncroneously). So the players stay in the same menu scene but they have to pick characters before the time runs out and the level itself starts. Is it possible to do that in multiplayer using the matchmaker? How can it be done if so? Thanks in advance!


iOS build size is too large in Unity I have finally completed my game and ready to upload my game to the App store, but my build size is too large. I have checked log statement and it is roughly 13.3 mb but when i build my game and test on iOS device it is 80.0 mb. Also Scripting Backend is 'Mono2x' Stripping Level is 'use micro mscorlib' Script Call Optimisation is 'Fast but no Exception' My Game size must be around 15 to 20 mb why it is too large? What i am missing?


Only 1 side is rendered I'm trying to get my .blend object into Unity but for some reason I see it differently in Unity than in Blender. I was trying to solve the problem and someone said that I have to go to the edit mode, then mesh, then change the normals but that is not working for me. Here is what I mean


Is WaitForSecondsRealtime() dependent on machine lag? I was reading the documentation and I'm trying to get some timing down for a few animations. My question is, is the WaitForSecondsRealtime dependent on machine lag or anything? A friend of mine said that WaitForSecondsRealtime was invoked at the kernel level and thus it would be as accurate as possible. Like I said I've read the documentation, but they don't really go into the specifics about how that works. Anyone have any insight?


Limit position rigidbody How can I limit the position of a rigidbody, between two values if I use this code public Vector3 dir Rigidbody rb void Awake() rb GetComponent lt Rigidbody gt () void FixedUpdate() rb.velocity new Vector3(0f, 0f, 6f) rb.AddForce(dir 1f, ForceMode.VelocityChange) If I use Vector3.Clamp then the object will shake


Sprite disappears after adding a material to it I have background which is FirsLayer, order in layer 0 and platform over it which is FirstLayer, order in layer 1. Once I add a material to the platform, the layer doesn't seem to change but it gets rendered behind the background. The material that I add 1)Why do I get such results? 2) How can I add the material to the platform and still keep it above the background? P.S. For further clarification if somebody didn't understand, I expected the sprite to stay on its original position(i.e. not to go behind the background when a material is being added to it)


How to handle global Data within a state machine setup? (C ) I am currently building a turn based framework (Unity,C ) I was tired of my former tight coupled systems and opted for a state machine this time, basically all components subscribe to the state Enter and state Exit event. I am aiming for scalability and structure. But I ran into a problem. If the components cannot communicate directly, how to store and forward data in between states? Example The game starts with unit placement. The player has the option to select a unit in his pool via the ui and place it on the board. The Unit creation logic is and should(?) be handled inside the level script. How does it know where to create which unit? Ive done a workaround with a static container class, with is basically my clipboard. The player assigns a grid cell for his selected unit and the game leaves the state. While leaving the state the level scripts scans the clipboard and creates any assigned units. But I feel like a cheated my attempt to really work strictly within a firm structure this time to guide the design process. Is there a better way?


Instantiating Prefabs at run time I'm trying to move my project to Addressables and upload assets, prefabs and screens to an archive on the server. I'm a new in Unity and this a bit challenging for me. I've prepared all prefabs for addressable usage and now I'm trying load them. All my prefabs have loads throw GameObject.Instantiate For example public class PlatformObject LocationObject other properties and methods public PlatformObject Clone() var clone ((Runner.PlatformObject)GameObject.Instantiate(this)) clone.Id this.Id clone.NextPlatforms this.NextPlatforms clone.IsStartPlatform this.IsStartPlatform clone.Level this.Level clone.Type this.Type clone.MinimumDistance this.MinimumDistance clone.AllowDispose false clone.Size this.Size return clone I've tried change this code for usage Addressables. public async Task lt PlatformObject gt Clone() var handle Addressables.LoadAssetAsync lt GameObject gt (this.name) var clone (await handle.Task).GetComponent lt PlatformObject gt () clone.Id this.Id clone.NextPlatforms this.NextPlatforms clone.IsStartPlatform this.IsStartPlatform clone.Level this.Level clone.Type this.Type clone.MinimumDistance this.MinimumDistance clone.AllowDispose false clone.Size this.Size return clone I've got a cloned object successfully, but object doesn't appears on the scene. Looks like object not initialized properly, bcouz I've got a lot of warnings like that Setting the parent of a transform which resides in a Prefab Asset is disabled to prevent data corruption (GameObject 'Mid Town 07'). UnityEngine.Transform set parent(Transform) I've googled and have found a few solution related with parent location. Made changed but it didn't help. I'm still getting those warnings.


How to Make UI Open and Close on Keypress I've been working on a 2D RPG and have been trying to make a script that will open or close the public UI element that is selected in properties. I don't receive any errors, but I do receive a warning that says Assets Scripts KeyManager.cs(7,18) warning CS0414 The field 'KeyManager.activeUI' is assigned but its value is never used Here's the script that is connected to my canvas using UnityEngine using System.Collections using System.Collections.Generic public class KeyManager MonoBehaviour private bool activeUI public GameObject UI void Start() activeUI false Update is called once per frame void Update() if (Input.GetKeyDown(KeyCode.I) amp amp (activeUI false)) activeUI true UI.SetActive(true) else if (Input.GetKeyDown(KeyCode.I) amp amp (activeUI true)) activeUI false UI.SetActive(false)


Increase animation speed according to the swipe speed in unity for Android I have the animation done through Maya and brought the FBX file to unity. Here is my code to calculate the speed of the swipe Vector2 speedMeasuredInScreenWidthsPerSecond (Input.touches 0 .deltaPosition Screen.width) Input.touches 0 .deltaTime Now I wanted to take speedMeasuredInScreenWidthsPerSecond and use it to increase the animation speed accordingly like this animation "gmeChaAnimMiddle" .speed Mathf.Round(speedMeasuredInScreenWidthsPerSecond) However, this results in an error that I need to convert Vector2 to float. So how do I overcome it?


(Unity) Spawning AI cars weighted to ahead of camera? I'm working on a little project where I drive around a small city with a top down but slightly angled camera view (like GTA Chinatown Wars). Cars are instantiated from spawners that aren't in camera view, then destroy if they drive too far from the player. To spawn a new car, I loop through all my spawner gameobjects and if they are within a certain distance to the player (and not in view of the camera), then they get added to a 'spawner' list, of which I pick a random. The loop is something like this float dist Vector3.Distance(player.transform.position, spawner.transform.position) Vector3 screenPos Camera.main.WorldToViewportPoint(spawner.transform.position) bool inView screenPos.z gt 0 amp amp screenPos.x gt 0 amp amp screenPos.x lt 1 amp amp screenPos.y gt 0 amp amp screenPos.y lt 1 if (!inView amp amp dist lt 15) list.Add(spawner) This works, but I find that when I'm driving around barely any traffic spawns on roads ahead of me, maybe because the camera angle is removing a chunk of the possibility area. Is there anyway to 'weight' it so spawners in the direction the camera (or beyond) have more chance of being picked, rather than ones behind me? In games like GTA Chinatown Wars you will be driving through rows of traffic, and I'm trying to get more density.


Unity Cannot access variable of C script from another object I have already found similar questions on stackexchange.com related to accessing variables from another object. But my question seems to have a slightly different context and the answers from those questions are not working. I have the following (stripped off) scene comprising the standard FPS character Scene001 FPSController FirstPersonCharacter My (stripped off) Assets hierarchy is as follows (folders are enclosed with lt brackets) lt Assets gt lt Scripts gt Actions.cs lt Standard Assets gt lt Characters gt lt FirstPersonCharacter gt lt Scripts gt FirstPersonController.cs Now FirstPersonController.cs is attached to FPSController by default and Actions.cs is attached by me to FirstPersonCharacter. Excerpt from FirstPersonController.cs is as follows ... namespace UnityStandardAssets.Characters.FirstPerson ... public class FirstPersonController MonoBehaviour ... private void GetCharacter() GameObject obj GameObject.Find("FirstPersonCharacter") ok here bool is acted obj.GetComponent lt Actions gt ().is acted error here, please see below ... Excerpt from Actions.cs is as follows public class Actions MonoBehaviour ... public static bool is acted ... All I want is to access bool is acted variable of Actions.cs from FirstPersonController.cs. Error is as follows Assets Standard Assets Characters FirstPersonCharacter Scripts FirstPersonController.cs(63,38) error CS0246 The type or namespace name Actions' could not be found. Are you missing an assembly reference? To me this seems to be a problem of namespace or folder location!!? Any help is highly appreciated. Thanks in advance. Updated above Changed Action to Actions. Corrected typo (). Sample project https ufile.io knmxj


3D game with Pre rendered background So a friend of mine and myself are starting to create our first game together. We descided on doing a 2.5D kind of game, so a static camera that moves with the player but cannot rotate. I got the collisions object from my friend which in unity looks like this Now I'd like to create an overlay with a JPG image which is going to cover the entire viewport and is going to "be" the map itself. I want to use this JPG as a kind of background image and then hide the collisions so the player will walk into the collisions and stop there but can't actually see them. In stead, he will see the image with buildings on it. How can I do this correctly? I've gotten as far as creating a second camera which will show me the image and then trying to create an Image (Create gameobject UI Image). But I cannot find any way to continue on this. Is this a good way to do this whole 2.5D kind of thing? We want lightweight maps in our game and thought this was a good idea to go about this. Edit My friend and me are trying to create an isometric game like this. The reason behind this is that the amount of work for the map is going to be massively reduced if we can do it like this since he can then just work in photoshop, in which he's super good. This was he does not have to bother with the 3d design in detail and can make the collision blocks much faster. So does anyone know how to get this to work? Maybe someone has a partial guide on this because I cannot seem to find anyone doing it like this but I imagine that ie Commandos is made like this. It would be much appreciated!


Unity2D Child class inheriting onCollisionEnter() methods I may be an idiot for asking this but I can't seem to solve it myself, I have a GenericWeapon class which has a onCollisionEnter() method which I want applying to all child classes which inherit from it, here is the code public void onCollisionEnter(Collider target) Debug.Log("Collided with player!") if(target.GetComponent lt Player gt ()) bc2d.enabled false rb2d.Sleep() equip(target.GetComponent lt Player gt ()) My child class is the following using System.Collections using System.Collections.Generic using UnityEngine public class RangedWeapon GenericWeapon Start is called before the first frame update void Start() Update is called once per frame void Update() public void attack() and my in GameObject has the RangedWeapon class as a component however the GameObject does not seem to be picking up any collisions with the player. Could someone point out where I'm going wrong with this?


How to load unload chunks data where view port is currently focused on? I have a 2D tile based engine with infinite procedural chunk generation. But I can't invent an algorithm, that will fill only chunk tiles on view port (and destroy old). Pls help ViewPort size can changing on the fly (2 100) I can't load all chunks completely, because I need to analyze the tiles in the visibility zone class Map public List lt Chunk gt get set public int viewPortWidth 2 ... 100 public int viewPortHeight viewPortWidth public Vector2Int playerPosition get set class Chunk Tile Tiles get set public int chunkWidth 16 public int chunkHeight chunkWidth public Chunk(int leftX, int bottomY) for (int y 0 y lt chunkHeight y ) for (int x 0 x lt chunkWidth x ) randomNumberGenerator.InitState(x leftX, y bottomY) chunk x, y randomNumberGenerator.Range(100) Tiles.Add chunk x, y


Quaternion.RotateTowards not working as expected when parent object moves rotates I have a Tank with a rigidbody. A Turret Base is attached to the Tank via a Hinge Joint. The below TurretController script is attached to the Turret Base in order to rotate it to point towards the direction of the mouse. The turret rotates flawlessly when the tank is stationary. But once I start moving the rotation behavior becomes very erratic https youtu.be v1VuTbMtcCM If anyone is able to help explain this behavior it would be much appreciated! lt summary gt Rotates a turret towards a point at a fixed angular velocity. lt summary gt public class TurretController MonoBehaviour public float m DegreesPerSecond 40f private Vector3 m TargetPosition Received from mouse move event public void Rotate(PointInputInfo inputInfo) m TargetPosition inputInfo.Point private void RotateTurret() Vector3 direction Vector3.Scale(m TargetPosition transform.position, new Vector3(1, 0, 1)) Quaternion targetRotation Quaternion.LookRotation(direction, Vector3.up) Debug.DrawLine(transform.position, m TargetPosition) Rotate at a fixed angular velocity. transform.rotation Quaternion.RotateTowards(transform.rotation, targetRotation, Time.deltaTime m DegreesPerSecond) private void FixedUpdate() RotateTurret()


Nuget in Unity with Mac OS I have moved over to Mac for Unity development, and am aware you can still use Windows .dll files in your project. I use NuGet as a secure method of getting specific dlls, and have usually done this on Windows by manually downloading the .nukpg and extracting the .dlls using WinRAR, then putting the dlls in Unity. So far, I have thought of two ways to do this on Mac 1.) Doing the same thing, but with a WinRAR alternative that can open .nukpg 2.) Using Visual Studio for Mac that has a NuGet interface built in with Unity Has anyone done this, or found a solution for getting package from NuGet in Unity for Mac?


Footstepper with Vr Unity I have the Footstepper Complete Footstep Solution from the unity store, and i dont get it working with the Vr, I made the footstep material like official documentation said, Then i put the Footstepper Setup in the ovrPlayer object. The problem is that sometimes sound the default fallback, so i think that the colission is not detected as it suppose. Some idea ?


Can I use two Collision Boxes on the same GameObject? I have two Collision Boxes on the same GameObject. I don't want the Collision Boxes to be triggers. I want the Collision Boxes on the actual GameObject, not its children. For example, if I want to check for a headshot. My reason for not wanting triggers is that a trigger is already being used. My reason for not wanting children is for cleanliness. I understand there are work arounds. I was wondering if there was a more direct approach. When there is a collision, how can I check which Collision Box is hit?


Making Modular Mini's Work in TTS This is not exactly game development, and I have also posted this in Arqade but it is development of a virtual playable version of a board game so maybe it loosely fits. Im hoping someone has an idea either way, or can point me to the right place to post this to get better results. I am working to create a Tabletop Simulator mod for a newly Kickstarted game Shiver Me Timbers. https www.kickstarter.com projects shivermetimbers shiver me timbers 0 description I have gotten all of the game pieces into the mod, all of the cards, tokens, tiles, I even made 3D models of the standees. Where I am getting stuck is the pirate ship miniatures. These modular miniatures are what you use to move around the board. In the game one of the things you can do is upgrade your ship. When you upgrade the ship, or get damaged in some way, (IRL) you physically add or remove pieces from the mini (when you upgrade your hull you pull apart the front and back of the ship and add another hull section in between and put them back together, when you upgrade sails you add a different Mast to the ship, when upgrading cannons you push a new cannon into one of the holes in the side of the ship, when taking damage to any of these areas the opposite. You can see how this works in the different GIFs on the kickstarter page above). Each ship can have a maximum of up to 7 hulls, 7 sails, 7 cannons or any combination in between. Also each "hull" piece has a disk wheel in it that determines what type of cargo you are carrying. The problem I am running into is making the different components come together in a way that 1. stays together when moved, 2. is able to later be removed, and 3 allows for the disks to rotate change as needed. I originally thought about just using different states for each configuration of the mini but that would turn out to be 343 states for just the ship (not to mention the 4 positions each cargo disc can be in) and creating that many states for one mini would not only take an insane amount of time making the 3D models, but would be a HUGE number of assets for the game to load, and be extremely confusing when trying to find the correct state for the configuration you need. I did decide (potentially incorrectly) to have set it up to use states for the 7 different hull configurations, and use the fixed joint tool to attach the cargo disks and that works, as long as you have each hull state set to be attached to the disk, or if you have each disk state (4 different states for the cargo types) set to attach to the base. But if I have both items having multiple states if I change the one that the Joint is going TO then it breaks and the disks fall out. The other issue with the mini's is attaching Sail Masts and Cannons. If I bring in the basic ship base and attempt to add a piece to it (aka one of the masts) I can create a snap point that allows it to fit to the correct spot but it always immediately falls over and off of the ship. I have thought about using the attach tool, but once you place the new part onto the base of the mini, by the time you can get to the attach tool and use it the new part has fallen off or fallen over. It cant just be pre done (with a gizmo on a locked object or something) because the players have to be able to modify mid game. I have enough ability with blender to work these models some (though still a bit of a beginner) and I have been trying to learn unity so that I can use the higher poly count ship models (the texturing was done with 3D geometry not a texture png) and set them up to be asset bundles. I have done a tiny bit of work with collider geometry in blender unity. I also have a minor amount of programming ability and could muddle through learning LUA and doing some scripting to make it work if that is the solution. Does anyone have any ideas how to make these "Modular" mini's a reality in the virtual space of TTS? Any Ideas are welcome. I Really want to figure this thing out. Thanks in advance.


Hierarchical state machines I have a rather simple state machine to control my Unity character and as the actions the character can perform increase, so does the complexity of state management, I have been reading about hierarchical state machines, they seem like the answer to my problems but I cannot 'connect' the theory to actual implementation, take for example the below Movement State public class Player Movement BaseState public Player Movement(PlayerController playerController, EntityStateMachine Comp entityStateMachineComponent) base(playerController, entityStateMachineComponent) public override void OnEnter() playerController.GetComponent lt Animator gt ().SetBool( quot IsMoving quot , true) playerController.GetComponent lt Cast Component gt ().OnCastReady.AddListener(() gt stateMachineController.ChangeToState(new Player Movement Casting( playerController, stateMachineController)) ) public override void OnExit() playerController.GetComponent lt Animator gt ().SetBool( quot IsMoving quot , false) public override void OnFixedUpdate(StateMachineContext context) If movement input is zero if ( playerController.PlayerInput.inputData.Movement.Input Vector3.zero) stateMachineController.ChangeToState(new Player Idle State( playerController, stateMachineController)) else playerController.motor.MoveAndRotateTowards( playerController.PlayerInput.inputData.Movement.Input CameraRelative) public override void OnUpdate(StateMachineContext context) if (Input.GetKey(KeyCode.LeftShift)) playerController.motor.IsSprinting true playerController.motor.Speed playerController.motor.walkSpeed playerController.motor.sprintSpreedModifier else playerController.motor.IsSprinting false playerController.motor.Speed playerController.motor.walkSpeed if (! playerController.motor.IsGrounded amp amp playerController.Rigidbody.velocity.y lt 0) stateMachineController.ChangeToState(new Player Locomotion Falling State( playerController, stateMachineController)) if (Input.GetKeyDown(KeyCode.Space) amp amp playerController.motor.IsGrounded) stateMachineController.ChangeToState(new Player Locomotion Jump State( playerController, stateMachineController)) My current goal is to have this become my super state for my movement state machine, I would like to add a sub state to this (Cast Movement) that simply calls playerController.motor.Move instead of playerController.motor.MoveAndRotateTowards as I would like to have a different style of movement while aiming a spell, but how would I write this substate so that it only handles how the character moves and falls back on the super state for everything else? I have the feeling I have to re write how my state machine works but I have no idea where to start except I probably need to seperate transitions out of the states themselves? perhaps? haha


sound stops after scene reloads in unity3d I'm recently facing problem regarding the inclusion of sounds in my game. Although i have used the technique of DontDestroyOnLoad() for background sounds and that work perfectly fine. But for the casual sound, it is creating problem that it stops during scene reloads. I have my script below that contains AudioClips and AudioSources and that script is attached to an empty game object, and calling that script in different scripts for the playback of the sounds. AudioScript.cs using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class AudioScript MonoBehaviour public AudioClip pinshit public AudioClip rowlingball public AudioSource rowling public AudioSource hit public AudioClip cheer public AudioClip strike public Text counttext public AudioClip spare public AudioClip sorrow public AudioClip winaudio GameObject music Use this for initialization void Start () rowling GetComponent lt AudioSource gt () music GameObject.FindGameObjectsWithTag("class") if (music.Length 1) else for (int i 1 i lt music.Length i ) Destroy(music i ) Update is called once per frame void Update () private void Awake() DontDestroyOnLoad(this.gameObject) To play sound on different actions routines sorrow.clip GameObject.FindWithTag("class").GetComponent lt AudioScript gt ().sorrow sorrow.Play() sorrow.volume 1


How do I get an NPC to follow the player(and stop when it gets within range) I'm making a game where you have a friend follow you. I have a script that partly works, but when the friend exits the trigger, it won't follow the player. How do I get the friend to follow the player once indefinitely, or until it hits the trigger again? Here is the script public Transform friend private int movespeed public int speed public Rigidbody rb Use this for initialization void Start() speedup() Update is called once per frame void Update() transform.LookAt(freind) Vector3 eulerAngles transform.rotation.eulerAngles eulerAngles.x 0 eulerAngles.z 0 transform.rotation Quaternion.Euler(eulerAngles) rb.AddRelativeForce(0, 0, movespeed) public void OnTriggerStay(Collider other) if (other.tag "Player") movespeed 0 else speedup() public void speedup() movespeed speed


Upgrade items on shop menu I made a game and I made a Magnet upgrade and I have 8 game objects to set active 1 by 1 every time when I upgrade the magnet and I have (int upgrade 0 ). But when I upgrade these game objects it's set active, but if I quit the game and start again all these game objects are FALSE. How can I make e.g if I upgrade to (int upgrade 6) and to make my game objects active only from element 0 to element 6. I do upgradeMagnet() to void Update but its make active only 1 game object depends from (int upgrade) if (int upgrade) is 5 and only game object element 5 is active. public GameObject upgranded public int upgrade 0 public void upgrandeMagnetButton() upgrade 1 upgradeMagnet() void upgradeMagnet() if (upgranded upgrade ) upgranded upgrade .SetActive(true)


Reading a Binary File in Unity I am trying to display the first two bytes of a binary file as a test. I have the following code. void DisplayValuestext() Stream s new FileStream("Assets testbinary.bin", FileMode.Open) BinaryReader br new BinaryReader(s) int dataVal br.ReadUInt16() Debug.Log(dataVal) The first 2 bytes of the binary file are "1E44" which the function ReadUInt16() should read. However, it reads the first byte of data, "1E" rather then the first 2 bytes "1E44". I believe it is because it reads 2 characters, rather than 2 bytes. When I display the 16 bit unsigned integer "dataVal" in the console, I get 25905. The value I am trying to get is 17438 which is "1E44" little endian encoded value converted to decimal. I have also attempted to use the function "ReadUInt32". This method should read the first 4 bytes, however it instead displaces by 4 characters, which is 2 bytes "1E44". The console displays "875849009". Why do I get these strange values "25905" and "875849009" and how can I resolve this to get the desired value of 17438?


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?


How to associate a number to a button and get that number when the user clicks on the button? I am creating buttons for each level through script as shown below private void CreateLevelButtons() for (int i 1 i lt no of levels i ) Button button Instantiate(button prefab) button.GetComponentInChildren lt Text gt ().fontSize 12 button.GetComponentInChildren lt Text gt ().text "Level " i.ToString() button.transform.SetParent(content.transform, false) button.onClick.AddListener(() gt OnClickLevelButton()) In OnClickLevelButton() function I want to determine the level number of the button that was clicked. Is there a way to associate a number to a button so that i can access that number later when the user clicks on the button?