Extend distance for rendering grass and tree objects on terrain I am trying to make an adventure game with a big landscape (made the terrain with terrain tools) with 3D models of grass (that I placed using terrain tools) but it only shows the grass trees that are within a small area. Here is a pic of what I am talking about I would not want to totally remove this because otherwise the framerate will go too low. I just want to make the circle bigger. thanks (


Look rotation viewing vector is zero in Unity when making UI How can I tackle the problem Look rotation viewing vector is zero? Here is how I get it I add an Image from UI. When the Image is added I click on it in the Hierarchy view. When focus is on an Image I take the Canvas border and move it left. I get the Exception. Here are some screenshots of the process which takes place In the last screenshot I selected the Canvas and tried to focus on it by pressing F in the Scene view. As you can see I am not able to resize the canvas anymore. That means that I would have to create a new Canvas and copy everything into it, which is pretty tiresome and error prone. That is a reason I am concerned with the Exception. Will appreciate any attention.


Character rotation according to camera causes rapid flipping when game starts When I load my scene, my character rotates 90 and 90 on the X axis very fast about 4 or 5 times, and then he stops at 90 on X axis (lays back down). When I move the character, the rotations are just the way I want them, but I need to fix that weird bug at the beginning of the game. Here's my character's movement logic. It's based on the rotation of the camera, which is a child of my character object. void Update() Vector2 vec new Vector2(horizontal, vertical) vec Vector2.ClampMagnitude(vec, 1) Vector3 camF cam.transform.forward Vector3 camR cam.transform.right camF.y 0 camR.y 0 camF camF.normalized camR camR.normalized transform.position (camF vec.y camR vec.x) Time.deltaTime MoveSpeed Vector3 deltaPosition transform.position prevPosition if (deltaPosition ! Vector3.zero) transform.forward deltaPosition prevPosition transform.position


How should the physics be on an halfpipe like in a skate game in Unity? I am making a inline skating game. My player is skating based on the normals of the surface of the ground. But when I skate up a halfpipe it flies in the Air but doesnt comes down like it should be, it changes position in the Air and my player falls horizontally on the ground I cant get up anymore like this when he is lying on the Ground. I want it to be physically jump up and come down again the player should align on the ramp again not just fly in the air and drop down on the ground? What infos should you need to answer this question properly I will edit the question then?


Player jittering against wall when held down button So, I'm making a top down RPG. Everything's going excellent, but this problem is quite annoying. Now, when the character moves against the wall, the player jitters back and forth. I'm guessing it's because the player is trying to move into the wall, and then the wall collision is pushing it back, which makes an annoying back and forth movement. My question is obviously, how do I stop this from happening? Thanks! PS I'm using transform.translate to move the player, and I'm using C . EDIT I'm also using a 2D Rigidbody, and 2Dbox colliders on both.


Is it possible in Unity to Flip a 2D Sprite Without Flipping the Object it is Assigned to? I 'built' (followed a tutorial) on a collision detection system, and when I flip the object to go left and right the collision messes up. So I have three options find a way to modify the collision detection, have sprites for all animations for left and right or to flip the sprite but no the object. if anyone has used RaycastHit2D, and has figured out a way to do it correctly, that would also be great.


Unity Static Camera Perspective, Walls Obscure Player Pretty simple and common problem here. The world I'm designing is fully explorable, no invisible walls or tricks. It's presented as a single seamless area, a School complex with 9 buildings, some of which have 2 or 3 floors and contain many rooms. The perspective I've chosen is simple, inspired by topdown RPGs A problem arises with walls. They obscure the player. I've tried some shaders which draw a silhouette of the player ontop but I don't like this approach, other objects and decoration remains obscured behind the wall. Some kind of dissolve effect allowing you to see through the walls would be preferable, but writing my own shaders is not my fort ... Another problem is with large buildings outside. The camera is at a fixed distance, about 14 metre's away. If the player walks behind a large building (over 10 metres tall) then the camera cuts off the top of it as it is now within the building. The only way I can think of fixing this is to adjust the distance between player and camera, but some of the buildings are so tall the zoom out looks very unusual and impractical. I suppose this is why you don't see this simplistic camera setup in large explorable games... While I've been developing games for some years now, I've only come to 3D and Unity fairly recently, so there might be a jaw droppingly simple solution which I'm not seeing. Anyway, I'd like to hear some interesting or novel approaches towards fixing these problems, besides the simple ones I've suggested. I hope that's not asking too much.


How do I handle loads of (prefab?) objects in Unity2D 3D? I have been looking around for information regarding this process but I was unable to come across anything that would help me out. Basically, in a game where you may have many items or enemies or player objects, how would one go about creating these objects? Am I supposed to be creating every single one of these objects as a prefab and then load them into the game when needed? Or is it possible to create one object that has references to the different variables needed to create the above objects and then load in from an external source all the necessary information? And then during run time, depending on what object I am looking at, the script will 'create' the object with the information from the external source. Meaning, if I decide to have 50 different enemies in my game, do I need to make 50 prefabs, one for each enemy? Or just one prefab that loads in data pertaining to the 50 different enemies and then build upon that information? Thank you!


Standard Asset package import in unity 2018.3 I am using iMac, I don't see any for import standard package in unity. My working project need to import standard packages. I use unity version unity 2018.3.0f2. Please guide me from where I get the unity standard asset package. Thanks.


Unity create water issue I use daylight water in my project but by the default it has not got any waves or light tracing effects. But in some tutorials I see how the user add standard water asset and it has got beautiful world reflection on the surface and beautiful waves. Is this issue because that I am using not a PRO version?


Unity3D animation trigger reset How can I reset conditions for animations using an animation controller? I have a door that will open when a boolean property in a script is set to true. This then calls setTrigger on the animator to play the open door condition and then reset the boolean property to false. After 5 seconds I then close the door. However when I change the boolean to true again to open the door, either the setTrigger isn't working again on the animator, or the trigger for the door close is conflicting. How would I resolve this? Is there a way in the animator to set a condition to false when a particular animation has finished? Initially I was using a boolean condition in the animator but ran into the same problem. I looked at the 2D sample project which used trigger instead and assumed this would only fire once. However I guess something else could be wrong. The code in my script is as follows (where anim is the animator component) void Update() if (open) OpenDoor() open false void OpenDoor() anim.SetTrigger ("OpenDoor") Invoke("CloseDoor",5) void CloseDoor() anim.SetTrigger ("CloseDoor") As I say the animation fires correctly the 1st time but not on subsequent times. I'm just trying this by changing the public "open" property in the inspector thanks


Particle spawn on collision spawns too many particles So i have the following code private void OnCollisionEnter(Collision collision) foreach (ContactPoint contact in collision.contacts) if (contact.otherCollider.CompareTag("Ground")) Instantiate your particle system here. Instantiate(Effect, contact.point, Quaternion.identity) Now this works great however it spawns way too many particles (as the animation I am doing with the item hits the ground a lot). Is there a way to limit the particles in a sensible way?


PlayClipAtPoint() playing multiple times on enemy death I am having problems with PLayClipAtPoint(). I want to play a given sound as soon as a gameObject is destroyed. Here is my code (the concerned parts) void Update() if (health lt 0) StartCoroutine(Death()) public IEnumerator Death() anim.SetBool("isDying", true) AudioSource.PlayClipAtPoint(dmgSounds 0 , transform.position) Destroy(gameObject, 3f) yield return null I assume that the problem is due to the fact that as soon as the conditions are achieved, in this case the health reaching zero, the coroutine starts and it will keep starting for each frame, but how else should I call it? Anybody has some hint to give? EDIT I have already tried to wrap the logic in a bool as suggested in the comment so that it would work only when the bool condition is valid, without success. Here is the code with the flag bool void Update() if (health lt 0) if(isAlive) isAlive false StartCoroutine(Death())


How can I rotate a cylinder so the top points at specific transform? I have a GameObject (goA) with a LineRenderer that has a single line drawn, on which I'd like to place cylinders so the top of the cylinder points to each end of the straight line that the cylinder sits on, (similar to a cylindrical bead on a straight piece of string, or a Candlestick chart). The cylinder GameObject (goB) is a child of the goA which the LineRenderer is sat on (goB.transform.parent goA.transform). goA is not rotated itself, and the Line drawn could be any angle relative to the GameObject, and it would be a bit of a hassle to refactor so that the Line is always vertical and instead rotate goA, and it seems this should be an easily solvable problem! I'm attempting to use either LookRotation or LookAt on the cylinder but for whatever reason all permutations I can think of simply are not working. Thanks for any advice!


Unity SpriteRenderer. Trying to make sprite from code using Texture2d.whitetexture I have been trying to write a method that fills a rectangle with a color. I've tried it as a new 2D and 3D project just in case, but this gives the same results. Basically, i want the script to make a new GameObject, give it a SpriteRenderer component and then fill the given rectangle with the given color. I have tried to work from the Unity docs and other sources of info, but no matter how much I look around, this now looks correct to me but doesnt work. The result (as pictured) shows the new object with the sprite renderer and even shows the right size (there are blue 'corner' icons in the scene view I can see but no sprite or rectangle of any kind. using UnityEngine public class GameBoard MonoBehaviour const ushort cellCount x 10 const ushort cellCount y 24 only 20 will be visible to player const ushort cellsize 50 GameObject testBlock SpriteRenderer testBlockRen private void Start() testBlock new GameObject() testBlockRen testBlock.AddComponent lt SpriteRenderer gt () testBlockRen.sprite CreateRectSprite(new Rect(0, 0, cellsize, cellsize), Color.red) Sprite CreateRectSprite(Rect rect, Color color) Texture2D tex Texture2D.whiteTexture tex.SetPixel(0, 0, color) tex.Resize((int)rect.width, (int)rect.height) Sprite sprite Sprite.Create(tex, rect, Vector2.zero) return sprite By the way I have made sure the camera 'z' is less than 0 (it's 10). And the camera is centred where the sprite is supposed to appear. Note I can get a sprite to render fine if I create a texture in gimp and then use Resources.Load() . But I am trying to create the sprite using no source texture whatsoever (other than Texture2d.whitetexture)


