Get Closest point between a Box 3D and a Point I have a point A (x, y, z), and a Box Center (x, y, z), Size (Width, Height) How to get the closest point in the box from the point A ? In Unity I can create a bound, and I can find the non rotated position like that Bounds bounds mesh.bounds Vector3 closestPoint bounds.ClosestPoint(pointA) But then If the bound is rotated, the result is not correct. So I have 2 options Find the way to rotate my closestPoint from the pivot. Find the math formula myleft. If someone can help ! thanks. EDIT here a video the red point is the one find with bound.ClosestPoint the yellow point is the one find with Vector3 closestPointInverse currentTarget.InverseTransformPoint(closestPoint) https youtu.be RMRRtSaJv8w I have also tryed to do my own rotateFromPivot function public Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 angles) return Quaternion.Euler(angles) (point pivot) pivot When I use it, I get the same result with the InverseTransformPoint method.


Unity Handling external data files I'm moving from an old game dev tool to Unity, and wondering how to go about handling external data files. In my previous program I'd set up external (txt ini) files like this Group1 Count 1 1 Hello Group2 Count 2 1 lol 2 end Then I would simply reference which group name and line I wanted to pull. What's the equivalent to this in unity? I see I can import TextAssets but I can't find functions to pull select data from it. Do these exist? Do I have to split by lines, loop through them all and convert it into groups (lists) manually? What is the standard method for doing this? Is it moving to xml files?


How can I make 2D fog like in Graveyard Keeper? I really like Graveyard Keeper's fog effect but I can't work out how to make it. It's 2D, and made in Unity. The characters all seem to be 'under' the fog, but the tops of tall trees and buildings poke out. It looks like this The developer has given a bit of information about how it's made on Gamasutra http www.gamasutra.com blogs SvyatoslavCherkasov 20181023 329151 Graveyard Keeper How the graphics effects are made.php "As you see, the tops of houses and trees are seen from the fog. In fact, this effect is really easy to make. The fog consists of a great deal of horizontal clouds spread across all the picture. As a result the upper part of all the sprites is covered with a fewer amount of fog sprites " I used the information from this article, and one of the developer's tweets that included this picture I attempted to recreate it this fog effect. When the character moves up or down the screen, it flickers as it crosses each fog sprite What have I missed? All of the sprites are on the default sorting layer and have sorting order 0. The project, in Graphics Settings Camera Settings has the custom axis and sort axis (0,1,0). The tree and character are on the same z position, and the fog is spread out over several z positions


How to prevent OnCollisionEnter2D calling a function again and again? My current code makes a ball keep jumping whenever it hits the ground. But when it hits a vertical ground it keeps calling the jump function again and again. That is because OnCollisionEnter2D makes the isGrounded bool true as long as it is in touch with a vertical collider. I tried several ways for example this didn't work for me void FixedUpdate() if(isGrounded true) Verticaljump() isGrounded false void OnCollisionEnter2D(Collision2D collision) if(collision.gameObject.CompareTag("H Ground")) isGrounded true As shown in the picture the OncollisionEnter2D starts and keep adding force on y axis.Is there any way I can call a function only once even if the gameObject keeps colliding with a surface. OnCollisionExit2D also does not work. So how can I call a function only once as it collides with ground and even if it keeps colliding with the ground?


How to prevent collisions between instantiated prefabs I'm creating a virtual creature evolution system like here. This type of project requires to define creatures, which are made of some 3d boxes and simulate them over and over again, making little changes along the way, until the point where they are good enough at a certain task. Basically, I'm using Genetic algorithms. I'm going to be doing a lot of simulation (a few hundred creatures each generation, times X generations, where X could be in the thousands). In order to save time, I want to simulate multiple creatures at once, so I must run collision checks efficiently. Each creature exists on its own and therefore should not be bothered by other colliders except himself and the ground. I have a prefab of a creature. Each creature is made of multiple 3d boxes with colliders. The nodes in the same creature should collide with themselves but should not collide with nodes that are in other creatures (because it should learn to perform based on the environment as it is). What is the most efficient way I could do this? I thought about checking the root of the collision object but that just prevents the collision and doesn't eliminate the useless checks that are being made. I've also looked at solutions involving the "Layer Collision Matrix" but still could not find a way to make it work. Thanks in advance.


How do I use Unity's OnPlayerConnected method? https docs.unity3d.com ScriptReference MonoBehaviour.OnPlayerConnected.html using System.Collections using System.Collections.Generic using UnityEngine.Networking using UnityEngine public class SendData MonoBehaviour void OnPlayerConnected (NetworkPlayer player) Debug.Log ("A player connected!") This code, surprisingly, doesn't work! Expected The server prints "A player connected!" in the Unity editor debug console. What happens Nothing is printed. It doesn't matter if I use print() or Debug.Log(). This script is applied to a standard object in the scene. It has a NetworkIdentity. I really don't know what else to try. The Unity documentation is very short and gives an example very similar to this. My code should be even simpler than Unity's example but it doesn't work.


