Unity2D Best way to determine degrees between two colliding entities? I'm trying to determine the collision direction between two objects. I'll be using this for various things such as creating blood entities in a specific direction proportional to where the other entity is hitting an entity. What's the best most efficient way to do this? I've been doing this but it seems unstable not to be working. Assuming both entities are center pivoted, I use trigonometry to find the angle like atan(b a). For some reason the output angle seems to be pretty random. Here's the method I made protected void checkCollisionDirection(Collision2D target) Vector3 positionDifference target.gameObject.transform.position gameObject.transform.position int quadrant 0 float x positionDifference.x float y positionDifference.y float degrees Mathf.Atan (y x) Mathf.Rad2Deg if (positionDifference.x gt 0 amp amp positionDifference.y gt 0) quadrant 1 else if (positionDifference.x lt 0 amp amp positionDifference.y gt 0) quadrant 2 degrees 180 else if (positionDifference.x lt 0 amp amp positionDifference.y lt 0) quadrant 3 degrees 180 else if (positionDifference.x gt 0 amp amp positionDifference.y lt 0) quadrant 4 degrees 360 hitDirectionDegrees degrees I'm open to any suggestions that can find an angle between two entities.


Adding a function call to a prefabbed button in Unity For each of my scenes, I have an empty GameObject Manager that stores my scripts for setting up the level, keeping track of variables, etc. On my main screen, I have a play button that isn't instantiated I simply dragged it into the editor. In my script Main.cs I have a function Play() which calls LoadLevel("Game"). To get my play button to call the Play function, I dragged Manager into the onClick slot and selected the function. This worked fine and I have a functional play button. Unfortunately, this is not working for the prefabbed buttons I need to instantaite in my Game scene. In Game.cs I have a function LayoutButtons() which is both public and returns void, yet I am unable to drag Manager into the slot on my prefabbed button. Even if I do it before converting the button to a prefab, it simply disappears once it becomes a prefab. I've managed to work around this by putting my LayoutButtons() function in a new script which I attached directly to the prefab, but I'd like to keep the function within Game.cs and attached to my manager object if that's possible.


Help creating combat for collection type game sorry for my odd terminology, I am rather new to all this I'm creating a collection pokemon type game. as of right now I have created a separate GameObject prefab for every monster character in the game. Each gameobject contains a script with enumerated values for it's stats. When combat begins It calls a random monster from a pool of gameobjets. The problem is at this point I'm not sure how to have it create a new instance of the enemy in a way where it retains the values in it's public floats from the prefab or have it's level be adjusted as it enters. And I don't know how I can derive it's stats and properties for scripts outside the function that spawned it. as the function that creates the new duplicate won't remember the new creature after the function resolves. so In short, How can I reference the enumerated integers of a newly duplicated gameobject I was asked to include some more information on what I've coded public List lt baseMonsters gt allMonsters new List lt baseMonsters gt () public void EnterBattle(Rarity rarity) this code swaps camera view to the battlefield from the overworld map playerCamera.SetActive(false) battleCamera.SetActive(true) call function to determine which monster appears baseMonsters battleMonster GetRandomMonsterFromList(GetMonsterRarity(rarity)) returns which monster was chosen Debug.Log (battleMonster.name) prevents the player from moving after combat begins player.GetComponent lt PLayermove gt ().isAllowedtoMove false Creates the defending monster GameObject dMon Instantiate (emptyMon, defencePodium.transform.position, Quaternion.identity) Ensures scale from original is preserved dMon.transform.localScale battleMonster.transform.localScale Vector3 MonLocalPos new Vector3 (0, 1, 0) dMon.transform.parent defencePodium dMon.transform.localPosition MonLocalPos Adds the stat components of the original prefab baseMonsters tempMon dMon.AddComponent lt baseMonsters gt () as baseMonsters tempMon battleMonster dMon.GetComponent lt SpriteRenderer gt ().sprite battleMonster.image bm.ChangeMenu (BattleMenu.Selection) the issue that I see with the code is that it's transforming an already existing object into what the prefab monster is, not copying it. what method can I use to copy the prefab in a way I can easily reference in the same function to change it's level? Update ok so changing everything over to instantiating a GameObject is what I want. now there is the other part from the code before public List lt baseMonsters gt GetMonsterRarity(Rarity rarity) List lt baseMonsters gt returnMonster new List lt baseMonsters gt () foreach (baseMonsters Monster in allMonsters) if (Monster.rarity rarity) returnMonster.Add (Monster) return returnMonster public baseMonsters GetRandomMonsterFromList(List lt baseMonsters gt monList) baseMonsters mon new baseMonsters () int monIndex Random.Range (0, monList.Count 1) mon monList monIndex return mon I was following a tutorial when I created this code, I am starting to understand more and more how spaghetti it is. sorry for all the Alike Terms, baseMonsters is a class that houses things like the rarity and stats of the monster. These functions are searching by and for that script. How can I convert these codes over to searching the class from a list, to a Gameobject from a list, and still be able to read baseMonsters of each respective GameObject and it's rarity int? as of right now, one workaround I can think of is to create a seperate list for each rarity. that way I can skip needing to read the rarities in the baseMonsters script entirely. But I will still need to know how I can call that class script for other things like determining level of the monster and what it's attacks will be?


Why does the object rotate to a random direction when I start dragging? I'm trying to do drag to rotate sort of thing, so far the code is fine. However when starting to drag (left clicking first), the object rotate to a random direction first which looks odd. here is my code public Camera cam public float smoothAngle, dragPower .3f public bool isRadial true float angle, angleOld, angleDelta, angleRef Vector2 mousePosOld, mousePosDelta Vector2.zero void Update() Vector2 mousePos cam.ScreenToWorldPoint(Input.mousePosition) if (Input.GetMouseButton(0)) mousePosDelta mousePos mousePosOld float rotX (mousePosDelta.magnitude Time.deltaTime) dragPower Mathf.Sign(mousePos.y) Mathf.Sign(Vector2.Dot(Vector2.right, mousePosDelta)) transform.Rotate(Vector3.forward, rotX) mousePosOld mousePos angleDelta Mathf.DeltaAngle(angleOld, transform.localEulerAngles.z) angleOld transform.localEulerAngles.z else transform.RotateAround(transform.position, transform.forward, angleDelta) angleDelta Mathf.SmoothDampAngle(angleDelta, 0, ref angleRef, smoothAngle) this is the effect


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


Checking if shapes will tessellate I'm trying to figure out where to start with getting code together to check if a shape tessellates. An example Consider that the shapes cannot be rotated, just as is. A 'compound' shape (as seen in the pic second and third shapes) will have a series of co ordinates that make them up. Where could I begin to getting the computer to figure out if they can tessellate? I'm using c amp unity. Thanks in advance.


Unity 2D Dealing damage when character is crushed between two solid objects Whats the best approach to dealing damage to a player when they get stuck between two solid objects? For instance, I'm trying to make moving platforms that the player can ordinarily touch. It's only when the player is caught in between the moving platform and the ceiling, for example, that damage is dealt or the player dies. So, what would be the best way to approach this? Thanks in advance!


Unity warning animations neck and head have scale I always get this warning if I import my model to unity Clip 'soldier idle' has import animation warnings that might lower retargeting quality Note Activate translation DOF on avatar to improve retargeting quality 'neck' has scale animation that will be discared. 'head' has scale animation that will be discared. Even though there are in fact no scale animations on the bones neck and head as you can see in my blender dopesheet. So why is this warning showing?


Equal 3D icon size visualization in Unity I have some Icons (Sprite rendered in 3d world) whose icons are equal size (scale 1). Now I am trying to implement a solution that icons visually show at same size. If you see the icon at distance then it looks very small when you near the icon then it look bigger. So I want to visualize them equally. For this reason, first I got the near scale value which is .5 (suitable) and far scale maybe around 1.5. Now, here is my code but it producing very large scale value. void Update() foreach (var item in iconsObjects) float size Vector3.Distance(activeCamera.position, item.transform.position) if (size lt 2000) for optimization purpsose only conside near object under 2000m distance float finalSize Mathf.Clamp(size, 0.5f, 2f) item.localScale new Vector3(finalSize, finalSize, finalSize) I thought Mahtf.Clamp will work within the context but it is not suitable here as it is applying scale 2 to the near objects where it should be around .5.


How do I change a Unity 4.6 Sprite's textureRect at runtime? I'm using Unity 4.6, and I've made a sprite like this AtlasFrameData frame testAtlas.GetFrameByIndex(0) Rect spriteRect new Rect(frame.Position.x, frame.Position.y, frame.FrameSize.x, frame.FrameSize.y) Sprite theSprite Sprite.Create( testAtlas.AtlasTexture, spriteRect, new Vector2(0, 0)) The texture is an atlas, and I have a bunch of data read in from an XML file telling me where the frames are. I want to do this in Update() AtlasFrameData frame testAtlas.GetFrameByIndex( currentFrame) Rect spriteRect new Rect(frame.Position.x, frame.Position.y, frame.FrameSize.x, frame.FrameSize.y) theSprite.textureRect spriteRect But I'm unable to do this since .textureRect is readonly. I could create a new Sprite each frame, but I suspect this is not going to perform well with tons of Sprites.


How can I add a glow effect around a pair of wings in Unity without post processing? Basically I want to use post processing and then I found a tutorial to achieve my goal. However, the artist want a pure shader to achieve this, without any C script hanging in the main camera. Any idea to implement?


Unity not opening in Ubuntu I installed the latest version version of Unity for Linux from the official website, but when I try to launch Unity, it displays a blank dialog box. I waited for a long time, but nothing happens. These are my system specifications. I was running Unity on the same computer, several months ago, using Windows. Model Thinkpad R500 Processor Intel Core 2 Duo CPU P8600 2.40GHz 2 RAM 2Gb DDR3 RAM Storage 155Gb HDD Graphics Card ATI Mobility Radeon HD 3400 Series 128mb dedicated GFX Why is it doing this? Is there a problem with the latest build? What should I do to fix it?


