Unity Calculating a rotation based on game time I have a simple script to make an object spin Spin Speed is the speed to rotate the object on each axis (preferably in degrees per second). Local is whether the rotation should be done based on world axes or object axes. Starting Rotation is the initial rotation of the object. Normally I would use Transform.Rotate to do the rotation, but in this case I have to make the rotation a function of time, so you can pass in any time value and it will return what the rotation should be at that time. Here is an example (this doesn't work properly for either world or object axis rotation) private Quaternion getRotation(float time) return Quaternion.Euler(InitialRotation SpinSpeed time) I just need some help figuring out the math behind calculating rotations for both world and object axes. I think that matrices can be used but I honestly don't remember anything about how to use them. Here's an example of using world axes with a SpinSpeed of 180 on the y axis and an initial rotation of 45 on the x axis https i.gyazo.com d7f41b6a88425b5d8b8237cd7ac40878.gif An example of using local axes with the same parameters as above https i.gyazo.com d453b3dd239c9f77b86ce372c499d068.gif


Unity trigger method does nothing I have the following script on my object public class PlayMyCube MonoBehaviour SerializeField private Animator myAnimationController private void onTriggerEnter(Collider other) if (other.CompareTag("Player")) myAnimationController.SetBool("playSpin2", true) private void OnTriggerExit(Collider other) if (other.CompareTag("Player")) myAnimationController.SetBool("playSpin2", false) When the player character is inside the first cube's trigger, my second cube should play a spinning animation. When they leave, the second cube should stop. But what happens in the game now is, when the character runs into the trigger, it does nothing. I have configured my trigger object like this I have configured the object that should spin like this And configured the Animation Controller like this And configured my Player object like this What can I do to make this animation play when the player is inside the trigger?


How do I edit a Unity InputField by clicking on Android UI Button? I have been stuck on this problem for a long time and not sure what I need to do. Would appreciate any help. I am building an Android app using Unity. In my app I have an InputField, a TMP InputField to be precise, in my Unity scene as a Prefab. I want to edit this input field by clicking on a button in my Android UI (not part of Unity scene). I don't want the input field to be editable by clicking on the input field itself. In order to achieve this, I enabled the Hide Soft keyboard option in the editor so that user can't edit the field by clicking on the field. But I am not able to figure out how to edit the input field. First problem is how to pop up the keyboard when I click on the Android button. I tried this. TouchScreenKeyboard.Open("") This pops up the keyboard but the input field doesn't show the caret and doesn't accept input. I also tried, EventSystem.current.SetSelectedGameObject(inputField.gameObject, null) inputField.OnPointerClick(null) and inputField.Select() inputField.ActivateInputField() But no success. I tried to play with the focused, interactable, activated properties but nothing works. This should be easy but I am unable to get it to work. Would really appreciate any help. Thanks!


Best way to do discontinuous animation? Or Best way to animate a character with a jerky center of mass? I am using Unity and need to know how to use it animation system properly for well let me describe it below. In this game I have this big 3D block like character that moves in an unusual fashion compared to most game characters. In most games, the character moves along a straight line at a constant rate. However this character, and other characters in the game, does not move in a continuous fashion. Instead it is discontinuous and choppy in unique ways. For example, here is how I want a big block character to move Basically the two corners in front of him are pivot points, and the character moves forward by alternating between these two points and rotating. How can I do this with Unity's animation system? For the most part the animations in Unity don't move the character but instead have an animation play, such as the "Run" animation, and then a script actually moves the character. Know I the animator has a use root movement or something that does exactly this, but I have heard that it can causes problems. I ve been considering just programming all of the animations, since they are relatively simple. However that makes fine tuning them a nuisance, and have some animations programmed and others not is probably not a good practice. I kind of also fear that if I don t end up programming it I will have troubles with detecting if a character can walk through a certain walkway, considering for example the above animation his walk width is greater than his actual width since he rotates side to side. Also keep in mind that there are other animations that are discontinuous like this but work in different ways. For example, another block that hops but pauses between hops. Another might rock backwards and then slide forward on the forward rocking animation. So I know there are multiple ways to tackle this, but my question is what is the best way to do this? How would you do it?


Unity2D Pressing my mute button twice in order for it to set music back to 1 So far my mute button works, its just that I have to press my button twice (when game is restarted) in order for it to put my volume back to 1. Does anyone knows the problem. Anyway this is my script public bool mute void Start() check if the player has a music volume preference if (PlayerPrefs.HasKey("musicVolume")) if yes, apply it. GetComponent lt AudioSource gt ().volume PlayerPrefs.GetFloat("musicVolume") private void Muted () AudioSource audioSource gameObject.GetComponent lt AudioSource gt () mute !mute if (mute) gameObject.GetComponent lt AudioSource gt ().volume 0 PlayerPrefs.SetFloat("mute", 0) else gameObject.GetComponent lt AudioSource gt ().volume 1 PlayerPrefs.SetFloat("mute", 1) write new music volume preference to persistent storage PlayerPrefs.SetFloat("musicVolume", audioSource.volume) Thank you. )


How can I restart an animation? The first time the player clicks a button, my animation plays properly. The problem is that when the player presses the button a second time, the animation does not play. Here is the code I'm using to control my animation public Animator anim public Animator animsfirst public Animator animssecond public Animator animsthird public Animator reanimsfirst public Animator reanimssecond public Animator reanimsthird public Animator closeinstruct public void instructionpanel() (instruction panel open animation) anim.enabled true when button click instruction panel open animsfirst.enabled true animssecond.enabled true animsthird.enabled true public void closeinstructionpanel() (instruction panel close animation) Debug.Log("animationrun") when button click instruction panel close reanimsfirst.Play("freverse") reanimssecond.Play("srevese") reanimsthird.Play("lreverse") closeinstruct.Play("clreverse") Here is the animator controller setup for the animsfirst object And for the reanimsfirst object How can I resolve this issue?


Client projectile ignores camera Y axis in multiplayer shooter I'm able to spawn the bullet and make it move. But the problem is, only the host can shoot the bullet in the way the camera is facing(takes both X axis and Y axis correctly). The client takes only the X axis of the camera and keeps the Y axis at zero. Here's the code for spawning and applying velocity Command void CmdFire() GameObject fb Instantiate(fireBall, spawnPoint.position, spawnPoint.rotation) fb.GetComponent lt Rigidbody gt ().velocity gameObject.GetComponentInChildren lt Camera gt ().transform.forward fireSpeed NetworkServer.Spawn(fb) And the code for the camera attached to the player void Update() mouseX Input.GetAxis("Mouse X") mouseSensitivity Time.deltaTime mouseY Input.GetAxis("Mouse Y") mouseSensitivity Time.deltaTime Horizontal Looking playerBody.Rotate(Vector3.up mouseX) Vertical Looking xRotation xRotation mouseY xRotation Mathf.Clamp(xRotation, 90f, 90f) transform.localRotation Quaternion.Euler(xRotation, 0f, 0f)


Character bobs when moving Whenever I try to move a character in unity, the character kind of, like, bobs around when walking. Is there any way to remedy this? I have tried the trick of putting the inputs into update and the outputs into fixedupdate, if that's any consolation. Also please ignore the fact that I've used the arrow keys instead of getaxis. using System.Collections.Generic using UnityEngine public class MovePlayer MonoBehaviour public bool upArrow true public bool downArrow true public bool leftArrow true public bool rightArrow true public float speed public bool test false void Update() if (Input.GetKey(KeyCode.UpArrow)) upArrow true else upArrow false if (Input.GetKey(KeyCode.DownArrow)) downArrow true else downArrow false if (Input.GetKey(KeyCode.LeftArrow)) leftArrow true else leftArrow false if (Input.GetKey(KeyCode.RightArrow)) rightArrow true else rightArrow false void FixedUpdate() if (upArrow true) transform.position new Vector3(transform.position.x, transform.position.y speed, 0) if (downArrow true) transform.position new Vector3(transform.position.x, transform.position.y speed, 0) if (leftArrow true) transform.position new Vector3(transform.position.x speed, transform.position.y, 0) if (rightArrow true) transform.position new Vector3(transform.position.x speed, transform.position.y, 0) void OnTriggerEnter2D(Collider2D bump) if (bump.gameObject.tag quot Wall quot ) test true else test false


How can I give a MonoBehaviour field a default value that depends on the object? In Unity3D, I have a MonoBehaviour which gets added to game objects. I'm adding a string "name" field to it. I'd like the default value for the name to be the name of the game object the component is added to. Is there an easy way to do this? Some more details The component is an existing one to which I'm adding the name field. In old versions, the name was always the name of the game object, and this is a new feature to allow them to be different. The common case is (still) for the name to be the name of the game object, so having that as the default would simplify the process of adding the component to a new object. Ideally, deserializing an old scene will fill in the default, so updating scenes takes zero effort. I'm less concerned about this than about newly created scenes objects. The component already uses a CustomEditor. I don't care about updating the name in the component if the game object's name is changed, or if the component values are pasted into a different game object. One way I can think of is to add a bool "override name" to the object. If the bool is unchecked, it uses the default name (the game object) if it's checked, it uses the new field. But I'd like to avoid adding complexity to the GUI to support it. The whole point of my request is to add the new functionality (overriding the name) without adding steps to the creation workflow.


How to make dynamic DOF from mouse position in Unity 5? I found a video a while ago for how to make a dynamic DOF in unity. It fires rays from the camera and positions an empty at the location that the ray first hit. How can I change this so that it doesn't fire rays from my camera but rather from my mouse position, and then positions the empty from there? Code public Transform origin Raycast origin public GameObject target public CameraMovement cameraMovement void Start () void Update () Ray ray new Ray(origin.transform.position, origin.transform.forward) RaycastHit hit new RaycastHit() if(Physics.Raycast(ray, out hit, Mathf.Infinity)) Debug.DrawRay(Input.mousePosition, origin.transform.forward, Color.cyan) target.transform.position hit.point else Debug.DrawRay(Input.mousePosition, origin.transform.forward, Color.red)


Unity won't slice images properly Okay, so I am very new to Game Development and I imported a .png file(made in Paint) to the assets and that file contains just a circle and an oval, not touching and far apart from each other, both of them coloured blue. When I open the sprite editor and click on splice, then select Automatic and Delete existing options and then click slice, I do not get different sprites, one containing the circle and the other containing the oval. The image isn't sliced at all. I have also set the sprite mode to Multiple, but to no avail. Can someone help me and tell me what I am doing wrong? The engine I am using is Unity. This is the image.