How do I implement corner correction in a platformer? I'm writing a platformer in Unity and I'm trying to make it so that when the player jumps up to a ledge but barely misses (imagine they hit their toe on the ledge, or maybe even their foot, I'll play with the values) they are nudged up onto the ledge instead of not making the jump (as it is now in my game). There's a thread showing that Celeste does this in a few ways here. My player character uses a dynamic Rigidbody2D and I move the character by setting the velocity directly.


Replicating Flight Mechanics of Star Wars Battlefront (2015) I'm trying to replicate the flight mechanics from Star Wars Battlefront (2015) in Unity and I can't get my head around what exactly is going on. Specifically, how do I get the camera to behave like this using Unity and C https youtu.be gxZdOUiEiyY?t 1m1s I don't mind if you don't give code, I'm just struggling to understand what happens and when in terms of camera movements and rotation.


Using shared memory instead of marshalling for C native plugins in Unity? So I'm a C developer who has been playing with C for a week or two in order to get acquainted with Unity, and I'm curious about the marshalling process used to transfer data for use in C native plugins. From what I can tell, the general consensus is that while using effective C plugins can be a performance increase for computation heavy tasks, the marshalling process of transferring data can be significantly slower than the potential gains provided by the C flexibility. I'm familiar with how shared memory works in C and it appears C has the functionality required to use the buffers as well. From what I understand, the process of marshalling is slow due to copying, creating buffers and transferring chunks from one memory segment into another. Even though there's the problem of cache coherency when operating in shared memory, it may be less than the cost incurred by marshalling. I'm sure I'll have to do some experimenting. Does anyone have thoughts or experience with using shared memory or marshalling in Unity who could weigh in on the question?


How can I rearrange layers in Unity 2D? I'm new to using Unity (2019.30a2) and am currently learning by watching Brackey's (youtube) "How to make a 2D Game in Unity" At 6 58 he is able to rearrange his layers easily. On my hand, I can create but am unable to change the order of the layers. Looking at other questions on similar subjects hasn't provided me with a solution yet. I'm currently working around it but feel this will hinder me in the future. The screenshot of the unmovable layers is included below


Unity Material Override Video is too dark I have made a TV in Blender, UV Wrapped a material and applied a video on it in Unity. But the picture is too dark, and I would like to make it brighter. How could I solve this problem? The left one


Where and how should I check for collision in multiplayer game? I'm making a multiplayer game. For now, I added a script to towers and I have booleans to change using OnTriggerEnter. When triggered, client sends a message to server and towers health starts to get lower. So it works. But I don't know if it's safe to use OnTriggerEnter because it calculates on the client side. Should I calculate on the server side ? And how I do it ? (Using Physics.ComputePenetration is a little bit slow.)


Room generation with external walls and doors I am looking to implement a means to generate rooms with outer walls with windows and doors from prefab game objects in Unity. The idea is that a group of tiles is defined as a room which I then iterate through to find the outer tiles and then use their external edges to generate the walls of the entire room. Gathering the outer tiles is easy enough and working out the external edges is already implemented. What I need to understand is the best approach for using prefab game objects as the set pieces for walls and floors. Currently for a single wall piece, I have created a quad and made that into a prefab which I then clone, position and rotate into place along the outer edges. The below screenshot shows a room with walls made using the prefab wall GameObject. In this screenshot, the room consists of 12 wall GameObjects. I want to avoid having lots of GameObjects for single wall segments and instead perhaps merge them all into a single mesh on a single GameObject. What I would like to achieve is to be able to create a consistent set of pieces for each outer wall, with windows and doors (most likely cloned from other prefabs) to build a realistic looking room. For example, any single length of a wall would be made up from Wall gt Wall gt Window gt Wall gt Wall Perhaps there is a much easier way to achieve this that I have overlooked but searching for room generation always leads back to examples for dungeon crawlers and roguelikes. I am not creating a dungeon crawler, nor am I generating the environment proceedurally, instead the player will be able to create rooms in a similar fashion to Evil Genius and The Sims. In the current approach, creating a room which is 5x5 would mean that there are a total of 20 wall GameObjects and 25 floor GameObjects. I am not keen on having this many objects in the scene for a single room. I would prefer to be able to create a mesh for the entire room, adding in the vertices and triangles from the prefab mesh to cut down on the number of GameObjects in the scene. Does anyone have any experience with building rooms in this fashion, or are there any clear examples of how to achieve this? I am not sure how to translate and rotate a prefab and then merge the translated meshes into a single mesh. Perhaps I am barking up the wrong tree and there is a better approach but for now, this is the only way I can see which is possible to achieve what I want.


Inaccurate UI button unity As you see in this screenshot I must hover the mouse on that that spot to click on button in overall you must hover the mouse upper than button to click on it, tried to change the Sprite but even with default Sprite I have this problem so I don't think there is problem with Sprites. Let me explain more about this panel In this scene I have two canvas's one for Pause button only and another one for this panel that is disabled. When you click on Pause this panel will appear ( second canvas will be activated. Why is that? I tried to change some things in the canvas like change UI scale mode to scale with screen size but no luck. I will be grateful for help I don't really know where problem is. Update I just now found very odd behavior when hit play if mouse be in game view that problem wont occur, after mouse leave the button issue will appear again.


How to blur entire scene but a specific spot in Unity? What I want is basically A way to blur every object sprite on the scene, but have a "blur free" circular zone, that can move. And everything that's behind that circular zone won't have the blur effect applied to it. In a 2D mobile game, how would I do that, especially in a way that's not too heavy, performance wise(if possible). And if it's not possible to do that in a way that won't completely destroy my performance, I also have those sprites already "pre blurred" so maybe there's a way to have both blurred and "unblurred" objects at the same position, and only draw the right parts of them as they go through the scene and reach the blur free zone. If there's a way to do that, that'd also help immensely. Thanks for your time.


Problems with Unity3D Animator controller states I have an object (a simple card) equipped with the Rigidbody, Collider and Animator components. In particular, Animator performs two simple clips Cover and Uncover that rotates the card 180 degrees. The first starting from 0 degrees to 180, the second from 180 to 0. So the clips should cover or uncover the card. The problem is that the card returns to its original state. For example, the original state of the card is the "uncovered state" so when I click on it to cover it covers as expected. The I register the state "covered" programmatically. However, immediately after the animation ends, it returns to its original state (uncovered). The card now has an internal (C variable) state as "covered", but I see it to still be uncovered. When I click it again, will be fired the correct animation clip "uncover". What should I do to leave it covered at the first click? I have uploaded here a short clip that shows the behavior of the card, also below find some screenshots that refer to the various views of the IDE that may have useful information. The video clip is uploaded to Dropbox for the while. The video of the behavior Dropbox link The code of the Flip script using System.Collections using System.Collections.Generic using UnityEngine public class Flip MonoBehaviour private Animator anim private enum cs e covered, uncovered private cs e coveringState Use this for initialization void Start () anim this.GetComponent lt Animator gt () coveringState cs e.uncovered Update is called once per frame void Update () private void OnMouseUp() Debug.Log("Mouse up") if (coveringState cs e.uncovered) anim.Play("Cover") coveringState cs e.covered else anim.Play("Uncover") coveringState cs e.uncovered private void OnMouseDown() Debug.Log("Mouse down") private void MouseDrag() Debug.Log("Mouse drag") Some screenshots


Unity 5.x Network Synchronization Concepts Bear with me, It will be long read I am working on the new Unity Networking system. I was using Photon and old (legacy) unity network API's before. But as it seems there are some good benefits of the new system than the previous ones, so I want to stick with it. (Despite of it being uncompleted) But there are some points that doesn't make sense to me with the API. Data Sync for example. So, in the old systems (both in Photon and legacy unet) we had functions called OnPhotonSerializeView or OnSerializeNetworkView depending on which API we use. Both API's are very similar as you may know. So in these functions we could send and recieve data between clients and server. Which makes sense, and was really usefull. But aperantly they changed this concept, (or it still exists, and i couldn't find it) There is a new thing called SyncVar , which syncs the data "ONLY" from server to client automatically. (Which really, literally doesn't make sense, I mean why not sync both server to client AND client to server? That would make everything much easier) According to the documents, you can ONLY send data from client to server by using Command 's. Which is basically (as far as I understand), "one way" version of old good RPC calls. Instead of calling function in all other clients, it calls it in the server. So, you can send data to server with function parameters like the way we did it with the old RPC 's before. Which is usefull on point but If this is the only way to send data to server, then it doesn't make any sense to me.. I mean there are variables that needs to be kept synced all the time, back and forth, like position or rotation vectors. And sending them with Command calls, contradicts with the concept of network framework in my mind. We used to avoid this kind of situation before, right? Why make it the obligation now? Or are there simply any other ways to send data from client to server that I couldn't find yet? There is a custom serialization with the SyncVar , with OnSerialization and OnDeserializaton functions. Which really looks like the good old OnSerialize functions but apperantly it's diffrent as it does what the SyncVar does. OnSerialization is only called on server, and Deserialization is only called on client. So we can only send from server to client even with it. If Command is the only way to send data to server, please say so. And clarification about why this concept is reasonable would be really nice. Please enlighten me more with the new concepts of the new UNET framework. Thanks in advance for any help.


How does Vector3.MoveTowards work in Unity? What I mean is that I don't understand what each part does, like in the example in the API, it didn't give much on what did what! I kinda need this for an aim script in a shooter game I'm working on. Any help will be good, but a direct answer would be great!


Why is this MeshRenderer null? The following line fails in my class MeshRenderer nRenderer Sphere.AddComponent lt MeshRenderer gt () This is the entire class. All works except the mentioned line. using System.Collections using System.Collections.Generic using UnityEngine public class SphereMaker MonoBehaviour private GameObject Sphere void Start() Sphere GameObject.CreatePrimitive(PrimitiveType.Sphere) Sphere.AddComponent lt MeshFilter gt () MeshRenderer nRenderer Sphere.AddComponent lt MeshRenderer gt () Material nMat new Material(Shader.Find("Universal Render Pipeline Lit")) I'm using the URP if (nMat null) Debug.LogError("no mat!! n") nMat.color Color.red nRenderer.material nMat float fSize 0.4f Sphere.transform.localScale new Vector3(fSize, fSize, fSize) Sphere.transform.position new Vector3(0, 0, 0) Does anybody see what I'm doing wrong? Thank you!


Sprite changing position on its own? I have a simple 2d scene, where I'm trying to have a sprite at x 8 which I can move up and down. The problem is, when playing the scene, the sprite "jumps" by itself to the middle, x 0, for no apparent reason. It then only goes back to x 8 when there is input to move it. How do I get it to stop "jumping" to the middle at the start of every play? using UnityEngine public class player1 MonoBehaviour Vector2 targetPos public float speed public float step void Start() transform.position new Vector2( 8,0) void Update() if (Input.GetKey("w") amp amp transform.position.y lt 3.8) targetPos new Vector2( 8, transform.position.y step) if (Input.GetKey("s") amp amp transform.position.y gt 3.8) targetPos new Vector2( 8, transform.position.y step) transform.position Vector2.MoveTowards(transform.position, targetPos, speed)


Game not accepted in Google Play even though it's built in 64 bit (Unity) I tried building my game according to the google play rules, but I get the following error message "This release is not compliant with the Google Play 64 bit requirement The following APKs or App Bundles are available to 64 bit devices, but they only have 32 bit native code 1. Include 64 bit and 32 bit native code in your app. Use the Android App Bundle publishing format to automatically ensure that each device architecture receives only the native code that it needs. This avoids increasing the overall size of your app." According to the documentation (https developer.android.com distribute best practices develop 64 bit) for Unity I should get a working version when I do Set Scripting Backend to IL2CPP Select the Target Architecture ARM64 checkbox Build as normal I've built the game both as APK and as AAB, but neither are accepted. I am using Unity 2018.3.14f1. I have downloaded this NDK https dl.google.com android repository android ndk r16b windows x86 64.zip and put the content to C Users MyName AppData Local Android


Why the state of the duration is all the time 7 even if updating the state inside the while in the ienumerator? I want to get the current coroutine state. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.PostProcessing public class DepthOfField MonoBehaviour public UnityEngine.GameObject player public PostProcessingProfile postProcessingProfile public bool dephOfFieldFinished false public LockSystem playerLockMode private Animator playerAnimator private float clipLength private Coroutine depthOfFieldRoutineRef private DepthOfFieldModel.Settings depthOfField private DepthField state void Start() if (depthOfFieldRoutineRef ! null) StopCoroutine(depthOfFieldRoutineRef) playerAnimator player.GetComponent lt Animator gt () AnimationClip clips playerAnimator.runtimeAnimatorController.animationClips foreach (AnimationClip clip in clips) clipLength clip.length DepthOfFieldInit(clipLength) state new DepthField() public void DepthOfFieldInit(float duration) depthOfField postProcessingProfile.depthOfField.settings depthOfField.focalLength 300 StartCoroutine(changeValueOverTime(depthOfField.focalLength, 1, duration)) postProcessingProfile.depthOfField.settings depthOfField public IEnumerator changeValueOverTime(float fromVal, float toVal, float duration) playerLockMode.PlayerLockState(true, true) float counter 0f while (counter lt duration) var dof postProcessingProfile.depthOfField.settings counter Time.deltaTime float val Mathf.Lerp(fromVal, toVal, counter duration) dof.focalLength val postProcessingProfile.depthOfField.settings dof state.duration duration state.focalLength val yield return null playerAnimator.enabled false dephOfFieldFinished true depthOfFieldRoutineRef null public struct DepthField public float focalLength public float duration public void Save() SaveGame.Save("depthoffieldstate", state) public void Load() Time.timeScale 1f depthOfField postProcessingProfile.depthOfField.settings DepthField state SaveGame.Load lt DepthField gt ("depthoffieldstate") depthOfField.focalLength state.focalLength StartCoroutine(changeValueOverTime(depthOfField.focalLength, 1, state.duration)) postProcessingProfile.depthOfField.settings depthOfField Inside the while loop I'm doing state.duration duration state.focalLength val The focalLength value does change if for example I save onethe game start the focalLength value will be 299 and if I will save after the coroutine has finished the focalLength value is 1. But the coroutine duration value is not changing it keep staying on 7 when saving even if the coroutine has finished and should be 0 it still 7. The value 7 of the duration is coming from the clipLength. I can't get the current duration time of the coroutine. In the Load function I'm starting the coroutine over again but since I'm using the loaded focalLength value and duration value it should look like the coroutine is continue from the last saved point. But I can't get the correct duration value when saving.


What's the best way to index my object? Obviously, lists automatically create their own index. So basically I wouldn't need this function at all. But I figured it was safer in case my list index ever changed (e.g. adding a new item at the beginning of the list, would shift the index numbers for all the other list items). public EmpireAgentView ShowEmpireView(int eIndex) foreach (EmpireAgentView e in EmpireViews) if (e.EmpireIndex eIndex) Debug.Log("Showing Empire for Agent " e.AgentName) return e Debug.LogError("No EmpireAgentView Found for that empire " eIndex) return new EmpireAgentView(9999) So in this case, I added the property "EmpireIndex" to the EmpireAgentView object. So now, whenever I need to access a specific EmpireAgentView from the EmpireViews list, I would use ShowEmpireView(1) instead of EmpireViews 1 . Each EmpireAgentView object has unique information about the same Agent object. For example, where the Agent is currently located. If we have 4 empires, than there will be 4 EmpireAgentView objects in the Agent class. Each empire has their own idea of where the Agent is currently located, so I need to be able to access the specific empires data on this agent. Right now, I assign a simple int called EmpireIndex to each EmpireAgentView, so that I can make sure I got the right view for the right empire. If i simply used EmpireViews 3 , and that list rearranged itself somehow, (like adding an EmpireAgentView object to the beginning of the list, presumably) than all that information would be mixed up for the empires. Is that the best way of doing that? is there a better way of finding it? Or am I being TOO careful, and just need to not add new EmpireView's to the beginning of the list? (I'm new to C , is there anything else that would change the index of a list item?)


Can I test collision inside an edge collider area in Unity? I have a triangle with its perimeter represented by an EdgeCollider2D, and I want to trigger an event when the player reaches this area. So I set the collider as a trigger and, I used the OnTriggerStay2D function in my code. But the event works only when the player is intersecting the line of the collider, not when the player is inside the triangle but not touching the edge. How can I continue to get OnTriggerStay messages when I'm inside the triangle, not touching the edges?


Why won't Unity drop objects to the origin position? It seems that my objects drop to the middle of the scene, not a global position of (0, 0, 0). Why is Unity behaving like this?


How to stretch screen image to fit higher res monitors set to lower resolutions with Unity? Using Screen.SetResolution(width, height, windowMode) , how might I stretch the image to match the monitor size? I've noticed this problem occurs both with this line of code and also the default unity configuration launcher. No body seems to discuss this issue which is odd to me.


Generating objects in Open Worlds using Unity I have an open world (infinite) which is proceduraly generated in chunks. In this world I want to proceduraly load objects trees grass by raycasting them around the player position and unload them when the player is far. My questions are What is the most optimized way of loading unloading large quantities of objects around a player ? Since I'd like players to be able to interact come back to objects, I'm thinking of using a blue noise seed to load objects, and unloading them by replacing them with an empty. Is that common practice ? I've looked in a lot of places for ressources but couldn't find much, I'd really appreciate any kind of link to tutorials, videos, pseudo code ideas and common practices for open worlds as I am not very experienced in video game design, but mildly familiar with code. Thanks !


How to get multiple string values from override ToString()? I want to get multiple string values(selectedNameand selectedCurrency) individually from public override string ToString()below. How do I go on about it? using System.Collections using System.Collections.Generic using UnityEngine CreateAssetMenu(fileName "Country", menuName "Country Country", order 0) public class country ScriptableObject System.Serializable public class Item public string Name public string Currency public string Capital public string City public override string ToString() string selectedName this.name string selectedCurrency this.currency return selectedName selectedCurrency public Item m Items public Item PickRandomly() int index Random.Range(0, m Items.Length) return m Items index I need to use the selected string values in the script below. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class GameController MonoBehaviour public country country This is the scriptable object country public Text countryText public Text currencyText void Start() countryText.text country.PickRandomly().ToString() This is where I need the country name string to show up. currencyText.text country.PickRandomly().ToString() This is where I need the currency string to show up. Right now it just displays a random country name and currency for example USA USD in both the fields.


Why do I get a jitter stutter when moving and following a target? I am using the script below to move a transform to quickly follow a target (the player), and come to a stop close to the player. When I move the player around, the transform is following the player, keeping the 1.5 distance. To ensure the transform can keep up with the player, I set the moveSpeed to 5, But when I do that, the transform jitters stutters when moving. If I set the moveSpeed to 1 for example, the transform will move smoothly but will not keep up with the player the player has to stop moving and wait for it to catch up. But increasing the speed makes the stutter return. Why is this stutter happening, and how can I make the movement smooth? using System using System.Collections using System.Collections.Generic using System.Linq using UnityEngine using UnityEngine.UI public class Follow MonoBehaviour public Transform targetToFollow public Text text public Text text1 public float lookAtRotationSpeed public float moveSpeed private float minMoveSpeed 0f private Vector3 originPos Start is called before the first frame update void Start() originPos targetToFollow.position Update is called once per frame void Update() Vector3 lTargetDir targetToFollow.position transform.position lTargetDir.y 0.0f transform.rotation Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(lTargetDir), Time.time lookAtRotationSpeed) var distance Vector3.Distance(transform.position, targetToFollow.position) text.text quot Transform Distance From Target quot distance.ToString() float ms moveSpeed if (distance gt 5f) ms moveSpeed 0.5f else if (distance lt 1.5f) ms Mathf.Max(minMoveSpeed, ms 0.3f) else transform.position Vector3.MoveTowards(transform.position, targetToFollow.position, Time.deltaTime ms) if (distance lt 0.5f amp amp originPos targetToFollow.position) ms 0f if (distance gt 1.5f) transform.position Vector3.MoveTowards(transform.position, targetToFollow.position, Time.deltaTime ms) originPos targetToFollow.position