Vive SteamVR Stereo Rendering mirror doesn't reflect lineRenderer lines steadily I'm creating a SteamVR game in Unity. I'm using the Vive SteamVR Stereo Rendering Toolkit to create the mirror effect. I also wrote a script to render three lines between headset, and two controllers, with lineRenderer. The lines are working fine, but in the mirror reflection, I can only see the lines rendered one at the time, as opposed to all three lines visible at the same time. Why is that? Edit 1 Add an image of what I see In my game, I used three balls to represent the headset, the left controller and the right controller. I see the lines between all three lines constantly (even though you can't see the ball in the headset obviously and the lines between the left right controllers to the headset are clipped, which is fine...), but I can only see one line at a time in the reflection, either the line between the head and left controller or the line between the head and the right controller. For example, if I move the left controller, the line between the head and the left controller in the reflection is working, while the other disappear in the reflection. Also, the line between the left and right controllers never appear in the reflection. Edit 2 Add another image to explain what I want vs what I have now


How can I avoid tight script coupling in Unity? Some time ago I started working with Unity and I still struggle with the issue of tightly coupled scripts. How can I structure my code to avoid this problem? For example I want to have health and death systems in separate scripts. I also want to have different interchangeable walking scripts that allow me to change the way the player character is moved (physics based, inertial controls like in Mario versus tight, twitchy controls like in Super Meat Boy). The Health script needs to hold a reference to the Death script, so that it can trigger the Die() method when the players health reaches 0. The Death script should hold some reference to the walking script used, to disable walking on death (I'm tired of zombies). I would normally create interfaces, like IWalking, IHealth and IDeath, so that I can change these elements at a whim without breaking the rest of my code. I would have them set up by a separate script on the player object, say PlayerScriptDependancyInjector. Maybe that script would have public IWalking, IHealth and IDeath attributes, so that the dependencies can be set by the level designer from the inspector by dragging and dropping appropriate scripts. That would allow me to simply add behaviors to game objects easily and not worry about hard coded dependencies. The problem in Unity The problem is that in Unity I can't expose interfaces in the inspector, and if I write my own inspectors, the references wont get serialized, and it's a lot of unnecessary work. That's why I'm left with writing tightly coupled code. My Death script exposes a reference to an InertiveWalking script. But if I decide I want the player character to control tightly, I cant just drag and drop the TightWalking script, I need to change the Death script. That sucks. I can deal with it, but my soul cries every time I do something like this. Whats the preferred alternative to interfaces in Unity? How do I fix this problem? I found this, but it tells me what I already know, and it does not tell me how to do that in Unity! This too discusses what should be done, not how, it does not address the issue of tight coupling between scripts. All in all I feel those are written for people who came to Unity with a game design background who just learn how to code, and there is very little resources on Unity for regular developers. Is there any standard way to structure your code in Unity, or do I have to figure out my own method?


How to make a class diagram and data model of a Unity3D game? I'm developing a 3D platformer video game on Unity3D and I've been asked to present its UML class diagram and data model. If I'm not mistaken Unity uses an entity component system, which necessarily doesn't use heritage. How would a class diagram from a Unity game look like, in that case? Also, I've been taught that usually data model refers to entity relationship models that represent a database. In the case my game doesn't use a database, how could I diagram the way the player's data is store on the game? I'm storing the player progress on a file in the user's computer.


Instantiate works fine in Editor and does not work after building game Here is the situation, In my project everything works fine. After I build the game for windows, the prefab does not instantiate. I don't know which part I missed. This is how I load the prefab from Resources folder private void Awake() areaButtonPrefab Resources.Load lt GameObject gt ( quot Prefabs AreaButton1 quot ) And this is how I instantiate prefab for each data in a List public void SetAreaToUI() foreach (var j in areaList) cloneItem Instantiate(areaButtonPrefab, originalRect.position, new Quaternion(0, 0, 0, 0), rect) TMP Text text cloneItem.GetComponentInChildren lt TMP Text gt () AreaButtonData buttData cloneItem.GetComponent lt AreaButtonData gt () buttData.area j text.text j.areaName cloneItem.SetActive(true) cloneItems.Add(cloneItem)


Unity Dropdown Stays Stuck Open As can be seen in the following video https youtu.be zb3uMUqub00 The dropdown stays stuck open when Unity launches the game. This happens even with a non modified dropdown that is plopped as a new UI object inside the canvas. I tried a blank project, and the issue does not reproduce. I tried in a blank project, and the dropdown works. I tried researching a solution, but not too sure how to find one with this problem. Maybe someone here will have an idea or two. The repo can be downloaded at https github.com DenisLabrecque Warglobe if desired.


How to get past Visual Studio "Setup Error" for Unity development? When I launch Visual Studio from Unity on my laptop, I get the following error Setup Error The setup for this installation of Visual Studio is not complete. Please run the Visual Studio Installer again to correct the issue. As instructed, I've tried reinstalling Visual Studio multiple times, or using the quot repair quot option, but nothing has resolved the error. How can I fix this?


Player wont rotate properly So Small problem. I'm able to rotate my camera around my player AND rotate the player when the camera moves around it, but the controls don't seem to move with it. Example W moves forward. If I look right then W should move forward in that direction. It doesn't, instead it will go left (the forward as it was before). SerializeField GameObject GameCamera private void PlayerRotateWithCamera() Quaternion CharacterRotation GameCamera.transform.rotation transform.rotation CharacterRotation private void FixedUpdate() PlayerRotateWithCamera() MovePlayer() I only think the player is rotating cause it looks like it is, but if you look at the move tool the axis dont seem to move with the Player Just in case my movement isn't getting along with the rotation private void MovePlayer() moveHorizontal Input.GetAxis("Horizontal") moveVertical Input.GetAxis("Vertical") more realistic ball movement Vector3 movement new Vector3(moveHorizontal, 0.0f, moveVertical) rb.AddForce(movement moveSpeed) I also have Tool handle rotation set to global because it's a ball, and well, those axis obvious go crazy while rolling around. Any help at all would really be appreciated!


Can I set a texture as the wallpaper of an iOS device? I have a game in Unity which creates drawings. I need to have a button which sets the drawing as the wallpaper (with permission from the user of course). Is it possible?


Limit buttontext to one line in Unity? I have many buttons in my game. There are different texts on them every time. But some texts are too long and get split up into two different lines. Is there any way I can fix this without resizing the button. How do I limit the button to one line. p.s I do have best fit on and need it.


Which is better practice in Unity? GetComponent() or making the variable public? There are two main ways I am aware of to modify an attached component. Say, the component attached to an object is of type Animator and the name is animator. So, in the script, I can write private Animator animator and then call the function animator GetComponent lt Animator gt () Or, I can define the variable as public public Animator animator and then, drag amp drop in the Unity UI. Which one is the better practice?


Inherited property in derived class reference only base class Context I am developing a game in Unity, and wanted to make a Game Manager. Like many examples out there, it uses a Singletron design pattern. But i have several other Managers, all using Singletron pattern, so i decided to make a Singletron base class and make all the managers derive from it. When trying to access the Instance property declared in Base Class within one method in Game Manager derived class, the Instance property refers to the Singletron base class, which is expected. But it s not the behaviour i need. I have tried to look for alternatives, but everytime i found a possible solution, i have to declare the member variables properties in the derived class, and there would be no need to a Singletron Base Class. I have also looked for generic alternatives (Singletron lt T ) but it was not clear how to use these without the need of another script calling it, which would be nonsense since the Game Manager should be the object to manage the game. I could use something like a root game object to creat the managers is instances, but it feels like a ugly and inelegant solution. The managers are all coded, and this refactor would improve code maintenance, in future. Code from Singletron Base Class public abstract class Singletron MonoBehaviour public static Singletron Instance get protected set protected virtual void Awake () if (Instance null) Instance this else Destroy (gameObject) DontDestroyOnLoad (gameObject) Pertinent code from Game Manager Derived Class public class GameManager Singletron public List lt GameObject gt gameObjectsList public static void SomeMethod() foreach (GameObject go in Instance.gameObjectsList) go.DoSomething() Question What can i do inside Singletron Base Class to make the Instance.gameObjectList refers the actual class (in example, Game Manager Derived Class) so that i could use the gameObjectsList? Should i cast it to the pertinent manager inside the method (which seens like an inneficient option)? Thanks in advance! Edit Looking into design patterns page in wikipedia, i found another design pattern related to singletron. In my case, each manager follows the singletron pattern, but its somewhat equivalent to my singletron base class following a Multiton Pattern


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


Ability Skill Data and Method Structure (C , Unity3D) So I've come to design my game which players will be having a unique set of skill or ability to come with. I can store skill name, mana cost, cooldown, etc in database which each skill have in common, but as we gamer know, a skill is unique not just by its attributes, like the sequence of movement, the object will be instantiate in the world, it's just that very unique. So the question is, where do I put this "unique", the skill sequences? Do I make skill1.cs, skill2.sc for every single skill? xml for sequence then make script to read and define myXml? For example, in a game, the effect of each card is very unique for example card1 allow player to deal damage and draw card, card2 just deal damage, card3 deal damage to enemy and then draw a card, and so on, where and how they store this sequences or method of each card effect?


Why does duplicating my object cause its vertex animation shader to distort it? I used a vertex shader (based on this example) to animate a flag waving. When I have a single flag in my scene, it works correctly. When I duplicate the flag, all of the copies become wildly distorted after I hit play. Here is the shader code I'm using Shader "Custom Flag" Properties MainTex ("Albedo (RGB)", 2D) "white" Speed ("Speed", Range(0, 5.0)) 1 Frequency ("Frequency", Range(0, 1.3)) 1 Amplitude ("Amplitude", Range(0, 5.0)) 1 SubShader Tags "RenderType" "Opaque" Cull off Pass CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" sampler2D MainTex float4 MainTex ST struct v2f float4 pos SV POSITION float2 uv TEXCOORD0 float Speed float Frequency float Amplitude v2f vert(appdata base v) v2f o v.vertex.y cos((v.vertex.x Time.y Speed) Frequency) Amplitude (v.vertex.x 5) o.pos mul(UNITY MATRIX MVP, v.vertex) o.uv TRANSFORM TEX(v.texcoord, MainTex) return o fixed4 frag(v2f i) SV Target return tex2D( MainTex, i.uv) ENDCG FallBack "Diffuse" How can I make this work with multiple flags using the same material? Should I use a new material instance for each object like this? It doesn't seem optimal material new Material (Shader) Create new material material.SetFloat (" Speed", Speed) material.SetFloat (" Frequency", Frequency) material.SetFloat (" Amplitude", Amplitude) material.SetTexture (" MainTex", MainTex) flagObj.GetComponent lt MeshRenderer gt ().sharedMaterial material Set values


How can I create "events" that are called in scripts without requiring subscriptions? I am creating an editor extension that includes an API for developers to use. It also includes events like (for example) "OnHealthChanged." The problem is that events I have stumbled upon would require a user to subscribe to them, which is not what I actually want. I want developers simply type in the event handler in their script, and it would just work. For example, I want a programmer to write a function "OnHealthChanged" in their own script. When the health changes, their code runs. void OnHealthChanged() code that is going to run when health changes Any idea where can I look? I want to create something like "OnCollisionEnter()" event in Unity, which runs code every time a game object collides with another game object. Hope it makes sense.


UGUI scripts stop my project from building Unity 2019.2.21 I am trying to build out my project to Android and I am getting the following error messages H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core Toggle.cs(121,18) error CS0234 The type or namespace name 'PrefabUtility' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core DefaultControls.cs(152,13) error CS0103 The name 'Undo' does not exist in the current context H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core GraphicRebuildTracker.cs(24,32) error CS0117 'CanvasRenderer' does not contain a definition for 'onRequestRebuild' H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime EventSystem InputModules StandaloneInputModule.cs(159,25) error CS0234 The type or namespace name 'EditorApplication' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core Slider.cs(380,18) error CS0234 The type or namespace name 'PrefabUtility' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core Scrollbar.cs(168,18) error CS0234 The type or namespace name 'PrefabUtility' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core Selectable.cs(771,48) error CS0234 The type or namespace name 'SceneManagement' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core InputField.cs(2458,43) error CS0234 The type or namespace name 'PrefabUtility' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) I tried updating Unity(from 2019.2.12 to current). Deleting some csproj files, and different settings in the Project settings Player. The problematic code is in an if UNITY EDITOR statement, and not meant to execute at all on builds, I guess. if UNITY EDITOR protected override void OnValidate() base.OnValidate() if (!UnityEditor.PrefabUtility.IsPartOfPrefabAsset(this) amp amp !Application.isPlaying) CanvasUpdateRegistry.RegisterCanvasElementForLayoutRebuild(this) endif if UNITY EDITOR