Unity LoadLevelAdditive and baked light scene settings I am a programmer for a small game. For our levels, I separated the UI from the level data, so one scene is a scene which contains only the UI, the other scene has all the gameobjects and models and ... the light. So when loading a level, I first load the UI scene (LoadLevel), then the actual play scene (LoadLevelAdditive). Now that our graphics guy wants to bake some lights, he is telling me it doesn't work, because whatever his settings in the play scene, Unity ignores them and uses the settings of the UI scene. He also tells me we cannot just ignore the light settings of the UI scene ... So my question is, how do I make Unity ignore the light settings of a certain scene (UI scene in my case) or how can I enable a settings override? Thanks.


Per object screen space uv issue I am currently trying to sample a texture in screen space. This works well float4 positionCS vertexInput.positionCS vertexInput.positionCS.w screenPos ComputeScreenPos(positionCS).xy float aspect ScreenParams.x ScreenParams.y screenPos.x screenPos.x aspect But I would like to be able to constrain uv position and scale based on object's position and distance from camera. I found some example but I also faced some issues and for the moment I don't see how to fix them. Here's the code float4 positionCS vertexInput.positionCS vertexInput.positionCS.w screenPos ComputeScreenPos(positionCS).xy float aspect ScreenParams.x ScreenParams.y screenPos.x screenPos.x aspect float4 originCS TransformObjectToHClip(float3(0.0, 0.0, 0.0)) originCS originCS originCS.w float2 originSPos ComputeScreenPos(originCS).xy originSPos.x originSPos.x aspect screenPos screenPos originSPos You can match object's distance like this float3 cameraPosWS GetCameraPositionWS() float3 originPosWS TransformObjectToWorld(float4(0.0, 0.0, 0.0, 1.0)) float d distance(float4(0.0, 0.0, 0.0, 0.0), cameraPosWS originPosWS) screenPos d And here's the issue I am facing. You can notice that when the object is near screen edges the texture starts to move. Is there a way to avoid that ? https thumbs.gfycat.com HairySpryArawana mobile.mp4 I am using URP but this doesn't really matter.


RTS Pathfinding without collision between units Options Ever since I made my units move to a certain location a problem has popped up that of course if I try to make two or more units go to the same place they fight for the same spot. Am I just being stupid and unity already has a way around this or do I need to do something specific? I have looked into flow field path finding but no way on how to implement it. I dont want to have to use a ready made script but some pointers and other options are more than welcome.


How to force a translation to go through an exact point? I have a camera object with a script that will whether translate it with a set speed, or stop it. I also have 7 "checkpoints", where there are 7 different quads, who will stop the camera whenever the camera reaches them. The problem here is that in my code void Update() if (scoreholder.CheckScore() lt scoretimer) if the current score is less than set X score if (killcam.transform.position.y quadholder.y) and if the camera's position equals the position of the generic quad PROBLEM HERE killcam.GetComponent lt cameraUp gt ().SetCam (true) stop the cam while (scoreholder.CheckScore () lt scoretimer) do stuff offset mr.material.mainTextureOffset offset.y offsetSpeed 0.1f mr.material.mainTextureOffset offset break else once the score is not less than the desired X score, move the cam killcam.GetComponent lt cameraUp gt ().SetCam (false) So my problem here is that this line of code if (killcam.transform.position.y quadholder.y) never happens, the translation skips some values, and the camera doesn't hit the exact quad spot. I tried to use gt instead of , but I ran into another problem, is that after the 3rd quad, since my camera speed increases in time, the code apparently doesn't get processed fast enough, and my camera goes beyond the 4th,5th,6th, and 7th quad without stopping. I have already tried Vector3.Lerp, and it gives me almost the same result, if I lerp between the beginning and the end of the track, I have to do it with an extremely small fraction, and I can't have my camera move at that speed.


How to create temp folder to store a file from external directory and use it in a game I would like to copy a 3D model from external library and save it in temp Resources StreamingAssets folder to instantiate an object in unity scene. public class FBXOBJLoader MonoBehaviour string src Use this for initialization void Start () src EditorUtility.OpenFilePanel("Select Model", "", "fbx") Output the Game data path to the console Debug.Log("Path " src) StartCoroutine("CopySomething") IEnumerator CopySomething() print("Start") string path path Application.temporaryCachePath FileUtil.CopyFileOrDirectory(src,path) yield return null It's creating some unknown file format in the asset folder. can anybody please help me to complete this task. Thanks in advance


Raycasting from an object to the center of the screen (crosshair) without clipping through objects Am trying to learn about Raycasting, and I thought I would start with something simple, and that was a laser that would come out of an object (think laser pointer in your hand) and always go to the crosshair. Using ViewportToWorldPoint I found it easy to cast a ray from the center of the camera, but this had an issue as you can see in this GIF below. The line would clip through because the ray was coming from the center, not off to the side where the laser pointer would be. Am not sure how to solve this. void Update() Vector3 ray Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0f)) line.SetPosition(0, transform.position) RaycastHit hit if(Physics.Raycast(ray, Camera.main.transform.forward, out hit, raylength)) if(hit.collider ! null) line.SetPosition(1, hit.point) else Vector3 pos line.GetPosition(0) line.SetPosition(1, ray (Camera.main.transform.forward raylength)) The closest thing I could find that I am trying to replicate for this exercise is the No Man's Sky mining tool


Post Processing effects not visible with LWRP in Unity3D I'm are running into an issue when setting up Post Processing effects for the new Lightweight render pipeline. Post processing effects are visible in scene and Game view, but not in Play mode. The project is using single pass rendering for VR We are using the LWRP 3.0.0 and the Post Processing package 2.1.2 (both are up to date) It seems like the Post processing volume and layer settings are working fine, as the effects are visible in scene and game view We tried Tweaking the quality and graphics settings Creating a new camera and setting the post processing settings again Removing all additional cameras in the scene Setting the exiting UI Canvas in the scene to Screen Space (Camera) instead of Screen Space (Overlay)


Combining several animations into a single FBX I'm trying to figure out a workflow for preparing character animations for Unity so that they are all combined in a single FBX file. The advantage as far as I see it is that it then uses only a single skeleton where multiple animation files would each have their own skeleton (which I think is unnecessary and would increase size considerably). I've tried using Maya for this but haven't been successful so far. Then I tried Motionbuilder and I can get the animations (takes) together into a single file but many of the animations don't look right afterwards. So I was wondering does anyone know of a solid workflow to achieve this? I'm having a hard time finding information about what I'm trying to achieve. This is probably a piece of cake for experienced animators but I'm just starting with animation now. So how do you combine several animation FBX files into single one (whith either Maya, Motionbuilder, or 3DSMax) and make sure that the animations are all properly retained like they should? I'm sure there are some additional things to take care of but I don't know exactly what they are.


Blurred sprite in Scene view The thread between the tree and the spider here is a LineRenderer. When the BackgroundLandscape or the Tree objects are selected it has this blur around the thread between the tree and the spider. When anything else is selected, it renders correctly. It always renders correctly in the Game view. What's causing this?


Retrieving an array of images from Firebase Storage As title says I'm trying to get all images on firebase storage and save them to an array which later on i will be using to load them into the scene. i can manage downloading on image so far but I'm unsure of how to make them into an array. This is the code I'm using now to download one image by name and assigning it into a texture variable storage FirebaseStorage.DefaultInstance storageRef storage.GetReferenceFromUrl( url) storageRef.Child( resourceName).GetBytesAsync(1024 1024).ContinueWithOnMainThread(task gt if (task.IsCompleted) Texture2D texture new Texture2D(1, 1) byte fileContent task.Result texture.LoadImage(fileContent) Debug.Log(texture.name.ToString()) selectedText texture if (task.IsFaulted) Debug.Log( quot faulted DOWNLOAD quot ) ) now through that i want to replace my current function which loads all images through the inspector. if (LevelSystemManager.Instance.CurrentLevel lt source.Length) selectedText source LevelSystemManager.Instance.CurrentLevel Source being the array i use from the inspector to load those images into the game scene which then are selected into the selectedTex Texture2D and loaded based on the level, so 0 element in array level0 , 1 level 1 etc. etc. So i was wondering if i have a couple of folders inside firebase with 10 to 20 images each how can i make that source array pull from that folder? And as a result remove the need to have them in the game and of course not setting them through the inspector.


Unity C Change color, or material of specific line segments on Line Renderer We're making a game that plays with a LineRenderer, and we want to give it a different visual feedback relative to the side of the screen that it's on. We want to change the feedback of the specific line segments that are on the other side (when they past the middle point). The API lets you map the segments positions, but isn't there a way that you can change the material color of that specific segment? I just see that you can do it, but only for the whole Line Renderer, not segment by segment.


Unity 2D play animation with flipX then enabling and disabling GameObject "locks" flipX I have a GameObject with an Animator that contains many different animations. In C I switch between these animations with animator.Play("AnimName"). Some of the animations have the flipX property checked, so I can use the same sprite for two different directions. This works well, but I have one animation where after it is done I call gameObject.SetEnabled (false) then re enable it a short while later. I achieve this through an event at the end of the animation which calls a method in my script. For some reason, if the last animation I played before disabling the object had the flipX property checked, then all the other sprite animations will be flipped after it is reenabled. I can fix this by adding the flipX property to the other animations then unchecking it, but I don't want to have to go through all my animations to add an unchecked property. This seems like a bug to me, but if it's not, is there some way I can change the behavior?


Inserting into the first available inventory slot Hello my inventory system picks up one item but does not pickup any more to fill the other two slots. It is saying the whole inventory is full when it should be one slot is full. Here is my code for the inventory and this is attached to the player. public class MedInventory MonoBehaviour public bool isFull public GameObject MedkitSlot public GameObject BandageSlot public GameObject CoffeeSlot This next script is attached to the items you pickup. public class MedPickup MonoBehaviour private MedInventory medInv public GameObject itemButton private void Start() medInv GameObject.FindGameObjectWithTag( quot Player quot ).GetComponent lt MedInventory gt () itemButton.SetActive(false) void OnTriggerStay2D(Collider2D other) if (other.CompareTag( quot Player quot )) GameObject targetSlot new GameObject 0 bool validItem true switch (gameObject.tag) case quot medkit quot targetSlot medInv.MedkitSlot break case quot bandage quot targetSlot medInv.BandageSlot break case quot coffee quot targetSlot medInv.CoffeeSlot break default validItem false break if (validItem) for (int i 0 i lt targetSlot.Length i) if (!medInv.isFull i ) medInv.isFull i true itemButton.SetActive(true) Instantiate(itemButton, targetSlot i .transform, false) Destroy(gameObject) break