A trigger collider in Unity doesn't allow the player to pass through It's my understanding that checking "Is Trigger" on a collider should allow rigid bodies to pass through without collision prevention, but my trigger isn't doing that consistently. The player cannot pass through, but other objects can. The trigger is a cube primitive with "mesh rendered" unchecked so that the cube won't be visible. The cube has a box collider with "is trigger" checked, and also a script. The script currently doesn't do anything except output from Debug.Log in OnTriggerEnter() as a test. Primitives are able to pass through. The test is just a basic Unity sphere with all the default settings, including a sphere collider. The only change was that I added a RigidBody. Imported models also pass through. I have a simple .blend model with a rigid body and box collider. The player does not pass through. The main difference between the player's object and the other imported model is that the player is using a custom mesh collider which is different than the player's rendered mesh. The rendered mesh is the game object and the low poly collision mesh is a child of that object. I've tried several variations, including switching the player from a mesh collider to a box collider, and also moving the box collider to the main mesh rather than a child mesh, but the results are the same. The player stops moving as soon as he hits the location of the trigger's box collider. Any ideas are appreciated. Thanks in advance. MORE INFO Here's a screenshot of the scene layout, with the invisible trigger collider selected. Also pictured is the hierarchy showing that the trigger collider ("Jump Pad Trigger") has no children. On the right is displayed every component that the trigger object has. I've also moved the collider from its original location several times to prove that it's not another object in the scene that the player is colliding with.


Character controller falling with positive speed I'm having very weird problems with my player's vertical movement. I'm using a Character Controller component with a capsule collider and no rigidbody. For testing purposes, I've ended reducing my jump script to just this line owner.CharacterController.Move(new Vector3(0, 0.01f, 0)) When executing this script, the player should just fly upwards at a constant speed, right? Well, what ends up happening is that the player starts jumping in place repeatedly. The jumps are smooth, as if the movement was being affected by gravity. I thought that the standard Character Controller doesn't handle gravity automatically and you have to do it yourself, so I can't understand what's going on here. There is no other code affecting the player, if I comment that line it just rests in place. If I try a different direction (like (0.01f, 0, 0)) the player moves in a straight line in the provided direction as expected. But when moving vertically, weird stuff happens S


NULL REFERENCE EXCEPTION Object reference not set to an instance of an object So I have 3 scripts first for my player movementscript second for my speed powerup speedscript third for my obstacle box script i I'm trying to get the component of box script in speed script, to get the function 'added' (which is in box script) into speed script but it keeps giving me nullreferenceexception error Here are those scripts public class box MonoBehaviour SerializeField GameObject effect public int damage 1 SerializeField float Speed 10f SerializeField GameObject audioexplosion void Update() transform.Translate(Vector2.left Speed Time.deltaTime) void OnTriggerEnter2D(Collider2D col) if(col.CompareTag("Player")) Instantiate(audioexplosion, transform.position, Quaternion.identity) Instantiate(effect, transform.position, Quaternion.identity) movment tmp col.GetComponent lt movment gt () tmp.health damage Destroy(gameObject) public void added(float spd) Speed spd And here is my speed script. public class speedscript MonoBehaviour SerializeField GameObject effect SerializeField GameObject speedaudio SerializeField public float speed public float add v 5 private float timeindue SerializeField public box io void Start() io GetComponent lt box gt () Debug.Log(io) void Update() transform.Translate(Vector2.left speed Time.deltaTime) void OnTriggerEnter2D(Collider2D sp) if (sp.CompareTag("Player")) Instantiate(speedaudio, transform.position, Quaternion.identity) Instantiate(effect, transform.position, Quaternion.identity) box io GetComponent lt box gt () Debug.Log(io) io.added(add v) Destroy(gameObject)


Applying velocity to parent that ignores children's mass not working I am making a VR data visualisation app in Unity and I have a parent with many children (just some primitive cubes) that I can toss around the scene by just setting the parent's rigidbody to the same velocity as my tracked VR controller. Rigidbody rb GetComponent lt Rigidbody gt () Vector3 controllerVelocity Player.instance.rightHand.GetTrackedObjectVelocity() how I ref the controller velocity in SteamVR rb.velocity controllerVelocity 2f the 2f is just to speed up the velocity The above code works fine, but the problem is I think the scale of the children objects, which can be adjusted by the player, is affecting the velocity the parent moves at. Or maybe just when the children are very large...the controller velocity is comparatively too slow? Basically I need this to not be the case I want the parent's rigidbody to move at roughly the same velocity no matter the children's scales masses. So to achieve that I thought to use Rigidbody.AddForce but it doesn't seem to be making any difference i.e. larger children are still moving slower. Here is what I have so far Rigidbody rb GetComponent lt Rigidbody gt () Vector3 controllerVelocity Player.instance.rightHand.GetTrackedObjectVelocity() rb.AddForce(controllerVelocity 2f, ForceMode.VelocityChange) I also tried ForceMode.Acceleration but then nothing moved at all? Am I using AddForce incorrectly? Or do I just need a scaling multiplier based on the size of the children? Any help is welcome.


Unity3D object fill shader I've been researching this for a while, and had no luck yet. I figured I'd ask here to see if anyone had any good ideas. Essentially what I want is a shader that can make only part of an object transparent based on a slider. Similar to fill effects on 2D sprites, the object would fill from the bottom up, when the slider was set to 0 the whole object would be transparent, when it was set to 50 just the bottom half would be visible, and when it was set to 100 the whole object would be visible. I've tried various masking effects, but it would be best if I could build this in to existing shaders or have a separate mask. Is there perhaps a way to adjust the alpha on individual pixels used for the diffuse texture without incurring great performance loss?


Volumetric Fog Shader Camera Issue I am trying to build an infinite fog shader. This fog is applied on a 3D plane. For the moment I have a Z Depth Fog. And I encounter some issues. As you can see in the screenshot, there are two views. The green color is my 3D plane. The problem is in the red line. It seems that the this line depends of my camera which is not good because when I rotate my camera the line is affected by my camera position and rotation. I don't know where does it comes from and how to have my fog limit not based on the camera position. Shader Pass CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" uniform float4 FogColor uniform sampler2D CameraDepthTexture float Depth float DepthScale struct v2f float4 pos SV POSITION float4 projection TEXCOORD0 float4 screenPosition TEXCOORD1 v2f vert(appdata base v) v2f o o.pos mul(UNITY MATRIX MVP, v.vertex) o.projection ComputeGrabScreenPos(o.pos) o.screenPosition ComputeScreenPos(o.pos) return o sampler2D GrabTexture float4 frag(v2f IN) COLOR float3 uv UNITY PROJ COORD(IN.projection) float depth UNITY SAMPLE DEPTH(tex2Dproj( CameraDepthTexture, uv)) depth LinearEyeDepth(depth) return saturate((depth IN.screenPosition.w Depth) DepthScale) ENDCG Next I want to rotate my Fog to have an Y Depth Fog but I don't know how to achieve this effect. It seems that this is caused by CameraDepthTexture, that's why depth is calculated with the camera position. But I don't know how to correct it... It seems that there is no way to get the depth from another point. Any idea ? Here is another example. In green You can "see" the object and the blue line is for me the fog as it should be.


Best C technique to pass variable from Instantiated object to GameObject There are lots of instantiated prefabs. Info from it is transmitted while it crosses a trigger zone. Some of these are calculated custom variables. I can print the custom variables from the instantiated prefabs. I can get the trigger zone to report standard things like "...transform.position" or "...transform.localEulerAngles", but not stuff I make up. Intellisense seems to see everything I am trying to get, and everything compiles. What's the best manner to perform this? Here's what I've tried Prefabs' Script public float infoToSend void Update() float infoToSend 10f ...actually, there's some math here, but it's a float. print("Sender " infoToSend) Works. Receiver Script on Trigger Zone void OnTriggerStay2D(Collider2D other) print("Receiver " other.transform.position) Works Fine. print("Receiver " other.transform.localRotation) Works Fine. float infoReceived other.GetComponent lt PrefabsScript gt ().infoToSend print("Receiver " infoReceived) Does not work! Any help, either fixing this arrangement or directing me to a different method, would be appreciated. Thanks. Edit to display the solution Corrected Prefabs' Script (changed third line down) public float infoToSend void Update() this.infoToSend 10f ...actually, there's some math here, but it's a float. print("Sender " infoToSend) Works. Correct Receiver Script on Trigger Zone void OnTriggerStay2D(Collider2D other) print("Receiver " other.transform.position) Works Fine. print("Receiver " other.transform.localRotation) Works Fine. float infoReceived other.GetComponent lt PrefabsScript gt ().infoToSend print("Receiver " infoReceived) Does not work! Many thanks, again! There's so many places to begin with, it's tough to find a "Beginner course" to cover everything.


What would be the best way to find a Game Object that is closest to another Game Object in unity? I made a 2d space shooter game awhile ago and I want to go back into it and overhaul some things. I'll provide a link to the game so anyone can play and get a better understanding of what I'm trying to do. https your pal drewdle.itch.io starspeed With how the game is currently set up, all the enemies are constantly setting their rotation to be facing the position of the player. I want to go back in and add a co op mode where there are 2 players, however, if I just added a second player without changing any code, the enemies would always be facing Player 1, never directly facing Player 2. I was thinking that I could get around this by giving each enemy an invisible circle with the center at the enemies position that would constantly expand until it hit one of the two players, I could then set the enemies rotation to face the point where the circle collides with one of the players. In theory, this would make it so that each enemy is facing towards whichever player is closest to it. So my question is How could I go about implementing this in unity? Or, is there a better or more efficient way to do this that would yield the same result? I've spent a decent amount of time researching this and I haven't had much luck. All help is appreciated, if you need more explanation just let me know and I will do my best to explain in more detail.


Why players who join late can't see other people data? I want to show the name of the players above their head but I have a problem where people joining late doesn't get other players' name. For example Player 1 joins to the server with the name Peter. Player 2 joins to the server with the name Josh. Peter (Player 1) sees Josh's name perfectly, but when Josh joins Peter's name is not synchronized correctly. My sync code looks something like this SyncVar private string NAME public override void OnStartClient() if(networkPlayerData is null) networkPlayerData BTNetworkController.Controller.playerData NAME BTNetworkController.Controller.playerData.Name SendPlayerNameToServer(NAME) Command private void SendPlayerNameToServer(string name) RpcSetPlayerName(name) ClientRpc void RpcSetPlayerName(string name) gameObject.GetComponentInChildren lt TMP Text gt ().text name So my question is how can I sync data to newly joined players and refresh player names accordingly.