Change animation speed through the editor in Unity How can I change the speed of the animation through the editor if I have the following animation structure? I would like Adult1 walk to play faster.


Detect collision without reaction Okay, so this has been bugging me for quite some time now. I'm making an old school platformer type of game in 2.5D, I want objects to pass through each other, but I still want a collision to be detected. If the player gets hit by an enemy, I just want to detect a collision for receiving damage to the player, I don't want the player to move on impact, and I just want the enemy to continue moving where he was heading. I'm using rigidbodies and box colliders on my objects. First I thought using triggers combined with ignoring layers was the solution, but apparently trigger events aren't called when ignoring layers. I still want to be able to use AddForce and stuff for moving objects. Is there someway I can still utilize Unity's OnCollision... OnTrigger... Or other... for just detecting a collision and having no impact movement added when a collision occurs? Have a nice day!


Unity, depth behind a transparent object Is there a way to know how far away is any object behind a transparent object in shader? Like making water fully transparent when close to shore.


convert clock input into 24 hour format I have stuck in a logical problem I have a third party package of DayNight. It takes hours input(24 hour format) to show dayNight effects in scene My code is to transform 12 hours clock cycle into 24 hours is if (todsky.Cycle.Hour gt 0 amp amp todsky.Cycle.Hour lt 11.97) Debug.LogError("1st") var degree 360 hourniddle.transform.eulerAngles.z var degreeToMintues degree 2 multiply each degree with 2 to get correct minutes ConvertMinutesToHours(degreeToMintues) else if (todsky.Cycle.Hour gt 11.97 amp amp todsky.Cycle.Hour lt 23.97) Debug.LogError("2ndt") var degree 360 hourniddle.transform.eulerAngles.z as rotation is anti clock getting rever degree var degreeToMintues degree 2 multiply each degree with 2 to get correct minutes var MintuestTo24HoursMintueCoverstion 720 degreeToMintues add 720 mintues into current minute in order to get 24 hour format ConvertMinutesToHours(MintuestTo24HoursMintueCoverstion) void ConvertMinutesToHours(float mintues) result TimeSpan.FromMinutes(mintues) Debug.LogWarning(result.Hours " " result.TotalHours " " result.Minutes " " result.TotalMinutes) todsky.Cycle.Hour (float) result.TotalHours Debug.LogWarning("setted hours " todsky.Cycle.Hour) But it is not working correctly . have made a clock GUI(360 degree) and as you know it only show 12 digits format not 24. I am getting clock needle movement which can be change through mouse drag. Needle z position up to 320 degree which means one degree is equal to 2 minutes and i am taking it as input from GUI. I write below code to integrate my clock needle with my DayNight package in order to integrate GUI with package and passing hour parameter into the package but it not working correctly. Problem is that else condition is skipping.


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


How can I play an animation as long as the player is on the pressure pad? I'm making a 2D platformer with Unity. Recently, I implemented a pressure pad system. Basically, when the player triggers the pad, a door near there should be opened. The system works properly but the only problem is when the player stays on the pad, the OpenWhenOn animation (an idle animation that is for the door opening) is not playing. I want to make this keep playing as long as the player is on the pad and if it exits the trigger, the DoorClosing animation should be played. I wrote this code mainly for playing the animation but it doesn't work and I get Null Reference error all the time. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Events public class PressurePad MonoBehaviour private Animator anim public UnityEvent OnActivate public UnityEvent OnDeactivate public GameObject door public float deactivationDelay 2f int objectsInContact Coroutine waitingToDeactivate IEnumerator Timer() yield return new WaitForSeconds(deactivationDelay) Tell our listeners we're switched OFF. if (OnDeactivate ! null) OnDeactivate.Invoke() Return to ready to activate state waitingToDeactivate null void OnTriggerEnter2D(Collider2D other) if (other.CompareTag( quot Player quot )) anim.Play( quot OpenWhenOn quot ) door.GetComponent lt Animator gt ().Play( quot OpenWhenOn quot ) objectsInContact Pressure pad pressed. if (objectsInContact 1) if (waitingToDeactivate ! null) Cancel deactivation timer. StopCoroutine(waitingToDeactivate) waitingToDeactivate null else if (OnActivate ! null) Tell our listeners we're switched ON. OnActivate.Invoke() void OnTriggerExit2D(Collider2D other) objectsInContact Pressure pad released. if (objectsInContact 0) Start a delay before telling anyone. waitingToDeactivate StartCoroutine(Timer()) This is my Animator Controller. HasExitTime is disabled for all the transitions. The condition for the transition between OpenWhenOn and DoorClosing is set to false.


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


Smoothly resize minimap camera rect width and height I have an orthographic camera that is working as a mini map. Now I want to make it resizeable using mouse drag. I have applied some UI beside my minimap camera rect and those UI resizing perfectly with this code. But I have no clue that how to resize my camera rect with mouse drag void Awake() rectTransform transform.GetComponent lt RectTransform gt () public void OnPointerDown(PointerEventData data) if (!resizePanelFeatureActive) return rectTransform.SetAsLastSibling() RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, data.position, data.pressEventCamera, out previousPointerPosition) public void OnDrag(PointerEventData data) if (!resizePanelFeatureActive) return if (rectTransform null) return Vector2 sizeDelta rectTransform.sizeDelta RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, data.position, data.pressEventCamera, out currentPointerPosition) Vector2 resizeValue currentPointerPosition previousPointerPosition sizeDelta new Vector2(resizeValue.x, resizeValue.y) sizeDelta new Vector2( Mathf.Clamp(sizeDelta.x, minSize.x, maxSize.x), Mathf.Clamp(sizeDelta.y, minSize.y, maxSize.y) ) rectTransform.sizeDelta sizeDelta previousPointerPosition currentPointerPosition


Blender Unity Import Animation Failing by Overlapping Mesh Objects I'm new to both Unity and Blender. I created this penguin 3d model, rigged it up and animated it in Blender and all looked good. When I imported it into Unity, I noticed that this idle animation did not appear to be working correctly. As the body moves, the body mesh overlaps the belly mesh and covers a portion of it. This is not the case when viewing the animation from blender 2.9. The belly uses a shrinkwrap modifier with the body as a target. Is this a problem with Unity import, or how I modeled this penguin in Blender? Can anyone see what I have done wrong here? Any help is much appreciated!