Basic billiards game Can't detect collision between cuestick and cueball I have a basic Unity project on GitHub. Basically, I have a Cuestick that aims and shoots using the mouse. You can rotate around the cueball with your mouse and when you're ready to shoot, you can hold down the right mouse button and move the mouse forward. The game came follows the cuetip. However, the collision between the cuestick and cueball is wonky. The cuestick protrudes through the ball and only pushes the ball forward only a little bit. I've created rigid bodies and colliders for both cuestick and cueball. I've set the cuestick's rigid body to kinematic (if it's unchecked, the poolstick will barely dent the ball). I've tried using OnCollisionEnter and a Debug.Log statement to no avail. Any help would greatly be appreciated. You can find my scripts in GameLogic (they're F sharp scripts whose binaries get compiled and outputted into the assets folder).


how to prevent a ball from bouncing only vertically I am trying to make a ball bounce off (and also sideways) when it gets into contact with another object. I am having an issue shown in the image below, where the ball rests on the triangle instead of falling off sideways. I tried playing round values for the bounciness and friction, but that didn't solve my issue. How can I solve this issue. I've added the inspector settings on the ball.


How can I destroy particles on collision with specific a GameObject? I wrote a script to manage my Particle System emission. The starting lifespan is set to infinite so that the particle never dies until it reaches a specific collider. I didn't find any method to destroy a specific particle in the Unity Manual. How can I do this? Here's the code (updated to show the partial fix) using UnityEngine using System.Collections.Generic public class PlayerDamage MonoBehaviour private ParticleSystem ps public List lt ParticleCollisionEvent gt collisionEvents public int attackValue 1 Range(0.0f, 100f) public int maxParticles public float particleLife public bool neverDies public float particleSpeed 8.0F void Start() ps GetComponent lt ParticleSystem gt () collisionEvents new List lt ParticleCollisionEvent gt () var collision ps.collision collision.enabled true collision.type ParticleSystemCollisionType.World collision.mode ParticleSystemCollisionMode.Collision3D void OnParticleCollision(GameObject other) int numCollisionEvents ps.GetCollisionEvents(other, collisionEvents) Rigidbody rb other.GetComponent lt Rigidbody gt () int i 0 while (i lt numCollisionEvents) if (rb.CompareTag( quot Enemy quot )) BaseHealth baseHealth other.GetComponent lt BaseHealth gt () if (baseHealth ! null) Vector3 pos collisionEvents i .intersection Vector3 force collisionEvents i .velocity 10 rb.AddForce(force) baseHealth.TakeDamage(attackValue) i void Update() var collision ps.collision collision.maxKillSpeed particleSpeed Debug.Log( quot Particles Alive Count quot GetAliveParticles()) ps.Emit(maxParticles) var main ps.main main.maxParticles Mathf.RoundToInt(maxParticles) main.startLifetime particleLife if (neverDies) particleLife float.PositiveInfinity else particleLife 5f int GetAliveParticles() ParticleSystem.Particle particles new ParticleSystem.Particle ps.particleCount return ps.GetParticles(particles)


Three button combination to open next scene I have thirty (30) buttons in a trivia game, they are laid out in the following configuration with three rows ( A, B, C, D, E, F, G, H, I, J) ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9) (00,01,02,03,04,05,06,07,08,09) Using these combinations of buttons and clicking one and only one from each row I have a thousand (1000) three (3) button combinations. E.g. A27 would be one combination of the thousand possibilities. These are not random combinations each opens a very specific scene. What I am trying to do is create a C script that when I click any of these three (3) button combinations it will open a new scene. Once that scene is open I m okay because then have my own scripts attached to the single buttons in the new scene to continue to a further scene. What I can t figure out is the syntax, should I use if Statements such as if (Btn A) amp amp (Btn 1) amp amp (Btn 01) then load scene such and such? Then do I attach the script to the canvas then to each of the three button combinations (A 1000 Scripts combinations)?


Change center point and size with the help of the Matrix in Unity Let us suppose I have an array of Vector3, it contains vertices. Now I want to scale the vertices and or change the center point of the texture (move texture relatively). I have a Vector3 which is a new center point and I have a Vector3 which is vector for scaling along x, y and z. How can I construct a needed matrix in Unity? I am very new to all this, so, please, in case of any misunderstanding ask me about it. Here is what I was able to find on my own. The problem with it, though, is that I can not infer what I need from it. I need a little bit more peculiar thing.


How to "properly" display a 2d sprites in a 3d environment? I would like to show "the classic" missile lock viewfinder (the target symbol) of a war aircraft. So the target symbol must follow the enemy, and became red when "lock" it. So i thought simply to Show the 2d sprite centered on screen (x and y screen.height and width 2 ) but, depending of the Z , the sprite became bigger (near camera) or smaller (far from the camera). How to display a 2d sprite indipendent from Z axis ? Thanks


Unity Best Random Movement Strategy? As of now, to get random movement of my enemies, I am adding a Rigidbody and a BoxCollider then "throwing" them (i.e. adding velocity) in a random direction for a random amount of time and making them choose a new direction if ever they get outside of their designated area. This does not seem to work that well all the time. Sometimes they manage to get themselves stuck inside obstacles which should be impossible. The more I add guys, the more it seems the physics can't keep up or something with the collisions. Is there a better method to random movement or is "throwing" them perfectly valid? Is my method expensive and terrible? I might have around 50 guys active at a time and perhaps a few hundred to a thousand static obstacles each with their own colliders.


Handling accelerate in different devices I am adding tilt controls to my game. The sensor values I get are different in different android devices which results in random behavior. Anyone knows how can I tackle this situation? I tried normalizing acceleration but it is still the same.


Rewarded video ads for two different functions Unity I'm implementing reward based video ads in my game. There are two functions that provide the reward. One is a ReceiveLife() function where once the player dies, if they click on the revive button the game restarts and the score is set to score before the player dies instead of 0. The other function is ReceivePoints(), where if the player clicks on the add points button, they are rewarded with 100 extra points. Here are the functions in the game manager script public void ReceiveLife() savedScore (int)playerScore SceneManager.LoadScene(1) public void ReceivePoints() playerScore 100 gameOverPanel.gameOverScoreText.text quot Score quot ((int)playerScore).ToString() Here is the unity ads manager script public void OnUnityAdsDidFinish(string placementId, ShowResult showResult) if (showResult ShowResult.Finished) gameManager GameObject.Find( quot GameManager quot ).GetComponent lt GameManager gt () gameManager.ReceiveLife() if (showResult ShowResult.Finished) gameManager GameObject.Find( quot GameManager quot ).GetComponent lt GameManager gt () gameManager.ReceivePoints() Once they watch the ad successfully, both the functions are being called. If the player clicks on the ReceiveLife(), he should only get one extra life and not the additional 100 points and vice versa. I'm not sure how to call each function separately. Do I have to create two separate admanagers in order to call these functions or is there a better method?


Divert gameobject around mesh surface I am trying to find a way to divert a vector3 position around the surface of a mesh which doesn't have a collider. I have a function (found online) that calculates the closest position on the surface of the mesh but it only works if the position is outside the mesh. In the diagram below, the red arrow represents whats currently happening. It works great when it's outside the mesh and will give a position on the surface of the mesh, but once it moves forward and enters the mesh, it just keeps walking straight. The green line shows what i would like to happen.


Unity sizeDelta of an Image update opposite to what it should I have an IEnumerator coroutine in which I call the UIManager script to update the Image size to fit the text size but it doesn't happen. when I use yield return new WaitForEndOfFrame() it sometimes solve the problem. but I don't want to use it. edit I tested the code like I was suggested in an empty unity project and it still happens, the width should change according to the text size but it happens opposite (when the text is small the width of the image is large and when the text is large the width of the image is small) (it only happens correctly at the first time the width of the image fits the text width) public class Example MonoBehaviour public Image image public Text text private int k 0 public void ButtonClick() text.text (k 2 0) ? "10" "10 10" image.rectTransform.sizeDelta new Vector2(text.rectTransform.rect.width, 30) k edit Solved! thanks for the help, Canvas.ForceUpdateCanvases() did the trick


Why is anti aliasing not being applied to my 2D objects in Unity? I am drawing 2D objects in Unity. Some of these objects are drawn using the standard sprite method that is built into Unity. Others are computed as distance functions in a shader. In both cases I can't get Unity to apply anti aliasing despite the setting being set. Is there an extra step that I am missing that is required to get anti aliasing to work properly? Would it be better to implement my own form of AA in a shader?


Creating animation by script with animation assets I'm very new to Unity (not to C and programming as well) but I managed to achieve some goals very fast. But some concepts I still don't get in their full aspects. I'm developing a small multiplayer game called skeet. It's about clay pigeon shooting. I have a static 2D scene, with 3 assets A gun, a bullet and a pigeon. These sprites I'm able to deploy on the scene by an event driven script and I'm able to react on collisions between objects. I reached the point I have to animate the pigeon and the bullets. First I have to animate the pigeon moving from border to border in a random direction on a random height. Second if a player presses its key to shoot its bullet must be animated from the bottom of the screen straight upwards. My current idea is to create some animations as assets and to assign them to the sprites I'm creating dynamically. But I don't know what I need in the Unity GUI and in the script. I'm not looking for a ready to run solution but an ordered list of concepts and advices I have to take a look into. Edit The bullets and pigeons are created dynamically and should be destroyed after the animation finished (by reaching any border of the screen or a collision). So I need to create an animation with assignable position parameters.


How to efficiently spawn instantiate a large amount of objects from a prefab I am trying to make a game where the whole world is consists of a very large amount of cubes (sort of a Minecraft Trove clone), but I keep running into huge performance issues due to the large amount of objects vertices being rendered at once. Just to clarify, the problem appears to be caused by the rendering, not the instantiation. I think so based on the fact that when I look away from the cubes, the frame rate will return back to normal ( 60). Is there any way to optimize this? Many answers to similar questions suggest disabling colliders, but that does not really seem to make much of a difference for me. I have also tried making the prefab static, but the problem still remains. Currently I keep getting 40 FPS with 10000 cubes (just the built in cube shape stored as a static prefab with a disabled collider). I believe there should be a way to have a larger amount of objects on screen without having such a performance drop. Does Unity have any way of storing information about a prefab in graphics card memory that would allow it to mass render its instances in a more performance efficient way (much like modern OpenGL uses vertex buffers)?