How to render text on an 3d Object? I want to render text on an 3d object. I'm trying to simulate a digital signage LED panel. My lcd Panel has a material and a texture. How can I do ? Using 3d Text ? Thanks


Unity I can't change the "colorOverLifetime" property of the "Particle System" via script The goal is to remove the particles via script with fade effect. But I'm not just interested in an alternative, I want to understand why my code doesn't work. The code below is modified to show only the important parts. I can't know before what time the particles will be dissolved, so I can't set the parameter from the editor. StarsConfig.Stars.colorOverLifetime.color.gradient.SetKeys This is the important point (see the log image). The gradient does not take my new values but alphaKey is correct. Why ? Thanks private bool FadeStarts false void Update() if (FadeStarts) return StartCoroutine(fadeStars(false)) private IEnumerator fadeStars(bool show) FadeStarts true ParticleSystem.ColorOverLifetimeModule c new ParticleSystem.ColorOverLifetimeModule() c StarsConfig.Stars.colorOverLifetime Gradient g c.color.gradient Debug.Log("OFF " c.color.gradient.alphaKeys 0 .alpha " gt " g.alphaKeys 0 .alpha) GradientAlphaKey alphaKey new GradientAlphaKey 2 alphaKey 0 c.color.gradient.alphaKeys 0 alphaKey 1 c.color.gradient.alphaKeys 1 while (c.color.gradient.alphaKeys 0 .alpha gt 0f) alphaKey 0 .alpha StarsConfig.VelocityAlpha Time.deltaTime alphaKey 1 .alpha StarsConfig.VelocityAlpha Time.deltaTime StarsConfig.Stars.colorOverLifetime.color.gradient.SetKeys(c.color.gradient.colorKeys, alphaKey) Debug.Log("g " alphaKey 0 .alpha " gt " StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys 0 .alpha) StarsConfig.Stars.colorOverLifetime.color.gradient.SetKeys( new GradientColorKey new GradientColorKey(Color.white, 0f), new GradientColorKey(Color.white, 1.0f) , new GradientAlphaKey new GradientAlphaKey(StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys 0 .alpha (StarsConfig.VelocityAlpha Time.deltaTime), 0f), new GradientAlphaKey(StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys 1 .alpha (StarsConfig.VelocityAlpha Time.deltaTime), 1f) ) yield return 0 StarsConfig.Stars.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear) FadeStarts false UPDATE Ed Marty's suggestion is correct, and the solution is there (thanks!). But I would like to understand what is the difference between these two codes. This code works var col StarsConfig.Stars.colorOverLifetime while (col.color.gradient.alphaKeys 0 .alpha gt 0f) float alpha StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys 0 .alpha (StarsConfig.VelocityAlpha Time.deltaTime) Gradient grad new Gradient() grad.SetKeys( new GradientColorKey new GradientColorKey(Color.white, 0.0f), new GradientColorKey(Color.white, 1.0f) , new GradientAlphaKey new GradientAlphaKey(alpha, 0.0f), new GradientAlphaKey(alpha, 1.0f) ) col.color grad yield return 0 And this doesn't work while (StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys 0 .alpha gt 0f) float alpha StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys 0 .alpha (StarsConfig.VelocityAlpha Time.deltaTime) StarsConfig.Stars.colorOverLifetime.color.gradient.SetKeys( new GradientColorKey new GradientColorKey(Color.white, 0f), new GradientColorKey(Color.white, 1.0f) , new GradientAlphaKey new GradientAlphaKey(alpha, 0f), new GradientAlphaKey(alpha, 1f) ) yield return 0


How to Trigger OnSelect on a Button? I'm new to Unity and C and have been struggling to figure out how to solve this. What I'm looking for is a way to make text display whenever a button is selected. (ex. Player selects a difficulty option, and text pops up describing what mechanics the difficulty will affect) I can get this to work with mouse input with no issue, with the following code attached to the button. void Update() if (this.IsHighlighted() true) gameObject.transform.GetChild(1).gameObject.SetActive(true) else gameObject.transform.GetChild(1).gameObject.SetActive(false) The aforementioned description text is set up as a child to the button, and will appear disappear depending on whether it's highlighted or not. The problem is that isHighlighted only occurs when the mouse is hovered over the button, and does not take effect when selected via directional inputs from a keyboard controller, which is what I'm looking for. I've done some research and noticed there is an OnSelect method, but I can't figure out how to implement it. Any advice would be greatly appreciated.


UV mapping. Texture blurry and overlapping. Unity3d In my voxel game, this is how I'm calculating UV coordinates for my cubes' faces public static Vector2 faceUVs(Direction dir) Vector2 sideUV new Vector2 4 new Vector2(0, 1), new Vector2(1f 3, 1), new Vector2(1f 3, 0), new Vector2(0, 0) Vector2 topUV new Vector2 4 new Vector2(1f 3, 0), new Vector2(1f 3, 1), new Vector2(2f 3, 1), new Vector2(2f 3, 0) Vector2 bottomUV new Vector2 4 new Vector2(2f 3, 0), new Vector2(2f 3, 1), new Vector2(1, 1), new Vector2(1, 0) if ((int)dir 4) return topUV if ((int)dir 5) return bottomUV return sideUV Then depending on which face is being generated, I return appropriate UV coordinates for it. This is the texture itself(pretty clean, each block is exactly 16 pixels wide and 16 pixels tall. Total length of picture is 48 pixels) But the result is terrible(Faces are almost correctly aligned with appropriate texture part, but the annoying keyword here is "almost") As you can see, edges of side faces contain few pixels of what should have been the texture of top face. I've set filter mode to point too. If I instead use 16x16 pixel texture, for example only side, then I get good result I suspect the problem here could be floating point precision. In that case, how do i resolve this error?