Finding if 2 polygons intersect using clipper library After realising my code was pretty inefficient at checking for polygon overlaps, I've turned to a mentioned library Clipper but finding it difficult to know hot to use it for this operation. I am using unity Vector2 for my shape descriptions Square Vector2 square new Vector2 new Vector2(0,0), new Vector2(1,0), new Vector2(1,1), new Vector2(0,1) I want to be able to do the above boolean comparison of 2 shapes. If anyone knows Clipper well, what methods can I use to do this check? I've recently tried the following but the result is always true even when the test shapes are completely separate from each other public bool CheckForOverLaps(Vector2 shape1, Vector2 shape2) List lt IntPoint gt shape1IntPoints Vector2ArrayToListIntPoint (shape1) List lt IntPoint gt shape2IntPoints Vector2ArrayToListIntPoint (shape2) List lt List lt IntPoint gt gt solution new List lt List lt IntPoint gt gt () c.AddPath (shape1IntPoints, PolyType.ptSubject, true) c.AddPath (shape2IntPoints, PolyType.ptClip, true) c.Execute (ClipType.ctIntersection, solution, PolyFillType.pftNonZero, PolyFillType.pftNonZero) return solution.Count ! 0 private List lt IntPoint gt Vector2ArrayToListIntPoint (Vector2 shape) List lt IntPoint gt list new List lt IntPoint gt () foreach (Vector2 v in shape) list.Add (new IntPoint (v.x, v.y)) return list And the tests Square Vector2 square new Vector2 new Vector2(0,0), new Vector2(2,0), new Vector2(2,2), new Vector2(0,2) Square Vector2 square2 new Vector2 new Vector2 (1, 1), new Vector2 (3, 1), new Vector2 (3, 3), new Vector2 (1, 3) Square Vector2 square3 new Vector2 new Vector2 (2, 0), new Vector2 (4, 0), new Vector2 (4, 2), new Vector2 (2, 2) Square Vector2 square4 new Vector2 new Vector2 (4, 0), new Vector2 (6, 0), new Vector2 (6, 2), new Vector2 (4, 2) Assert.IsTrue(tc.CheckForOverLaps(square,square2)) Assert.IsFalse(tc.CheckForOverLaps(square,square3)) Assert.IsFalse(tc.CheckForOverLaps(square,square4)) Many thanks.


Unity Array of custom class with a superclass using generics does not show in the inspector I want to create 2 classes for Scriptable Object Weapon and Armor. Because both have similar functionality, I made a base class for both of them. using UnityEngine public abstract class Gear lt T gt ScriptableObject public int price public int level public Sprite image Header("Levels List") public T levels public T CurrentLevel() return this.levels this.level public T NextLevel() return this.levels this.level 1 public bool UpgradesLeft() return this.level 1 lt this.levels.Length public void Reset() this.level 0 public bool Upgrade() if (!this.UpgradesLeft()) return false this.level return true System.Serializable public abstract class StatsLevel public int price Both weapons and armors have the properties in common like they all have a price, they all have a Sprite Image, and so on... and more importantly they all have an array of Stat Levels. Meaning that every armor or weapon can have different levels, and depending on their level, the stats will be different. For that I used Generics. So when I created the Armor, I did it this way using UnityEngine public enum ArmorStat Low, Med, High, Super CreateAssetMenu(fileName "Armor", menuName "NARG Armor", order 1) public class Armor Gear lt ArmorStatsLevel gt Armor custom logic System.Serializable public class ArmorStatsLevel StatsLevel public int weight public ArmorStat blunt, slash, range in this class I define the stats unique to an Armor. Up to here everything looks peachy. But the issue comes with the Inspector As you can see, the inspector is not showing the array with the list of Stats on different levels, and I after a lot of research, I think it has to do with the Generics. If instead of unifying the common code between Armor and Weapon on the Base, I duplicate it each subclass, the Array is shown without problem. How could I make it so that the array information is shown in the inspector?


M bius effect in Unity This morning I've seen the following animation on Twitter. It is a kind of M bius strip effect. It's cool! Isn't it? So I've decided to build something similar using Unity, just for fun. I want to build the effect using just the cameras, as this way we can use it for any rotating scene. The first step has been to create a circle scene and make it rotate Note that the camera uses an ortographic projection so perspective does not deform it. This is important so we can merge different views later. Then I've replaced the main camera by two different ones, located in opposite positions (horizontal and vertical) and rendering to textures. A simple Canvas with two panels (divided vertically) shows the partial result (one camera texture per panel) I know this is cool, but not perfect yet, as the center of the rendered output shows clearly where a panel finishes and the other one starts. Look at the center of the rendered output above. The original inspiration video shows no perspective in the center, and I think that is the trick, but I cannot achieve that with an orthographic camera (or I don't know how). Do you know any approach to distort the camera or something similar, so the cameras are perpendicular in the middle of the scene (and only in the middle)? Are you able to think a solution to dissimulate the joint of both camera views? As a first approach (dismissed for the moment) I've tried to add another camera, perpendicular to the scene so there is no perspective in that point. Then I render its output in the UI in another panel on top of the previous ones. And it is not too bad, but again the joint is too obvious and now I have two joints instead of one


Click to move get NavMesh layer I'm using NavMesh, and NavMeshAgent for my character movement and Pathfinding. I made a testing NavMesh with 2 area layers 0 Walkable 3 Water. In have a click to move script, and i need to get the ID of the NavMesh Area where the player clicked. I tried to get the ID of the layer where the player clicked, using NavMeshHit.mask but is always resulting 0, even if I click where the NavMesh area ID is 3. From Unity documentation Mask specifying NavMesh area at point of hit. Script RaycastHit hit NavMeshHit nHit Ray ray Camera.main.ScreenPointToRay (Input.mousePosition) if(Physics.Raycast(ray, out hit)) bool hasHit NavMesh.Raycast (this.transform.position, ray.direction, out nHit, NavMesh.AllAreas) if (hasHit) Debug.Log ("Area ID " nHit.mask) targetPosition hit.point


How can I stop showing camera image in my Scene? Unity How can I stop showing camera image in my Scene in Unity? As you can see on the screenshot there is an image of a camera inside a player in the Scene view. How can I disable the image?


Updating game objects already placed in scene I have about 20 game objects placed in certain positions in my scene. I then realized i need to attach two additional game objects to each one of these as children. Is there a simple way of doing this? I really don't want to remove them all update the prefab and then place them back. Is there a way that i can add the two children to the prefab and all 20 something objects in the scene will also be updated?


JSON Parse (Invalid Value) My settings.json (generated with JsonUtility.ToJson) "masterVolume" 0.10000000149011612, "fullScreenMode" 1, "cheatsEnabled" false Offending line SettingsData sd JsonUtility.FromJson lt SettingsData gt (Application.dataPath " Settings settings.json") My SettingsData class. System.Serializable public class SettingsData SerializeField public float masterVolume SerializeField public int fullScreenMode SerializeField public bool cheatsEnabled public SettingsData(float masterVolume, FullScreenMode fullScreenMode, bool cheatsEnabled) this.masterVolume masterVolume this.fullScreenMode (int)fullScreenMode this.cheatsEnabled cheatsEnabled I really can't fathom why it's having trouble reading this back in, I even tried to save the enum as an int instead, but still no luck.


How to Subscribe to Events from Unity's VRInput Script I am new to Unity and trying to modify the Unity tutorial Interactive 360 Sample. I want to be able to call a function when a user swipes using an Oculus Go Controller. I noticed that the VRInput script is included in the project, which seems to be able to detect swipe gestures. But where do I attach that script, and how do I subscribe to the OnSwipe event. I am currently trying by making an empty game object, and attaching the InputVR script as well as my own script called "GestureHandler" (I'm not sure whether InputVR is already attached to something else in the sample project, or whether I need to attach it at all). In my GestureHandler script I currently have the following using System.Collections using System.Collections.Generic using Interactive360.Utils using UnityEngine public class GestureHandler MonoBehaviour void onEnable() VRInput.OnSwipe HandleSwipe void onDisable() VRInput.OnSwipe HandleSwipe void HandleSwipe() Debug.Log("swipe") and currently have the following errors An object reference is required for the non static field, method, or property 'VRInput.OnSwipe' Assembly CSharp No overload for 'HandleSwipe' matches delegate 'Action lt VRInput.SwipeDirection gt ' Assembly CSharp An object reference is required for the non static field, method, or property 'VRInput.OnSwipe' Assembly CSharp No overload for 'HandleSwipe' matches delegate 'Action lt VRInput.SwipeDirection gt ' Assembly CSharp


Null instance on manager class extending from singleton class I have four classes class A, which is abstract and partial extending from singleton class C. class A1, which is partial and extending from class A . class B, extending from class A. class C, a singleton which has code to throw an exception if the instance is null, and otherwise uses DoNotDestroyOnLoad(). In scene view, I add class B to the scene. It works, but throws a null instance exception for class A, as it's instance is not present in scene. I think this is because class A extends from a singleton class, and it has ability to throw exceptions when the instance is null. I can not add the class A to the scene because it is abstract. What can I do to in order to add the class A component to the scene, or otherwise not to get this error?


Using points to unlock next scene in Unity Below is my code and I'm a beginning game designer trying to make my first game for art school teehee! ) I'm not sure how to unlock the next level with a scene I've already made called Rust Room Any ideas? o I also attached the error codes I'm getting! using System.Collections using System.Collections.Generic using UnityEngine.SceneManagement public class Example HUD hud int points const int ScorePrefix "Score " int score public void LoadLevel() if ("Score 45") load the nextlevel SceneManager.LoadScene(SceneManager.GetSceneByName(Rust Room)().buildIndex 1)