How can i display a nice big gui text in the middle of game view screen? The same idea like the message "Display 1 No cameras rendering" I'm trying to do it too but i don't see anything when running the game. In the Hierarchy i have a empty GameObject and in the Inspector attached to it the script and two components GUI Text and GUI Texture This is the script using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class SwitchCameras MonoBehaviour Header("Cameras Init") public Camera cameras public Vector3 originalPosition HideInInspector public Vector3 currentCameraOriginalPosition, currentCameraPosition Space(5) Header("Cameras Switch") public string currentCameraName public Vector3 lastCameraPosition private int currentCamera 0 Space(5) Header("Gui Text") public GUIText myGUItext public GUITexture texture public int guiTime 2 void Start() cameras Camera.allCameras lastCameraPosition new Vector3 cameras.Length if (cameras.Length gt 1) originalPosition new Vector3 cameras.Length for (int i 0 i lt cameras.Length i ) originalPosition i cameras i .transform.position if (cameras.Length 1) myGUItext.text "Need more then 1 camera for switching.." myGUItext.gameObject.SetActive(true) texture.gameObject.SetActive(true) StartCoroutine(GuiDisplayTimer()) else Debug.Log("Found " cameras.Length " cameras") for (int i 0 i lt cameras.Length i ) cameras i .enabled false cameras 0 .enabled true currentCameraName cameras 0 .name currentCameraOriginalPosition originalPosition 0 void LateUpdate() if (Input.GetKeyDown(KeyCode.C)) cameras currentCamera .enabled false if ( currentCamera cameras.Length) currentCamera 0 cameras currentCamera .enabled true currentCameraName cameras currentCamera .name currentCameraOriginalPosition originalPosition currentCamera lastCameraPosition currentCamera cameras currentCamera .transform.position currentCameraPosition lastCameraPosition currentCamera IEnumerator GuiDisplayTimer() yield return new WaitForSeconds(guiTime) myGUItext.gameObject.SetActive(false) texture.gameObject.SetActive(false) I used a break point and it's getting to the line myGUItext.text "Need more then 1 camera for switching.." But not showing it on the game view when running the game.


RectTransform Button Start shaking with Vector3.MoveTowards() I have a RectTransform Button that i want to make it move to a de terminated vector3. To move the button i use this code (it is inside Update()) int i 1 foreach (RectTransform Button in Buttons) i Vector3 NewPosBtns new Vector3(StartButtonsVect i .x, (StartButtonsVect i .y 192.5f), StartButtonsVect i .z) Vector3 CurPosBtns StartButtonsVect i Button.localPosition Vector3.MoveTowards(CurPosBtns, NewPosBtns, AnimationSpeed) Buttons is a array and i add the button to the list using unity editor StartButtonsVect is of vector3 that i add the using this code void Start() foreach (RectTransform Button in Buttons) StartButtonsVect.Add(Button.localPosition) For some reason the button start shaking instead of going to the target position (NewPosBtns)


Does destroying object at List element make it null? I'm using a list in Unity and I'm adding objects to it as they are collected through the game. But they will then be used and destroyed. My first question is do I use Destroy(), or should I just use List.Remove()? I'm not sure what happens to an object once it is removed from a list and not used anymore. Does garbage collection get it? My other question is, when I check the list (I will always be checking the first index), if that object was just destroyed or removed, will that element now be null? I've tried reading about this but it's hard to find an exact answer. Thanks for the help. For reference, here is the code that I came up with based on my current assumptions about lists public List lt BasePickUp gt pickUpQueue new List lt BasePickUp gt () public bool pickUpActive false void Update () if (pickUpQueue 0 ! null amp amp !pickUpActive) pickUpActive true pickUpQueue 0 .ActivatePickUp() Edit I have been playing with the if statement conditions, and even if I change pickUpActive to true, it somehow still manages to get inside the if statement to the breakpoint there. How is that possible? The condition says pickUpActive must be false, and yet it blows right by it. When I set the first condition to pickUpQueue ! null, I get an error for index out of range once, when it is set to check the first element, as it is in the above code, I get an index out of range every frame. I finally changed it to pickUpQueue.Count ! 0, and that finally kept it from getting into the if statement. If anyone can help me understand what is going on with my bool, and to understand exactly how to handle this list, I would greatly appreciate it! Thanks!


specific function of class Time Is there a function that according to the name of the object, its tag and the time taken since the beginning of the game(for example time Time.deltaTime), gives the position of this object? if yes which one? thanks from a rectilinear trajectory unknown to a randomly translated object, I need to press a Q key to know its direction vector. For this, I get the position of the object to the object. Q support and if I get the position of the object in the lapse of time preceding the moment of this support, the difference of these 2 positions gives me the direction sought of the trajectory at this moment. When I have perfectly resolved this script, I will create another very similar one that will give me the vector direction of the rectilinear trajectory of the object at each collision on another object Here is my script Blockquote using System.Collections using System.Collections.Generic using UnityEngine public class script5 MonoBehaviour public GameObject sphere public static float t public float laps time public static float temps public float difftime float temps appui float x1,y1,j1 float x2,y2,j2 float x3,y3,j3 Vector3 cat transform.position struct vecteur public float k1 public float k2 public float k3 Use this for initialization void Start () temps Time.deltaTime fonction retournant la position d'un objet un instant pr cis vecteur function script6(float t) vecteur v v.k1 0 v.k2 0 v.k3 0 Vector3 cat transform.position if (temps t) v.k1 cat.x v.k2 cat.y v.k3 cat.z return v Update is called once per frame void Update () float temps appui public float difftime public float laps time t Time.time donner les coordonn es de la sph re au temps o la touche Q est appuy e if (Input.GetKeyDown (KeyCode.Q)) donner les coordonn es de la sph re au temps o la touche Q est appuy e temps appui temps difftime temps appui laps time function script6 (temps appui) donner les coordonn es de la sph re au temps juste avant l'appui de la touche Q function script6 (difftime) x1 function script6(difftime).k1 x2 function script6(difftime).k2 x3 function script6(difftime).k3 j1 function script6 (temps appui).k1 j2 function script6 (temps appui).k2 j3 function script6 (temps appui).k3 donne le vecteur de la trajectoire de la sph re l'appui de la touche Q y1 function script6 (temps appui).k1 function script6 (difftime).k1 y2 function script6 (temps appui).k2 function script6 (difftime).k2 y3 function script6 (temps appui).k3 function script6 (difftime).k3 print ("(position appui " j1 "," j2 "," j3 ")") print ("(position difftime " x1 "," x2 "," x3 ")") print ("(vecteur trajectoire " y1 "," y2 "," y3 ")") print (" ") almost everything is good except for the position of difftime which is always null. Why?


Debug.DrawRay() does not draw rays in game view Here is the relevant code protected override void Update() base.Update() Debug.DrawRay(this.transform.position, this.transform.forward 100f, Color.red, duration 2f) When running the game, I can see the ray being drawn in Scene View. However, in Game View, no ray is displayed. As you can see from the screenshot below, I have already enabled gizmos in Game View. What should I do to ensure that rays are being drawn in Game View when debugging?