Lightmapper artifacts I really don't understand why this is creating these kinds of artifacts. I'm starting to think something is wrong with Unity. There are clearly no overlapping faces on the Model. There is enough of a margin to remove all chances of bleed. Yes the lid is a seperate object but any UV's of the lid and it's box are not overlapping. Thix odd pixelation occurs no matter the quality. It happened all the time sofar here and there and it forced me to replace a few objects in older projects. No idea what causes it. Really sick and tired of this. Edit when I rotate the crate by 90 degrees the artifacts appear on the adjacent side of the cube. From the perspective of the camera it would be the same side. So clearly it's not the UV's or anything. Lightmap settings Object Import settings


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


How can I reduce the draw calls in a split screen game? I am working on a split screen game with one camera per player. It appears that the number of draw calls is multiplied by the number of cameras I have, which makes perfect sense. More cameras means more drawing means more draw calls. So for every player, there is effectively a new instance of the game that must be rendered. What do developers do when presented this problem? Do they scale down their game? Or are there practices I am unaware of to where this should not be an issue? (I am using Unity, if it is relevant.) How can I improve rendering performance in a split screen game? Example


Unity3d iOS build where are the textures? First time building and running my Unity3D app on my iPhone and it appears that all the textures are missing. Everything is just a solid block of whatever color I made it. When running in Unity I see everything correctly. See images below. To complicate things I'm using custom shaders, and all the objects are custom procedural meshes. Quads that I build in script. If I switch the paper backplate shader to a built in shader I still only see white on the iPhone. So I suspect that somehow the textures just aren't making it to the iOS project. When I look in the iOS project I can't find any textures. Where would they be in the iOS project? For example in Xcode under Build Phases Copy Bundle Resources the only thing there is the Images.xcassets, which only contains the splash screens and icons. Surely I'm missing something simple. I tried renaming the folder where I keep my textures to "Textures". Also my textures are not built in to the shader but added programmatically like this void Awake () meshFilterComponent GetComponent lt MeshFilter gt () Material material GetComponent lt MeshRenderer gt ().material material.SetTexture(0, paperTexture) material.color new Vector4(1f, 1f, 1f, 1f) Where paperTexture is set up in the GameObject to point to the correct texture. Is there any way to force a texture to be part of a build? Let's say that you swap out textures in code, like swapping themes, how would you make sure they're all there to be loaded as needed? Running On iPhone Running In Unity3D


unity3d Object keeps falling down I have an object that moves towards another object using this line transform.position Vector3.MoveTowards(transform.position, target.transform.position, speed Time.deltaTime) this is it's attributes It doesn't use gravity, kinematic and it's Y position is frozen, but it keeps falling to the floor and colliding with it. How do prevent that and keep it floating ?


How to use Input.GetAxis("Mouse X Y") to rotate the camera? I want to make a first person camera that rotates with the mouse. I looked at the Input.GetAxis Scripting API page and found a sample code, which I have included at the bottom of my post. Upon trying it out, I realized that although it has the same basic functionality I hoped it would have, it does not keep the camera parallel to the xz plane, particularly when moving the mouse in circles. After a while the camera would be at an odd angle, and the player would be completely discombobulated! Is there a quick fix to this code that would restrict the camera movement somehow, or is there a better way to rotate the camera? using UnityEngine using System.Collections public class ExampleClass MonoBehaviour public float horizontalSpeed 2.0F public float verticalSpeed 2.0F void Update() float h horizontalSpeed Input.GetAxis("Mouse X") float v verticalSpeed Input.GetAxis("Mouse Y") transform.Rotate(v, h, 0)


Client side prediction buffer size considerations for jitter I am currently having a FPS game with client side prediction. Every 20ms, the client sends it's input to the server. The server buffers 5 ticks worth of input (100ms) and starts consuming the inputs each tick and sends a world snapshot to the client. The client then validates the predictions and corrects the simulations if there is a misprediction. The setup works fine under ideal network conditions. However when the latency suddenly spikes from say 50ms to 400ms, the client's tick packet is delayed which causes the server to eat through all of the available inputs in the buffer and resort to using the previous tick values to perform server simulation. When the client input finally arrives at the server late, the server discards the input because it has already processed the input for that particular tick (using old input values). How do I handle this edge case of latency increasing and decreasing? Sure I could use a larger buffer size for the inputs, but that will cause delays between client state and server state. Using a smaller buffer will cause the server to stall from inputs if there is a jitter that is more than the duration required by the server to process the inputs. I was under an impression that I would need some kind of dynamic buffer size that expands and contracts. However, I am out of ideas to implement something like this. Does anyone have a solution?


Unity 2d overlapCircle melee combat issue I have an issue with my overlapCircle melee combat in the game. I'm not good at such things, so I just copied that code from some YouTube tutorial. But the thing is that if the enemy is behind the collider, I can still damage and kill him. And I don't want this. Is there a solution to this problem except recreating the melee combat system from the ground up? Maybe changing circle radius when close to collider?... Here's a video clip that may help show the situation. void Attack() Collider2D hitEnemies Physics2D.OverlapCircleAll(attackPoint.position, attackRange, whatIsEnemy) foreach (Collider2D enemy in hitEnemies) Debug.Log( quot Melee hit quot enemy.name) if (enemy is BoxCollider2D) CinemachineShake.Instance.ShakeCamera(3f, 0.2f) SoundManager.PlaySound( quot Knife kill quot ) if (enemy.tag quot Melee enemy quot ) enemy.GetComponent lt enemy melee gt ().TakeDamage(attackDamage) else if (enemy.tag quot Gun enemy quot ) enemy.GetComponent lt enemy gun gt ().TakeDamage(attackDamage) animator.SetTrigger( quot Melee attack quot ) animator.SetBool( quot IsCrouching quot , false) animator.SetBool( quot IsJumping quot , false)


How do I get the Oculus Rift's position and rotation? I'm looking for the functions to get the position and rotation data of the rift headset itself in Unity. I have the Oculus integration SDK installed and want to avoid using any pre fabs.


How do C and UnityScript differ in Unity development? Other than the obvious language differences, how do UnityScript and C differ when developing games in Unity3D? Is there a noticable performance difference? Is the UnityScript code packaged as is? If yes, does this help the game's moddability? Is it possible to use libraries developed for one language while developing in the other one? Can the two languages be mixed in the same Unity project coding some parts in C and others in UnityScript?


Will I lose the mesh if I delete the original prefab? I'm working in Unity 5, and I currently have the following setup My project contains two prefabs which we'll call "Cube" and "CubeT". Cube was imported from an FBX file generated by Autodesk 3DS Max, and CubeT was created within Unity. I want to be able to modify Cube's mesh collider, but Unity will not allow me to do so. Therefore, I've thought about adding the mesh within Cube to CubeT and removing Cube. The thing is, I'm worried that I'll lose the mesh when I delete Cube, and subsequently lose the reference to it in CubeT. If I reference Cube's mesh in CubeT and then remove Cube from the project by deleting the asset within Unity, what will happen? Will the needed mesh remain in the project or am I going to have to find another way?


How to playlay multiple Particle Systems when colliding with multiple obstacles using object pooling? I have two types of particle, one for each player Player 1 (Red Particle) Player 2 (Blue Particle) When player 1 collides with an obstacle then I want to play the red particle system, and when player 2 collides with an obstacle then I want to play the blue particle system. Code TouchControll.cs public GameObject PlayersPartical void OnTriggerEnter2D(Collider2D other) here my player collided with obstacle foreach (Transform child in transform) if (child.tag "point") GameObject partical Instantiate(twopartical Random.Range(0,1) , transform.position, transform.rotation) ParticleSystem heal partical.GetComponent lt ParticleSystem gt () heal.Play() GameObject partical Instantiate(PlayersPartical, transform.position, transform.rotation) ParticleSystem heal partical.GetComponent lt ParticleSystem gt () heal.Play() ObjectPooler.Instance.SpawnFromPool("redandbluepartical", transform.position, Quaternion.identity) ObjectPooler.cs public static ObjectPooler Instance public void Awake() Instance this System.Serializable public class Pool public string tag public GameObject prefab1 public GameObject prefab2 public int size public List lt Pool gt pools public Dictionary lt string, Queue lt GameObject gt gt pooldictionary which gameobject you should be pool void Start () pooldictionary new Dictionary lt string, Queue lt GameObject gt gt () foreach(Pool pool in pools) add a pool in list Queue lt GameObject gt objectpool new Queue lt GameObject gt () for(int i 0 i lt pool.size i ) GameObject obj Instantiate(pool.prefab1) GameObject obj1 Instantiate(pool.prefab2) obj.SetActive(false) obj1.SetActive(false) objectpool.Enqueue(obj) pooldictionary.Add(pool.tag, objectpool) public GameObject SpawnFromPool(string tag,Vector3 position,Quaternion rotation) two tag red and blue partical if(!pooldictionary.ContainsKey(tag)) Debug.Log("doesnot exist" tag) return null GameObject objecttospawn pooldictionary tag .Dequeue() here how to call my trigger objecttospawn.SetActive(true) objecttospawn.transform.position position pos objecttospawn.transform.rotation rotation rotation pooldictionary tag .Enqueue(objecttospawn) return objecttospawn Image1 Image2 How do I call these particles?


How to rotate a whole Bezier Curve around a given point I am using the code from the question Adding functionality to make individual anchor points of bezier continuous or non continuous to create bezier curves (I added a line renderer). How can I rotate the whole bezier curve (which may contain multiple cubic B zier segments) around a point? Please note that the rotation point could be any point including the one of the curves anchor points or control points.


Get MonoBehaviour components from Prefab I need to assign the script values for the following Prefab in Unity 3.5 The structure is the following Kinect Prefab MonoBehaviour Script Missing Mono Script MonoBehaviour Script Missing Mono Script MonoBehaviour Script Missing Mono Script MonoBehaviour Script Missing Mono Script All the components have the same name. I have tried to obtain all of them in an array, but the GetComponents method does not seem to work properly. var mono MonoBehaviour mono Kinect Prefab.GetComponents(MonoBehaviour) The thing is the resulting array is empty. Any idea what might be wrong? EDIT When I do GetComponents(MonoBehaviour) I get the following error InvalidCastException Cannot cast from source type to destination type. I have tried receiving the components in var mono Component but I still don't receive anything