Unity Opacity over Distance with Surface Shaders I want to tweak the alpha value based on the distance to the camera. But I see no way of passing the vertex position on to the surface function using surface shaders. Not a problem with frag shader. It's for fading out vegetation and creating LOD systems. Shader quot asdf quot SubShader CGPROGRAM pragma surface surf StandardSpecular alphatest Cutoff addshadow vertex vert struct v2f float4 pos TEXCOORD1 struct Input float2 uv Maintex v2f vert (inout appdata base v) v2f o o.pos mul(unity ObjectToWorld, v.vertex) return o void surf (Input IN, inout SurfaceOutputStandardSpecular o) Need vertex or pixel distance here float dist length(v2f.pos.xyz WorldSpaceCameraPos.xyz) o.Alpha saturate(50 dist) ENDCG


creating a trigger to play multiple animations at once I need a "button" like trigger. The player would walk within the invisible cube that is the trigger, once the player is in the trigger (and only in the trigger) they would be able to press 'e' on their keyboard which will cause the animations to play at once. After the animation plays, the screen fades to black and loads the next scene. I'm still incredibly new to Unity so a brief summary of the code you provide would be much appreciated! (but not at all demanded!) Personally I'm a lot more comfortable with C so if the code can be in that, it would really help. Thank you!


How to sample from six cubemap images for a skybox in Shader Graph? I'm trying to update a skybox shader to URP and reimplement it in Shader Graph. The shader code itself is pretty straightforward, but I don't know enough about Shader Graph yet to set up the basic skybox. It's a standard cubemap skybox made up of six textures for x, x, y, y, z, and z. Trying to Google different variants of "unity shader graph cubemap skybox" turns up tons of noise and nothing actually useful that I can see. Does anyone know what the basic node setup is I would need to input six images and output a skybox?


Why the while loop is not pausing the coroutine? I'm trying to find a way to pause the game the whole game. timeScale 0f is not working on coroutines. I have this script that pause the game on escape key using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class BackToMainMenu MonoBehaviour public static bool gamepaused false private void Update() if (Input.GetKeyDown(KeyCode.Escape)) gamepaused true Time.timeScale 0f And a script with a coroutine using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.PostProcessing public class DepthOfField MonoBehaviour public UnityEngine.GameObject player public PostProcessingProfile postProcessingProfile public bool dephOfFieldFinished false public LockSystem playerLockMode private Animator playerAnimator private float clipLength private Coroutine depthOfFieldRoutineRef void Start() if (depthOfFieldRoutineRef ! null) StopCoroutine(depthOfFieldRoutineRef) playerAnimator player.GetComponent lt Animator gt () AnimationClip clips playerAnimator.runtimeAnimatorController.animationClips foreach (AnimationClip clip in clips) clipLength clip.length var depthOfField postProcessingProfile.depthOfField.settings depthOfField.focalLength 300 StartCoroutine(changeValueOverTime(depthOfField.focalLength, 1, clipLength)) postProcessingProfile.depthOfField.settings depthOfField IEnumerator changeValueOverTime(float fromVal, float toVal, float duration) while(BackToMainMenu.gamepaused) yield return null playerLockMode.PlayerLockState(true, true) float counter 0f while (counter lt duration) var dof postProcessingProfile.depthOfField.settings if (Time.timeScale 0) counter Time.unscaledDeltaTime else counter Time.deltaTime float val Mathf.Lerp(fromVal, toVal, counter duration) dof.focalLength val postProcessingProfile.depthOfField.settings dof yield return null playerAnimator.enabled false dephOfFieldFinished true depthOfFieldRoutineRef null But when I hit the escape key the freeze for a second or two but then the blurry effect in this script is keep on going then it also keep on running the game after this script part. It seems that the timeScale is not pausing the game at all but only for few seconds if at all. Or pausing only some stuff. What I want is to pause the whole game. Maybe I should use a game state somehow? I don't want to disable enable the gameobjects in the hierarchy. I checked again now. For example the player I can't move it with the keys but I can rotate the player looking around with the mouse while in pause mode. But other things are paused like other npc's I have they stopped moving(Not using animation). So some stuff is paused but some stuff not.


My GUI stopped working? Okay I bought this asset online so I would like not to show the whole script. The problem is this asset stopped working when I updated from unity 5.0 to 5.1.2. The script is for a controller GUI interface but it seems to be giving me an error NullReferenceException Object reference not set to an instance of an object UnityEngine.UI.Selectable.Select () on this line of code selectedOject.GetComponent lt Button gt ().Select () so there is a null reference and its no longer recognizing the child objects as buttons is what I'm assuming if you want to have a better look at his set up he has a short video On youtube HERE I would like to continue to use this script and continue updating Unity.


Disable audio listener warnings? "There are no audio listeners...", "There are 2 audio listeners..." The scene I'm working in constantly spams the message There are no audio listeners in the scene. Please ensure there is always one audio listener in the scene. If I add a dummy camera with an Audio Listener, I then get There are 2 audio listeners in the scene. Please ensure there is always exactly one audio listener in the scene. I know this happens because our camera is created programmatically, with an audio listener. I also realize this will not affect the non development build in any way. Is it possible to disable these warnings completely?


How to add high score? I wanted to add a high score to my game but I don't know how I already tried to find some videos for it but I just can't find the right one. I already have a scoreUI on my game I just wanted to add a high score. Here is my UIManager's script which consists of different functions including the score system. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI using UnityEngine.SceneManagement public class uiManager MonoBehaviour public Button buttons public Text scoreText int score bool gameOver Use this for initialization void Start () gameOver false score 0 InvokeRepeating("scoreUpdate", 0.5f, 0.25f) Update is called once per frame void Update () scoreText.text "" score void scoreUpdate() if (gameOver false) score 1 public void gameOverActivated() gameOver true foreach(Button button in buttons) button.gameObject.SetActive(true) public void Play() SceneManager.LoadScene("level1") public void Menu() SceneManager.LoadScene("Menu") public void Retry() SceneManager.LoadScene(SceneManager.GetActiveScene().name) public void Pause() if (Time.timeScale 1) Time.timeScale 0 else if (Time.timeScale 0) Time.timeScale 1 I got the score system from Charger Games. Here is the link to the Video and here is what my game looks like