Why my dynamically generated Sprites overlap? I'm trying to dynamically generate scene representing chess board made from sprites. I'm using two textures for these pieces.png (taken from here http opengameart.org sites default files chess 2.png) tiles.png (drawn by hand, consists of two 128x128 squares filled with different colors) The best result I achieved so far is a board with overlapping tiles The sprite mode for these textures is "Single" and pixels per unit are set to "128" (unsure whether I should've done this or not) The textures are being sliced to sprites in my MonoBehavior.Start var tiles new Dictionary lt int, Tile gt () var sprites new Dictionary lt int, Sprite gt () Load all tilesets foreach (var externalTileset in map.tilesets) var tilesetAsset (TextAsset)Resources.Load ("Boards " externalTileset.source) var tileset (Tileset)tilesetSerializer.Deserialize (new StringReader (tilesetAsset.text)) Texture2D texture (Texture2D)Resources.Load ("Boards " tileset.image.source.Replace (".png", ""), typeof(Texture2D)) Debug.Log ("Texture for " tileset.image.source " loaded " texture.width 'x' texture.height) int tilesPerRow tileset.image.width tileset.tilewidth int totalTiles (tileset.image.width tileset.tilewidth) (tileset.image.height tileset.tileheight) for (int tileId 0 tileId lt totalTiles tileId ) float x tileset.tilewidth (tileId tilesPerRow) float y (tileId tilesPerRow 1) tileset.tileheight sprites externalTileset.firstgid tileId Sprite.Create (texture, new Rect (x, texture.height y, tileset.tilewidth, tileset.tileheight), new Vector2 (0.5f, 0.5f)) if (tileset.tiles ! null) foreach (var tile in tileset.tiles) tiles.Add (externalTileset.firstgid tile.id, tile) And when sprites are added to newly created game objects float minX 4 float maxX 4 float minY 4 float maxY 4 for (int i 0 i lt map.height i ) float y minY i (maxY minY) map.height for (int j 0 j lt map.width j ) float x minX j (maxX minX) map.height if (pieces i, j ! null) GameObject piece new GameObject (pieces i, j .properties "Color" ' ' pieces i, j .properties "Type" ) SpriteRenderer renderer piece.AddComponent lt SpriteRenderer gt () renderer.sprite piecesSprites i, j piece.transform.position new Vector2 (x, y) if (tileSprites i, j ! null) GameObject tile new GameObject ("Tile") SpriteRenderer renderer tile.AddComponent lt SpriteRenderer gt () renderer.sprite tileSprites i, j tile.transform.position new Vector2 (x, y) I believe I can hack something to make this work, but I want to know how to do it properly What's wrong with my code or scene resources setup?


How can I send commands to only certain clients? I am building a multiplayer game server with Unity. In the game there are players moving around the map. Now, because this map is quite large compared to the number of players, I was thinking to have the server send each clients' position only when they are nearby, and then slow the rate down when they are far away. At first I was using the convenient SyncVar to do sync everyone's position, until I discovered its shortcomings, that is there is no conditional way to either sync or not a certain value. I came out with this player synchronization class so far (I removed all optimizations for simplicity) public class PlayerSyncPositionConditional NetworkBehaviour Vector3 lastPos void FixedUpdate () TransmitPosition() ClientCallback void TransmitPosition () CmdProvidePositionToServer(transform.position) Command void CmdProvidePositionToServer (Vector3 pos) transform.position pos Now, what this code does is nothing more than sending its position to the server when I am looking at the dedicated server instance, each players' position is correct. Also, as expected, each client will not receive any updates. From my research, I found that instead of SyncVar, I can use Server and ClientRpc to dispatch commands from the server to all clients, so this Server public void MoveTo() RpcMoveTo(transform.position) ClientRPC void RpcMoveTo(Vector3 newPosition) transform.position newPosition this will run in all clients would move all clients to the transform current position whenever needed. Now, the problem is that those commands, apparently affect every client, while I only want to affect ones that are near each other. I know how to have the server issue the MoveTo at any rate I want, setup more than one interval, etc. but I don't know how to have it send only to certain clients at a single time. I am not asking for the code itself, but I am getting really confused with all these client server architecture concepts, which class does what, etc. so any heads up will be greatly appreciated.


Unity TextMeshPro bounds.size is wrong when hovering first time over gameobject I have this weird issue, which I am not able to fix. This is my third attempt and I need some help. Basically I have a hover element which spawns when I hover over a gameobject. The height of the element is determined by the amount of text (TextMeshProUGUI). The issue happens only when I hover first time, also not always (I have no clue how to reliably to reproduce it). Here is what happens (sec 10 ) https vimeo.com 449387131 I have tried to add these everywhere and different combinations LayoutRebuilder.ForceRebuildLayoutImmediate(hoverElementRect) hoverElementRect.ForceUpdateRectTransforms() Canvas.ForceUpdateCanvases() txtMeshPro.ForceMeshUpdate() They dont seem to help. I assume the problem is here float bgHeight txtMeshPro.bounds.size.y 25 The bounds.size.y is wrong the first time I hover, but I have no clue why. Here is the whole code for spawning the GUI element public static void SpawnGeneralHoverElement(string descText, RectTransform hoverOverRect, float guiWidth) Canvas hoverCanvas instance.hoverElementGeneral.GetComponent lt Canvas gt () EnableCanvas(hoverCanvas) TextMeshProUGUI txtMeshPro hoverCanvas.GetComponentInChildren lt TextMeshProUGUI gt () RectTransform hoverElementRect hoverCanvas.GetComponentsInChildren lt RectTransform gt () 1 float scale hoverCanvas.GetComponent lt RectTransform gt ().localScale.x txtMeshPro.text descText Need this to be dynamic, if I change hover element size, it will still work float hoverElementWidth guiWidth Forces canvas update because of stackoverflow.com questions 55417905 why is textmeshpro not updating textbounds after setting text Canvas.ForceUpdateCanvases() LayoutRebuilder.ForceRebuildLayoutImmediate(hoverElementRect) hoverElementRect.ForceUpdateRectTransforms() txtMeshPro.ForceMeshUpdate() Need this because otherwise the element spawns too far away on smaller resultions float spawnOffset (txtMeshPro.bounds.size.y hoverCanvas.GetComponent lt RectTransform gt ().localScale.x) (Screen.height 0.022f) float bgHeight txtMeshPro.bounds.size.y 25 hoverElementRect.position new Vector3(hoverOverRect.position.x, hoverOverRect.position.y spawnOffset, hoverOverRect.position.z) hoverElementRect.sizeDelta new Vector2(guiWidth, bgHeight) Debug.Log(hoverElementRect.sizeDelta) LayoutRebuilder.ForceRebuildLayoutImmediate(hoverElementRect) hoverElementRect.ForceUpdateRectTransforms() Canvas.ForceUpdateCanvases() txtMeshPro.ForceMeshUpdate() Slide in form left to right if off bounds, need for traps for example float leftOffset hoverElementRect.position.x ((hoverElementRect.sizeDelta.x scale) 2) if (leftOffset lt 0) hoverElementRect.position new Vector2(hoverElementRect.position.x (leftOffset 1) 15, hoverElementRect.position.y) Slide in form right to left if off bounds, need for traps for example float rightOffset Screen.width (hoverElementRect.position.x ((hoverElementRect.sizeDelta.x scale) 2)) Debug.Log( quot Screen width quot Screen.width quot nrightOffset quot rightOffset) if (rightOffset lt 0) hoverElementRect.position new Vector2(hoverElementRect.position.x (rightOffset 1) 15, hoverElementRect.position.y) LayoutRebuilder.ForceRebuildLayoutImmediate(hoverElementRect) hoverElementRect.ForceUpdateRectTransforms() Canvas.ForceUpdateCanvases() txtMeshPro.ForceMeshUpdate()


Prefabs scaling change also the original prefab I want to work with a prefab as local and global variable? something like that. So my question is how to change a prefab scale without affecting the original prefab.


Attaching objects on collision in Unity? I'm trying to make a game where the player can connect objects Lego style with objects becoming children of any object they come into contact with, so if the parent object is moved the child is moved too, but the child object can be dragged away to disconnect it. What is the best way to go about doing this?


Match 3 should pieces store their location in the matrix? I'm making a match 3 game. I have a TileManager script which stores all the tiles in a matrix, it's a singleton and it handles tile swapping and basicly everything regarding the management of tiles. I have a variable called selectedTile. I have a method called SwapSelected which swaps the currently selected tile with the one you just clicked on. As pieces don't know their location in the matrix I can only loop through the whole thing to find them but it feels extremly stupid I just feel like there's gotta be a better way. If pieces stored their location and I kept that updated all the time that'd feel stupid too. What could I do to make this method work nicer and more optimalized? Is there a way or there is no problem with how I do it? public void SwapSelected(Tile tileToSwap) Vector3 tempPos selectedTile.transform.position selectedTile.transform.position tileToSwap.transform.position tileToSwap.transform.position tempPos Vector2Int tileToSwapPosition new Vector2Int( 1, 1) Vector2Int selectedTilePosition new Vector2Int( 1, 1) OPTIMALIZE!!!!!!!!!!!!!!!!!!!!!!!!!!!!! for (int x 0 x lt tileMap.GetLength(0) x ) for (int y 0 y lt tileMap.GetLength(1) y ) if ( tileMap x, y tileToSwap) tileToSwapPosition new Vector2Int(x, y) if ( tileMap x, y selectedTile) selectedTilePosition new Vector2Int(x, y) tileMap selectedTilePosition.x, selectedTilePosition.y tileToSwap tileMap tileToSwapPosition.x, tileToSwapPosition.y selectedTile UpdateTileName(tileToSwap) UpdateTileName(selectedTile)


How can I make natural rain drops on screen? I'm trying to make rain effect drop with metaballs and trail on screen.I find a clue in shadertoy but I didn't understand how implemented https www.shadertoy.com view ltffzl unfortunately it have many math calculations and i can't use it in unity because it produces a lag.obviously I should use textures but how can I have trail effect?! my idea is using a texture and trail renderer for droping but how can I have metaballs effect? Update I could Implement Metaballs by This Article https github.com smkplus RainFX tree master but I haven't Idea about trail


Unity my game starts in windowed mode, but the fullscreen box is checked When I open my game the fullscreen box is checked, but the game is windowed. If I uncheck and check the box it will go into fullscreen. What is the fix? public class Settings MonoBehaviour public void SetFullscreen (bool isFullscreen) Screen.fullScreen isFullscreen I save the current display resolution when the player hits the quit button public void Quit() if UNITY EDITOR UnityEditor.EditorApplication.isPlaying false else Application.Quit() endif


Making an enemy follow player (Unity) I'm working on coding enemy ai for a star fox esqe shooter and I need the enemy to approach the player, stay a certain distance away and stay in front of them until destroyed. I can get the enemy to approach the player and I can get the enemy to stay a certain distance from the player but I'm not sure how to get the enemy to actually stay in front of the player. For a bit of extra information, the player makes a number of sharp turns and the like throughout the level. Also, as a stand in I tried simply causing the enemy to parent to the player within a certain radius but that causes clipping issues with buildings and the ground. public class EnemyCar MonoBehaviour public float safeDistance 20f How close the enemy can get to the player ... Update is called once per frame void Update() transform.LookAt(player.transform) Vector3 targertLocation player.transform.position transform.position float distance targertLocation.magnitude Decrease our speed as we get closer rb.AddRelativeForce(Vector3.forward Mathf.Clamp((distance 30) 50, 0f, 1f) thrust)


Unity Default Shader Greyed Out I created a pland in Unity 3D and then tried to alter the material. I looked at it's material component, but all the options are greyed out! how do I fix this problem?


Unity Matrix4x4 to rotate a point around a pivot axis I need the Matrix4x4 to rotate around a given axis that does not go through (0,0,0). Is there some built in straightforward way to do this in the Unity libraries, or do I need to build and maintain my own? Below is the formula I'd use to build my own in case somebody needs it We will define an arbitrary line by a point the line goes through and a direction vector. If the axis of rotation is given by two points P1 (a,b,c) and P2 (d,e,f), then a direction vector can be obtained by u,v,w d a,e b,f c . ... Assuming that u,v,w is a unit vector so that L 1, we obtain ... Source I do need the rotation Matrix, not just the rotation. If I didn't need the Matrix I could use (not tested, may contain flaws, but you get the idea) public Vector3 RotatePointAroundAxis(Vector3 point, Ray axis, float rotation) return Quaternion.AngleAxis(rotation,axis.direction) (point axis.origin) axis.origin So far the best I've got is the equivalent of the above (not tested, may contain flaws, but you get the idea), but it looks quite wasteful public Matrix4x4 RotationMatrixAroundAxis(Ray axis, float rotation) return Matrix4x4.TRS( Axis.origin, Quaternion.AngleAxis(rotation, Axis.direction), Vector3.one) Matrix4x4.TRS(Axis.origin, Quaternion.identity, Vector3.one)


DontDestroyOnLoad() doesn't work in Unity I have a problem with DontDestroyOnLoad() in Unity. It does not work! My code private static PlayerSpawningScript instance public void Awake() Debug.Log ("PlayerSpawningScript awake") Debug.Log ("Instance " instance) if (instance null) Debug.Log ("Initializing PlayerSpawningScript instance") instance this DontDestroyOnLoad (gameObject) if (instance ! this) Debug.Log ("PlayerSpawningScript instance exists. Destroying new copy.") Destroy (gameObject) Debug.Log ("PlayerSpawningScript instance " instance) public void OnDestroy() Debug.Log ("Destroying PlayerSpawningSceript instance " instance.ToString ()) Basing on the console output, I successfully create an instance in scene1, but when I change the scene, it gets destroyed I know this because I get "Destroying PlayerSpawningScript (...)" before the new scene is loaded, and the same script set up in scene2 does not find an existing instance (which held data saved in scene1) and sets up itself as the instance instead of getting Destroyed. What am I doing wrong?


When an animation involves movement, where is the movement better to implement? For context, I am using Blender and Unity. Regarding the question, as an example, in some games, when you get hit, your character tucks a bit and gets knocked back a few distance. The tucking animation I want to implement in Blender but how about the knockback distance? Do you move your model in Blender (tuck and knockback), or do you do the tuck animation only (tuck in place) and then handle the knockback in Unity (basically triggering the tuck animation and then moving the model backwards a bit). My question basically is, what's commonly done and if there's any specific reason, why?


How to use a .cube LUT file with Color Lookup? I have used quot Image 2 LUT quot to create a LUT for Unity from a certain movie. However, currently quot Image 2 LUT quot only outputs quot .cube quot files. For HDRP, this is great, but for some reason, URP doesn't accept .cube file. URP expects specially laid out .png LUT file. Is there any way to convert a .cube LUT file to a PNG that I can put into the slot of Color Lookup gt Lookup Texture with URP? Unity expect this format The tutorial that Google finds and recommends is this. However, I don't have Photoshop. Also, the tutorial deals with a square LUT that looks like this So even if I had Photoshop and I would follow the tutorial, I would still have a square LUT which is not laid out as Unity would expect it, so I did not use that tutorial. How do I create a LUT png from a .cube file that I can use with URP? Thank you.


Modify the effect of a card being played I'm trying to recreate a simple card game. Each played card has an action (draw extra cards, peek at draw stack, eliminate an opponent card, etc). Once played, it goes on a stack, and the card effect is executed in order. Cards added by effects are added at the end of this stack as well, and executed once it is their turn. Each player also has a different unique influence on exactly one type of cards that changes the effect (enhances it like draw 4 instead of 2 or taking cards instead of trashing them to graveyard). So far a card has a simple interface with value, type and doAction. While I could on each card do a check if a player influence would take effect, this seems like a hard coded noodle salad and makes it difficult to add new cards or influences. And more than once influence can take effect on the same card (for example, one effect could be steal 2 instead of 1 and the second effect, you can steal only a certain type of card from a second influence instead of free choice) I'm looking for a way to react on a method call (played card that gets executed) and change it accordingly. I'm investigating using delegates for this purpose.


Unity3d Get a direction vector parallel to plane I need to send a raycast from my camera which is parallel to the plane (Ground) and in the same direction of its forward vector (Represented by the black color vector) I cant use world space direction because the global forward vector of the camera points at the same direction no matter how much I rotate it (Since its a VR camera) I tried to use Vector3.ProjectOnPlane, but not sure how it works. Can someone help me?


How to prevent a duplicated shadow? It's a blob shadow which is built in Unity's standard asset package. As you see in the figure below, a shadow that is created by the Unity Projector is duplicated at the floor below. How can I prevent this duplicated shadow?


How to make one material on object with many parts inside? I have a weapon witch have many parts, it also have many materials. Do I really need to make it like that? It's like about 8 mats! (


Low Res Atlas Texture vs. Many different materials without textures So I have recently started to look into optimizing a medium complex 3D scene, more specifically i am looking to improve the performance i get from a fairly realistic bus. I am currently using the Unity3D standard shader. There are a lot of different objects within the scene, most of which are repeated and instanced. While many individual objects require only limited color variance often enough just a solid color and no texture at all. I have read a lot about batching and atlasing but can't quite find an answer on the trade off of using textures when no textures are required. I understand that reusing the same material allows for batching and can greatly reduce the amount of draw calls, however how does this compare to the complexity of texture mapping if this could be avoided entirely? Is it still good practice to atlas solid colors on very low resolution atlas textures and thus combine materials together? How does it look if i intend to use metallic and smoothness maps as well? Does it all come down to scene complexity and a number game or is there a straight answer? I have the same uncertainty when it comes to objects which are made up of an arbitrary single digit number of solid colors given supporting geometry, is it better to assign different materials with solid colors to regions of the object or create low resolution textures? In general what is the point at which atlasing becomes the worse choice? Thanks in advance!


Unity prefab functionality without files? Task Display a UI list Assumptions Most UI parts only get their data during runtime UI parts need to be styled in the editor ( before runtime) UI editing should be done with real time preview in the editor The items in UI list should look the same Current solution Save a list item prototype as a prefab (drag amp drop in the editor) Set that prefab as the reference in the script managing the list During runtime, instantiate the referenced prefab as needed However, this needs a prefab file, which seems like an unnecessary additional point of failure. Just one annoying example More often than not I forget to click "Apply" after editing such a prototype which only becomes apparent at runtime. Suggested solution In the script managing the list, set the list item prototype as a reference On Awake(), create a prefab and store it in a class field During runtime, instantiate the prefab from the class field Question I got the suggested solution working withPrefabUtility.CreatePrefab(). The only issue with that is that it still saves a prefab file. I currently just save those to a temp directory, but that is a workaround. Is it possible to have a prefab which does not exist as a file, but still allows copying with Instantiate()?


How can I model a star? I'm trying to model a star in Unity, and it, sort of works, but it's not ideal. Currently, I'm using a large sphere with a self illuminating material containing a star texture applied to it's surface, and a spotlight to create the effect of starlight, like this While it works, it doesn't look the greatest. I'm looking for an effect more along the lines of how Kerbal Space Program models a star How can I achieve this effect?


Rotate around moving object I'm using the function Transform.RotateAround in order to make my player rotate around objects in my game, it's the main feature. The thing is, when I'm making my levels harder and make the objects (that the player rotates around) dynamic and add some movement on the X amp Y axis, the rotation movement is inconsistent, obviously, since the function recalculates each frame a different pivot to rotate around, the player distance from the object changes and not staying static throughout the rotation cycles. The question is, is there a way to get around this and make the player rotate around the object in a static, permanent distance from the object even though it's moving? Maybe by predicting the movement of the object or somehow quot diffusing quot the effect of the object movement..? Any comment would be helpful. Thanks in advance!


Vector2.Distance on different resolutions firstTouchPos Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position) endTouchPos Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position) the height of the background(previously scaled to fit the screen) 10 minSlidedDistance (int)(SpriteRend.bounds.size.y 10) if (Vector2.Distance(firstTouchPos, endTouchPos) gt minSlidedDistance) do smth This way I check if the player has slided into any direction with a slided distance longer than minSlidedDistance. It works perfectly for different size devices. Is unity going to make the calculations itself if I simply write minSlidedDistance 100? I.e. is it still going to work same way on all devices? P.S. this is not the full code, there are many other IF checks, like the ones for assigning the value to firstTouchPos amp endTouchPos