Algorithmically fracture a mesh in Unity3D? I want to create a plugin which shatters fractures meshes, so I can make every object destructible if I want to. Like in Unreal's built in feature. My quick approach to this problem is randomly generating cuts (planes) every cut divides the mesh into 2 groups left side of the cut and right side of the cut, at the points where it intersects the mesh, I add vertices to both groups. and add 1 1 face to each group with these new vertices. create the new mesh. Is there a better way? What do you recommend? Is my way even possible? If yes, what API methods should I use?


Need help to make and optimize a dense forest in Unity with bird view camera I'm currently developing a RTS game that has a bird view camera operating while playing the game. One of the core aspects of my game are trees. So in the previous days i was playing with trees in Unity. First i played with Unity Tree Creator however later i realized it is broken since 2018.3, and devs said it wont be fixed because it will be a community developed package in the future Then i downloaded assets from the store that are said to be highly optimized trees, however they are mostly for "3rd person camera projects" thus having around 7 14k triangles. After these experiences, i decided to export a tree prefab to fbx, then manually decrease the triangle count to around 2.5k in 3ds max, then reimport it to Unity. With this technique i was able to produce quite good results, but still not very satisfied with it. My camera view, and my "dense forest" 180 300fps... and only like 3 4 shadows For the above picture i used a Tree with 2 LOD and one billboard(BB). After playing with this i realized i can sure do better especially with playing LOD numbers, material optimization, and with the default tree trinagle optimization. However the problem is i can't model pine trees that satisfy my needs in 3ds max. So i started looking into SpeedTree documentation, however it seems a bit too professional for my needs(All the tutorials also make trees with like 20k poly tri). So regarding this story. I would like to ask the following question a bonus one about LOD Can you model quality trees with SpeedTree for Unity that have like around 1k 2k triangles, or SpeedTree is for high quality high poly trees, they algorythms won't work with lower polygon count etc? (I heared they have a simplify modifier is it good? like make a 7k triangle tree then cut it to 1k 2k) I'm thinking about using 4 5 LOD and a BB for smooth transition. In my picture i use 2 LOD and a BB and sometimes when moving the camera fast, transitions are not as smooth as i want it to be. So i would like to rather have more lower detailed meshes before trasitioning to BB. So does having a 4 5 LOD s a common practice or any better ides for this?


Every X months Visual Studio Code says 'UI' does not exist in the namespace 'UnityEngine' I've tried countless fixes in the last 1,5 year, and I still don't know what is the absolute fix for this. Or after fixing it, why it got fixed. Usually this happens after a Unity update, or after updating the IDE packages. I tried lots of fixes, and it seems like that it's always changing what fixes it Sometimes it's fixed by regenerating all projects files, also sometimes manually deleting them. Sometimes it's fixed by reinstalling Visual Studio. Sometimes it's fixed by downgrading the IDE packages (until now not for me, but based on some browsing, it works for some people) Switching to Visual Studio in the preferences, opening it, then switching back to Code. (At first I thought that this is just regenerates the projects files, but who knows, maybe it does something else in the background.) This time it got fixed after I switched to Visual Studio, opened Visual Studio, and it showed missing references. So I closed it, regenerated all project files, and then reopened it. Now Visual Studio works. And after this, I switched back to Visual Studio Code, and now it works there as well. (I always restart Unity and Code after these) Sometimes it isn't fixed by just going through this list one by one. Sometimes none of them fix it, so I try them all again, in different order, etc, and then it's fixed after some random combination. Most of the times only Visual Studio Code is broken, but sometimes Visual Studio is missing the references as well. Could someone tell me why this keeps occurring for a lot of people, and what is the absolute fix and why? In the log, it says that UnityEngine.UI got successfully loaded and added OmniSharp.MSBuild.ProjectManager Successfully loaded project file 'c Projects RPG UnityEditor.UI.csproj'. OmniSharp.MSBuild.ProjectManager Adding project 'c Projects RPG UnityEditor.UI.csproj'


How to get the physical camera sensor size on iOS Android in Unity I'm trying to get the physical camera sensor size on iOS and Android mobile devices for intrinsics calculations. On Android the sensor size should be found in the SENSOR INFO PIXEL ARRAY SIZE (Android CameraCharacteristics API). However I don't find a way to access that array via ArFoundation. I can imagine to write a plug in for that, but I would also require a plug in for iOS so I don't know if that's the right way to go. Is there maybe another (easier) way to get the physical sensor size?


Unity 2018.3.0f2 Blank Errors I am getting these blank errors in unity for quite a while now, as soon as I create a new Project 2D or 3D I am presented with the following and can't enter in play mode. And as a workaround I have to change the Scripting Runtime Version to 3.5 in the project settings to make it work. I cannot able to work with version 4.x I have the Window 7, .NET Framework 4.7.2 Installed, any help or advice is much appreciated. Thank you.


Unity3D position of 2D objects with size of Object I'm making a 2D project in Unity3D. I want to place an image in the right upper corner. I've got this working, but ofcourse the image is falling of the screen for a part (and completely when I change the screenrotation). This is the code I've got for it posImage new Vector2(Screen.width imgGear.transform.localScale.x, Screen.height imgGear.transform.lossyScale.y ) As you can see in the code I've tried to adapt the position with the size of the object, using localScale 1.0f and lossyscale 0.9...f doesn't really do much as it will be changed with 1 unit. Is their a way to get the real width and height of the objects?


How do I find the name of the current audio clip being played? I have a title scene and a credits scene that use the same music. When I start my game the title scene music plays, and I have my game set up so the audio manager is not destroyed on load. When I enter my credits scene I do not instruct any new music to play, but each time I reload my title scene the title music restarts because a script in the scene tells it do so. How can I get the name of the current audio track so that I will only play audio if it differs from what's currently being played? This is my "LevelMaster" script which is responsible for handling the audio in each scene. public class LevelMaster MonoBehaviour private AudioManager AudioManager SerializeField private string trackName private void Start() AudioManager GameObject.Find("AudioManager").GetComponent lt AudioManager gt () AudioManager.Play(trackName) public void PlaySound(string soundName) AudioManager.Play(soundName) public void StopSound(string soundName) AudioManager.Stop(soundName)


Instantiate prefab randomly but not in already occupied position I want to generate bubbles randomly on screen. When a bubble is generated in one place then other bubbles should not be generated near its radius 1 area, so they can not collide or trigger with any other bubbles. How can I do it ? public void GenerateBubble () newBubbleXPos Random.Range ( 7, 7) newBubbleYPos Random.Range ( 3, 3) bubbleClone (GameObject)Instantiate (bubblePrefab, new Vector3 (newBubbleXPos, newBubbleYPos, 0), Quaternion.identity) UIManager.instance.ChangeBubbleSprite (bubbleClone) bubbleList.Add (bubbleClone) if (bubblePosList.Contains (bubbleClone.transform.position)) bubbleClone.transform.position new Vector3(Random.Range ( 7,7),Random.Range ( 3,3),0) bubblePosList.Add (bubbleClone.transform.position) bubbleClone.transform.parent UIManager.instance.CurrentLevel.transform GLOBALS.bubbleCounter In this code every bubble is generated in a different position, but they can collide with other bubbles. I want to generate new bubbles not at the same position. My bubble colliders's radius is 1.


How can I ensure a radius variable doesn't get reduced below 0? For some reason when I'm using the mouse to change the radius in the Update, the minimum radius is 1 even if I set the range in the top of the script to be 0,50 and even if I check that the xradius is be 0 or higher it's still getting to 1. using UnityEngine using System.Collections using System.Collections.Generic using System.Linq using System RequireComponent(typeof(LineRenderer)) public class DrawCircle MonoBehaviour Range(0, 50) public int segments 50 public bool circle true Range(0, 50) public float xradius 15 Range(0, 50) public float yradius 15 LineRenderer line public float drawSpeed 0.3f void Start() line gameObject.GetComponent lt LineRenderer gt () line.positionCount (segments 1) line.useWorldSpace false private void Update() if (xradius gt 0) if (Input.GetAxis("Mouse X") lt 0) xradius xradius 1 CreatePoints() if (Input.GetAxis("Mouse X") gt 0) xradius xradius 1 CreatePoints() private void CreatePoints() if (circle true) yradius xradius float x float z float change 2 (float)Math.PI segments float angle change for (int i 0 i lt (segments 1) i ) x Mathf.Sin(angle) xradius z Mathf.Cos(angle) yradius line.SetPosition((int)i, new Vector3(x, 0.5f, z)) angle change In the Update I did if (xradius gt 0) But yet when using the mouse for the minimum radius it set both xradius and yradius in the sliders to 1 not sure how can it be 1 if I set the range in both xradius and yradius to be 0,50 You can see in the screenshot in the Inspector in the right both Xradius and Yradius are 1


Unity DontDestroyOnLoad FindObjectsOfType(GetType()).Length is always returning 1 I'm trying to have an object with the DontDestroyOnLoad property. I want an object with NetworkIdentity to persist across scenes, so I can have a holder script for RPCs. This answer suggests the following code public void Awake() DontDestroyOnLoad(this) if (FindObjectsOfType(GetType()).Length gt 1) Destroy(gameObject) Despite this, I still end up with duplicate objects. FindObjectsOfType(GetType()).Length is always returning 1, and I don't know why, or how to fix it. It makes no difference whether this object is a prefab instance or a simple object in the hierarchy. I have also tried to clone this object in my NetworkManager script, which is automatically persistent, but GameObject.Find("ObjectNameHere(Clone)") is always returning false. However, the above solution seems simpler so I'd prefer to figure out FindObjectsOfType(GetType()).Length.


NullReferenceException Object Reference Not Set to an Instance of an Object (How is that so and I should I solve it?) I am stuck several days because of this problem, which I am almost on the verge of giving up. (Using Unity Engine 2019.3a by the way). The TextButtonName.text can't read what TextButton is throwing to it. Meanwhile, when I did a Debug.Log test, the console shows what is the text in the TextButton. What the console showed about Debug.Log() thing should be the value of a variable assigned (hence, the Is there any way that whatever is the text at the button, will be the value that can be used for Switch Statements? If there is a way (I am sure there is), how? Thanks. When pressed, ButtonPress() will be triggered and will go to Experiment Information Scene public void ButtonPressTutorial() TextButton gameObject.GetComponentInChildren lt Text gt ().text TextButton EventSystem.current.currentSelectedGameObject.GetComponentInChildren lt Text gt ().text TextButtonName.text TextButton TextButton, although has value shown in Debug.Log, the problem is that it throws a NULL value when being thrown to TextButtonName.text Why is that? Is there that I need to do? Debug.Log(TextButton) SceneManager.LoadScene(5) Switch statements switch (TextButtonName.text) case " Tutorial" ExpNum.text "Tutorial" ExpTitle.text "Coke With Mentos Experiment" ExpDetails.text " Details will be shown here" break case "Experiment 1 Button" ExpNum.text "Experiment 1" ExpTitle.text "Lemon Volcano Experiment" ExpDetails.text " Details will be shown here" break default ExpNum.text "No Experiments" break