Detect collision from a particular side I'm making a platform sidescrolling game. All I want to do is to detect if my character is on the floor function OnCollisionStay (col Collision) if(col.gameObject.tag "Floor") onFloor true else onFloor false function OnCollisionExit (col Collision) onFloor false But I know this isn't the accurate way. If I hit a cube with a "floor" tag, in the air (no matter if with the character's feet or head) I would be able to jump. Is there a way to use the same box collision to detect if I'm touching something from a specific side?


How to do pixel perfect movement with Unity3D? How would you be able to make sprites move pixel by pixel in Unity3D? I've tried the following things. int x (int) transform.position.x int x Mathf.FloorToInt(transform.position.x) int x Mathf.RoundToInt(transform.position.x) I don't know what else to try Because I'm making an SNES looking game, and when things move, there is very bad pixel crawl in the sprites.


Level Selector with possible future levels? Unity I have a level select screen which is a simple grid layout of my levels. The level data comes from a scriptable object for each level. The problem I have is what is the best method for populating the grid of levels that use the scriptable object and is able to add more levels to the grid layout if let's say I add an asset bundle in the future? My thought was that I use a levelDB which holds a list of all of the scriptable objects. Then when an asset bundle is used then it adds the content to the levelDB. The UI would then just use this levelDB to populate the screen. NOTE I have very little to no knowledge of how asset bundles work and what you can, and cannot do with them.


unity graphics initialization Pretty short question, when I load unity, I get this error Is this fixable with driver downloads, or do I need a new PC? if so, how do I find out my computer's default built in graphics driver?


Gfx.WaitForPresent performance issue I am making a 2D mobile game and it runs really well (60 fps) on my phone. However, in some cases the performance goes down drastically to the point where it runs at 20 fps or even less. It happens at random times so I can't pinpoint what is causing this. During the performance decrease Gfx.WaitForPresent appears in my profiler which eats a lot of power. I am aware that this might be because of Vsync being turned on, but I have it disabled, along with shadows, AA and everything else that absolutely kills mobile performance. What else can be the problem? My game relies heavily on good performance for gameplay so this needs to be resolved ASAP. Edit I also noticed that the GPU stays at 0 ms which is really odd as well.


Why is perlin noise generating flat terrain in Unity? I am trying to generate terrain using perlin noise however the terrain being generated is a plateau. Here is the code that I'm using var xlength 65.0 var ylength 65.0 var scale 4.1f var heights new float xlength, ylength function Start () for (var i 0 i lt xlength i ) for (var j 0 j lt ylength j ) heights i,j Mathf.PerlinNoise(Time.time i xlength scale 1000,Time.time j ylength scale 1000) i j gameObject.GetComponent(Terrain).terrainData.SetHeights(0,0,heights) What am I doing wrong here?


Unity immediate mode I have some existing C 2D game code that draws using immediate mode (i.e., each frame is drawn bottom up one sprite at a time by my game code not using a scene graph or other retained mode concepts). I'm wondering if I can port this code to Unity without having to rework the game code to operate in terms of retained mode (adding objects to a scene, removing objects, etc.). I have read that Unity has an immediate mode GUI option. But in my case I want to use this for the game sprites themselves, not just the UI elements. I realize that for a 2D game there isn't a big difference between UI elements and game sprites. But I need to be able to do things like rotation and render to texture, so I wasn't sure if I'd run into trouble "misusing" the immediate mode GUI mechanism to handle the whole game. Alternatively, does Unity have a more general immediate mode option? (I did search for it and didn't see anything aside from the immediate mode GUI stuff.)


How can I economically check if a UI DropDown is open or closed? I've recently come across a problem with the UI DropDown component. I would like to resize other UI components depending on whether the dropdown is opened or closed. Unfortunately, the dropdown dynamically creates and destroys its own "Dropdown List" component, making it difficult to check whether it is open or not, without having to check with Update or FixedUpdate (both being expensive on the performance). I have tried to implement a solution with event handlers, but it seems as if the even handler triggers before the "Dropdown List" is created. Thus this does not work. Am I simply missing an easy way to check whether the dropdown is open or closed?


FindWithTag returning a game object from "Preview Scene". What is that and why is it not detecting from the active scene? I have a script that fetches a transform using GameObject.FindWithTag("Tag").GetComponent lt Transform gt () . This has worked fine for a long time, but now it retrieves a transform from a preview scene(whatever that is). How do I prevent it from looking at preview scene?


Unity question on OnTriggerStay() function I'm currently working on a soccer game.I have a script for the ball that whenever the ball collides as trigger with the goal line,the ball will return to the middle point.But seems like the ball doesn't Lerp() back,afterward I tried to check if Unity counts it as collide or not with Debug.Log("Goal") but nothing is logged to the console.Please help me with that.Here is the first code public var smooth float private var newPosition Vector3 function Awake () newPosition transform.position function OnTriggerStay (ball Collider) var positionA Vector3 new Vector3(0, 0.3, 0) newPosition positionA transform.position Vector3.Lerp(transform.position, newPosition, smooth Time.deltaTime) Here is the second code (after changing to Debug.Log()) function OnTriggerStay (ball Collider) Debug.Log("Goal")


How can I parent an object whilst animating? Much like in Blender where you can parent an object to another, or the Armature, is it possible to parent an object to another, so when animating, the child object moves with the parent? I've tried dropping the object I want influenced onto the character's parent object in the hierarchy and accessed it via the Animation tab. I added the object as a property and adjusted it's position, but the results have been pretty mixed. How can I have an object automatically follow the animation without manually adjusting its curves for each frame?


How to make a 2D neon like trail effect in Unity Recently I've been toying around with neon ish effects for a game I'm making and wanted to share my results with you. If you guys have any other methods of achieving this result, please be sure to share.


Is it possible to make a randomly rotating terrain texture painting brush in Unity? I wanted to make a terrain in unity with a dirt texture painted onto the original grass texture to make a path, but when I tried, the dirt (and grass) looked repetitive and full of patterns. My question is, is there any way I can make a texture's tiles randomly rotate when being applied or painted onto an object?


Changing distance after some time on OnGUI Unity Though I am using IEnumerator to calculate the distance travelled value, the distance is updated very frequently, how can I change that? and why exactly increasing the time in WaitForSeconds function not changing the behaviour? void OnGUI () GUI.contentColor Color.black GUI.Label (new Rect (40, 40, 140, 40), "Speed " speed, "color") StartCoroutine (distancetravelled ()) GUI.Label (new Rect (40, 100, 100, 140), "Dist " Mathf.RoundToInt (distance 1000) " Kms", "color") IEnumerator distancetravelled () timeInHours (Time.smoothDeltaTime 60) 60 if(PlayerControl.collision ! true) distance speed timeInHours yield return new WaitForSeconds (60)


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


Unity Change the type of a Texture2D to "Normal map" through script I am making procedural terrains through c script, and while I achieve to produce a texture, a heightmap and a normalmap to Texture2D, it seems they are not being applied correctly to the material. the texture (albedo) is applied the noise map is applied (but as a "default" texture, I think?) the heightmap is not even selected The trick I currently use is to also save the Texture2D to files. After generation I manually affect the file normalMap and it goes fine. But you'll understand this is not satisfactory, I want the script to set the normal map correctly. I suspect this is because the file's texture type is force to normal map. But I cannot see how I can change the type of an in memory Texture2D through code. Researches gave nothing fitting my concerns, any help will be appreciated. Thanks ) EDIT I tricked by passing a pre made normal map as parameter, to use instead of the one I generate. Guess what? It works instantly.


Add Rigidbody and MeshCollider at runtime is it a bad practice? Good day. To simulate an explosion of a vheicle, I decided to do this When I need to explode veichle , at runtime, i add rigidibody for every single part of veichle (5 10 part door, wheel, hood etc), and collider (mesh). I detach them from parent I apply an AddExplosionForce to every single part This cause a big lag in my game, so I'm supposing this is not the efficent way. The other way could be to add Rigidbody and Collider in my prefab, with Rigidbody.gravity false, and isKinematic true, then enabling after explosion, but also this is not good for performance. Do you have some suggestions to achive my scope, considering that I could have a lot (5 10) enemy veichles at time on my scene ? Thanks


UI Button sprite not changing on click I'm trying to make the sprite of my button change on click, and i used this script to achieve it public Button botonPlayMaster i assign the button on the inspector Image imagenBoton public Sprite botonPlay same with the sprites, i send them on the inspector public Sprite botonStop Start is called before the first frame update void Start() imagenBoton botonPlayMaster.GetComponent lt Image gt () i get the component from the button public void cambiaSprite () if (imagenBoton.sprite botonPlay) imagenBoton.sprite botonStop else imagenBoton.sprite botonPlay This script is attached to a GameManager GameObject. I assign the sprites and the GameObject Button on the inspector, and then send the GameManager object to the OnClick() function on the button's inspector and select the cambiaSprite() function. But when i click, nothing happens. Any help would be appreciated. Thanks!


Code Logic's execution with respect to time Events I have to show complete 24 hours cycle in Unity3d Scene. Where different kind of task will be executed in different Times. Suppose at 2pm I have to move a car, at 6pm An Aeroplane will land on airport at 07 07pm I have to open the door of Market's Buildings and so on different task works execution at different timing. Now, I have some basic animation e.g., car, Aeroplane and door etc.,. Now I am confuse that how to play and stop my animation according to the time. And time can also be changed manually using GUI. If currently 6pm (animation working) then user can switch to 8am to view 8am time's animation (or code execution). And User can also fast the timing to view complete hours in a single minutes or in an hour. I can use if else in Update Events but I guess this is not the right way to do and will be very difficult if I require to show significant number of works in different time duration (which means significant number of if else statements). Just like below void Update() if(time 1) logic if(time 2) logic if(time 3) logic ... so on, tedious way ... and also not possible if time require between the hours, suppose 06 06pm What to do ? How to handle this?


Is it cheaper to let each tile have its own collision? I'm just now playing around with Tiled, and I think this is the way I'm going to go to create tilesets for my game maps, but I'm curious about the cost (memory CPU) difference between setting a collision for a specific tile so that Tiled creates them all individually versus manually drawing collision polys around larger sections by hand. For instance By Tile Manual There are fewer polygons in the manual draw (4), and it's not terribly difficult to create them, but is there a benefit one way or the other?


Bubble Text appears issue? I'm trying to make a dialogue between characters using bubbles witth text. But the text appears not clear to player. The Cam is far from the canvas 13.5f. What to do fix it ?


Move ball based on direction of force? I'm trying to make a ball that will move in the direction I push it from, and later pull it to me based on where the player is standing. using UnityEngine using System.Collections public class BallForce MonoBehaviour public float thrust public Rigidbody rb Use this for initialization void Start () rb GetComponent lt Rigidbody gt () Update is called once per frame void Update () if (Input.GetMouseButton (0)) rb.AddForce (transform.forward thrust) This seems to work, but I'm not sure how I get it to move based on the position of the player. How would I do this?


Old tv effect in shader graph I am trying to use Unity's shader graph to create this old tv effect I thought about using a noise node, and somehow randomize the noise's seed. Can anyone help me?


How do I rotate a gameobject towards a point in world space? I wanted to create a very simply turret. This turret should aim at the point on the screen where the mouse pointer is currently located. I have added a cube to serve as a very simple turret in my scene. To visualize its aiming direction, I'm drawing a ray from it. To rotate the quot turret quot to the mouse pointer position, I have created a script and added it to the quot turret quot gameobject void Update() var mousePos Input.mousePosition mousePos Camera.main.transform.forward 10f Make sure to add some quot depth quot to the screen point var aim Camera.main.ScreenToWorldPoint(mousePos) transform.LookAt(aim) RaycastHit hit int layerMask 1 lt lt 8 layerMask layerMask Color color if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask)) color Color.green else color Color.red Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) 10000, color) However, there must be something wrong in my code. In this screenshot, I have added a red arrow that points to the position of the mouse pointer The mouse pointer is over that orange tool. However, the turret is rotated towards the floor while it should be rotated upwards to the orange tool. I do believe that my turret is well positioned (the blue arrow points forward) How do I change my code so that it aims correctly, and what is my mistake? I guess the problem is in these 2 lines, but I don't see what's wrong about it mousePos Camera.main.transform.forward 10f Make sure to add some quot depth quot to the screen point var aim Camera.main.ScreenToWorldPoint(mousePos) Thank you. Edit I finally understand what Kevin wanted to tell me. I made a thinking mistake, and really need the Raycast to determine where my Worldspace point actually is. Here is why Even though the Y screen coordinate of the mouse position is just a few pixels different in each game window on the right side, the worldspace point is totally different (as can be seen in the scene view window on the left side). I thought in 2D space, while I should have thought in 3D space.


Unity C Changing Button Color? void OnMouseDown () foreach (Button thisButton in buttonArray) thisButton.GetComponent lt SpriteRenderer gt ().color Color.black GetComponent lt SpriteRenderer gt ().color Color.white This code results in whichever button I select changing color to white while the rest are black. However, I am not understanding how this works. How does it know to specifically change ONLY the selected button to white while the rest are black. Seems contradictory to me...


How to find the angle of an arc for reflection I am using the following code to calculate points for a circle arc drawn with a Line Renderer. for (int i 0 i lt pts i ) float x radius Mathf.Cos(ang Mathf.Deg2Rad) float y radius Mathf.Sin(ang Mathf.Deg2Rad) arcLine.positionCount i 1 arcLine.SetPosition(i, new Vector2(x, y)) ang (float)totalAngle pts How can I change the angle ang to create a reflected arc along the line P1P2 as in the image below? Please note that totalAngle represents the portion of the circle that is to be drawn between 0 and 360.


How can I fix this shadow slicing the mesh on Android? I have a golf ball in my Unity game for Android, which is an icosphere (imported from blender) with a baked normal map. There are 18 tracks located in one level around the (0, 0) coordinate, rotated in different directions. The game uses Distance Shadowmask to create realtime shadows for near objects. In the editor and Windows builds, this works perfectly. On Android, the shadow has a lower resolution, which is fine, but it seems to slice through the ball. It is visible in the following screenshot. If the ball moves, it looks like it passes through several planes casting a shadow. This is heavily depending on the current track the ball is on. In 3 of the 18 tracks, there are very noticeable errors. Some other locations show very small errors. However, those tracks are on seemingly random position. While the heavy errors appear on tracks located mainly in this ( x, z) area, the small errors appear on arbitrary other positions. I already tried changing shadowmap resolution changing the directional light's near plane changing the directional light's bias and normal bias changing the directional light's position and rotation rebaking the ball's normal map using another ball mesh removing the normal map from the material using a different device


Syntax error in multi pass Surface Shader I'm trying to make a Surface Shader that uses multiple passes, with two different blending functions for each one, but I get the following error I don't understand Parse error syntax error, unexpected TOK PASS, expecting TOK SETTEXTURE or ' ' at line 28 SubShader ZWrite Off Tags "QUEUE" "Transparent" "IGNOREPROJECTOR" "true" "RenderType" "Transparent" "PreviewType" "Plane" Pass transparency Blend SrcAlpha One CGPROGRAM pragma surface surf Lambert pragma target 3.0 struct Input sampler2D void surf (Input IN, inout SurfaceOutput o) ENDCG Pass alphabend Blend SrcAlpha OneMinusSrcAlpha CGPROGRAM pragma surface surf Lambert pragma target 3.0 sampler2D fixed4 struct Input void surf(Input IN, inout SurfaceOutput o) ENDCG


Load the prefab in the array by name in Unity I'm using this line of code to select my level, and currently I have different scenes for each levels. I want to be able to reuse the same scene to change levels as well but I don't know how, here's the line button.GetComponent lt Button gt ().onClick.AddListener(() gt Levels("Level " button.levelText.text)) Since I'm using string to load my scene with the function below void Levels(string value) SceneManager.LoadScene(value) I really wish I could use prefab name instead the scene name and I don't want to have 20 scenes for it. Any help would be appreciated.


Trouble with assigning a model's own mesh to a mesh collider in Unity I'm trying to use a mesh collider on the player's avatar, rather than the box collider. I've added the mesh collider to the game object (which also has a rigid body) and selected the "convex" checkbox. However, the player still falls through all geometry, including Unity primitives, terrain, and other models. In the mesh collider's property box, there's a value for "Mesh", which I have set to "None (Mesh)". I was led to believe this defaults to the model's own mesh, but now I'm not certain. If I change the value to something else from the "select mesh" list, like the cube, the collisions work. When I click over to Select Mesh Scene, the list is empty. I'm assuming I need to add the model's mesh to the list, but I can't find any documentation about that.


Orthographic Camera Movement inside Rotated Boundary Rectangle Weird Behaviour Unity3d Basically I have an orthographic camera that is looking at a simple square. The camera is sitting above the square and tilted by x 45 and y 45 , so the camera sees the square as a rhombus diamond shape. I want the camera to be moveable within a rectangular boundary that appears to be leveled with the camera, so it would need to be rotated by 45 around the y axis (up vector in Unity) in World coordinates. I already figured out the math to constrain the camera to this shape, but there is a weird thing going on when the movement gets clipped The camera doesn't follow the outline perfectly, but in a rounded shape (see screenshot). Could this be due to a rounding error? Code snipped below. using System using UnityEngine using static UnityEngine.Mathf public class InputController MonoBehaviour private const float CamHeight 10f SerializeField private GameObject gameBoard SerializeField private GameObject camBounds SerializeField private float camBoundRadius 5f private Vector3 camOrigin private MeshCollider collider private Vector3 difference Change in position of mouse relative to origin private Camera mainCamera private Vector3 origin Place where mouse is first pressed private Plane worldPlane private void Start() mainCamera Camera.main if ( mainCamera is null) throw new Exception( quot No main camera could be found! quot ) Set the camera so that the board is always in the center camOrigin new Vector3( CamHeight Sqrt(2f), CamHeight, CamHeight Sqrt(2f)) mainCamera.transform.position camOrigin collider gameBoard.GetComponent lt MeshCollider gt () worldPlane new Plane(Vector3.up, 0) For dragging the camera around private void LateUpdate() if (Input.GetMouseButtonDown(0)) origin MouseWorldPosition() if (Input.GetMouseButton(0)) difference MouseWorldPosition() transform.position var newPos origin difference var absDiff newPos camOrigin var angle Angle2Pi(Vector3.right, absDiff) var constraint SawTooth(angle) if (absDiff.magnitude lt constraint) transform.position newPos else transform.position camOrigin absDiff.normalized constraint private Vector3 MouseWorldPosition() var clickedPoint Input.mousePosition var ray mainCamera.ScreenPointToRay(clickedPoint) var worldPos Vector3.zero if ( worldPlane.Raycast(ray, out var raycastHit)) worldPos ray.GetPoint(raycastHit) return worldPos private float SawTooth(float theta) var x 4f PI camBoundRadius (1f 1f Sqrt(2f)) x Abs(theta (PI 2f) PI 4f) x camBoundRadius Sqrt(2f) return x private static float Angle2Pi(Vector3 from, Vector3 to, Vector3 normal default) if (normal default) normal Vector3.up var angle Vector3.Angle(from, to) (PI 180f) var sign Sign(Vector3.Dot(normal, Vector3.Cross(from, to))) angle 2f PI angle sign return angle


WHY !! CountDown not Working inside the IF Condition? i need a way to make the countdown decreasing inside the if statement i am stacking in this problem for more than 3 days .. Don't suggest to me Coroutine cause it will not working in my case cause i am using clones (initiated prefabs) i know that the countdown will work only one frame if it's inside an IF Statement ... Any Ideas to make it working ...Ty The game is about cars ... and every instantiated car has a random countdown timer void Update() if(carNumber lt cars) SpawnCars() and this is the spawn function void SpawnCars() randomSpawnPoint Random.Range(0, spawnPoints.Length) randomSpawnCars Random.Range(0, Cars.Length) GameObject obj Instantiate(Cars randomSpawnCars ,spawnPoints randomSpawnPoint .position, Quaternion.Euler( 90, 180, 0)) as GameObject carNumber obj.gameObject.tag "select" k rcf obj.GetComponent lt RayCastForward gt () TextMesh txt FindObjectOfType lt TextMesh gt () time Random.Range(4, 20) txt.text (time Time.deltaTime).ToString("0") print(time) print(carNumber) EDIT time is the timer


Unity3d Do I need to destroy gameobject AND script? From proper leak protection do I need to delete both of these or will getting rid of one take care of both? Currently I am destroying the script AND the gameobject private void OnDestroy() Destroy(this.gameObject) Destroy(this)


Moving panel between two positions smoothly? I'm trying to make my panel moving from one position to another one smoothly. What I get is more faster no matter what I did to make it slower never get slow !! Both Vector3.Lerp and Vector3.MoveTowards did not give me a slow movement. Here is my script public GameObject gunsWindow private Vector3 a, b public bool open use inspector void Start() a gunsWindow.transform.position b new Vector3(100.0f, gunsWindow.transform.position.y, gunsWindow.transform.position.z) void Update() if(open) gunsWindow.transform.position Vector3.MoveTowards(a, b, Time.deltaTime 1) weaponPlane.transform.position Vector3.Lerp(a, b, Time.deltaTime) panel shaking else gunsWindow.transform.position Vector3.MoveTowards(b, a, Time.deltaTime 1) weaponPlane.transform.position Vector3.Lerp(b, a, Time.deltaTime) shaking


How to make AI detect a target behind a wall, who is only partially exposed? I'm making an FPS game where, even when a target's whole body is behind a wall or box, but its finger or foot exposed, the AI should be able to detect it and shoot its finger. So far the way I've thought of to implement this it so traverse all the targets, find who is near a wall, and compare their position with the corner of wall. But I don't know how to check whether its finger is exposed. I could use a raycast forward from the AI's gun, but would I need to add a collider to every small body part of every target?


Make a door in a cube wall I have created a wall using a cube in Unity. Now I want to create a door in it. How can I make a door in that cube? Consider that the cube is automatically generated, so i have to generate the door in a C script.


Unity3D Multiple OnTriggerEnters are called before the first one could finish and destroy the object I'm working on a projectile which explodes when it reaches a destructible object and damages its voxels. (The projectile is a trigger) But the problem is that I use raycasting in OnTriggerEnter which makes it slow to finish. Which lets multiple OnTriggerEnter to be called before it could be finally destroyed. I fixed it by having a flag which lets only one call to be executed. But it feels a bit hacky, so I decided to ask you, maybe you have some better solutions. void OnTriggerEnter(Collider collider) if (!hit amp amp LayerMask.LayerToName(collider.gameObject.layer) "Destructible") hit true DoImpact() Destroy(gameObject) void DoImpact() Do 1 SphereCast RaycastHit hits Physics.SphereCastAll(transform.position, ExplosionRange, transform.forward, 0.0001f, 1 lt lt LayerMask.NameToLayer("Destructible")) Iterate through voxels foreach(var hit in hits) the parent object which manages its voxels var destructible FindDestructibleParent(hit.transform) Make some damage to that voxel based on the projectile, the voxel, and some "whole container parent object properties" destructible.TakeDamage(this, hit.transform.gameObject)


How do I override a SteamVR Controller's transforms in Unity? I'm trying to provide an illusion to the user by rotating the controller about an arbitrary axis in the LateUpdate() method. But this doesn't seem to be having any effect as the controller probably is constantly getting updated by its real world location. Is there any way to override its real world position and orientation with a transformation in script?


How to dynamically create an UI text Object in Unity 5? I have been searching for something that should be simple, but Unity 5's documentation on that is fairly outdated. What I want to achieve is to be able to create UI Text totally from script, i.e. fully dynamically in my real case application, I will do that in a loop of not pre defined number of iterations. A search using Google will find quite many examples on how to do that, but all I saw either use methods that are already deprecated (are from before Unity version 5) or are simply wrong (no surprise here...). I already know that I should first add a Canvas to my project, then I should include using UnityEngine.UI in my C code, and also that I could declare a UI Text like Text guitext. However, the code below does not work. I mean, it's not that it crashes, but rather that nothing is shown using UnityEngine using System.Collections using UnityEngine.UI public class MyClass MonoBehaviour Text guitext Use this for initialization void Start () guitext.text "testing" Update is called once per frame void Update () Worse than that, it seems that while game is played, no new object appears in the object hierarchy list. Could you please point me out in the right direction here? Thanks.


Spriterenderer on top of canvases I have two canvases. One with a background image and one with all overlaying elements like texts and such. The background canvas has an order of 0, the overlay canvas of 1. Now, I'd like to create an animating sprite on top of those canvases but I can't for the life of me get the sprite on top of the other images. I can see the sprite being on top on the stage, but when I switch to gameview, it's gone! There are no scripts attached to the sprite. Only an animator(Which works fine when I play it). Note My canvases have a render mode of Screen space Overlay. I've set the spriterenderer on Sorting Layer 9, order 300. Although it's the only sprite out there. layer 1 or order 1 didn't do anything different, though. The other elements in the canvases are either UI texts or Images All the elements in the canvases are on either BackgroundLayer or OverlayLayer The canvases themselves are on the UI layer


How to decompose a 4x4 TRS transformation matrix with negative scale? As the title says I need to decompose 4x4 TRS transformation matrices and extract the proper scale vectors and the proper rotation vectors (or rotation quaternions). I know how to extract those information when the upper 3x3 matrix determinant is not negative. The problem is that those matrices can have that negative determinant and as far as I could understand, this negative determinant indicates a flip or mirrored transformation. What do I have to do to extract the proper values for scale and rotation in those cases?


How can I obtain the file size of a Unity build at runtime? I'm wondering if it is possible to obtain the filesize of a game's build at runtime. Searching this topic only yields results for reducing the build size, which is not at all what I'm looking for.


Best practice for toggling between ragdoll and CharacterController One feature of the game I'm working on is that if a character is hit with a certain amount of force, it will temporarily ragdoll, then get up off the ground after a small period of time. This character is moved by a CharacterController (CC) component. At the moment, I have the model as a child of an object with a CC component and movement script. My issue is that when the ragdoll is activated animator is disabled, the model moves independently of the CC if it ragdolls with some arbitrary force in any direction, the CC does not move with it (as you'd expect). This would be fine if the ragdoll wasn't meant to be re enabled, but it is. At this stage, the model teleports moves to where the CC is, and it looks very weird. I have tried a few different methods to synchronize the two Decoupling the CC and model. Both objects are children of a shared parent, and I added them both to an PhysicsIgnoreLayer (for now eventually if I go with this I'll probably add all the ragdoll colliders to an array and ignore them individually). When the ragdoll state is enabled in the parent, the CC is disabled and the object is teleported to the root bone every frame. When the CC is enabled, the model is teleported to the CC object every frame. See here. The issue here is that setting the position means extra Update() calls and it lags behind the controller a little. Also, because the model isn't a child of the controller, it doesn't inherit the velocity of the controller, so it needs to be manually applied. Changing the parented GameObject at runtime. Depending on the state of the character, the CC model will be parented to each other if the CC is active, the model is set as its child and vice versa using SetParent. I couldn't get this one working (the local position variable was a little confusing to me, but no configuration I tried worked for me). Conjoined CC and model. I placed the CC on the same object as the model. This isn't really ideal for me because I want greater control over the rotation and presentation of the model. I couldn't get this one working either I don't know how I could set the position of the CC without moving the whole thing. Is there a more effective way of doing this? If so, what? I feel like I am greatly overcomplicating this. Any help would be great. In an ideal situation, I could have the model as a child of the controller (or behave that way) and move the CC when it is inactive without affecting the model position.