Unity launches both Visual Studio and Monodevelop simultaneously When I open a script for editing from Unity, both Visual Studio and Monodevelop are launched, resulting in two instances of the same solution to be open in two different script editors. I am presently running the latest version of Unity 5.50fs (though I also experienced this issue in the previous build prior to installing Unity's latest update), in conjunction with Visual Studio Community Edition 2015, and Visual Studio Tools For Unity 2.3.0. I also have my external script editor set to VS in the preferences window of Unity. While investigating this issue I came across a forum thread of someone experiencing a similar problem, where MD opens instead of VS. This seemed to be a result of a hard coded reference to MD for redundancy in cases where VS might fail to load, which I thought sounds like a plausible explanation for my situation as well. The general consensus was that when VS takes a little too long to open, Unity reverts to MD under the assumption that their is a problem with VS. This explanation seems even more likely in my case because this issue only occurs when I first open Unity for the day if I have had VS open recently MD does not open, and VS opens quite quickly, likely a result of being cached in my computers memory. The work around offered to avoid MD launching instead of VS in that thread, was to change the name of the MD executable, so that Unity would be unable to launch MD, giving VS time to finish loading. I was however hoping to find a better solution. I like the fact that Unity has that redundancy in place and would rather keep it intact, and I don't know why but changing the executable solely for that purpose makes me feel a little OCD. Other ideas I have tried include reinstalling Unity, running both Unity and VS as an administrator, and launching VS prior to opening the script in Unity (in this case Unity opens a second instance of VS). Has anybody else experienced both script editors being launched simultaneously and or have any other ideas on how to resolve it? It's obviously not a critical issue or anything, but it is a bit annoying.


Vertex position problem for connected lines I m trying to generate a mesh to display connected segments representing street lines in a mini map. I have problem with vertex orientation that my math knowledge has hard time to resolve. Let s consider 3 points p0, p1 and p2. I use this code to create the vertices from the segment between p0 and p1 (the same code is then used for the segment from p1 to p2) height 2.0f desired line thickness vertices 0 new Vector3(p0.position.x, p0.position.y height 2.0f, 0) vertices 1 new Vector3(p1.position.x, p1.position.y height 2.0f, 0) vertices 2 new Vector3(p0.position.x, p0.position.y height 2.0f, 0) vertices 3 new Vector3(p1.position.x, p1.position.y height 2.0f, 0) The result looks like this Not that bad, except that the "thickness" of the line is not constant. If you look closely to the segment left and right borders, they are aligned (going from bottom to top). The problem comes from the height variable that is added or subtracted too naively to the positions. What I d like to have is something like this, with oriented borders vertex. However I don t know how to proceed. Any help or comment would be appreciated. Thanks for your time. EDIT Thanks to wondra's solution I managed to do what I needed to. Here is how Returns point of intersection TODO check if lines are parallel public Vector3 LineIntersection(Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4) float ma (p2.y p1.y) (p2.x p1.x) float mb (p4.y p3.y) (p4.x p3.x) float ba p1.y (p1.x ma) float bb p3.y (p3.x mb) float x (ba bb) (ma mb) float y ma x ba return new Vector3(x, y) LOOPING THROUGH POINTS wondra's solution Vector2 dir (sec node.position prim node.position).normalized Vector2 perp new Vector2(dir.y, dir.x) vertices vert idx prim node.position (perp height 2.0f) vertices vert idx 1 sec node.position (perp height 2.0f) vertices vert idx 2 prim node.position (perp height 2.0f) vertices vert idx 3 sec node.position (perp height 2.0f) if ( vert idx gt 4 ) int vert idx bis vert idx 4 vertices vert idx LineIntersection(vertices vert idx , vertices vert idx 1 , vertices vert idx bis 1 , vertices vert idx bis ) vertices vert idx bis 1 vertices vert idx vertices vert idx 2 LineIntersection(vertices vert idx 2 , vertices vert idx 3 , vertices vert idx bis 3 , vertices vert idx bis 2 ) vertices vert idx bis 3 vertices vert idx 2 END LOOP


FBX model from Blender doesn't show it's surface in Unity3D I've create a model from Blender and exported it as .FBX file. However when I import this into Unity, the surface is missing.how can i fix? Screenshot attached in Blender it look like this in Unity it look like this which only shows it inside


Why does the size extents of a bounding box of a BoxCollider in Unity show the Z element being double what it is? As you can see from the picture below, I fetch the BoxCollider inside CollisionHandler and Debug.Log() it to the screen. In this case, I'm logging the size, but the same thing happens with extents. There are 4 logs because I have 4 instances of the object in the scene. The Z value of the Vector3 is double what it should be, whereas the other values are, for the most part , normal. Also, it seems that each object prints a slightly different value for extents.z. Most stay around 1.3, but one gave me 1.07 . Additionally, it inverts the order for 2 of the objects. I don't know why. None of the objects are scaled and all use the exact same values for their collider. I tried drawing a cube with the same size as the BoxCollider's bounding box, and here's what I got I'm not entirely sure if the misalignment with the Collider in the scene is a sign of a problem or just how Gizmos.DrawCube() works. Here's the code that does this private void OnDrawGizmosSelected() Vector3 origin coll.bounds.center transform.TransformDirection(new Vector3(0f, 0f, 0.675323f skinWidth)) The hardcoded number above is Z extent of the box. Vector3 direction transform.TransformDirection(Vector3.forward) 2 Gizmos.color Color.red Gizmos.DrawRay(origin, direction) Gizmos.DrawCube(origin direction, coll.bounds.size) Where coll is a reference to the BoxCollider, cached in Awake(). Unity version 2019.3.15f1. For the X value of 2.286476, it rounded to 2.1 in the 3rd log for some reason. And in the first log, it rounded the doubled value of Z to 2.4 rather than 2.6...


Dynamically applied texture to GameObject using GUI button In a scene I have multiple different GameObjects (almost 30 kinds) with parent child relationships. At run time (by using a GUI button) I want to change the texture of each clicked GameObject. As the user clicks specific GameObjects, a GUI with a multiple texture button will appear. By clicking on the button, that specific texture will be applied. Is there a smarter way to do this? Do I need to apply a script to every object? I have tried to apply a script with some specific code it's working but not regularly and correctly. Additionally, I want different texture options for each kind of GameObject.


How to trigger onclick for Unity Selectable by script? As title, I know Button can be triggered onclick by button.onClick.Invoke() But how to simulate onclick event of Selectable? Thanks for the help.


How can I handle two collisions in the same frame? My problem is that I have a player with collisions, and enemy can collide with players collision and execute Hurt function in players script. But the problem is enemies can overlap and can hit the player in the literally same frame. So they both execute Hurt function. In my Hurt function I change players collision layer for a 2 seconds, and he is no longer be able to seen by enemies. But it doesnt matter because of the same hit by two or more enemies in the same frame. How can I solve this? I tried bool to check if Hurt function is executed but it doesnt work too... Here is Code on Enemy IEnumerator OnCollisionEnter2D(Collision2D collision) if (collision.gameObject.CompareTag("Player")) buras kediler st ste bindiginde birden fazla kez calisabiliyor charMovementRef.StartCoroutine(charMovementRef.Hurt()) Debug.Log("hasar yedi") Code on Player Hurt should only works one at the same time public IEnumerator Hurt() layer de i tirerek d man collisionlar ndan ka gameObject.layer 9 can azalt health HeartUI() show the new health on UI karakter g r nt s yan p s ns n gameObject.GetComponent lt SpriteRenderer gt ().color new Color(1f, 1f, 1f, 0.5f) player z plat rb2D.velocity new Vector2(rb2D.velocity.x, 0) rb2D.AddForce(new Vector2(0, jumpPower 1.2f)) 2 saniyeli ine colliderlar kapal kals n, sonra eski haline evir yield return new WaitForSeconds(2) gameObject.layer 0 gameObject.GetComponent lt SpriteRenderer gt ().color new Color(1f, 1f, 1f, 1f)


Unity Instantiate an object respecting the prefab's default rotation Simple question, I hope. I've built a variety of prefabs for an isometric shooter game (hazards, enemies, health indicator bars, popup texts, shots, explosions). All of these prefabs were constructed with default rotations appropriate for the gameplay. My problem is that Instantiate() will overwrite the default rotation of the prefab with whatever is specified as the rotation parameter. So I'm left with hard coded rotations in my Instantiate() calls to get things oriented correctly in the X Z plane. (0,180,0) and (90,0,0) are common ones. I'd much prefer to Instantiate prefab gameObjects consistently with "no change to their default rotation," but I'm not sure how to accomplish this. Thanks for the help, Mike.


Autonomous robot moving from 1 object to the next object This question falls in line with my last question Unity 3D create autonomous moving robot in house first person camera movement What I have I have a 3D model of a house a first person camera with movement through the house a robot that autonomously moves. What I want I want the autonomously moving robot to search the house for certain objects. I have placed 4 guns (same model) in the house. This is the code I have now. This works for 1 gun not multiple game objects using UnityEngine using System.Collections public class MoveTo MonoBehaviour public Transform goal void Start () NavMeshAgent agent GetComponent lt NavMeshAgent gt () agent.destination goal.position What I want extra If possible, I want it to communicate with the person navigating the "game" with the first person camera. For example, if it finds a gun, I want it to say to the person "playing" the game I found a gun. If it finds the next one I found 2 guns I found 3 guns etc etc. For that, I used the following code for the player using UnityEngine using System.Collections public class UGV MonoBehaviour public Player player assign this variable in the inspector, or using another method public void CallMethodBInPlayer() if(player ! null) player.MethodB() public void MethodA() do something (Robot) And the same for the robot (but changed accordingly). I will be honest with you that I have very little understanding of programming or Unity. I want you to know I've been looking for an answer for many hours but even though the idea might be too complicated for me just yet, I still hope you can (and want) to help me )


Is Update() called on the very first frame in Unity? I'm calling Time.frameCount inside Update() and then immediately Debug.Break() to pause the simulation before Update() is finished. This of course happens (supposedly) on the very first frame, and yet Time.frameCount returns 1, as if one frame had already been rendered by at that point. Also, I'm calling Time.deltaTime the same way, on the first frame inside Update(), and it returns a value too, as if a previous frame had been rendered and took X milliseconds. Considering Time.deltaTime returns the value of the "time it took to complete the last frame", and I'm calling it on the first frame and it's returning a value, is there an "invisible" first frame that Update() doesn't run on? I couldn't find any reference to this specific issue on the Unity docs.


Mesh vs LineRenderer Performance I've created a script, which is drawing a line along a bezier curve, so that I can animate whatever I want with lines, mostly for UI purposes. For the moment I'm using a line renderer, which works, but the performance is not that great in my opinion. So I was wondering if there are actually some better methods to draw lines, like simply creating a mesh along the path I've got.


How to detect collision in C script not attached to any game object I have public variables which I populate through the inspector. One script is attached to a single object and the other script has a gameObject array property. Please see below public class GamePlayScript MonoBehaviour public BallScript ballScript public BrickGroupsScript brickGroupsScript Use this for initialization void Start () Update is called once per frame void Update () BrickGroupsScript contains an array of bricks which has a isBroken bool property. Also the above code is attached to an empty game object. How can I detect when the ball game object is in contact collided with a brick with isBroken true?


Would it be possible to randomize LOD distance in unity like in BOTW grass I was studying the BOTW grass shader and noticed how the grass appears uniform at a distance but complex up close. From watching gameplay it appears the LOD is randomized to make the transition between the two types of grass smooth. I can't find any way to do something like this in unity and am wondering if anybody has advice, or can guess as to how they did it. Thanks!


How do I set the Foot IK property of an animator state by code? I would like to set Foot IK to enabled via code, but I can't find how. Which type is quot Foot IK quot a part of?


Initialize an object in property drawer based on an int variable in Unity I have created following classes for my game in unity System.Serializable public class abstract BaseA System.Serializable public class DeriveABaseA BaseA System.Serializable public class DeriveBBaseA BaseA System.Serializable public class abstract BaseB public int Type 0 public int AType public BaseA A System.Serializable public class DerivedABaseB BaseB DerivedABaseB() Type 1 System.Serializable public class DerivedBBaseB BaseB public DerivedBBaseB() Type 2 System.Serializable public class ClassC public int BType public BaseB B public class ClassD MonoBehaviour public List lt ClassC gt C now, I'm trying to add my custom editor for them. this is the first time I'm using editor scripting and I have few question regarding how to add custom editor scripts for my classes What is the correct way of adding new element to variable C How can I call PropertyDrawer for ClassC when I'm drawing C elements? How to initialize variable B of class ClassC based on the user entered value for variable BType in class ClassC? How can I call DerivedABaseBPropertyDrawer or DerivedBBaseBPropertyDrawer based on type of variable B in class ClassC? How to initialize variable A of class ClassB based on the user entered value for variable AType in class ClassB? This is code code that I was able to get it to work except for 2nd and last question CustomEditor(typeof(ClassD)) public class ClassDEditor Editor ClassD m target public override void OnInspectorGUI() m target (ClassD)target if (GUILayout.Button("Add")) Is this the correct way of adding value to this list? m target.C.Add(new ClassC()) foreach(var c in m target.C) How propertydrawer can be called for each element of C? CustomPropertyDrawer(typeof(ClassC)) public ClassCPropertyDrawer PropertyDrawer public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) Is the following code valid (it's working) and is there a cleaner simpler way of doing this? object obj fieldInfo.GetValue(property.serializedObject.targetObject) var index System.Convert.ToInt32(new string(property.propertyPath.Where(c gt char.IsDigit(c)).ToArray())) ClassC objC ((List lt ClassC gt )obj) index if(objC.BType 1 amp amp typeof(objC.B) ! typeof(DerivedABaseB)) objC.B new DerivedABaseB() else objC.B new DerivedBBaseB() CustomPropertyDrawer(typeof(ClassB)) public ClassBPropertyDrawer PropertyDrawer public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) How to get access to B instance object var type property.FindPropertyRelative("Type").intValue var a type property.FindPropertyRelative("AType").intValue var drawer null if(type 1) drawer new DerivedABaseBPropertyDrawer() else drawer new DerivedBBaseBPropertyDrawer() if(a type 1) Set A new DeriveABaseA() else Set A new DeriveBBaseA() CustomPropertyDrawer(typeof(DerivedABaseB)) public DerivedABaseBPropertyDrawer PropertyDrawer public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) CustomPropertyDrawer(typeof(DerivedBBaseB)) public DerivedBBaseBPropertyDrawer PropertyDrawer public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)