How can I make a chest that can be opened and shut in SteamVR? I'm working in Unity with SteamVR for a school project. I'm trying to have a chest that can be opened and shut. I tried using a hinge joint but it would break if the attached body was static which is what I want. I'm now trying to use a circular drive which works better but the lid to the box will move away from the intended position when colliding with the body of the box which is set to static and kinematic. I can fix this by setting the lid to kinematic but it won't collide with the body anymore. Both the lid and body are properly colliding with the hand and with a sphere I added to help test collisions. I'm assuming the issue is that two kinematic objects can't collide with each other but I don't know how else to approach this.


Why do asymmetric specular highlights appear in a scene with only ambient lighting in Unity? I have a scene in Unity (2019.3.0f3 Personal) using the High Definition Render Pipeline. There are no lights in the scene, and Baked Global Illumination is disabled. The skybox is a GradientSky. By all means, the lighting in the scene should be absolutely uniform, but instead there is a gradient from one side to the other. This is what the scene looks like Though the effect is faint, you can see that the right side of the plane is slightly lighter than the left. The ground shader is HDRP TesselationLit, and by bringing the Smoothness Remapping to max I can exaggerate this effect, as shown below. This is why I am under the impression the effect is specular in nature. Interestingly, if I switch the camera to the Isometric mode, the effect disappears Finally, the effect appears to occur in world rather than camera space, as shown by the changes in lighting when I rotate my camera in increments of 90 degrees What is causing this effect, and how can I disable it?


How do you pass arguments with UnityEvents? I was inspired by a great talk at Unite by Ryan Hipple. https youtu.be raQ3iHhE Kk?t 28m His examples didn t cover passing arguments with UnityEvents Do I need to extend UnityEvent, GameEvent and GameEventListener from a generic base class for this to work properly? If so do I need to make a new set of classes for each Type and combination of Types that I want to pass? Game Event Scriptable Object CreateAssetMenu public class GameEvent ScriptableObject lt summary gt The list of listeners that this event will notify if it is raised. lt summary gt private readonly List lt GameEventListener gt eventListeners new List lt GameEventListener gt () public void Raise() for(int i eventListeners.Count 1 i gt 0 i ) eventListeners i .OnEventRaised() public void RegisterListener(GameEventListener listener) if (!eventListeners.Contains(listener)) eventListeners.Add(listener) public void UnregisterListener(GameEventListener listener) if (eventListeners.Contains(listener)) eventListeners.Remove(listener) Listener Class public class GameEventListener MonoBehaviour Tooltip("Event to register with.") public GameEvent Event Tooltip("Response to invoke when Event is raised.") public UnityEvent Response private void OnEnable() Event.RegisterListener(this) private void OnDisable() Event.UnregisterListener(this) public void OnEventRaised() Response.Invoke()


Unity calculate the size of a text box before text gets drawn so it can lerp to the next size Im trying to make a dialog box image that lerps to the next size. In order to do that I need to calculate the size of the image before the text gets drawn. My idea is to use the legacy GUI stuff like guiStyle.CalcSize to get the width and guiStyle.CalcHeight to get the height. then im setting the image's layout elements min values to the GUI sizes. the width is set to the longest string in the array of "lines" the problem is that while the image does scale it doesn't do so correctly. perhaps my approach is wrong and there's an easier way? private void Update() lineText dialogueRunner.dialogText drawnText dialogueUI.lineText.text Debug.Log(prefferedValues) numberOfCharactersInLine dialogueRunner.dialogText.Length lineTextWithNewLine NewLineAfterNChar(lineText, 18) string lines lineTextWithNewLine.Split(new " n" , StringSplitOptions.None) for (int i 0 i lt lines.Length i ) longest lines.OrderByDescending(s gt s.Length).First() prefferedValues textMesh.GetPreferredValues(longest) Debug.Log(longest.Length) scale isnt correct layoutElement.minWidth size.x layoutElement.minHeight size.y void OnGUI() guiContent new GUIContent(longest) guiStyle GUI.skin.box guiStyle.alignment TextAnchor.UpperLeft guiStyle.wordWrap true boxSize new Rect(Screen.width 2, Screen.height 1, txtBGRect.sizeDelta.x, txtBGRect.sizeDelta.y) boxSize.center new Vector2(Screen.width 2, Screen.height 2) Compute how large the button needs to be. size.x guiStyle.CalcSize(guiContent).x width size.x 1 size.y guiStyle.CalcHeight(guiContent, width) height size.y GUI.Box(boxSize, longest) this draws the box Pass it a string and it will insert a line break after every n characters at end of words. public static string NewLineAfterNChar(string inputText, int lineLength) string stringSplit inputText.Split(' ') Split string into array seperatly "word1" "word2" "word3" etc... int charCounter 0 string finalString "" for (int i 0 i lt stringSplit.Length i ) iterates per word count finalString stringSplit i " " "word1 " "word2 " "word3 " charCounter stringSplit i .Length if (charCounter gt lineLength) after n characters finalString " n" charCounter 0 return finalString


Movement in grid in Unity I am a beginner at Unity. I want to make a game like Lightbot, but in 2d (without the z axis movement) with some obstacles. Before making the function system of the Lightbot, I want to make the in game character move on a grid by the set of key inputs (e.g. WASD) by the player. But I'm stuck here. I searched on Tilemap which makes a grid, but I have no idea how to save the set of input keydowns and move my character on this grid at once. Suppose my character is on the (0, 0) square for example. After the player taps WWDD, then my character should move to the following squares, in the following order (0, 1) (0, 2) (1, 2) (2, 2) How can I achieve my goal?


Unity 5 Input Field How to confirm password entry with ENTER only and not a click loss of focus I have an input field password box, currently the password is 'submitted' either by clicking Enter or by clicking elsewhere on the screen. This seems to be the designed way, as it states this in the documentation (https docs.unity3d.com Manual script InputField.html) "A UnityEvent that is invoked when the user finishes editing the text content either by submitting or by clicking somewhere that removes the focus from the Input Field." As I have other buttons on the same screen that users can click on, I would like it so mouse clicks are not counted as an invoke. Is this possible? Many thanks in advance


Prefabs moved to before position when zooming scene I have build some pipes for waterline drawing, like following screencast https youtu.be WnJb1JwOW78 As you can see, when I zoom in the scene, Pipes moved to lower position. When i zoom out, Pipes moved to higher position. Actually I have changed the position and moved down the pipe position before, the unexpected higher position was the pipe before position. So i guessing this problem might about cache clean. So I I try to clear the GI cache, but the problem still exist. And then I try to build a windows executable file and run game again, problem still. How to fix it? I am using Unity 2018.4


How can I make a gameobject snap to something when it gets close to it? Any idea if there is a way I can make a gameobject snap to something when it gets close to it? Like drag a cube around and when it gets close to something then snap to it.


Where does Unity save Inspector properties for objects in a scene? If I add a collection of objects to my scene and configure Inspector properties on those objects (like name, layer, tag, transform parameters, attached Components and their parameters), where does the information about those Inspector properties get saved within my project? Is it all saved within the scene's .unity file or are there other files I should look at?


Unity raycasting not always detecting component I am trying to determine what object I am clicking with the help of a raycast, however it doesn't always work In update I call if (Input.GetMouseButtonDown(0)) selectedObject null selectedUnits new List lt Unit gt () Select(Input.mousePosition) startPos Input.mousePosition which calls void Select(Vector2 screenPos) Ray ray cam.ScreenPointToRay(screenPos) RaycastHit hit Debug.Log( quot 1 quot ) if (Physics.Raycast(ray, out hit, 100)) OnClicked(hit.transform.tag) Debug.Log( quot 2 quot ) if (hit.transform.GetComponent lt Unit gt ()) Debug.Log( quot 3 quot ) if (!selectedUnits.Contains(hit.transform.GetComponent lt Unit gt ())) Debug.Log( quot 4 quot ) selectedUnits.Add(hit.transform.GetComponent lt Unit gt ()) if (hit.transform.GetComponent lt Building gt ()) if (hit.transform.GetComponent lt Building gt () ! selectedObject) selectedObject hit.transform.gameObject Detecting a quot building quot always works and is fine, but clicking on a quot unit quot works anywhere between 0 and 5 times per play session before it returns nothing anymore like the object doesn't exist. I have tried to find where it gets stuck and it gets stuck after the 2nd debug (debug 1 and 2 print but 3 and 4 do not). This is the Unit in the inspector and this is it in the hierarchy When drawing the ray here you can see it hits the cube 3 times before it just passes right through the 4th time. it seems like after each hit the ray penetrates the collider more and more But how and why can it only hit it a couple of times before it passes through. After a certain amount of clicks with or without moving my mouse it just doesn't hit it anymore even though in the inspector nothing changes and there are no scripts that alter the box collider. I hope someone knows what's going wrong, thanks!


Transform manipulator for Unity Oculus Touch game like in Quill, Medium etc I'm trying to create a script to manipulate the transform of a gameobject using the Oculus Touch just as in for instance Quill or Medium, with rotation, translation and scaling. Can somebody help me with this? My initial attempt was to focus on rotation and I got it almost working I think. Here's the code void Update() On button down if (OVRInput.GetDown(OVRInput.Button.SecondaryIndexTrigger)) originalRotation transform.localRotation originalControllerRotation OVRInput.GetLocalControllerRotation(OVRInput.Controller.RTouch) While button is down if (OVRInput.Get(OVRInput.Button.SecondaryIndexTrigger)) var controllerRotation OVRInput.GetLocalControllerRotation(OVRInput.Controller.RTouch) var rotation originalRotation rotation Quaternion.Inverse(originalControllerRotation) rotation controllerRotation transform.localRotation rotation This kind of works but the rotation center doesn't look right. I want it to rotate around the center of the right touch controller and it looks to be rotating around the local origo of the gameobject. How do I modify the code so it rotates around the controller instead?