Problem with Factory Method Pattern when I try to create a Weapon MonoBehaviour I'm learning about Design Patterns using Unity and I'm not sure about how to solve the following problem with the Factory Method Pattern I want to read a XML file and using the Factory Method Pattern to create a Component (a Weapon) to add it to a GameObject which will be cointained on a Pool Manager, but Weapon "Is A" MonoBehaviour and for that reason It can't be instantiated using a "machineGun new MachineGun() " public abstract class WeaponFactoryMethod protected string fileName "weapons.xml" public abstract Weapon CreateWeapon() public class MachineGunFactoryMethod WeaponFactoryMethod public override Weapon CreateWeapon() string filePath Path.Combine(Application.streamingAssetsPath, fileName) Weapon machineGun null XmlReader xmlReader new XmlTextReader(filePath) if (xmlReader.ReadToDescendant("Weapons")) if (xmlReader.ReadToDescendant("Weapon")) do I CAN'T DO THIS machineGun new MachineGun() machineGun.ReadXml(xmlReader) while (xmlReader.ReadToNextSibling("Weapon")) else Debug.LogError("There aren't definition for Weapon") else Debug.LogError("There aren't definition for any Weapon") return machineGun public abstract class Weapon MonoBehaviour, IXmlSerializable public float AttackRange get set Every weapons Shoots in a different way public abstract void Shoot() Serialization public XmlSchema GetSchema() return null public void ReadXml(XmlReader reader) XmlReader childReader reader.ReadSubtree() while (childReader.Read()) switch (childReader.Name) case "AttackRange" childReader.Read() AttackRange childReader.ReadContentAsInt() break public void WriteXml(XmlWriter writer) public class MachineGun Weapon public override void Shot() Raycasting.. At the end I want something like GameObject (player) Component (A Weapon script with the data from the xml) Should I just create a GameObject (player) and do an "AddComponent lt MachineGun " and later copy the info from the xml file instead using the Factory Method Pattern?? Is there a better way?? Any suggestions, corrections or advice will be very grateful. I'm sorry by my English.