How to lock aspect ratio when resizing game window in unity? I want a scalable game window that when resized stays at 16 9 aspect ratio. The goal is for the user to be able grab the window on the right or bottom and resize it. The game should adjust the corresponding side of the view port to lock the aspect ratio. I've tried forcing certain values in the update line of a script on the camera, but it did not work. the game is 2d and most of the elements are scripted using the gui functions. I'm having a very hard time finding exactly what I'm looking for as it is, most of what I've found is in an attempt to create black bars and keep the game from stretching, but that doesn't help ongui using matrices. here are the resources I've tried so far http goo.gl 8FuyRC this one is a script someone wrote that I attached to the main scene camera, I then built it, however that didn't work. http goo.gl qZ5DAl this is something from the unity website regarding camera aspect ratio. I put a line of code in the update function of my camera object pragma strict function Start () function Update () Camera.main.orthographicSize 3.596306 as well as pragma strict function Start () function Update () Camera.aspect 1 none of the above worked. http goo.gl MbTDcz was the last thing I tried, and it just made some more black bars... so far nothing has worked. not sure why. to reiterate, the goal I'm trying to accomplish is that, when the user grabs the edge of a windowed player, and drags it, the corresponding x or y axis will follow in suit to keep the aspect ratio the same.


Unity game crashing when dialogue with NPC initiated I have 3 NPCs in my "Game". When the player walks up to any of them, they're supposed to have their own dialogue I've tested this, and they do. I tried to create a display that shows this dialogue text using a TextMeshProUGUI attached to a blank GameObject called dialogDisplay (tagged DialogDisplay). There is one DialogDisplay object in the scene that I'm trying to get each of my NPC's to use. I tried to make the display object inactive in the NPC Start() function, and enable it when it's time to display the NPC's next sentence. When I run my game, I get an error on line 21, where SetActive() is called "Object Reference Not Set to an Instance of an Object". Here's the NPC script (DisplayNextSentence() is at the bottom, where dialogDisplay is used) public class NPC Character private bool charInRange public Dialogue dialogue public bool talkedTo false private Queue lt string gt sentences public TextMeshProUGUI textPro public GameObject dialogDisplay private bool isTalking Use this for initialization void Start () charInRange false textPro FindObjectOfType lt TextMeshProUGUI gt () dialogDisplay GameObject.FindGameObjectWithTag("DialogDisplay") dialogDisplay.SetActive(false) Update is called once per frame void Update () if player is in range and presses space, triggers NPC dialogue if (charInRange amp amp Input.GetKeyDown(KeyCode.Space)) TriggerDialogue() if Player gameObject is in NPC collider, player is in range void OnTriggerEnter2D(Collider2D other) if(other.gameObject.tag "Player") charInRange true if player exits NPC collider, player is not in range void OnTriggerExit2D(Collider2D other) if (other.gameObject.tag "Player") charInRange false if NPC has been talked to before, displays next sentence if not, loads dialogue and displays first sentence private void TriggerDialogue() if (!talkedTo) talkedTo true StartDialogue(dialogue) else DisplayNextSentence() loads a queue with lines from Dialogue and displays first sentence public void StartDialogue(Dialogue dialogue) sentences new Queue lt string gt () foreach (string sentence in dialogue.sentences) sentences.Enqueue(sentence) DisplayNextSentence() displays next sentence in the queue public void DisplayNextSentence() string sentence bool done false if last sentence in the queue, display it again if (sentences.Count 1) sentence sentences.Peek() textPro.text sentence Debug.Log(sentence) return sentence sentences.Dequeue() textPro.text sentence dialogDisplay.SetActive(true) while (!done) Debug.Log("In WHile Looop") if (Input.GetKeyDown(KeyCode.A)) done true dialogDisplay.SetActive(false) Grateful for any insight or tips you can provide. Happy to provide further information if it helps. Thank you!


Limit rotation angles for Quaternion I have a short snippet that's rotating the meshes of the wheels as I'm driving forward, but it's also rotating wheels to match the direction I'm turning, and I wish to turn this off completely. Quaternion quat Vector3 position m WheelColliders i .GetWorldPose(out position, out quat) m WheelMeshes i .transform.position position m WheelMeshes i .transform.rotation quat How would I lock what angles I don't want the wheel meshes rotating?


Screen Space vs World Space Canvas When should I use one over the other? I'm pretty sure I understand the key differences, but I'm not sure which use cases would prefer one over the other. For example, let's say I have objects on the ground in my 3D game and they have UI Images above them with the objects' names. Which method is better? Should I stick to world space for objects which are located in the 3D world and screen space for overlay type stuff?


Why do my animations need to be marked as "legacy?" I'm in the beginning of a project and I'm not really using 3D models but rather a hierarchy of primitive shapes. I made a couple of animations that suddenly don't work anymore. I get an error about that I need to mark them 'legacy'. I came across this suggestion to mark them as legacy in the rig tab via the model, but I'm not using a model so that doesn't help. I don't understand how the animations that I made in Unity yesterday don't work today? What is this legacy problem?


How to Change position rotation of a parent while keeping X and Z Rotation Sooo this question is a problem , a evolution by another solution of this problem here How can I change the parents rotation so the childs rotation is looking at a specific direction Basically We have a "Eye" (HTC Vive). We have a "Parent" which is the Parent of "Eye". We can not change the position or rotation of the Eye in code. We can only change the position and rotation of the Parent. 1.We want to modify the Parent Position so that Eye to goes to a certain "Target 1" position. 2.We want to modify the Parent Y Rotation so that the Eye looks at a certain "Target 2" position. 3.While doing this we dont want to modify the Parent X or Z , because this would lead to a Rotated game experience. The Parent Position changes so the Eye gets to "Target 1" position. The Parent Position changes so Y Rotation should look at Target 2 position The Parent X Z Rotation should not modify the Eye X Z


how to transform the position of an object I am trying to transform the position of an object. I have totally 3 Objects and 2 triggers, objects are 1. Left Wall, 2. Right Wall, 3. Obstacles. 1st trigger for transform the position of an objects y 50, 2nd trigger for transform the position of an objects y 7. Left wall and Right Wall are placed inside the environment. the environment will instantiate automatically for looping. if the player crossed the first environment previous environment will delete automatically. at that time in second clone environment if the player triggered means it will display a message as MissingReferenceException The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. In first Clone environment its working perfectly. second clone environment its not working.


Creating a custom Editor Window using a Multi Column Header Hey there I'm trying to use the MultiColumnHeader to create a tool to view materials in the scene, inspired by the light explorer. The problems I'm facing are two fold. First I can't figure out how to place the content of the MultiColumnHeader in a scrollable view and secondly I can't figure out how to give the rows a different background color that alternates like in the light explorer. This is my OnGUI code void OnGUI() windowVisibleRect.width position.width windowVisibleRect.height position.height draw the column headers var headerRect windowVisibleRect headerRect.height columnHeader.height float xScroll scrollPos.x columnHeader.OnGUI(headerRect, xScroll) draw the column's contents for (int i 0 i lt columns.Length i ) calculate column content rect var contentRect columnHeader.GetColumnRect(i) contentRect.x xScroll contentRect.y contentRect.yMax contentRect.yMax windowVisibleRect.yMax Rect rowRect new Rect(contentRect.x, contentRect.y, windowVisibleRect.width,20) for (int j 0 j lt analyzerList.Count j ) Rect MatcellRect columnHeader.GetCellRect(0, rowRect) Rect ShaderCellRect columnHeader.GetCellRect(1, rowRect) Rect GameObjectsRect columnHeader.GetCellRect(2, rowRect) rowRect.y 25 EditorGUI.ObjectField(MatcellRect, GUIContent.none, analyzerList j .mat, typeof(Material), false) EditorGUI.ObjectField(ShaderCellRect, GUIContent.none, analyzerList j .shader, typeof(Shader), false) analyzerList j .ShowGameObject EditorGUI.Foldout(GameObjectsRect,analyzerList j .ShowGameObject, quot Show quot analyzerList j .gameObjects.Count quot GameObjects quot ) if (analyzerList j .ShowGameObject) foreach (GameObject go in analyzerList j .gameObjects) GameObjectsRect.y GameObjectsRect.height EditorGUI.ObjectField(GameObjectsRect, GUIContent.none, go, typeof(Material), false) rowRect.y GameObjectsRect.height If a Editor GUI guru could explain to me how to do it like I'm a child that would be great ). I don't do custom GUI stuff and most of this is beyond me. As per requested I'm uploading two example images. One from unity and one I randomly found from the net. Note that I do not need the quot stacking quot (I dont know how to call them) headers from the second example. I do how ever require a vertical and horizontal scrollbar like in the second example. And finally just for reference this is what my code does so far


Gameobject with Canvas child (Unwanted inspector behavior) When I try to focus (by double clicking or pressing f) on gameobjects in my scene which have a Canvas as a child, the scene view zooms out to show the Canvas. I would like to be able to see the gameobjects themselves when focusing on them. Is there a way to do this?


Global variables in a multiplayer environment I would like to know what's the best approach to solve this problem. In a racing game, i need to create the final result chart. In a single environment i've tought something like private string arrivalOrder void playerArrived(string playerName) arrivalOrder arrivalOrder.getLength() 1 playerName I would like to know how to do in a multiplayer environment. How the client can communicate to server "my player finishes the racing"? Thanks


Is it possible to use an SVG as a texture for a 3d object? I'm using the Vector Graphics plugin for Unity 2019 and am able to drag an SVG into the scene. However, I am not able to drag it onto a 3d object as I am with a PNG. My goal is to make 3d cubes that rotate with a particular icon on each side of the cube. I came across this related post SVG textures for 3D game objects in Unity? but I'd like to make sure there haven't been any advancements since 2017 in this area. Also, would it be possible to add an SVG to a material? I can't figure out a way to do it but I am not very experienced with Unity.


Serialize classes based on Generics. Is it different? I have a certain ScriptableObject. public class Biome ScriptableObject ... If I write the following in a component public List lt Biome gt list1 This is what appears in the inspector So far so good. But if I try to make my list more generic, like this public class DistributedList lt T gt public List lt T gt items System.Serializable public class BiomeList DistributedList lt Biome gt This is what I get on the inspector All I can seem to be able to add now is just a name, not the Object itself. Why is this?