How can I play a particle system only when it's visible? I am making a game and it has a lot of particle systems in it as special effects, and all of them are supposed to be playing at the same time, but doing that will be heavy on the game's performance, then I thought Is it possible to play a particle system only when it is visible to the camera and stop playing it when it is out of range or hidden from the camera, maybe with physics raycasting? If it is, can someone help me to write codes that will do so.


When scene loaded up, Position player at a start point. (Unity2D) If pointName and player.startPoint are true, shown by the inspector, why doesn't the player's position go to the start point with a pointName of "ToNeighborhood". Note The code runs if pointName player.startPoint. It isn't running even when they both contain the same string shown by the inspector using System.Collections using System.Collections.Generic using UnityEngine public class PlayerStartPoint MonoBehaviour private PlayerController player private CameraController theCamera public string pointName Use this for initialization void Start () player FindObjectOfType lt PlayerController gt () theCamera FindObjectOfType lt CameraController gt () if (pointName player.startPoint) Debug.Log("Changing") player.transform.position gameObject.transform.position theCamera.transform.position new Vector3(transform.position.x, transform.position.y, theCamera.transform.position.z) Update is called once per frame void Update ()


What the difference between public int and int? I was trying to understand the difference of int and public int by checking how unity respond to it using UnityEngine using UnityEngine.Assertions.Must using UnityEngine.SceneManagement public class Bird MonoBehaviour int CurrentState 1 int PreviousState 1 Void Update() (if CurrentState ! PreviousState) transform.localScale new Vector3(transform.localScale.x 1,transform.localScale.y 1,transform.localScale.z 1) Since the equality is false, the scale of object remail unchange and in my next step, I changed quot int CurrentState 1 quot to quot public int CurrentState 0 quot and quot int PreviousState 1 quot to quot Public int PreviousState 1 quot . Isn't that this time, the equality is true as 1 ! 0 but the scale of object remained the same. Once I deleted the word quot public quot on both currentstate and previousstate, the scale increase indefinitely. I thought the word quot public quot basically meant there no access restriction but why it looks like the quot if quot statement couldn't retrieve the info correctly?


Create Bezier curves with random heights that connect In unity, I am trying to create several curved platforms that connect using bezier curves, however I am having issues. I understand the basics of genertating a bezier curve and I have something working well My goal is to generate a series of forward moving Bezier curves, that are all connected to each other, while also having varying lengths and points. I have something working, however I am having issues connecting the curves, while retaining random Y values for different heights in the 4 points. Below is my attempt Below is a Sketch I did in MS Paint to help explain goal From the sketch you can see that there is a diffrence in height between gameobject 0 and 1 but they are still connected. How can I generate the next points with random Y values, while still accounting for the previous curve? Any help would be greatly appreciated, Thank you for your time.


Unable to edit tile sizes in unity I'm trying to change the size of sprites in unity to fit the palette. Except there are no options to change multiple sprite sizes at once. But when I watched a youtube video on tilemaps and palettes, there were options to change the size of the entire palette! v2019.2.11f1 (Personal)


2D engine that uses Flash Platform classes? I want to develop a 2D game for Android, but, I want to use Flash Platform's framework APIs, ex Sprite, Shape, Graphics, Bitmap .. etc as I have already wrote my game in AS3 .. Is there a 2D engine for Android that uses Flash Platform's framework APIs? If not, does Unity use Flash Platform's framework APIs? I know that I can Adobe AIR to port the game to android, but, I want it a native code based to avoid Adobe AIR player as a requirement .. Any guidance?


How do I calculate UV space from world space in the fragment shader? In my vertex shader I have calculated the world space o.worldSpacePosition mul(unity ObjectToWorld, vertIn.vertex) How do I convert that world space into uv space coordinates in my fragment shader? float4 frag(VertexShaderOutput i) COLOR SV Target0 float2 uv i.worldSpacePosition ??? I have tried float4 mvp UNITY MATRIX MVP 3 float2 uv mvp.xy p.w but that does not appear to work as the uv is always (0, 0) EDIT I am drawing a mesh on the screen in world space coordinates which needs to lookup into a screen space texture The way I am currently solving this is by calculating the uvs for each vertex of the mesh using the following calculation camera.WorldToViewportPoint(vertices i ) Unity uses normalised coordinates for the viewport 0,1 rather than 1,1 . This works fine but I wasn't sure of the behaviour if part of the polygon is off the screen. I presume I should clamp the uv? Screen space might not be the correct term for the uv coordinates. Perhaps texture space is a more appropriate term?


Unity2D Floor tiles moved or missing I'm following the 2D Roguelike tutorial, which can be seen here. I don't want to get fancy, just follow the existing steps. I've reached the part where all it's supposed to do is draw the playfield. But it looks like this and I don't know why. Some of the floor tiles are appearing beyod the outer wall, and others are missing (or maybe they're stacked on top of other tiles). (EDIT I discovered that the "missing" tiles are because I had the sprites in the wrong layer, and fixed them. I still have several appearing to the left of the outer wall, though.) I tried to debug it in Visual Studio. The plan was to step through it line by line to see how the tiles are put down, but the debugger doesn't show the playfield until the whole thing is complete.


Why Godot over Cryengine, UE4, Armory3d or Unity3d? Godot have a low performance in linux systems and lack of functionalities? This appear not been in account when peoples vote for him over other engines and i wonther whi. I know it is under MIT lisence, but the others engines have a very permisive licences and in some cases they help you with funding for your games. I ask this because i have maded survey on google plus about a selection of engines, and people still bote for godot over other engines. I want to select an engine for my future games, and when i compared, godot's not get a good place.


When creating an FPS style game, how should the iron sights be setup? I am working on creating an FPS style game for learning purposes. I previously was using self created animations for aiming down the iron sights of a gun. The animation would play when you zoom to iron sights and it would hold it there as long as you have the mouse held down. However, talking to a high rated designer, he told me usually it is done with a second camera that sits perfectly aligned with the guns iron sights. I would imagine you would still have to have an animation that then transitions you into that iron sight camera though. Now my animation works fine but I feel I may run into a problem later down the road if I am approaching it the wrong way from the start. Can someone verify the right way to do this and explain why it is?


Updating the position of a prefab in Unity for A pathfinding I am trying to use Aron Granberg A pathfinding project in my game. I am very new to Unity, so I am having some trouble figuring out how to instantiate multiple enemies from a prefab that will seek out my player. I am unable to set the player object from the scene as the target, since prefabs cannot take in scene objects. However, if I use the player prefab as the target, the enemies will only go toward the starting position of the player. Is there any way to update the prefab position as the player instance moves? Or is there a better way of doing this? I want this to be a top down shooter style game (2D) with constant enemy spawning, so it doesn't make sense to set the target for each individual enemy instance. Any help would be greatly appreciated. Thank you!


Unity Manually sync location of players from server to client I am new to Unity networking. I've set up my scene with NetworkManager and the Player prefab having NetworkIdentity. I originally had my players set up to sync with a NetworkTransform. This worked, but the objects were very choppy whenever they were children of a moving object. In order to fix this issue, I've replaced NetworkTransform with a class extending NetworkBehavior, using UnityEngine.Networking, and containing the following code to sync localPosition void Update () CmdSyncPos (transform.localPosition, transform.localRotation) Command protected void CmdSyncPos (Vector3 localPos, Quaternion localRotation) transform.localPosition localPos transform.localRotation localRotation This works really well! The only problem is that this is one way, the server now has the updated position of all clients but the clients only have the updated versions of themselves. How can I do this in reverse Manually sync the location of non local players from server to client?


Unity Performance How many Materials per Object? I have learned that a Mesh with 4 Materials each 1024x1024 in Size is somewhat slower than a Mesh with 1 Material 2048x2048 in Size? In my usual workflow I tend to seperate different Materials into different Materials so an Object tends to have around 2 8 Materials. I have created more than a hundred Assets like this. Is the performance dramatically affected by this? Is it acceptable to upload such Objects to sites like turbosquid or sell them on Unity Asset Store or will the buyer behead me after noticing? Window Textures need to be transparent, Metal Wood Concrete need different smoothness settings. As far as I know Unity doesn't support Gloss maps.


ParticleSystem, performance behind the technique on batching with different materials I found that guide https thinhhb.wordpress.com 2016 03 27 unity3d optimization make atlas textures for particlesystem reduce drawcall why not which is quite clever. As far as I know, we can't batch ParticleSystems with different materials, for example A star (Particles Additive) A smoke (Particles Additive) give 2 draw calls. The guide points, that we can use a TextureSheet trick to achieve batching of different graphics on multiple ParticleSystems like that We create a spritesheet manually and cut it in Unity's SpriteEditor into a grid, and create a material Then, we create our ParticleSystems and attach generated sprites into Texture Sheet Animation Module And here the magic happens. They batch. My question is, what is the overhead behind this? Is the TextureSheetModule expensive? If I have 15 different sprites, their ParticleSystems create 15 batches, which is quite expensive on mobile. Is it wise, to move to TextureSheet and save these 14 batches?


In Unity, how do I make text annotations appear when I mouse over GameObjects in playmode? How do I make text appear when I mouse over GameObjects in game? What is the Unity jargon for this? I'm assuming it's 'annotations'.


Can't join to room through Unity's Matchmaking system on the Internet It works perfectly when I try to connect locally from my editor to my running build. But after I start the server on my Android, and try to connect to it from my editor, it time outs As you can see, it finds the match, and then tries to join, but it can't. If I try to do it from a build, the log says the following Log cannot connect after 10 attempt address ffff 127.0.0.1 7777 ClientDisconnected due to error Timeout Why does it tries localhost, when I obviously use the Matchmaking system? When I tried it on 2 Android devices, the same happened. Ps. I know that it's going to be depracated, I just want to use it during a short term gift. Thanks in advance! Starting Matchmaker in a Start networkManager.StartMatchMaker() networkManager.matchMaker.baseUri new System.Uri("https eu1 mm.unet.unity3d.com") When the MatchScene ("Battle") is loaded if (this.isHost) networkManager.StartHost() else networkManager.StartClient() And the Play button's handle (still same component) public void Play() networkManager.matchMaker.ListMatches(0, 1, string.Empty, true, 0, 0, OnMatchList) void OnMatchList(bool success, string extendedInfo, List lt MatchInfoSnapshot gt matches) if (matches.Count 0) networkManager.matchMaker.CreateMatch("match", 2, true, string.Empty, string.Empty, string.Empty, 0, 0, OnMatchCreate) else networkManager.matchMaker.JoinMatch(matches 0 .networkId, string.Empty, string.Empty, string.Empty, 0, 0, OnMatchJoined) void OnMatchCreate(bool success, string extendedInfo, MatchInfo matchInfo) this.isHost true this.networkId matchInfo.networkId SceneManager.LoadScene("Battle") void OnMatchJoined(bool success, string extendedInfo, MatchInfo matchInfo) SceneManager.LoadScene("Battle")