Unity DirectoryInfo not working in OSX standalone build So I'm building an application in unity which I hope to use at a market day coming up soon at my school (it's not a game, it's basically like a checkout app, kind of...) Anyway, I'd like to be able to import images from the app and to have the option to change them while the app is running. Currently I have the images in a folder and I'm using DirectoryInfo to get the contents of that folder and load the images. Works like a dream inside the editor but as soon as I build the app (on OSX), everything is blank. Other people seem to have similar issues but I'm a little unsure as to how they fixed it. Could someone please help me, this is kind of urgent!


Using Unity's transform.translate() to translate relative to an object but only using two axis I'm using transform.translate() to move an object around the world space, relative to the camera that is following it. The camera has an angle of 23 degrees on the X axis. The problem is that when I move forward the object tries to go into the ground and when going backward the object starts jumping because of the angle of the camera. What I want to do is freeze the Y axis of the object However if I did this the object would no longer be able to jump. The other solution to this would be to write a method which rests the object to the ground when not jumping but them if the object was jumping and going backwards it would go flying backwards again. How do I solve this issue?


Advantage of Using Addressable Over Asset Bundles in Unity I have a project that already uses asset bundles. I download assets when the game starts and show them to the user when needed. I see that Unity provides addressables as new solution for asset management. As its new (not very new as its accessible from 2018.2, but official docs dont say a lot) there is not so much about it on the web. From what it seems, in addressables you dont need to care about the bundle version, or which asset is in which bundle. In addresables, Unity automatically uploads assets to your host, and Unity automatically correctly manages local caching or downloads from a server, so objects behave like they are in the main game package but you have to check if they are loaded or downloaded. Am I right? Are there any other features that addressables offer?


How can I get Unity to tell me the battery status of my OS X laptop? How do I get battery status on an OS X laptop in Unity? This is un Googlable I keep finding either mobile stuff (iOS or Android) or people complaining about laptop battery life.


How do I create this windblown snow effect? How do I create this snowy wind kind of effect, where wisps of snow appear to blow through the air close to the ground? I have seen this in several games like Skyrim, the new God of War, but I don't know what name to call it by. I found this God of war gameplay https youtu.be b7u59Iutb0c


How to modify the Unity sprite renderer (or create a custom one) that can display the sprites on the X Z plane? Prefix I am NOT trying to rotate a sprite 90 degrees by it's transform, this changes what is up down and forward backwards for the object. I need the sprite displayed on the X Z plane in comparison to the default X Y plane in it's natural state in the game world with rotation transforms of 0. I'm trying to use 2D sprites on the X Z plane, how do I go about either modifying the built in sprite renderer to do this, or creating my own custom sprite renderer component?


Unity animator controller animations don't work I'm having problems animating a character pack I purchased from unity asset store. I've placed the character in an environment and created an animator controller. After I drag the animation that to the animator tab, there aren't any motions. Even if I place triggers or booleans in my script as parameters in the animator it doesn't work. It worked with other characters but the animations were somehow embedded in the 3d models. How is this supposed to work?