Quaternion.Lerp does not actually rotate object when called inside an "if" clause Let's say I have a RotatableObject class, which inherits from MonoBehaviour. Here is its Start() method private void Start() this.startingLocalRotation this.transform.localRotation this.finalLocalRotation Quaternion.Euler(this.startingLocalRotation.eulerAngles.x, 150f, this.startingLocalRotation.eulerAngles.z) Initialize other private fields It has a method called Rotate(), defined as follows private void Rotate() this.transform.localRotation Quaternion.Lerp(this.startingLocalRotation, this.finalLocalRotation, 0.2f) Given the following Update() method, the object rotates as expected private void Update() this.Rotate() However, if I make the following changes to Update(), then the object does not actually rotate, even though the Rotate() method is hit private void Update() if (this.SomeCondition) this.Rotate() this.SomeCondition always has the value true over multiple frames. What is my mistake, and how can I fix it? EDIT In response to this comment When you say "the object rotates as expected" do you mean that the object rotates from starting angles until final angles and then stops rotating (without the if) ? Yes. could you provide some more details about what SomeCondition is? this.SomeCondition is determined by the state of another object, say, Puppy. E.g. if puppyInstance.Mood Mood.Happy, then this.SomeCondition is true. Did you try replacing the condition with the word true No, I have not tried that. However, when stepping through the call stack in debug mode, I can see that this.SomeCondition is true and Rotate() is called I managed to step into the Rotate() method itself. EDIT I tried the first approach described in this answer. However, it did not produce the effects that I was aiming for. I set a breakpoint here transform.localRotation Quaternion.Lerp( startingLocalRotation, finalLocalRotation, rotationProgress ) Every single time the breakpoint was hit in the Update() call, I could see that the value of rotationProgress was steadily increasing. However, the value of transform.localRotation never actually changed it was always ( 0.7, 0.7, 0.0, 0.0). If I updated transform.localRotation outside of an if clause, however, that game object rotates as expected transform.localRotation gets updated as rotationProgress gets updated. EDIT Never mind, I am an idiot. The problem lies elsewhere in the code. The suggested approach works and I have accepted it as the answer.


Unity's CharacterController vs. Rigidbody with Collider With a few friends I started to make a 3D game in the style of the old platformers la Super Mario 64 Spyro Banjo Kazooie. So now we are thinking about the controls and how to do them. There seem to be two mutually exclusive options Giving our character a rigidbody and however many colliders we want OR using a character controller. At the moment we have a rigidbody with a collider which technically works, but we have to make our own grounded check, and movement, while those two in particular are relatively easy to implement. If we start to use a character controller OTOH, we won't have all the collisions anymore and programming logic needs to be applied in a different way. Let's take a jumppad as example If we use a Rigidbody, the jumppad itself checks if someone is standing on it, and if so it increases the jumpstrength while that someone stands on it. If we use a CharacterController, we'd have to check not only if we are standing on a jumppad, but also on which one, to determine the actual jumpstrength, as they might differ between pads. So, is there a clear winner to use in a 3D platformer with fighting elements or do we have to work with limitations on either and just have to work around them?


How to detect a sign out from Google Play achievements or leader boards UI? I am making an android game in Unity (C ), in which I've used the Google's official plugin for Google Play Services. My question is how to detect that a player has clicked on sign out button on Google's UI


Player is instantly teleported back I built a teleporter that changes a players position and rotation. He is instantly teleported back. Why? I'm using the standard FPS Controller.


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


Cinemachine third person camera movement causes misalignment I'm working on third person movement using CinemachineFreeLook as the player camera. At first I thought it was working fine but I've noticed that moving left right actually moves the character with a curve instead of straight left right. This behavior can be observed in the following video https imgur.com sLGIia8 As you can see when trying to make the character move left right the character doesn't stay on the grid but instead curves a bit to the left right. I'm inclined to believe that this occurs because of cinemachine camera but I am unsure what exactly is going on and how to fix this. I feel that this is a bit over my head and am thus asking for help in figuring this out. The simplest form of movement code is as follows (the exact code that moves the character in the video) private void FixedUpdate() Vector2 input playerInput.MoveInput bool hasInput Mathf.Abs(input.x) gt float.Epsilon Mathf.Abs(input.y) gt float.Epsilon if (hasInput) get camera direction Transform cameraTransform Camera.main.transform Vector3 cameraForward cameraTransform.forward Vector3 cameraDirection Vector3.Scale(cameraForward, Vector3.right Vector3.forward) transform camera direction vector to a quaternion Quaternion cameraRotation Quaternion.LookRotation(cameraDirection) transform input vector2 into x z vector3 Vector3 inputDirection new Vector3(input.x, 0f, input.y) create desired velocity from input and current camera rotation Vector3 desiredVelocity cameraRotation inputDirection settings.Speed Vector3 delta desiredVelocity body.velocity delta.y 0f Vector3 acceleration delta Time.deltaTime if (acceleration.sqrMagnitude gt settings.SqrMaxAcceleration) acceleration acceleration.normalized settings.MaxAcceleration body.AddForce(acceleration, ForceMode.Acceleration)


read in an xml server from Unity3D 4.xx I need examples of how to read an xml from a server, using Unity3D.. I think it's something like this.. but I can not retrieve the information from the nodes.. An example would be of great help.. thank you.. var url "http server.com test2.xml" var www WWW new WWW (url) yield www var xml XmlDocument new XmlDocument()


Avoid players getting stuck by placing items in the same place Let's assume a multiplayer game of two players. These two players have to place six elements at six different positions. The order or exact place does not matter. As the items are placed correctly, they cannot be replaced anymore. Issue Both place an item at the same position and now there are basically two items at a position where only one should be. This makes the task impossible to complete, as one item is missing now for the last position. My assumption is that while both are really doing that in parallel, the communication between both computers is too slow so the other player can't know there is already an item. I encountered this issue in a game recently and I wonder how to avoid this. The simplest solution would be that the items can be replaced when placed. But let's see it more technical A correctly placed item cannot be replaced so how to circumvent or how to avoid this situation?


Flatten transform hierarchy at build time Nested hierarchies cause a performance overhead when they include moving objects. Every time a GameObject moves, altering its transform, we need to let every game system that might care about this know. Rendering, physics, and every parent and child of the GameObject needs to be informed of this movement in order to match. As the scope of a game increases, and the number of game objects skyrockets, just the overhead of sending out all these messages can become a performance problem. However, nested hierarchies are useful in organising a scene and keeping logical groups of gameobjects separate. What options exist to save performance whilst keeping the hierarchy? Is there any pre existing solution to flatten a hierarchy when building only?


How to physically move a rigid body up the stairs? When an object is controlled by a CharacterController, it is easy to make it climb ramps with a certain slope, or climb steps with a certain height. When the object is controlled by a RigidBody instead, it can still climb ramps naturally I just use AddForce and it walks on ramps just like on any other surface. I do not have to add any special logic for a ramp. However, it does not climb stairs. Is there a natural "physical" way to make the RigidBody climb stairs, without explicitly checking that there are stairs ahead?


Physics2D.IgnoreCollision not work when rb not moving I want to use Physics2D.IgnoreCollision for ignoring collision between enemy and player, when player have shield. But I have enemy who some time is static and some time jump only on y axis. When enemy not moving Physics2D.IgnoreCollision not work and physics collision between player and enemy occur even Physics2D.IgnoreCollision is called. When i add some velocity to enemy in update method Code (CSharp) rb.velocity new Vector2(0.1f, rb.velocity.y) IgnoreCollision work like it should. Can some one tell me why this happens? Thanks


How to make switch work with enum? C Unity I'm working on a script to fade UI elements in Unity, similar to a selector, where you can select the type of fading, and duration, and image to fade I found that enum is the best option to achieve that result, but I have a problem, when I run the code only element of the enum work and the other don't, no matter if I use switchor if just the first statement run, I don't know what's wrong with the code Please explain your answer Please explain why the code is wrong Please give feedback on how to improve I'm using Unity version 5.3.5f1 and Visual Studio Community 2015 Goal Make the enum work properly using either switch or if Be able to use the variables inside the FadeOperations class to make the calculations inside the Test class Select from an array the type of desired operation Select an UI element from Heriarchy and fade it Steps Create new Unity project (2D or 3D) Create UI Image Create Empty game object Create new C script (I called it Test) Attach new script to empty game object Code Here's my code so far... using UnityEngine using UnityEngine.UI public enum FadeManager fadeIn, fadeOut System.Serializable public class FadeOperations Tooltip("Type of fading") public FadeManager fadeType Tooltip("Duration time of the fading") public float duration Tooltip("Select the image to fade") public Image fadeImage public class Test MonoBehaviour Tooltip("Select your type of fade") public FadeOperations fadeOperations Reference to the class FadeOperations private FadeOperations fo new FadeOperations() Loop for debug private void Update() switch ( fo.fadeType) Debug.Log( fo.fadeType) This statement works case FadeManager.fadeIn Debug.Log("Fadein") Only this piece of code works break This statement doesn't work case FadeManager.fadeOut Debug.Log("Fadeout") break The result of the Log ( fo.fadeType) before the switch fadeIn UnityEngine.Debug Log(Object) Test Start() (at Assets Scripts Test.cs 34)


UI clicks hitting game objects below I have a canvas with a panel with set width height inside. The canvas rendermode is set to ScreenSpace Overlay. My clicks on the panel are falling through and hitting the game objects below triggering their mouse events. The little green circle is a Sprite with the following event public void OnMouseDown() Debug.Log("click") Vector3 newPos Camera.main.WorldToScreenPoint (this.transform.position) newPos.x panel.GetComponent lt RectTransform gt ().rect.width 2.0f newPos.y panel.GetComponent lt RectTransform gt ().rect.height 2.0f panel.transform.position newPos I've been reading through the docs but I'm missing something... How do I stop my clicks hitting the game objects below the panel?


StartCoroutine from other MonoBehaviour is not working I am trying to replicate the model of Unity documentation about coroutines, but I want to partition it in another class I have these two public class A MonoBehaviour void Start() print("Starting " Time.time) B test new B() StartCoroutine(test.WaitAndPrint(2.0F)) print("Before WaitAndPrint Finishes " Time.time) public class B MonoBehaviour public IEnumerator WaitAndPrint(float waitTime) yield return new WaitForSeconds(waitTime) print("WaitAndPrint " Time.time) It prints, ignoring the coroutine Starting 0 Before WaitAndPrint Finishes 0 The two methods work well in the same class.