Unity Convert Camera Gyroscope Attitude to World Space Canvas rotation Suppose you have a worldspace canvas parallel to a camera that is rotated by the gyroscope. How do you convert from the camera's gyroscope attitude to get the world space canvas rotation?


Associating game object with some class Disclaimer Somewhat long winded question amp new to developing In my game I have a class called Item which defines what an item is. It contains several fields like the name of the item, the sprite of the item, the item's ID number, etc. I also have little physical objects on the ground that "represent" items, but they aren't really tied to the Item class in the way I want. I'll get back to this point. So, when an enemy dies in my game, SpawnItem(Item item) is called. Depending on a randomly generated number, SpawnItem(ItemData.sword) might be called or SpawnItem(ItemData.axe) and so forth. SpawnItem itself just instantiates a generic prefab (that little physical object on the ground), modifies some state like bool itemDropped and int numItemsDropped, makes some calculations to determine where to drop the item, and displays that item's name in a UI label above the item. I'm currently in the process of making an inventory system, and I've realized something. Those physical objects on the ground that are supposed to be items don't really know that they're items (in the sense defined by the class). A sword doesn't know it's a sword, and an axe doesn't know it's an axe (the game object sword doesn't know that it's a sword Item defined by the class) So when I pick up an item, I can probably do some code gymnastics to get the appropriate sprite to appear in the inventory, but that doesn't seem like a smart solution. So, my question is how do I get my sword game object (just a sphere on the ground representing a dropped item) to be linked to the sword Item? How do I get the sphere to know that it represents a sword with the ID number "1", the name "Sword", a weight of "1.5" etc. so that I don't have to do awkward code gymnastics? After all, when I'm adding an item to my inventory, I don't really think of it as JUST drawing that item's sprite in the first non empty slot of the inventory. I would think it's much better to get each game object to know what Item it represents than to just try and get that sprite to show up in the inventory. I might be overlooking something basic, but understand that I'm pretty new to Unity. Anyway, thanks for the time and help!