Run a Script at Game Startup in Unity I have a script that is made to run when the game is loading. That script set the resolutions, fullscreen, and loads other screen and important settings and it applies them. I have the script attached to a gameObject in the main screen that have some game and scene scripts. The problem is that everytime that you return to the main scene, that script runs again and cause several bugs. So, there is a way to run a script only at game startup?


Microphone channel not detected in Unity This is very specific to Unity. A few testers are reporting that their microphone output isn't being detected. The code below works for the vast majority of users, but certain microphones seem to be outputting on the wrong channel (R maybe)? AudioClip current microphone recording clip Microphone.Start(microphone name, true, 30, 16000) How can I capture and analyze output from several channels? I don't see any channels parameter for Microphone.Start


Color bands over tile when scaling texture in shader I want to have tiles with different sprites on the back. Initally I thought I will mix two textures together and then apply mixed texture to game object. I thought that should be easy, but google returned discussion about shaders and their superiority. After reading about shaders I decided to use shaders instead. Also I am using rather big sprites and I am scaling them down in shader. Kind of want to be sure that tiles look good on big screens also. Also to be sure that game works on smaller screens I change camera distance when game does not fit in the screen. Everything is working nice when tile is "near". But when tile is far away it starts to show artifacts over all surface of tile. It appears that scaling is done not pixel by pixel but in some chunks. Modified shader code (I commented out mainTex because it does not change anything from "bug" perspective) Shader "Custom TwoTextureShader3" Properties Color("Color", Color) (1,1,1,1) MainTex("Main Texture Color (RGB)", 2D) "white" MainTex2("Overlay Texture Color (RGB) Alpha (A)", 2D) "white" Glossiness("Smoothness", Range(0,1)) 1 Metallic("Metallic", Range(0,1)) 0.2 OffsX("Offset X", Range( 2, 2)) 0 OffsY("Offset Y", Range( 2, 2)) 0 Scale("Scale", Range(0, 10)) 1 SubShader Tags "RenderType" "Transparent" LOD 200 CGPROGRAM Physically based Standard lighting model, and enable shadows on all light types pragma surface surf Standard alpha fullforwardshadows Use shader model 3.0 target, to get nicer looking lighting pragma target 3.0 sampler2D MainTex sampler2D MainTex2 fixed OffsX fixed OffsY fixed Scale struct Input float2 uv MainTex float2 MainTex2 half Glossiness half Metallic fixed4 Color void surf(Input IN, inout SurfaceOutputStandard o) float4 mainTex tex2D( MainTex, IN.uv MainTex) fixed2 offsetUV fixed2( OffsX, OffsY) float4 overlayTex tex2D( MainTex2, IN.uv MainTex Scale offsetUV) half3 mainTexVisible mainTex.rgb (1 overlayTex.a) half3 overlayTexVisible overlayTex.rgb (overlayTex.a) float3 finalColor (mainTexVisible overlayTexVisible) Color o.Albedo finalColor.rgb o.Albedo overlayTex.rgb o.Metallic Metallic o.Smoothness Glossiness o.Alpha max(mainTex.a,overlayTex.a) o.Alpha 1 ENDCG FallBack "Diffuse" Tiles looks good when they are near Tiles looks awfull when they are far away Currently I am thinking about using two Meshes for single tile, so that game never hints about what is on the back of the tile even when graphics hardware really want to.


Does 2D Platformer games still have popularity among gamers? I'm currently working on a 2D platformer game that i wanted to put out as my first game but seeing the popularity of other games made by Voodoo and others are quite distressing and made me ask myself this question and now you guys. will the 2D Platformer games that had the popularity will have any popularity for developers to take interest and make some living out of it in the for future projects or can they work on the more popular games like color bump 3d.


Saving a high score and updating it as score increases I'm following Brackeys "Dodge the Blocks" tutorial. In the video, he covered everything accept the score high score system. I have a working score system, which gives you 1 point every time you collect a coin. In the scene where you play the game, I have a text UI that says "Score ", and another one for the score number, another that says "Best ", and one more for the best number. I want to make it so that your high score gets saved, and updates in real time with your score every time you pass the score. Here are some of the scripts UI Manager (Where I want to put the high score code) using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class UIManager MonoBehaviour public Text scoreText int score public static int coinAmount void OnTriggerEnter2D(Collider2D col) CoinTextScript.coinAmount 1 Destroy (gameObject) public void scoreUpdate() score Coin Text Script using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class CoinTextScript MonoBehaviour Text text Text bestScoreText public static int coinAmount public int score void Start() text GetComponent lt Text gt () void Update() text.text coinAmount.ToString()


Unity facebook sdk 'Didn't find class "com.facebook.FacebookContentProvider"' any more fixes workarounds for this? How to replicate this error... Create a new Unity project. Import the facebook sdk unitypackage Set your App Id for facebook via Facebook Edit Settings Using Assets External dependency manager Android, press 'Resolve dependencies', then press 'delete resolved libraries' (otherwise the build will fail at the gradle stage) Build and run. When the app tries to run I immediately get the error message on my phone 'app has stopped working' and see this error in the logs ... Caused by java.lang.ClassNotFoundException Didn't find class quot com.facebook.FacebookContentProvider quot on path DexPathList zip file quot data app com.SandwichGeneration.MakeASquare nLEHpzOYlwW6XKmGzPfIw base.apk quot ,nativeLibraryDirectories data app com.SandwichGeneration.MakeASquare nLEHpzOYlwW6XKmGzPfIw lib arm64, data app com.SandwichGeneration.MakeASquare nLEHpzOYlwW6XKmGzPfIw base.apk! lib arm64 v8a, system lib64, system vendor lib64 Suggested fixes I've tried from here I've tried different combinations of old or new facebook sdks and old or new versions of Unity. I've tried building from a few different machines to different Android devices. I've deleted the external dependency manager included with the facebook sdk and used this one instead. In order to get this one to resolve I had to set a 'Custom Gradle Properties Template'in the player setting under publishing settings. I've set a Custom Proguard file'in the player setting under publishing settings, and I added the following two lines to the file.. keep class com.facebook.internal. keep class com.facebook. So I've tried all the suggested fixes and various combinations thereof. I dont know what more I can do. Can anyone suggest anything else to try?


Collision Detection Response Issues in Unity Sprite A Box Collider 2D and Rigidbody 2D. Sprite B Box Collider 2D. Both sprites have a Sprites Default material with Pixel Snap enabled. The textures being used are set to Truecolor Format and Point Filter Mode. No Mip Maps and 1 Pixels Per Unit (higher PPU seems to make the issue more obvious, but lower value does nothing but scale the problem down). I put Sprite A above Sprite B, hit play. I see Sprite A fall into Sprite B and hover slightly above it. I think this is horrible, so I look it up. I find I can lower Min Penetration For Penalty to help.. but not fix.. this issue. It's barely noticeable now. After a while, I noticed Sprite A sometimes overlaps Sprite B briefly during collisions. I can't seem to find a clean fix to either of these issues. Is Unity's physics engine just not designed for the level of accuracy I'm wanting? It seems the whole way the physics engine works is by allowing overlap (minPenetrationForPenalty) before pushing objects out of each other. I've been coding for many years as a hobbyist, so no professional experience, but this seems.. wrong. Are there options that don't involve overlapping of objects? Thanks for any and all help.


Realistic angular velocity for rolling sphere in Unity 5.1 I'm trying to make a small 2D game with a rolling ball sphere using Unity 5.1, but if find the angular velocity of the ball weird. On this first image (http imgur.com 8wBoGms), you can see the sphere in 2D and in its initial position. On this second image (http imgur.com ArCRSZn), the sphere was moved by rolling until it made a 90 turn. But the distance traveled by the sphere is greater than it should, if you wanted to be to be realistic you can see that the radius of the circle is equal to the size of the squares' sides, so the circle circumference should be equal to 6.28 (in square side size). If the sphere was traveling realistically, it should travel 1.57 (in square side size) to turn 90 . But in the second image, we can see that it take 3 and not 1.57 . The controller of the sphere is simply adding a force when a left or right button is pressed public class PlayerController MonoBehaviour public float speed private Rigidbody2D rg2d void Start() rg2d GetComponent lt Rigidbody2D gt () void FixedUpdate() float moveHorizontal Input.GetAxisRaw("Horizontal") Vector2 movement new Vector2(moveHorizontal, 0.0f) rg2d.AddForce(movement speed Time.deltaTime) So my question is how can I make the angular velocity realistic in this situation? Or am I doing something wrong? Thanks for taking the time, I really appreciate !


How do I bring a child object in its original position after it is translated and rotated? This is the original position of the cube and its child object cone. Over here, I have translated the cone for 2 units Now I have rotated the parent cube around 25 degrees wrt to the Y axis If we translate the cone 2 units back again, it's not in the original position What formula do I need to apply to the cone while translating it back to bring it back to it's original position? Code The below code is a coroutine for translating the child object IEnumerator MoveToNewPos() Vector3 newPos Quaternion.Euler(0, 0, 135) Vector3.left distance float t 0 float animTime 30 isMoving true for ( Vector3.Distance(transform.position, newPos) gt 0.001f t Time.deltaTime) float p t animTime transform.position Vector3.Lerp(transform.position, newPos, p) yield return null isMoving false


Lightmapping custom model manifold What are the things one should consider before doing light maps? We have custom models in Unity Scene,while doing light mapping it stuck at "Clustering job 5 11". After researching I come to know models should be "Manifold" to be light mapped so we did manifold our custom models and now light maps are occurring properly though at the cost of lot of polys which is causing performance hit on Android device. So my question is has anyone faced similar issue or workaround for same?