How to capture image from camera with post effects? Mysteriously only get emission(?) pass I have a separate camera from my main camera, whose purpose is to take screenshots, or render a quot live feed quot of the action, at different angles. Hierarchy as such The game object labeled as quot main camera quot captures the 3D scene just like a normal main camera would, including post processing components. The GUI camera captures just the UI layer. The canvas and image are simply a watermark, rendered by the GUI camera. I have removed this and it has no bearing on the issue at hand. I point both the main camera and GUI camera to the same target render texture. The result of the render texture appears to be correct in the inspector. One way or another, it appears that I can only get access to the quot bloom, quot and nothing else (On black so it's easier to see.) If I assign the render texture onto a Raw Image canvas element, it only shows the quot bloom. quot If I try to convert the render texture to a regular texture, it also only shows the quot bloom. quot RenderTexture.active renderTexture destination.ReadPixels(new Rect(0f, 0f, renderTexture.width, renderTexture.height), 0, 0) destination.Apply() (I have also tried AsyncGPUReadback. Its resulting texture looks like a flat gray without variance in the inspector.) I have found if I disable post processing, everything works as intended, no changes required. Of course, I am missing the post processing, which I want! Somehow, somewhere, Unity is getting data external of the texture itself, depending on context Using Unity's ReadPixels method only picks up the quot bloom. quot Using Unity's EncodeToPNG method only picks up the quot bloom. quot Putting the RenderTexture on a Raw Image only picks up the quot bloom. quot If I use a separate PNG encoder using the same Color32 data, I get the final correct image. The inspector successfully renders the final correct image. I have actually run into this issue multiple times, and never found a proper solution, and definitely never a real time solution, which I now desperately need.


In Unity Move a GameObject at Animator State I want to move one of my GameObject to a different vector 3 position, when animator transit to a new state. How do I do it? Also there shouldn't be any delay.


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


.NET Framework version is fixed for Unity scripts? It seems that the C project that Unity creates uses version 4.7.1. But I want to use only the latest version and do not want to install lots of older versions of .NET Framework targetting packs that I do not use. Even if I change the version to 4.8 and save the project, if I add a new script asset, then the version changes back to 4.7.1. So, my question is, do I have to use the version that Unity sets by default? Or is there a way to make Unity always use the latest .NET version such as 4.8, in this case? If the answer is the former, I will give up and install 4.7.1.


Score does not increment by 1 in Unity I have made a simple code where once the player moves through the collider that acts as a trigger then Unity adds a score. However, it increases by increments of 8 and I am not sure why. using System.Collections using System.Collections.Generic using UnityEngine public class Game MonoBehaviour public int Score 0 void Start() Update is called once per frame void Update() private void OnTriggerEnter2D(Collider2D other) AddScore() void AddScore() Score


How to export a terrain from Unity to Blender? I'm trying to make an environment for my scene that consists animations and other objects such as trees. Making a terrain in Unity seem to be a lot easier than in Blender, so I want to export that environment which I've made in Unity to Blender. How can I do this?


What would be the best way to implement a multi directional "board game" movement system? I'm pretty new to game dev, and can't figure out how to do this, even though it is probably really easy. If you need more reference, look up some gameplay of the Wii game Dokapon Kingdom, that's the kind of system I'm trying to create. I also made a picture to help you better understand my dilemma. Thank you all so much in advance!


Unity 2D map and walkable collisions I have a 2d player who can only walk on black area. There is a red collider so player can't walk past it. Player has capsule collider. The problem is player can't walk toward the edge with his feets becasue of the it's collider. But player would probably want to walk toward the edge. Here is a sketch I've made. Is there a way to tweak this ?


Smooth Scene transitions with SceneManager and additive scene in Unity I'm trying to work with the new SceneManager class with Unity, I'd like to have smooth transitions between scenes. Currently I suppose that the only way to do those transitions is to manually implement them on the scene objects leveraging on the fact that scenes can be loaded additively. In pseudo code I image something like for gameObject in previousSceneGameObjects gameObject.animateSceneExit() endFor for gameObject in nextSceneGameObjects gameObject.animateSceneEnter() endFor I feel that there is something I'm missing P which is the best approach that you'd suggest? Is it my approach valid?


Strange momentum on projectiles shot out of "parent" object I'm trying to shoot a projectile out of a moving quot parent quot object. Both objects move off of rigidbody physics, so I'm using addforce for the projectile. Whenever I move the quot parent quot object and turn while it's moving and shoot the projectile, I instantiate the projectile, copy the projectile spawn position to the projectile's position, copy the rotation of the quot parent quot to the projectile, then add force to the projectile. It'll shoot but I notice it moves in the direction of the momentum of the quot parent quot rather than straight forward from where it was created. I'm pretty sure this is just me not understanding how rigidbody physics works for adding force but if anyone has any suggestions as to how to make the projectile move straight forward from where it's created rather than copying the momentum of the parent I'd appreciate it greatly. My code for moving and creating a projectile looks like this void FixedUpdate() if (Input.GetKey(KeyCode.W)) player.transform.Translate(Vector3.forward 10f Time.deltaTime) this.GetComponent lt Rigidbody gt ().AddForce(transform.forward 15) if (Input.GetKey(KeyCode.S)) this.GetComponent lt Rigidbody gt ().AddForce(transform.forward 15) if (Input.GetKey(KeyCode.A)) transform.Rotate(Vector3.up 15 Time.deltaTime) if (Input.GetKey(KeyCode.D)) transform.Rotate(Vector3.up 15 Time.deltaTime) void ShootBullet() create bullet GameObject bullet Instantiate(bulletPrefab) set location where bullet will spawn from bullet.transform.position bulletSpawn.position set direction of the bullet bullet.transform.rotation bulletSpawn.transform.rotation add force to the bullet bullet.GetComponent lt Rigidbody gt ().AddForce(bulletSpawn.forward bulletSpeed, ForceMode.Impulse) destroy bullet after x time Destroy(bullet, lifeTime)


Unity3D How to just center a mesh inside a character controller! Hi I have a simple character mesh and it's parented to my character controller invisible capsule object and all the moving code is applied to the parent (if that's relevant), but the point Is I'm trying to line up the mesh to be exactly inside the capsule to make it look like the player is walking ABOVE the ground (pretty normal ...?) So by default the character controller is origined in the center so I move it up by half of it's height to try to get it to line up with the character mesh, which has it's origin below it's feet a little, and this is the result as you can clearly see, his feet slightly go into the ground, I have no idea why this is happen, then should be just above the ground like any other normal feet! Here's the code for setting the capsule up half of it's width, since it starts by lining up the mesh in it's CENTER for some reason Vector3 tempPos player.transform.position tempPos.y (capsuleSize.y 2) chassidSize.y 12 chassid.transform.position player.transform.position player.transform.localPosition tempPos chassid.transform.parent player.transform and here's a picture of the mesh (which is just a blender file, easier for import) As you can see, in the blender file, the origin is slightly below the characters feet, IN THE CENTER, so I don't know why it's not working as planned. Also, you can see in the first picture that he's slightly moved to the center of the controller on the z(?) axis, but I want him to be completely centered in, any idea how to fix this?


Why does using .Lookat() cause the enemy to look left instead of at player, and how can I fix it? I am new to Unity. I have searched but I couldn't find any answers on this. Here is my code somethingPosition new Vector3(player.transform.position.x, transform.position.y, player.transform.position.z) transform.LookAt(somethingPosition) The somethingPosition only allows rotation of the Y axis so. Anyways, I have this script on the enemy AI. The issue is this the enemy looks at the player but looks to the left of the player. The same issue occurs when I have my follow code happen transform.position Vector3.MoveTowards(transform.position, player.position, speed Time.deltaTime) The enemy will continue going to the left of the player but will not hit the player. What are some suggestions you guys can survive? Thanks! I am aswell using a NavMesh and NavMeshAgent


For creating a distant moon in a 3D game, is it better to use a model or texture? I'm working on my indie game and I want to create a moon (it's a 3D game) however I am unsure if I should create a model and put it far away, or if I should use a texture on a plane and have it constantly move so the face of the plane is facing the player. The problem I had last time I tried a model is the render view, as the model was really far away (as when I did it very small, you could sort of tell it was a tiny model rather then a far away moon) and with the texture I'm not sure if it comes across as tacky. I'd really like to hear the pros and cons of each, since I'm planning to use the 'render objects only when in view' method and basically want advice on which I should go with.


Understanding Screen Position Node in Unity Shader Graph I'm struggling to understand what exactly the Screen Position node outputs in Unity's Shader Graph. I'm using the screen position with scene depth to calculate the distance between two objects. Every tutorial I saw (like Brackey's forcefield one) is using the alpha channel of the Screen Position output I read that the Screen Position node outputs the mesh vertex screen positions. Does it means the 2D position on the screen projection? Or the vertex 3D position from the eye space? And more importantly, what is exactly the apha channel of this output? (I have the feeling this is related to the quot clip space W component quot in the documentation)