Is it possible to make isometric game of 200 200 tiles per map in Unity? We made an isometric game in AndEngine. Now we want to convert this game into Unity. I am searching for tiles map support plugin in Unity. I come across a plugin called Map and nav http forum.unity3d.com threads 138355 Tile Based Map amp Nav . but the problem is it only support 50 50 tiles per map. My map is 200 200 tiles. I want to know is there any plugin or way to acheive 200 200 tiles per map in Unity ? Thanks


How to show a canvas text when i click an UI button on Android I am trying to show a text when i click on a ui button but i don't know how to implement this. On PC platform I have a collider per object and when the player stay and click the E button, a canvas text appear on screen, but i don't know how to do this on Android. I want something like Resident Evil old style action button, opening doors and getting object description. How could i do this? The Script public class readingNote MonoBehaviour public AudioSource audio public AudioClip collectSound public bool playerNextToKey false bool hasCollided false public GameObject pic public GameObject text public GameObject notePad private Collider other void Start () pic.SetActive(false) text.SetActive (false) public Button yourButton void Start() pic.SetActive(false) text.SetActive (false) Button btn yourButton.GetComponent lt Button gt () btn.onClick.AddListener(TaskOnClick) void TaskOnClick() can't text.SetActive(true) because when i get out the scene, text is showing up (I use the same button to open doors and get text description). void OnTriggerStay ( Collider other) if(other.gameObject.tag "Player") if(Input.GetKeyDown(KeyCode.E)) text.SetActive (true) pic.SetActive(true) AudioSource.PlayClipAtPoint(collectSound, transform.position) void OnTriggerExit ( Collider other ) if (other.gameObject.tag "Player") enter false print("close") playerNextToKey false hasCollided false pic.SetActive(false) text.SetActive (false)


How can I remove Unity Hub in Ubuntu? I installed Unity Hub 1.4.0 and it works well. For now I want to update the version of Unity. I need to install hub 2.0.0. But when I download the 2.0.0 hub and intsall it always link to 1.4.0 and I want the version Unity 2019.1.10f1. I can't find some uninstall files. How can I remove Hub 1.4.0?


Create 3D line instead of a thin line in Unity in runtime with mouse drag I know how to use line renderer to drag and drop to create line in runtime, but the line appears to be thin when looking from the end of the line, I want to create a real line that has a thickness(think of it as a tube or pipe shape), no mater where the look direction is, they should has a thinkness. How would you achieve this effect, I've got two ideas, 1.Create a rectangle shape, then extrude this shape to create mesh during runtime, but the manipulation of mesh during runtime is too complicated for me. or 2.Create prefabs, and spawn new prefabs and connect them along the cursor routing to make them looked as they were a continous line. Would you suggest me of some new ideas or existing package to achieve this effect, or is the first option is the way to go? What I want to do is to make a shader editor like appearence in 3D space, what I need to create is the edges, and the edges should look 3D instead of 2D line.


How to make gameObjects in Unity move in predefined patterns easily I am trying to make a bullet hell game. I want my 2D enemies to move in predefined, curving patterns. How should I do this? The difficulty I have is being able to quickly produce enemy movements that are (A) predefined, not random (B) curved (C) easy to make, with little coding (D) visually able to see what is going on, maybe in the inspector? Perhaps a 3rd party tool may be warranted?


Why my calculated value is far different from actual value? I using CharacterController and not using a Rigidbody so I writing a script for downward velocity which is velocity 9.81 (time) and I declare my initial velocity as 12. Supposing from this calculation, the max height it can reach from the equation is roughly 6.7891 unit on y axis. By using the formulae distance travel initial velocity (time) 0.5g (time) 2,differentiate this w.r.t time, getting time u g 12 9.81 1.223, then max distance travel 12 (1.223) 0.5 ( 9.81) (1.223) 2 7.339 but from the coordinate below, can clearly seen the max distance travel before falling down is 13.2803unit 0.5499unit 13.8302unit? This is far exceed calculated value, wonder what went wrong? Initial coordinate of y on ground 0.5499 approximate final coordinate of y 13.2803 using UnityEngine public class NewPlayerMovement MonoBehaviour public CharacterController Controller speed of the character public float Speed 12f earth gravitational value public float Gravity 9.81f Vector3 velocity hit point of character float hp 90 bool Grounded true public void OnControllerColliderHit(ControllerColliderHit hit) Grounded true hp velocity.magnitude velocity.y 0 Debug.Log(hp) public void OnControllerColliderExit(ControllerColliderHit hit) Grounded false public void Checkstatus() if(Grounded false) velocity.y 0.5f Gravity Time.deltaTime void Update() float x Input.GetAxis( quot Horizontal quot ) float z Input.GetAxis( quot Vertical quot ) Vector3 move transform.right x transform.forward z Controller.Move(move Speed Time.deltaTime) if (Input.GetKeyDown(KeyCode.Space) amp amp velocity.y 0) velocity.y 12 Grounded false check if it grounded Checkstatus() Controller.Move(velocity Time.deltaTime)


Unity 5.5 Modify image of a button from an array of images via script Logic Help Right now i have this Is a placeholder for what i want to do. This blue circles are images in different buttons, i have a blue image circle for every letter. I have to display the correct letter image to create a word. For example word "DOG" and the word is created by the "D" "O" "G" images. That is the logic i cannot get my head around. How can I, via script, select which image to show depending on the word given? IDEAS I have an array of (INDEX, "letter") in my GameController.CS. Maybe i can add a number to the different images name. Separeate the word in characters. Look the position of this character in the Letters and that number turn it into a string and find the image with that number in the name. I really need help to figure this out. Thanks in advance for any help.


How can I detect continuous touches pressed with Unity 4.6's UI elements? I've recently switched to Unity 4.6. My previous workflow when creating continuous input controls (the kind where you measure continuous touch input on a single button) was to create a GUITexture and then perform hit testing on that texture as long as a finger was touching the screen. With the new GUI there seems to be no way to measure this type of input, as GUITextures objects can no longer be created and the new UI types don't support hit testing. I'm talking about a button that's supposed to act like a car accelerator where, for example, a simple OnClick() doesn't work because I need to measure if the button is being pressed continuously rather than it working as an on off toggle. How can I implement this?


How do make a box collider align with a line renderer continuously? I am having the issue of aligning my BoxCollider2D with my linerenderer. I am trying to have a laser shoot using Physics2D.Linecast(startingPoint.transform.position, maxEndPoint.transform.position) This works fine and the line is always shooting in the right direction and angle when I rotate the object. But, when I am drawing a box collider, the box doesn't align at the correct position. Firstly, the boxcollider is attached as a child component of the line renderer. I am using this code to get the size of the collider, which seems to work fine. float lineLength Vector3.Distance(lazer.GetPosition(1), lazer.GetPosition(0)) This code is for aligning the collider with the line renderer. I know I am supposed to get the midpoint, because that's how you control the location of the box collider, but I need to know the math to always make it align. lazerCollider.offset new Vector3(0, ourHitPos.y startingPoint.transform.position.y, 0) 2 lazerCollider.size new Vector3(lazerWidth, lineLength, 0) I know right now I am only using the Y coordinate... I just need to know the math to make this work.


Can I use trilinear filtering for my sprites, but keep their outlines unfiltered? Suppose that I have two images of equal size. They both contain a square https i.stack.imgur.com BI62X.png https i.stack.imgur.com Nev5Z.png When overlapped, both squares will appear next to each other. If both images use Point (no filter), they will contact without issues regardless of the amount of zoom or scale If you use either Bilinear or Trilinear, there will be an artifact visible in certain zoom scale levels Of course, that is to be expected from the very nature of the filters. As much as I would like to just leave it at Point (no filter), my game looks far better using Trilinear instead except of course, for the "borders" or points of contact. The ideal scenario for me as bizarre as it may sound, is to be able to use Trilinear filtering generally, but force the "outlines" of my sprites to stay as if they were Point (no filter). This way, my game looks painterly when zoomed in out (the game isn't pixel art), and I also avoid the "glitch" in specific contacts. Yes, the glitch is only noticeable if you use a scale zoom that is higher than 100 . Unfortunately, due to the nature of the game, the player should be able to zoom in out if they desire, so I can't just pick "the" ideal camera size or sprite scale because it can't be constant. I've tried using Canvas and its Pixel Perfect checkbox to no avail. I didn't really expect that to work though. What can I do to achieve the desired effect, then?