RaycastHit2D.point is acting weird when used with circlecast2d When I make circleCast2d intersects with another circle collider, I get a RaycastHit2D.point that doesn't point at the tip of the collision as it states in the documentation. Instead it always points at the centre of the intersected junction or pointC as shown in the figure below. I checked this numerous times with different values to make sure the error was not from my end. Is this intended? If so is there another way where I can actually find the closest point from collider(B) to the centre of collider(A) which corresponds to point(D) in the figure? This is a picture of what looks like A circleCast B collided object C where RaycastHit2D.point is pointing at D where I'd like it to point.


Problem picking up a value, Delegate I'm having trouble passing values that are inside an int function to an onclick delegate. this script causes the object to move in vector3 ( 1 to the left and 1 to the right), these two values are inside the (int value), but I am trying to pass them to a delegate, but when inserting it it is adding different values than being in the script video of the problem private int index, index2 0 SerializeField private Vector3 Myposic1, Myposic2 SerializeField private Button left, right here I change the positions of Myposic1, Myposic2 SerializeField private float time public int slide 0 index between Myposic1, Myposic2. void Update() call() public void previous() slide call() public void next() slide call() void call() if (slide lt 0) slide 0 if (slide gt 1) slide 1 if (slide 0) left.onClick.AddListener(delegate player( 1) ) right.onClick.AddListener(delegate player(1) ) this.transform.position Vector3.Lerp (this.transform.position, Myposic1 index , Time.deltaTime time) if (index Myposic1.Length 1) right.interactable false else right.interactable true if (index 0) left.interactable false else left.interactable true Debug.Log("1") if (slide 1) left.onClick.AddListener(delegate player2( 1) ) right.onClick.AddListener(delegate player2(1) ) this.transform.position Vector3.Lerp (this.transform.position, Myposic2 index2 , Time.deltaTime time) if (index2 Myposic2.Length 1) right.interactable false else right.interactable true if (index2 0) left.interactable false else left.interactable true Debug.Log("2") public void player(int valor) index index valor public void player2(int valor2) index2 index2 valor2


Activate and Deactivate Collider with Click I'm having some trouble working with this, it's basically a sword that points toward your mouse position, and when you Left Click, a Trigger Collider is activated and then deactivated, but I can't get it to work. Here is my code void Attack() Activates the Sword Collider polygonCollider2D.enabled true Debug Line Debug.Log("Collider Active") StartCoroutine(Wait(0.1f)) polygonCollider2D.enabled false IEnumerator Wait(float seconds) yield return new WaitForSeconds(seconds) I did it this way hoping that the Wait method would give the game enough time to react to an active collider, and using some Debug.Log(). I know that the collider actually activates, but it does not react to other colliders. I keep wondering if this is the proper way of working with this. If it's not, do let me know.


Unity UI circular clickable area I'm building some somewhat involved UI stuff using the Shapes vector package. I need to be able to detect clicks on a circle, but also need to be able to click on things right next to that circle in all directions (it's a large circle). I can limit the detected clicks to within the circle by simply using a square and checking distance of click from center of circle. But this still obscures clickable things behind the square but outside of the circle (in the corners of the square). How can I detect those? Thanks!


Round to the nearest multiple of 0.75 in C How can I round a number to the nearest multiple of 0.75 in C Unity? The context is that I have a block and I want its position to be rounded at the nearest 0.75 multiple. For example 0, 0.75, 1.5, 2.25, 3, 3.25, 4.5, 5.25, 6, ... How can I do that?


Collision, triggering, and range detection in an RTS. What are the optimal solutions for unit spatial awareness? I've finally ran into the problem of multiple triggers and collisions within my 2D RTS. Up till now I've been using unities sphere colliders as a way of simulating spatial awareness. To trigger when objects have entered and exited a specific area around a unit or building so that they can be appropriately targeted. This became a performance problem when I started having hundreds of colldiers overlapping each other. Since the units are aware of projectiles as well as other units buildings, this becomes very expensive very fast. I've found that I can only manage to have a couple hundred projectiles and about 100 colliders within close proximity of each other before the game slows to a crawl just from PhysX. (hundreds of projectiles entering and exiting 100 collliders all the time) I did some research and found spatial partitioning mentioned all over the place. Is this a solution to the problem I am currently presented with? Are there other solutions for objects to have spatial awareness of potentially hundreds of other objects at a time without bringing my CPU to it's knees?


Open sourcing a Unity game with assets So, I have a goal to make and publish one (small, stupid, simple) game every Saturday. (I've made two, so far, thanks for asking.) I've started in Unity, because it's convenient. My plan for each game was to have a free version with ads, a paid version without, but also have it open sourced (and if they're willing to go to the trouble of removing the ads themselves, so be it). Now, concurrently, I keep wandering into e.g. Humble Bundle, or Unity Asset Store sales, and picking up things I probably don't need but maybe might use. It has just occurred to me, though, that if I'm open sourcing these games I kinda suspect the owners of these assets aren't going to be happy with me just posting all their files on the internet. Pretty sure I can't open source assets I've purchased. Now, I could probably just use free assets and make note of where they came from, and everyone would PROBABLY be ok with that. But that significantly restricts the things I can use. (And it would be kindof a waste you don't want to know how many ancient untouched game dev Humble Bundles I'm sitting on, haha.) Is there some kind of workaround? Like, if I posted the whole project, but included a license stating that only my code was open sourced, and the rest could not be used in anything else, for instance? Anybody know any nice solutions?


Combine all animation state into one clip (.anim) file in unity I have an animation controller where different animation states(clips) are available. Like this Now my aim is to convert all this states animation into a single clip (.anim file). Is this possible. ? I am able to copy one animation clips frame using this. But it very time consuming.


Culling mask don't work I have the following setup MainCamera render everything except ImageTurret layer. TurretCamera render only ImageTurret layer on a RawImage My problem is MainCamera render everything and TurretCamera render nothing TurretCamera render only if set to default layer.


Unity associated game object is null when running I am just starting with Unity. I have two UI Text game objects, Atext and Btext. I have associated them by drag dropping with my PlayerController script public variables, say public Text atext and public Text btext. Before running, the Unity editor correctly shows that Atext and Btext are correctly associated with the public variables. When running with debug, I get a null reference exception with btext and even the Unity Editor shows the association as None (Text). After stopping, the association turns to Btext as it is supposed to be. The script is very simple and I don't set btext to null at any point. When I create a new UI Text object by duplicating Atext, it works correctly after associating it with some new variable. When I create a new UI Text object by Create UI Text, it doesnt work Might be a stupid question but what am I forgetting? Edit Here is the problem again with code Before running with debug, the editor shows PlayerController2 (Script) Script PlayerController2 Speed 7 Countboxref Countbox(Text) Winboxref Winbox (Text) Brokenboxref Text (Text) where Countbox, Winbox, and Text are Canvas UI Text objects which I have drag dropped into place. Winbox object has been created by duplicating it from Countbox, Text has been created by Create UI Text. enter using UnityEngine using UnityEngine.UI using System.Collections public class PlayerController2 MonoBehaviour public float speed public Text Countboxref public Text Winboxref public Text Brokenboxref private Rigidbody rb private int boxit void Start () Countboxref.text "count" Winboxref.text "winner" Brokenboxref.text "broken" When the program breaks on line Brokenboxref.text "broken , the editor shows Brokenboxref None (Text) and when the execution is stopped completely, it again returns to Brokenboxref Text (Text) Note 1 In this project, every Text object created with Create UI Text is broken. A new Text object works only when I select Countbox or Winbox and duplicate it. Thus it is not possible that the object would be explicitly destroyed in the code. I can create as many Text objects as I wish by copying (all don't work) and as many Text objects as I wish by duplicating (all will work). Note 2 when I create a new project from scratch, of course everything works as expected. I assume the project is somehow corrupted. Edit 2 No prefabs or such. Just the basic roll a ball tutorial. But this was my son's project so I am not sure what he has done when following the tutorial. Note 3 The problem went away when I deleted the Library folder and forced Unity to rebuild it. Don't know yet if I caused any other problems by doing that. I saw that somewhere as a suggestion for corrupted projects. I don't know if there is a proper way to refresh. Also, this project was originally started with Unity 4.6 and upgraded to 5.02


Do editor errors affect device performance? Do errors that come up in the Unity editor affect a game's performance on a device (on Android in particular)? I'm talking about errors that keep coming continuously during Update() such as NullReferenceException and "Debug.Log".


Picking targets for homing missles I'm developing 2.5D space shooter (3D objects, 2D gameplay). I'm searching for a way to pick targets for homing missiles. There are two types of missiles active radar guided and heatseekers. The first ones are relatively simple to implement I search for a target once and then store it in the missile's navigation code. If object is destroyed or escapes missile's triangle of view, I seek for another target. Searching for target is costly, because I have to iterate through all game objects and eliminate ones behind the rocket or out of its "radar range". However, that happens rarely only after launch and when missile loses the target from sight, so I guess it will be acceptable. Now imagine heatseeker missile. Situation is different here I have to make decision about flight direction on every frame gather information about nearby heat sources, create some kind of heatmap, find hottest direction and navigate rocket towards it. This may degrade performance especially if I have multiple missiles on scene and this is very likely scenario. I thought of using collider as first degree sieve to keep track of potential targets. This collider would have to be quite big but it would narrow down count of potential targets to 10 20 and I guess that should be acceptable for processing. However, I'm falling into problem of multiple colliders I use one for regular collisions and I wouldn't want the other one to interfere. Also, I'm not sure what is the performance penalty for having a couple of big colliders on scene. How can I solve the problem of picking target for missile every frame such that it won't have big impact on overall performance? Are the colliders correct path to follow? Or should I rely more on coding than on built in features?