Unity Water shader vertex offset how to add mesh collider which updates with vertex offset? I have written a shader (in the new LWRP shader graph) which simulates an ocean with vertices which offset to create a moving "waves" effect. I believe that in order to have objects "float" on my moving waves, I shall need to create a mesh collider which is a trigger (please correct me if I'm wrong) which updates with the moving vertices of the mesh as per direction from the shader. How is such an effect possible? Am I taking the correct approach here? Please advise ) Many thanks in advance!! (the original model for the water is a plane which has been subdivided multiple times to provide suitable resolution for the vertices to be offset)


Can I develop a game for Kinect without a Kinect? I have to make a game in Unity3D using Kinect. The problem is I don't have the Kinect yet. I need to wait until they deliver it to me. Can I imitate Kinect's movement for debugging my app?


Wait for AudioClip finish before destroy Object If I Play the gun sound on my "bullet" object, how can I prevent the end of Audio sound if the bullet hit something so it destroy. To clarify Bullet prefab Audio Source Audio Clip MachineGun.mp3 PlayOnAwake true When I instantiate bullet, MachineGun AudioClip is played. But the bullet is fast and hit something before the clip is end. This Kill the machine audio effect making it irrealistic. How can I tell Unity "Play the sound to the end, despite the object is destroyed". I've tried Destroy(gameObject, AudioClip.length) But it seems not works


When is transform width in code not equal to the transform width in inspector? I've come across a strange case in Unity's UI where the width of a RectTransform isn't the same as what is being reported. I have a transform which is 50 by 50 with no scaling, it is a root object of the canvas yet when I use the information that I get from the transform in code to draw from the bottom left edge of the transform to the top right it doesn't reach all the way! Gizmos.color Color.red Vector2 pos new Vector2(transform.position.x, transform.position.y) Gizmos.DrawLine(pos transform.sizeDelta, pos transform.sizeDelta) Vector3 corners new Vector3 4 transform.GetWorldCorners(corners) Gizmos.color Color.magenta Gizmos.DrawLine(corners 3 , corners 0 ) Gizmos.DrawLine(corners 0 , corners 1 ) Gizmos.DrawLine(corners 1 , corners 2 ) Gizmos.DrawLine(corners 2 , corners 3 ) The first section should draw a line from the bottom left to the top right according to what the transform reports are the width and height however they don't reach across the entire transform. Using GetWorldCorners the actual corners can be found and drawn around, with that data you can extract that the actual width is 60 (150.2 30.2 120 2 60)! Why? Is this a bug or an I missing something obvious here?


Getting the Halo property of a point light in Unity I am adding point lights in my scene ( max 6 ) and I want to be able to enable its Halo property via script. However in the documentation reference, they haven't mentioned how to enable the halo property of a light source via script. This is what I have so far. GameObject lightObj new GameObject("Light") lightObj.AddComponent lt Light gt () lightObj.light.color Color.blue lightObj.transform.position city.transform.position new Vector3( 6.0f,0,0) Point Lights have a property "Draw Halo" on the Inspector but how do I enable it via script?


Upon import, isosphere is missing To build my tank for a Unity game, I am using Blender. Currently, I am making a turret consisting of an isosphere with half of the faces removed (I needed the bottom to be "flat") with some minor visual edits, two cylinders (one is the hatch, the other the antenna), and a cube to act as a hinge The inside is hollow. When I imported it to Unity (drag and drop from File Explorer straight to Unity Assets folder), the entire isosphere was missing as you can see from the preview I have tried to correct the normals with CTRL N as mentioned in other Blender forum pages but it still doesn't work. How exactly do I make my isosphere appear in Unity? NOTE This works if imported as a .fbx file but I would much prefer the file to be a .blend file instead (which is default).


Unity text component not updating text properly It was worked fine previously, but after some point, it's not working. This is the code. It's not a pseudo code, actual code in game public Text healthText void Start() healthText GameObject.Find("UI InGameUI CharacterStatus HealthText").GetComponent lt Text gt () void Update() if(healthText) print(health) healthText.text Time.deltaTime.ToString() healthText.text "HP " health.ToString() healthText.text "HP " health variable "health" is float value. I just want to print it to the screen, but it's always prints "Health 100" even it changes. So I printed the value to the console, but it prints well in the console and only text components was not printed properly. So I printed Time.deltaTime instead of the health and it works! Seriously, what the hell is happening? Is this a bug? If health variable wasn't changed, it should be also printed 100 in the console, but it's not! Try this to another text component, still not working.


Unity ECS Issues with rotation Posting this here because I spent several days trying to figure out why I couldn't rotate my entities the way I wanted to in Unity. For a little bit of background, I'm creating a flight dynamics model using Unity's Entities package. Part of this project involves providing keyboard input to a system in order to manipulate the motion of an aircraft a very basic simulator. I encountered an issue when I tried rotating my aircraft entity using the Rotation.Euler() method. In fact, just about every approach I saw on every forum I visited could not provide the answer I was looking for. My keyboard input logic manipulated the bank angle (roll), alpha (pitch), and yaw, and I was trying to set an absolute angle for my entity based on those values. It seemed that I was unable to set the rotation values the way I would in the inspector panel, since rotating the entity one direction would make rotating it along another axis unpredictable. Such is the nature of quaternions. Thus, I found a solution to my issue, involving a simple helper function that converts a float3 array of rotation values (one for each axis) to a quaternion. I'll be posting the code and explanation in the answer below. EDIT In the previous iteration of my code, this is what I had tried in order to update my entity's rotation Vector3 temp transform.rotation.eulerAngles temp.x 90.0f state.bank temp.y 0.0f temp.z state.alpha Entities.ForEach((ref Translation translation, ref Rotation rotation, ref AircraftData aircraftData) gt translation.Value position rotation.Value Quaternion.Euler(temp) ).Schedule() All other code within the answer below was the same (minus the new quaternion calculations).


How to access "move" values from move node in Rain behavior tree? I have a blend tree for the NPC that takes an "input magnitude" value 0 to 1.0 for how fast the character should move...and an "angular input" float negative pi to positive pi for how fast the character should turn. How do I get the rain behavior tree to update these values correctly in the behavior tree "set parameter" leaves? I see that I can set the parameter with some kind of variable name, but I don't see where I can specify that variable with a script...and I don't see how I can access the "move" instructions given from the move node on the behavior tree, and use them to set the variables either. How would I accomplish this steering with Rain?


Unity Erase Image from mouse pointer I want to erase the image for mouse pointer in unity. My pointer should be as a eraser. What is I do create the eraser? My sprite is always change because it provide from the server. Please help me.


Unity3d seamless level loading I've read that application.loadLeveAdditiveAsync is a pro only feature. I'm looking for an asset that can do something similar. I would like to load assets based on the camera player position. Ideally, it would be great to dispense with scenes entirely and just load information based on some distance value. This asset seems to be doing just that https www.assetstore.unity3d.com en ! content 8015 however I'm not sure if the author is active anymore, and recent customers are complaining about a serious bug. Any recommendations about assets that allow for seamless, open world style transitions between scenes would be great. (using Unity 3D 5, basic version, and writing in c ).


Detecting if "Wall" To The Left or Right Of Player Unity3D I am working on a 3D Platformer in Unity3D and I need to prevent the player from going through walls. The movement for my player works like this (A bird eye view representation)The areas the player can move a divided into layers. He can slide into the 2nd, 1st , or 3rd layers. The player is not a rigid body, and is controlled using a character controller. To move the player into these layers I simply increase his Z Axis. Currently if my player is behind the wall he will slide directly into it. How can I determine if there is a wall to the left of the player in Unity 3D? If so, I simply wont allow the user to move to the layer until they have steered clear of the obstacle. Does anyone have any suggestions of what I should do?


How to update Unity? I have clicked on check for updates but it says I have latest Unity. But latest is 5.6. How to update it to 5.6?


How can I stop showing camera image in my Scene? Unity How can I stop showing camera image in my Scene in Unity? As you can see on the screenshot there is an image of a camera inside a player in the Scene view. How can I disable the image?


How to destroy a clone of an effect attached to an object? I want to use some particle effects into a bonus object that will be destroyed upon contact with the player object. This object as its name suggests will add a certain benefit for the player for a certain amount of time. I was following a tutorial on Youtube. The code from the Tutorial worked fine but there is one problem I was not able to solve the explosion will not be destroyed after the object is collided with player and after the script is triggered because it seems that it was cloned into the scene. The instantiation created a clone of the effect's prefab I referenced into the script. After looking into the internet, I tried to affect the instantiation of the effect into a variable called clone and then destroyed it after the bonus is over but the problem was still present. I researched and I really did not obtain any answer. bonus.cs using System.Collections using System.Collections.Generic using UnityEngine public class bonus MonoBehaviour public float multiplier 2.0f public GameObject pickup effect public float duration 10 private GameObject clone private void OnTriggerEnter(Collider other) if (other.CompareTag("Player")) StartCoroutine( pickup(other)) IEnumerator pickup(Collider player) Debug.Log("You picked a bonus!") spawn cool effect clone Instantiate(pickup effect, transform.position, transform.rotation) apply effect yo the player our.score value 10 player.transform.localScale multiplier GetComponent lt MeshRenderer gt ().enabled false GetComponent lt Collider gt ().enabled false wait x amount of seconds yield return new WaitForSeconds(duration) remove the effect from theplayer player.transform.localScale multiplier Destroy(gameObject) Destroy(clone,4f) I tried disabling the "loop" option in the effect's particle system options but it gave the same results. I disabled the "Play on Awake" option and the effect will not play at all. The script is added directly to the object that is a simple 3D cube with MeshCollider, Mesh Renderer and Box collider. The effect I used is a BigExplosionEffect taken from Unity Particle Pack 5.x from the Asset Store. I would like to know what is exactly wrong? Is it probably related to the effect itself rather than the script? Or is there a far better solution?


Unity Button still interactable even when interactable is set to false my button can still be pressed in game even if I set it to button.interactable false What I'm trying to achieve is when the Panel CropsPanel is opened, or active in Unity, I want the EquipmentButton to be disabled and to be not usable by the user. Here is the code I've written public void Start () GetComponent lt Button gt ().interactable false if (CropsPanel.activeInHierarchy true) EquipmentButton.interactable false I have also set all buttons in the inspector, placed a Debug.Log("msg here") to see if the particular code is working. But I can't seem to get it working. Am I missing something? Thanks guys!


Pixelated shadows in Unity I have tried everything I can think of and all the solutions I could find on forums, but I haven't been able to fix this problem. I have a point light that is shining on several spheres which are casting shadows. The shadows work fine, but they are quite obviously pixelated. How do I get them to be smoother? These are the settings that I took this screenshot with. I've tried tweaking most of the them, but it's possible I wasn't using the right combination to get the smoother shadows.


Unity create water issue I use daylight water in my project but by the default it has not got any waves or light tracing effects. But in some tutorials I see how the user add standard water asset and it has got beautiful world reflection on the surface and beautiful waves. Is this issue because that I am using not a PRO version?


Adding Grass to a Low Poly Mesh in Unity How would I go about adding grass to a low poly mesh in Unity? Here is what I have looked into Object2Terrain I am not using Unity's built in terrain system because I am going for a low poly art style. I tried converting my terrain mesh object to a terrain (using Object2Terrain) however this removes the sharp edges on the terrain, because Unity uses a height map for optimization. PolyMesh From the get go I knew this approach wasn't going to work. I knew it would be incredibly inefficient to render that many meshes at once. I still tried it though, and to no surprise, it was very laggy. Particle System From what I've read, this should work fine for randomly scattering grass over your mesh, however I do want some control when placing grass. I followed this tutorial image as suggested by a comment in this question on Reddit, however, I was never able to achieve the desired result. Nevertheless, I do want control over placing the grass, and so I moved onto another approach. Shaders I'm not experienced at all when it comes to creating (or even using) shaders, and it's quite a daunting topic to me. I've read that this is the most efficient approach, however haven't been able to understand how this means I could draw grass onto a mesh? On the same Reddit post linked above, "UpstairsCurrency" was kind enough to link their source code (here), however I'd like to understand what is happening? I'm reluctant to say that I'm not even sure I understand how to implement it into my project in the first place. Would appreciate any sources for reading up to help understand what is going on! Thanks!


Fill all unallocated space with texture I have a system of bunkers underground, and I need to fill all the free space where there are no buildings with earth. Yes, I can manually add a ground texture to the plane, but I have procedural level generation. I thought there might be some kind of filter on the camera that I don't know about. Or maybe there are some other solutions?


Get all objects of Additively loaded Scene? (LoadSceneMode.Additive) I learned how to Load and unload scenes in unity. using LoadSceneMode.Additive. I like to spit up my scenes as much as possible and retain the stuff I need as I go along. I'd like to be able to find all objects loaded from a specific scene. Obviously Unity knows but I can't find how to get them. For now, my workaround is to put them in a specifically named empty or have them tagged in a certain way, but that is a workaround. Is there an easier way?


How to remove terrain in 3d? After the release of Minecraft I saw more and more rip offs of the game but some actually began to change it up a bit making the game have a organic look instead of the iconic blocky one that Minecraft does. If you'd like to look at the game that i'm referring to you can do so here. If you skip to around 50 seconds on the first video the steam page offers you can see the mining part that i'm wondering about. I was wondering how this affect is achieved where they are able to remove part of the 3D object on collison with the players pick. I have heard about constructive solid geometry before and figured that could have been used but i'm not so sure.


How make animation only consider the final position? I'm trying to make an energy indicator for a puzzle, and i decide to user animation to set the position of the red indicator(photo). My first ideia is to make 9 animations, and for every black arrow i set the final position to the red indicator. And organizer in the animation controller. But the main problem is, after every animation, the red indicator got to the first position, in the case the first arrow black, and then go the final position, because all the animation have the same position in the begin (0s). How can i animation the trasition of red indicator to only got to the end position? Like, if the position of the red indicator was in the 7th black arrow and then go to 3th arrow. Is possible with animation?


How to Replace two object by rotating in center I created Find Rock game but I have problem In replacing two object by rotating in center and when rotating finish stop rotating how can I do this? using UnityEngine using System.Collections public class example MonoBehaviour public GameObject obj public int Randomize new int 2 void Start() StartCoroutine (Delay ()) IEnumerator Delay() Randomize 0 Random.Range (0, obj.Length) Randomize 1 Random.Range (0, obj.Length) while (Randomize 0 Randomize 1 ) Randomize 0 Random.Range (0, obj.Length) yield return new WaitForSeconds (2) obj Randomize 0 .transform.rotation Quaternion.Euler (new Vector3 (0, 0, 0)) obj Randomize 1 .transform.rotation Quaternion.Euler (new Vector3 (0, 0, 0)) StartCoroutine (Delay ()) void Update() if (obj Randomize 0 .transform.rotation.eulerAngles.y lt 90 obj Randomize 1 .transform.rotation.eulerAngles.y lt 90) obj Randomize 0 .transform.RotateAround (obj Randomize 1 .transform.position, Vector3.up, Time.deltaTime 100) obj Randomize 1 .transform.RotateAround (obj Randomize 0 .transform.position, Vector3.up, Time.deltaTime 100) I can make this game but when rotating finish they aren't Directed. this video link describe my problem and this is unity package of my game. how can I use mathf clamp RotateAround for stopping rotation?!


Shader to see silhouette through alpha blended sprites I want to achieve in Unity a see through effect like the one in these examples In my specific scenario there are a couple of requirements Sprites are using alpha blending, and sprites have transparent areas. There are 2 kind of elements that occlude the character. One should create the silhouette effect, and the other one should behave like normal. For occluding elements that create the silhouette I enable ZWrite, and disable it for elements that doesn't. For the character I tried setting the queue of the shader to transparent 1, and added this pass Pass ZTest Greater Lighting Off Color Color And the effect works partially The silhouette is drawn all over the character, even the parts that are transparent. Transparent parts shouldn't create a silhouette. The silhouette is created when the character is behind a sprite, even if that part of the sprite is transparent. Being behind a transparent part of the sprite shouldn't create the silhouette. The character appears infront the rest of the elements, even if it is behind them. I guess this is because setting the queue to Transparent 1. But if I leave it as Transparent, the character is drawn in the correct order, but the silhouette is never seen. I tried to follow these tips someone gave me, but I'm unable to get it to work 1) Leave the pass that renders the sprites as is. 2) Add a pass that writes to the z buffer, but has a shader that uses clip() to discard pixels based on alpha. You can't use the z buffer to make soft z tests without using MSAA and alpha to coverage. The quality of that won't be great, but it's the best you can do. A faster alternative is a pattern or noise dither, or a good old fashioned threshold if your sprites all have fairly sharp edges. 3) Add third pass to occludable objects that draws the occlusion color using the z test and make sure it's drawn as a final pass. I'm kind of new to shaders, specially in Unity, and I just can't figure out how to make it work properly.


How to make the camera follow the mouse in first or third person camera I currently I have a game made of a few small scripts, the PlayerController, PlayerStats, and CameraChange (each below). My question is how do I get the camera to follow the mouse movement? I want the player to be able to switch between each camera and look around with the mouse. Any idea as to how I'd go about doing this? My current theory is I would some how have to access the current active camera and make it follow the mouse but not sure how to do that. PlayerController using UnityEngine public class PlayerContorller MonoBehaviour Update is called once per frame void Update () var x Input.GetAxis("Horizontal") Time.deltaTime 150.0f var z Input.GetAxis("Vertical") Time.deltaTime 3.0f transform.Rotate(0, x, 0) transform.Translate(0, 0, z) PlayerStats using System.Collections using System.Collections.Generic using UnityEngine public class PlayerStats MonoBehaviour public int Health 100 public int Stamina 100 public int magic 100 Use this for initialization void Start () Update is called once per frame void Update () if () CameraChange using System.Collections using System.Collections.Generic using UnityEngine public class CameraChange MonoBehaviour public GameObject ThirdCam public GameObject FirstCam public int CamMode Update is called once per frame void Update () if (Input.GetButtonDown("Camera")) if (CamMode 1) CamMode 0 else CamMode 1 StartCoroutine(CamChange()) IEnumerator CamChange() yield return new WaitForSeconds(0.01f) if(CamMode 0) ThirdCam.SetActive(true) FirstCam.SetActive(false) if(CamMode 1) FirstCam.SetActive(true) ThirdCam.SetActive(false)


How can I create a tunnel parallax depth effect based on mobile device tilting? I would like to create applications similar to what's displayed in these videos VR Tunnel Live Wallpaper for Android The parallax view Part 1 These mobile application are supposed to react to tilting of the phone, so I created a few 3D objects for this purpose in Blender (one similar shape 2nd link), but I do not know how to move the back of this object in Unity because I am a beginner. Can you give me some tips on how to figure this out? I m not talking about a ready solution or something, I just do not know how to ask a specific question and I do not know what to do next.


Problem with coroutines unity 3d I cannot understand why the coroutines are not waiting the designated number of seconds before executing the code below it. At the moment, the animation bleeds into the next state. I could get around this by using .time and if statements but I thought the whole point of coroutines is that you can avoid that sort of mess. public IEnumerator LoadBow() this.gameObject.GetComponent lt Animation gt ().CrossFade("Load Bow") yield return new WaitForSeconds(this.gameObject.GetComponent lt Animation gt () "Load Bow" .length) aimStates AimStates.Draw public IEnumerator DrawBow() this.gameObject.GetComponent lt Animation gt ().CrossFade("Draw Bow") yield return new WaitForSeconds(this.gameObject.GetComponent lt Animation gt () "Draw Bow" .length) aimStates AimStates.Aim public void Aiming() moveTarget.SetActive(false) switch(aimStates) case AimStates.Load StartCoroutine(LoadBow()) break case AimStates.Draw StartCoroutine(DrawBow()) break


How do you "branch" a Unity project How do you branch a unity project? Suppose you have Game Project A, and say there is variant A' that requires a large convoluted plugin. But the idea is also that you want to keep developing this without the plugin getting in the way, for the other variants say A and A'' that don't require it.


Terrain Destruction Accuracy I am making a game in unity that allows you to destroy terrain, The problem I am having is that the farther away that I get from the origin (0,0), The more inaccurate the point where the destruction occurs is. Is there a way to make it more accurate? Use this for initialization void Start () The width and height of the heightMap xRes TerrainMain.terrainData.heightmapWidth yRes TerrainMain.terrainData.heightmapHeight Getting the heightMap points saved TerrainMain.terrainData.GetHeights(0, 0, xRes, yRes) heights TerrainMain.terrainData.GetHeights(0, 0, xRes, yRes) void TerrainDestruction() Vector3 actualPosition actualPosition.x MyPosition.x actualPosition.y MyPosition.y actualPosition.z MyPosition.z Getting the x and y position of the player int xPosition (int)(actualPosition.x) int zPosition (int)(actualPosition.z) Debug.Log("x " xPosition) Debug.Log("z " zPosition) heights zPosition, xPosition 0.001f TerrainMain.terrainData.SetHeights(0, 0, heights) TerrainMain.terrainData.SetHeights(0, 0, heights) void OnApplicationQuit() TerrainMain.terrainData.SetHeights(0, 0, saved) Update is called once per frame void Update () Getting the actual Position of the player with respect to the terrain MyPosition MyMouse.mousePosition if (Input.GetMouseButtonDown(0)) TerrainDestruction()