Recursively calculate possible pathway on a grid depending on max walk distance I have a character that is placed on a grid. It has a variable maximum walking distance. Grid fields can be walkable or not walkable. As the character may has to walk around certain not walkable fields to reach his destination his maximum walking distance isn't allways represented by a circle. See these examples Without obstacles, walking distance 7 With obstacles, walking distance 7 Note how the obstacles affect the players maximum walking distance To calculate this i've written this recursive function static Vector2Int GetWalkableFields (Vector2Int position, int steps) List lt Vector2Int gt walkableFields new List lt Vector2Int gt () if (steps gt 0) foreach (Vector2Int v in GetNearbyFileds(position)) if (m mc.IsInBounds(v) amp amp m mc.IsWalkable(v.x, v.y)) walkableFields.Add(v) walkableFields.AddRange(GetWalkableFields(v, steps 1)) return walkableFields.ToArray() else Vector2Int v position return v And this function, that returns all four neighbour fields of a field public static Vector2Int GetNearbyFileds(Vector2Int position) Vector2Int neighbors new Vector2Int 4 neighbors 0 new Vector2Int(position.x, position.y 1) neighbors 1 new Vector2Int(position.x, position.y 1) neighbors 2 new Vector2Int(position.x 1, position.y) neighbors 3 new Vector2Int(position.x 1, position.y) return neighbors The function is called with the players position and maximum walking distance (steps) and get's the four neighbour fields and unless the steps are zero calls itselve for every neighbour field with the maximum walking distance decremented. As you can see in the screenshots, this works absolutely fine. The problem is, as the calculation not only goes away from the player but, in some recursion paths, goes back and fourht between tiles until stepcount zero is reached without even having traveled one field, that this way of calculating the path is really resource heavy. For a walking distance of 7 there are 27646 possible walkways that all are getting calculated. If a player is able to walk 11 fields the calculation takes a few seconds, if he can walk 12 fields Unity crashes while calculating. Is there a way to calculate this more efficient? Thank you in advance.


Chess engine stock fish process for mobile I am making the chess interface I designed for a game. I am using the process to get answers from a stock fish binary stockfish new Process StartInfo new ProcessStartInfo FileName System.IO.Directory.GetCurrentDirectory () " Assets Scripts Stockfish stockfish.exe", Arguments "", UseShellExecute false, RedirectStandardOutput true, RedirectStandardInput true, RedirectStandardError true, CreateNoWindow true The problem I face is it worked for my Windows build but for mobile package build it won't work with the executable. Is there a way around it?


Offscreen arrow indicator appears only when the user go near to the object I have placed four gameobject at different place.And I have a player and have applied movement to it through keyboard control.I have added script for arrow indication towords this gameobject.But the problem is that,the arrow appeaar only when the user go near to the gameoobject.I need the arrows to appear on the screen so that the user initially know where the gameobject is placed on the scene. Here is the code for onscreen arrow.I have attached this script to each gameobject public Texture2D icon The icon. Preferably an arrow pointing upwards. public float iconSize 50f HideInInspector public GUIStyle arrow GUIStyle to make the box around the icon invisible. Public so that everything has the default stats. Vector2 indRange float scaleRes Screen.width 200 The width of the screen divided by 500. Will make the GUI automatically scale with varying resolutions. Camera cam public bool visible false Whether or not the object is visible in the camera. void Start () visible GetComponent lt SpriteRenderer gt ().isVisible cam Camera.main Don't use Camera.main in a looping method, its very slow, as Camera.main actually does a GameObject.Find for an object tagged with MainCamera. indRange.x Screen.width (Screen.width 6) indRange.y Screen.height (Screen.height 7) indRange 2f arrow.normal.textColor new Vector4 (0, 0, 0, 0) Makes the box around the icon invisible. void OnGUI () if (visible) Vector3 dir transform.position cam.transform.position dir Vector3.Normalize (dir) dir.y 1f Vector2 indPos new Vector2 (indRange.x dir.x, indRange.y dir.y) indPos new Vector2 ((Screen.width 2) indPos.x, (Screen.height 2) indPos.y) Vector3 pdir transform.position cam.ScreenToWorldPoint(new Vector3(indPos.x, indPos.y, transform.position.z)) pdir Vector3.Normalize(pdir) float angle Mathf.Atan2(pdir.x, pdir.y) Mathf.Rad2Deg GUIUtility.RotateAroundPivot(angle, indPos) Rotates the GUI. Only rotates GUI drawn after the rotate is called, not before. GUI.Box (new Rect (indPos.x, indPos.y, scaleRes iconSize, scaleRes iconSize), icon,arrow) GUIUtility.RotateAroundPivot(0, indPos) Rotates GUI back to the default so that GUI drawn after is not rotated. public void OnBecameInvisible() visible false Turns off the indicator if object is onscreen. public void OnBecameVisible() visible true How can I make the arrows to appear on the edges of the screen


How can I keep the drawn lines instead deleting them? using System.Collections using System.Collections.Generic using UnityEngine public class DrawLines MonoBehaviour private Transform startMarker, endMarker public GameObject waypoints private float speed 2f private float startTime 0f private float journeyLength 1f private int currentStartPoint 0 private LineRenderer lineRenderer public void StartInit() currentStartPoint 0 SetPoints() lineRenderer GetComponent lt LineRenderer gt () lineRenderer.startWidth 0.2f lineRenderer.endWidth 0.2f void SetPoints() startMarker waypoints currentStartPoint .transform endMarker waypoints currentStartPoint 1 .transform startTime Time.time journeyLength Vector3.Distance(startMarker.position, endMarker.position) void Update() if (waypoints.Length gt 0) float distCovered (Time.time startTime) speed float fracJourney distCovered journeyLength Vector3 startPosition startMarker.position Vector3 endPosition Vector3.Lerp(startMarker.position, endMarker.position, fracJourney) lineRenderer.SetPosition(0, startPosition) lineRenderer.SetPosition(1, endPosition) if (fracJourney gt 1f) if (currentStartPoint 2 lt waypoints.Length) currentStartPoint SetPoints() else if finished, disable lineRenderer and this script lineRenderer.enabled false this.enabled false Each time it's drawing a line between two waypoints but then the line is deleted and then it's drawing a new line between the next two waypoints. Instead I want it to draw one line between all the waypoints. And to keep the line in the end not to delete it.


Are there still favored of using bluetooth devices today in modern games for multiplayer gameplay? I was wondering. Most multiplayer gameplay always favored by Wi fi during team up or to compete each other. I know that when in comes in huge groups (say 100 to 500 players or more online) in online games whether it's cooperation or battle, most players relying on Wi fi to play in very huge group. What if some persons wants to play in small groups and can be played offline (like in racing games or fighting games for example) using smartphones via bluetooth? The question is that are there most game apps for multiplayer gameplay still favored or popular of using bluetooth when playing in a very few no. of players (let's say only two players) on a certain game? Also, is it possible to create a game app for iPhone or any smartphones that run on Android that features bluetooth for multiplayer via Unity 3D game development software?


Physics.CheckSphere() appears not to work in Unity My scene is simple, I have a single GameObject with the following script attached usings ... public class GalaxyManager MonoBehaviour public int numberOfStars 300 public int maximumRadius 100 public float minDistBetweenStars 2f void Start() for (int i 0 i lt numberOfStars i ) float distance UnityEngine.Random.Range(0, maximumRadius) float angle UnityEngine.Random.Range(0, 2 Mathf.PI) Vector3 cartPosition new Vector3(distance Mathf.Cos(angle), 0, distance Mathf.Sin(angle)) if (!Physics.CheckSphere(cartPosition, minDistBetweenStars)) GameObject star GameObject.CreatePrimitive(PrimitiveType.Sphere) star.transform.position cartPosition else i Update is called once per frame void Update() What this is supposed to do is generate 300 quot stars quot within the maximumRadius of 100 that are separated by at least minDistBetweenStars. I haven't been able to figure out what's actually happening sometimes the check finds a collider and sometimes it doesn't. It's almost as if the CheckSphere() check is happening before the stars get placed via the star.transform.position cartPosition. I'm very new to Unity and appreciate the help. Anyone have any idea what's going on? edit Some more information, I've tried the script in both 2020.1.12f1 and 2019.4.14f1 to no avail. I'm also aware that this will lead to an infinite loop if it can't find a placement.


Unity how to switch between ratios in a Scene View? I'm complately new to Unity, but I know what's going on, I've made some games with LibGDX earlier. In GDX, to handle all resolutions perfectly I always create 5 different sets of backgrounds (cause they have to be perfectly sized) and I place UI widgets on percentage for each ratio independantly (hardcoded values). I was just checking what's the ratio on runtime. As we know, there are only 5 possible aspect ratios for mobile devices (I target mobile only). Now, when I started using Unity, the first thing I looked up was how devs handle ratios. I found some scripts in the web, which add pillarboxes which in my case is unacceptable. So I thought ok, let's do it my way, and make it for all aspect ratios. And my question is Is there any option in Unity, which will allow me to 'switch' in the Unity Editor between ratios and the 'Scene View' will understand this and resize? What I want to do is to create a 16 9 with the editor, then switch to 5 3, adjust elements for it, and remaining ratios too. To be clear, I don't mean the 'preview', when you check the desired device and it shows how the game will look like. Any help and tips are appreciated! )


Is it possible to interpolate different sprites? I can interpolate different animations based on position, rotation, and scale. I want to do the same for different sprites, automatically. For example, lets say I have a soda can being crushed. I have 2 sprites One is the soda can uncrushed, and one is the soda can fully crushed. I want to only use those 2 sprites, and have Unity automatically transition from the normal can to the crushes can. How can I do this without making a bunch of key frames in between?


Rotate on one axis, but visibly keep the other axes stable and editable It's been a long two weeks. Quaternions are freaking complicated. I've managed to make a few baby steps towards finishing my project, but I've hit a brick wall and could use a few of your beautiful minds to help me past it. I'm making an asset for Unity that will automatically rotate shift objects to make them appear 2.5D. What I'm having trouble with is the rotation part. I go through a trigonometric process to get a calculation of how much, between 0 and 180 degrees (typically), that the object should rotate on its x axis. The rotation of this object should be locked between 0 and 180 degrees. Think of it this way my trigonometric calculation is telling me whether the object should be flipped right side up or upside down So, we've got the angle it should rotate. Just plop it in a Quaternion.Euler(MyNewXValue, prevEulerY, prevEulerZ) and we should be good, right? WRONG. There are a number of things wrong with this. The previous eulers can come back a bit wonky since they can correspond to multiple values in the 360 to 360 degree range, so we have to "normalize" them a bit. Due to the rotation order, it ends up "swirling" in 3D space and altering the other two rotations instead of maintaining a stable x axis rotation change. With that said, here is my code C if (current euler.z lt 180f) rot Quaternion.Euler(rotation angle.x, current euler.y, current euler.z) else rot Quaternion.Euler(rotation angle.x, current euler.y 180, current euler.z 180) Ignore the (if lt 180). That's just so I can get this test running and working. I'll find a proper way to normalize it later. Anyway, this snippet works, but has one problem It twirls in 3D space and doesn't remain locked on its x axis. I've tried numerous other solutions, but they either spin out of control or... they all spun out of control. My question Is there a way to set the rotation by rotating on one axis, while allowing the other rotations to change at the user's command without it "swirling" in 3D space? EDIT SOLUTION For my use case I was able to use transform.localScale and modify it's Y scale as a solution to my issue. It has the exact effect as I was looking for, and is definitely more stable. I accepted Lunin's answer, however, as it seems to be another possible solution, and is written on this forum ). To clarify, my wish was to rotate a 2D object on its x axis, which would cause it to rotate vertically. At the same time, I wanted to allow the other axes to be editable at any given time. I can mimic a vertical rotation by changing the y scale of the 2D object. 1 y scale is normal, 1 y scale is flipped upside down. Since I only needed that one axis to change, this workaround worked perfectly.


In Unity shaders, how is IN.worldRefl calculated? I want to know how the world reflection vector in shaders is calculated so that I can manipulate it, but there is no documentation on what it does or how Unity calculates it. How is the reflection vector calculated and exactly what does it do?


Real Time Speech Verbal Communication with a Mecanim Character What would be the simplest method of integrating real time verbal communication within a mecanim character that is already being used in a Unity app project? Something like an SDK or toolkit? I have such a character that is animated by a motion capture device, so the user puts on the suit and the Unity character is driven by receiving live motion data. This is the non verbal part for research in Social Sciences amp Psychology. I tried integrating the Virtual Human Toolkit into my Unity app to use its real time speech amp lip sync amp facial gestures, but their character is set up in a complicated way, so I still cannot animate it by using my motion capture device. So, now I am thinking what is the next best thing to do with a Unity mecanim character to make it say something, etc...?


How could I make the player's movement more responsive? I am working on an Air Hockey game I tried making the movement physics based, by doing this using UnityEngine public class Player MonoBehaviour private Rigidbody m Rigidbody private float HorizontalInput private float VerticalInput public float Speed 1.0f private void Start() m Rigidbody GetComponent lt Rigidbody gt () private void Update() HorizontalInput Input.GetAxisRaw( quot Horizontal quot ) VerticalInput Input.GetAxisRaw( quot Vertical quot ) private void FixedUpdate() m Rigidbody.AddForce(new Vector3(VerticalInput Speed, 0.0f, HorizontalInput Speed),ForceMode.VelocityChange) and by adding a PhysicsMaterial to the MeshCollider attached to my player The movement should be quick and responsive, but it feels rather sloppy and unresponsive I also tried using Input.GetAxisRaw(...), but the controls become quite clunky. How can I improve on this? Is there a go to way to do this type of movement in Unity? (I would like the final version of the game to be played on controllers)


Prefab can't accept script created material I am doing mod support for my game. I want users to be able to change materials of any prefab in the game. In order to achieve that, I create a new material from the imported data and then apply it to an existing prefab. However, it does not work. It works if I try to assign the newly created material to an object on the scene (not a prefab) and it works if I try to assign an existing material to a prefab. However, assigning a new material to a prefab results in this I am fairly certain that is exactly the issue since it can be reproduced as easily as with this snippet of code GameObject prefab Resources.Load( quot Prefabs Cubes IceCube quot ) as GameObject prefab.GetComponent lt MeshRenderer gt ().sharedMaterial new Material(Shader.Find( quot Standard quot )) What am I doing wrong? How can that be worked around?


Why is the player not showing up on UI when connecting to server? I want to create a playerList, that whenever a player joins server, his her name will show up on a list in UI. But currently the names are only showing up on the Client host side. Below is my NewtworkManager code. lobbyPlayerList is just a UI element with VerticalLayoutGroup. lobbyCharacter is just UI textElement with a networkBehavior script that sets the text field value and also has newtworkIdentity and networkTransformation. public struct PlayerInfo NetworkMessage public string name public class LobbyManager NetworkManager public GameObject lobbyCharacter public GameObject lobbyPlayerList Start is called before the first frame update public override void OnStartServer() base.OnStartServer() NetworkServer.RegisterHandler lt PlayerInfo gt (CreateLobbyCharacter) public override void OnClientConnect(NetworkConnection conn) base.OnClientConnect(conn) PlayerInfo info new PlayerInfo name quot Test quot conn.Send(info) private void CreateLobbyCharacter(NetworkConnection conn, PlayerInfo info) GameObject gameobject Instantiate(lobbyCharacter, lobbyPlayerList.transform) gameobject.GetComponent lt LobbyCharacter gt ().SetText(info.name) NetworkServer.AddPlayerForConnection(conn, gameobject)


Controlling a balance wheel using a Unity script I am working on a small demonstration project with Unity like this (screenshot from footage below). I don't want to use Unity physics, which is too heavy. I plan to create a rotation function with ratio params for gears. But I am not sure how to control the balance wheel rotation like that video, I tried animation tools which is hard to make the acceleration like real physics.


How can I get game objects and prefabs to recognize modifications in enum values from scripts in the scene window I have made a script with several properties and enums that I attached to an empty game object. I am making changes to the values within the inspector, since they a public. How can I get the scene window to recognize these changes as they occur?


Moving Object Interception Projectile Collision I am using Unity to attempt to have missile A launch at incoming missile B and blow it up. However in order to do this accurately, A must be able to take into account B's current velocity, direction and distance in order to calculate where it needs to aim in order to succesfully hit it. How do we go about this using the below as an example?


OnMouseDown() and Collision not working for game object created within another game objects script I have created a game object (Brick) and added a script (BrickScript) to it. Within this script I create a Window game object if a certain condition is satisfied. Please see code below if (hasWindow) if (window null) var size gameObject.GetComponent lt SpriteRenderer gt ().bounds.size window (GameObject)Instantiate (Resources.Load ("Prefabs OtherPrefabs Window"), new Vector3 (transform.position.x 0.5 size.x, transform.position.y 0.5f size.y, transform.position.z), Quaternion.Identity)) window.name gameObject.name "Window" nbsp The Brick and window game objects actually overlap a bit. I realized that when hasWindow true (the window is created) the condition in the code below is not satisfied and other game objects don't collide with the Brick. But when hasWindow false (the window is not created), everything seems to work well. How can I solve this? void OnMouseDown () if (Input.GetMouseButtonDown(0)) Debug.Log ("touch down") hasBeenTouched true


How do I ensure consistent behaviour when using Unity's Collider2Ds for triggers and collisions? I am experiencing inconsistent behavior using Unity's 2D Physics engine and their Collider2Ds to detect collisions and triggers on my projectiles. I will classify it into two problems. The first is that occasionally the projectile will pass through walls objects it should collide with. The second is that occasionally the projectile will pass through enemies that it should hit without triggering. I will try to elaborate in detail below. A projectile is organized into a container Projectile GO and two children GO a PhysicsColliders GO and a HitBoxColliders GO. The PhysicsCollidersGO job is to hold the colliders that define the solid regions of the projectile using Collider2D components. It's GO is on a Projectile layer which is set to collide with other solid layers such as the ones my walls are on. Walls are static colliders. The HitBoxCollidersGO job is to define the a HitBox area. It's GO is on a HitBox layer and also uses Collider2D components that are set to be triggers. A HitScript on the GO listens for OnEnterTrigger. Projectiles are set in motion by setting the velocity of the RigidBody once upon firing. Here is a visual of the structure ProjectileGO PhysicsCollidersGO HitBoxCollidersGO Here are descriptions of the GameObjects and their components ProjectileGO RigidBody2D Component (collisionDetectionMode is set to Continious) PhysicsCollidersGO (Layer is set to Projectile) BoxCollider2D Component HitBoxCollidersGO (Layer is set to HitBox) BoxCollider2D Component (IsTrigger is set) HitScript Component Problem 1. Projectiles will sometimes not collide with walls solid objects etc... Problem 2. Projectiles will sometimes not trigger a hit. What could be causing these inconsistencies? How can ensure that collisions and triggers will consistently behave correctly?


Null Reference to camera when loading new scene I am getting the error MissingReferenceException The object of type 'Camera' 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. The camera in my game contains a persistent object script, which prevents the camera from being destroyed when loading a new scene. private void Awake() DontDestroyOnLoad(transform.gameObject) The scene is switched via a method in the GameManager public void loadScene(UnityEngine.Object arena) operation SceneManager.LoadSceneAsync(arena.name) state GameState.LOADING and finally the camera contains another script which adds a distortion effect void OnRenderImage(RenderTexture source, RenderTexture destination) distortCam.CopyFrom(mainCam) Error occurs here distortCam.backgroundColor Color.grey ...Some more code ... The error occurs in this last method, but the camera still exists in the editor. mainCam is a Camera object that is assigned onAwake via mainCam GetComponent lt Camera gt () Also if I switch the loadScene method to public void loadScene(UnityEngine.Object arena) operation SceneManager.LoadSceneAsync(arena.name, LoadSceneMode.Additive) state GameState.LOADING it works perfectly, but it is inconvenient to always have to loadScenes additive. Why is the reference to the mainCam being lost? I have tried to check if it's null and reassigning it before using it, but so far I still have the problem. Any ideas?


Sprite button not triggering "On Click()" event Unity Hi have created some buttons from sprite and I added image and button components on it. I am just using sprites because In my game the camera can be moved on x and y. But I don't want my button to move and since UI buttons move with camera that is why I am not using them. Here is the GIF to explain the scene


How to automatically destroy a gameobject after a method or block of code In Unity I frequently find myself doing this in C GameObject myObject new GameObject() try do something with that object finally Destroy(myObject) A good example is creating a temporary pivot point for another object. I create the object, parent whatever object I want to rotate, do the rotation, then destroy the object. It's in a finally block so in case anything goes wrong it still destroys the object. Does Unity have any elegant way to do this? Writing this all the time is tedious, and it's easy to forget the Destroy method at the end.


Using Unity Post Processing v2, how can I apply processing effects to just the UI? I am using Unity 2018.3 with HDRP 4.9, and Post Processing 2.1.3. I would like to apply post processing effects (i.e bloom) to the UI only. I tried the 2 camera approach, but still can't get it working correctly. I have a post processing volume that is global, and also one that is global but for the UI. Not sure if this is correct. Basically I don't want the first processing volume to apply to the UI. I can apply post processing if I ignore all this second camera stuff and set the canvas to screen space camera. I then get the effects like bloom applied to the UI. However, I want to have different post processing for the UI, the global bloom is too much. First image is the UI Camera. Second image is the main camera. Third image is the Canvas for the UI.


SerializeField vs GetComponent Efficiency As far as I know, there are two built in ways to get an instance of a component in Unity. 1 Serialize the field and drag in the component manually in the editor SerializeField private MyScript script 2 Using MonoBehaviour's GetComponent method script GetComponent lt MyScript gt () I would think that it is more efficient to drag the component in the editor lest making the engine illiterate through every component in the GameObject to find the component. Is it more or less efficient to drag the component in the editor compared to using GetComponent? Or does Unity find components in a different way or dragging components in the editor is handled in a different way such that it would be more efficient to use GetComponent? Would using one over the other have any impact on performance in the real world? A similar question would also be raised regarding GameObject.FindGameObjectWithTag() vs dragging in the editor. As far as optimization go, should you use one method over another?


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


Synchronize running code over the network Unity I want my code to run perform the same on different Unity clients. I don't know if this is hard to achieve. Here hare my problems The enemies movement I have a pathfinding that should always give the same results on server and on clients. Because I use the same pathfinding algorithm on server and client, and the position the algorithm chooses is synchronized with a network transform. But it does not give the same results on client and on server. Bullets make enemies die over all clients I have a script with OnTriggerEnter2D(Collider2D collision) that never gets called at the same moment on clients and server. The clients might miss touching a bullet on an enemy on server but not on a client. So in server enemies died and on client they have not. How to synchronize OnTriggerEnter2D() ? I will update the question to improve it with more examples when I find them.


unity2D Top Dow Mobile rigibody2D im using this code for my 2D TopDown mobile player movement.but when i move player With UI Image buttons player keep moving.it didnt stop.and also player starting of move he is very slow. the he accelerate his speed.how can i fix this. i add BoxCollider 2D and Rigibody2D my sprite.the set Gravity to 0. this is my code. public class PlayerScript MonoBehaviour public float speed 150f float hInput void FixedUpdate() Move (hInput) public void Move(float horizontalInput) if (horizontalInput.Equals(1)) rigidbody2D.AddForce (Vector2.right) if (horizontalInput.Equals(2)) rigidbody2D.AddForce ( Vector2.right) if(horizontalInput.Equals(3)) rigidbody2D.AddForce (Vector2.up) if(horizontalInput.Equals(4)) rigidbody2D.AddForce ( Vector2.up) public void StartMoving(float horizontalInput) hInput horizontalInput


Should my terrain be one big mesh or several medium ones? While creating a subterranean level with probuilder (irregularly shaped rooms and corridors), I was wondering if I should merge all "terrain" meshes into one or keep them as separate meshes? What are the good practices ? I'm creating each room as I go and its not hard to create openings and align doors vertices (with progrids) but once I start moving them around (like with polybrush) I'm sure it will soon be a nightmare. I can see pros and cons for both. Separate meshes would be easier to edit, duplicate or replace, probably better performances but at the risk of overlaps or holes because it would get hard to keep connected cleanly. I guess with one mesh you take the risk of having it eat memory and computation time, or having it too big to edit easily. I settled on each mesh consisting of a room and all half corridors going out of it, to hide the stitching and keep it simple. Still I wonder if there's a consensus.


How do I get the InputManager to recognize a certain axis Vector2D with a Vive motion controller? Right. So basically I want to map the Vive motion controller touchpads (certain locations) to the certain inputs in Unity's InputManager. How do I do this? Like I want a certain area on the touchpad to equate to forwards backwards in the InputManager. How would I do this? I am not seeing a way to do it natively. Long story short I'm wondering if I can use the Vive with the InputManager or not.


Problem connecting to Steamworks via Facepunch.Steamworks I'm using Facepunch.Steamworks (https github.com Facepunch Facepunch.Steamworks) to connect my Unity game to Steam. The login seems to work fine. The board object is an FP class, and AddScore is a call to the library to send the score to Steam. I have the boards set up on Steam, and they come out with IsValid true. Here are the output and the code. The boards currently have no data in them, so I don't think it's because the score isn't beating an existing one. xxxxxxxx Standard Normal True Fail public void SubmitScore(Globals.ApplicationMode mode, Globals.SkillLevels skillLevel, int score) int index GetLeaderboardIndex(mode, skillLevel) if(index 1 !IsSteamPlatform()) return Leaderboard board m leaderboards index Debug.Log("xxxxxxxx") Debug.Log(board.Name) Debug.Log(board.IsValid) board.AddScore(true, score, null, AddScoreSuccessCallback, AddScoreFailureCallback) private void AddScoreSuccessCallback(Leaderboard.AddScoreResult result) Debug.Log(result.Score) private void AddScoreFailureCallback(Facepunch.Steamworks.Callbacks.Result result) Debug.Log(result.ToString()) Here's a shot of the leaderboards on the Steam control panel. They seem in order their "Writes" attributes are false so that the client can submit to them directly.


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


Unity Smooth player input direction when changing camera Preface I'm very new to Unity. I'm working on an exercise using fixed cameras like how they work in the PSX final fantasy games. I have the camera scripts working fine but it's an aspect of the character control that I'm struggling with. My character moves relative to the cameras facing position, but when the camera suddenly changes to another angle, my running direction instantly and abruptly changes too. In the final fantasy games it sort of keeps going roughly in the same direction you were briefly. input new Vector2(Input.GetAxis( quot Horizontal quot ), Input.GetAxis( quot Vertical quot )) input Vector2.ClampMagnitude(input, 1) get camera direction need to add something here for in between camera switches! camF Camera.main.transform.forward camR Camera.main.transform.right camF.y 0 camR.y 0 camF camF.normalized camR camR.normalized transform.position (camF input.y camR input.x) Time.deltaTime 8 I saw someone with a similar game comment on an article with his solution, but I don't quite know how to put it into code. The quote quot Player just gets a rotation based on where the camera is looking and multiplies the character s motor force by that .forward and .right. I only update that rotation after a big delta in input so you can smoothly move between shots. quot This is his small (online) game which he's talking about, I'm trying to mimic the movement basically https ocias.com games foggy shore Can anyone give me some pointers? Updated It doesn't quite play how it does in the demo game, but it's getting there. input new Vector2(Input.GetAxis( quot Horizontal quot ), Input.GetAxis( quot Vertical quot )) input Vector2.ClampMagnitude(input, 1) if (!cameraChanged) lastCameraInput input camF Camera.main.transform.forward camR Camera.main.transform.right camF.y 0 camR.y 0 camF camF.normalized camR camR.normalized else if (Vector3.Dot(input, lastCameraInput) lt 0f) cameraChanged false transform.position (camF input.y camR input.x) Time.deltaTime 8


Prediction of collision place and time in Unity I have two moving objects. I have chosen trajectories for objects that they would definitely collide if they don't change speed or trajectory. Is there easy way to check at which point and time the objects will collide with given parameters (current object positions, their velocity vectors and speeds or any other parameter accessible from Unity)?


Gameobject not destroyed OnCollisionEnter I have this GameObject with the tag coin I am trying to destroy when the player collides with it using this code located in a player script attached to the player public void OnCollisionEnter(Collision col) var hit col.gameObject if(hit.tag "Coin") Destroy(hit.gameObject) However upon collision nothing is happening


All sides shadow outline in Unity NGUI How can I make such exactly the same shadow using NGUI?


Switch UNet From LocalHost to IP I have set my game up so that I can run one instance as host and one instance as client and I see two people in the room. How do I get from that setup to another computer (as client) connecting to mine (as host) without matchmaking. I understand I will need a static IP, and have set my router up for port forwarding (I tested it with an FTP server application I made). I am specifically asking for what options you select in the Unity NetworkManager to do this. Here is my current NetworkManager (I erased the last number in my IP so I dont get DDos)


Unity animation transition with 0 Exit Time doesn't transition immediately Question Why doesn't an animation transition with an Exit Time of 0 immediately transition to the next state? Minimal example Using Unity 2018.3, I set up an AnimatorController with two states Initial and Next. I wanted Initial to transition to Next immediately, so I tried setting an Exit Time of 0. However, this doesn't transition immediately As shown above, Initial state still runs instead of transitioning immediately to the Next state. (There is no Motion attached to the AnimationState, so perhaps it's using a default duration.) Below are screenshots of my animation transition settings. Strange behaviour with small non zero ExitTime I also tried using an Exit Time of 0.01 (i.e. transition after 1 of the animation has played), and it transitions almost immediately as I expect most of the time. However, occasionally it will still play the Initial state In this case, even though it transitions to Next immediately most of the time, it still occasionally waits for the Initial state to complete. (It happens much less frequently than the image above suggests, but the issue becomes more frequent if I set the ExitTime even lower, e.g. 0.003). Workaround From searching online, the recommended solution for immediate animation transitions seems to be to turn off Exit Time and use a condition (e.g. bool or trigger) to transition immediately instead. (Edit in my case, I've defined an animator bool parameter called ImmediateTransition and set it to true by default instead of using Exit Time 0.) This seems to work, but I would like to better understand how Exit Time works and why it's not working the way I expect.


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?


Collision not smooth in unity3d I am working on a project(Racing car). When it hit an object the object should be destroyed. The Object is being destroyed when it is hit, but the car stops for a moment after hitting like an obstacle. How can I make this smooth, like the object is there and it is destroyed on collision but the car moves with the same speed? Script attached to the object void OnCollisionEnter(Collision col) Destroy (gameObject) Nothing needs to stop or slow down. It doesn't need to exert any physical force. Thanks.


Does Unity for PC use Direct3D or OpenGL? I am a mac developer using Unity and I hardly use a PC. When you build a Unity game for Windows, does it use Direct3D or OpenGL? P.S. I'm not sure if it's called Direct3D or DirectX


How to scale our multiplayer support, similar to Among Us We are a small team with the goal of creating our first multiplayer game, and we want to support multiplayer that can rapidly scale up as Among Us has successfully done. We don't have a huge budget and we are struggling to find an appropriate way to implement multiplayer, including peer to peer (although it would be exhausting to combat cheating and make a smooth experience). Our game has no more, no less than 50 players in a very tight space. As an example, we're looking at the indie game Among Us. They went from such a small game with barely any players, to maintaining well over 3 million CCU (concurrent users). How can we achieve similar scalability?


Exporting WebGL For Mobile Browsers I was asked by a client to create a pretty simple 3D game that will be embedded on a website, a plain landing page that will contain the game and will be played on mobile devices. The game itself has no complexity whatsoever, not in the functional aspect and not in the lighting shaders aspect the basic functionality is a simple finger swipe in order to quot throw quot a ball. I have checked and concluded that opening a webGL game on mobile devices might cause issues and only high end devices can run the game smoothly. My question is Is there a go to solution or any solution in which I can develop the game on Unity and build it for webGL in a way that it will be compatible with mobile devices? Or my only option is to develop the game using plain JS?


Procedural planet to sphere texture I'm making a 4x space game. I have a procedurally generated galaxy with planets in 3D space. The view is above the planet plane at 45 dec y up i.e 45 deg isometric. I procedurally generate the planet surfaces on a hex grid which can be viewed 2D 2.5D when clicking on the planets, ala GalCiv etc by placing meshes for mountains, seas, forest and so on on the hex grid. For realism, I'd like the textures of the planets when viewed from space to (at least roughly) mirror the view you get in the surface view. I'm struggling to think how this might be achieved in Unity. I figure I could create a render texture after generating the planet's surface and store it on the users HD. This has a few problems though taking up HD space and not mapping well to a sphere (unless I always make the poles a uniform colour, which doesn't look good as the rest of the surface is quite highly detailed). Another idea would be to create many generic textures for the space view of roughly each type of planet generated (blue green large continent archipelago etc) and select a texture which most closely fits the procedurally generated map at run time. As long as the same texture isn't used for planets close to each other and the user doesn't compare the 3D view with the 2D view to closely then hopefully they won't notice! So, any other ideas of how this might be achieved? I'm not looking for code, just a brainstorm of how I might get a procedural 2D map to be represented on a 3D sphere, or at least create a convincing illusion.


How can i set OnClick equal to UnityEvent The Problem I'm making a dialogue system for a small 2d rpg. I Have a Dialogue class with two lists for pages and responses. The response class has a UnityEvent so i can use the ui in the inspector to set methods like a button. Then in a DialogueManager class i have a Show() method which makes a button for every response in the list from Dialogue. The problem is when i try to set the created button's OnClick() event to the UnityEvent in the response. The Question So the question is how can i set the button's OnClick() to the methods in the UnityEvent from the response?


Unity Visual Effect Play() has no effect I am making my first visual effects, and I make effect, when my ship is flying. So I am want to play it only when the ship is actually moving. I would suppose it's easy, you call Play(), it will play. You play Stop() it will stop. But when I call play, nothing happens. public void Update() ship.Rotate(Input.GetAxis( quot Horizontal quot )) var move Input.GetAxis( quot Vertical quot ) ship.Move(move) if (move gt 0) FlyEffect.Play() FlyEffect.SetVector3( quot Velocity quot , new Vector3(0, ship.Speed move, 0)) else FlyEffect.Stop() When I let in Initial Event Name OnPlay, it is playing as it should be. But nothing from the script... What I am missing here?


Prefab instantiate or create gameobject at runtime? I'm developing a skill system for a client server game, all available player's skills server send to it, then client load it and put it to a spellbook. So I stuck in loading stage, how for performance and or memory will be better Save all spells in a bunch of prefabs and then just instantiate them Create JSON binary etc file, parse them and create a gameobject at runtime From the side of editing, both methods are equal.


Restrict render in Blender is not working I click "Restrict renderability", so that everything except the item I want to export is grayed out. However, it still exports lights and everything when I import it into Unity. How can I fix this?


How do I get the networkId of an object? My clients have a way of spawning "defense" barriers and I would like to limit the number of defense barriers per client to 1 A way of doing this is to destroy the old defense (if any) and then spawn the new one. Since this defenses are spawned by the server, how can I tell the server to destroy only the defense that was created by that client? I guess that by storing the networkID of the spawned defense I can later tell the server to destroy it and repeat. Am I attacking this right? Having this Command void CmdDefenseSpawned(string playerID, string PlaceToDefenseName, Vector3 toDefense, Quaternion defenseRotation) Debug.Log("Player " playerID " placed a defense on " PlaceToDefenseName " Position " toDefense) GameObject defenseInstance Instantiate(defense, toDefense, defenseRotation) NetworkServer.Spawn(defenseInstance) I would like something like this NetworkInstanceId defenseInstanceNetId defenseInstance.NetworkIdentity.netID So I can later delete the object whenever the client wants to spawn it again.


Understanding pixel art in Unity 2d I am struggling to understand the basics behind pixel art in Unity. I understand what a unit is, and that if I draw my sprite with 16x16 pixels, I should set PPU to 16. Take stardew valley for example, in the image below you can clearly see that the player is not square. The creator of the game said he made everything in 16x16, but then how is there so much detail in the characters? Surely you do not patch several 16x16 squares together to make a character (as you would with a tilemap)? What is the "common" way of dealing with things that are not square, like the characters in the image. Do you just make 16x32 sprite and set PPU to 16? Wont that make it look a bit weird next to 16x16 sprites? Do you generally pick one size (i.e 16, 32, 64) And then stick to that for everything in the game? The visual Issue I've seen is this, where a 32x32 sprite looks very out of place (too sharp) next to a 16x16 sprite. So I am wondering, how do you mix sizes wihout getting this effect where one image looks much sharper than the other. If I for example wanted a character to be 16x32, or any non square value, when my tiles are 16x16


Unity keepy uppies game Hello guys I'm tryting to make a game in unity of keepy uppies but I can't make the ball bounce to different directions like keft and right only staright up. using System.Collections using System.Collections.Generic using UnityEngine public class physics MonoBehaviour public Rigidbody rb public float force 10 void Start() rb.velocity new Vector3(0, 0, force) void Update() if (Input.GetMouseButtonDown(0)) RaycastHit hit Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) if (Physics.Raycast(ray, out hit, 100.0f)) if (hit.transform ! null) PrintName(hit.transform.gameObject) if (rb hit.transform.GetComponent lt Rigidbody gt ()) LaunchIntoAir(rb) private void PrintName(GameObject go) print(go.name) private void LaunchIntoAir(Rigidbody rb) rb.velocity new Vector2(rb.velocity.x, 3) This is what I have done until now.


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


Efficient way to load chunks of a 2d level to prevent game from loading stutters I am building a 2D sidescroller game in Unity3D. It's tile based. To get better performance I divided the level into chunks. I activate these chunks when the player enters 2D Triggers and deactivate it again when he exits the 2d trigger. So I normally only have a max of 2 chunks loaded. This works good BUT I do have some loading stutters of a few frames when I load a new chunk. How can I prevent that from happening? Thank you!


Why does a UI button that is child to a canvas not appear in game view? I am trying to place a button onto a canvas background using C script. I want the button specific to the canvas (i.e., if I move the camera to look at another canvas, I do not want the button visible). My C script is below. I have attached it to an empty game object. When I run the game, the Heirarchy panel of Unity shows that the canvas and button are created OK, and that the button is a child of the canvas. The canvas appears in game view at the right size (200 x 200). But in game view, there is no button! The button is definitely present clicking on its name the Heirarchy panel shows me a location and size in the scene view that are exactly as specified in my C script. But nothing happens when I click the region in game view where the button is supposedly present. Unity's Inspector panel shows that a "Button (Script)" has been attached to my button object, with Rect Transform parameters as specified in my C code. I tried messing with the colors, but still no button. The "On Click()" window contains nothing except the message "List is Empty". How do I make the button appear in game view? How do I make the button work (i.e., generate the Console message "button pressed")? using UnityEngine using System.Collections.Generic using UnityEngine.UI using UnityEngine.EventSystems public class TestScript MonoBehaviour private GameObject myGO private Vector2 buttonSize private Vector3 buttonPosition void Start () setup a canvas myGO new GameObject () Canvas myCanvas myGO.GetComponent lt Canvas gt () myCanvas.renderMode RenderMode.WorldSpace RectTransform parentRectTransform myGO.GetComponent lt RectTransform gt () parentRectTransform.sizeDelta new Vector2 (200, 200) set size of parent rectangle create and place the button Vector2 buttonSize new Vector2 (10, 10) Vector3 buttonPosition new Vector3 (150, 70, 1) CreateButton (myGO.transform, buttonPosition, buttonSize) end Start() public void CreateButton(Transform panel ,Vector3 position, Vector2 size) GameObject button new GameObject() button.name "Button" button.transform.parent panel button.AddComponent lt RectTransform gt () button.AddComponent lt Button gt ().onClick.AddListener (handleButton) button.transform.position position void handleButton() Debug.Log("Button pressed!") end class TestScript


How are Roguelike Bullet Hell mechanics stored in Unity? I'm going to be creating a roguelike bullet hell game wherein the play will be a bullet hell game, but you will be traveling between "rooms" wherein the action takes place. The "rooms" will be randomly generated like in roguelikes such as The Binding of Isaac, but with bullet hell play similar to Touhou or Batsugun, with a possible twist. It will be similar to Enter the Gungeon, but there will be some differences. I'd like to know how Unity will deal with storing possibly thousands of different "rooms" and generating these each time, along with the enemies and bullets these enemies will begin to shoot after you enter the room. Only one room will be visible at a time. How would Unity deal with mapping possibly thousands of rooms, and will it be able to store this while generating bullet patterns? I know that in classic bullet hell arcade games, when there were many bullets on the screen, the game tended to slow down because of hardware limitations.


movement control with the 2D driving game I am working on a 2D driving game.I have a button(forward).I need to move the vehicle by pressing on the button. When the button is pressed the vehicle should accelerate upto its maximum speed and when the button is release the vehicle should gradually slow down. float rotateSpeed 0.1f float speedForce 15f float torqueForce 200f float driftFactorSticky 0.9f float driftFactorSlippy 1 float maxStickyVelocity 2.5f float minSlippyVelocity 1.5f bool moveForward false bool moveBackward false bool turnLeft false bool turnRight false Vector3 myRot void FixedUpdate () Rigidbody2D rb GetComponent lt Rigidbody2D gt () float driftFactor driftFactorSticky if(RightVelocity().magnitude gt maxStickyVelocity) driftFactor driftFactorSlippy rb.velocity ForwardVelocity() RightVelocity() driftFactor Move rover forward and backward if(Input.GetKey(KeyCode.UpArrow) moveForward true Input.GetButton("Accelerate") ) Debug.Log ("Uparrow....................................................") rb.AddForce( transform.up 0.3f) if(Input.GetKey(KeyCode.DownArrow) moveBackward true Input.GetButton("Brakes") ) Debug.Log ("break....................................................") rb.AddForce( transform.up speedForce 30f ) float tf Mathf.Lerp (0, torqueForce, rb.velocity.magnitude 2) rb.angularVelocity Input.GetAxis ("Horizontal") tf if (Input.GetKey (KeyCode.RightArrow) turnRight true) transform.Rotate(0,0, 0.5f) if (Input.GetKey (KeyCode.LeftArrow) turnLeft true) transform.Rotate(0,0,0.5f) Vector2 ForwardVelocity() return transform.up Vector2.Dot( GetComponent lt Rigidbody2D gt ().velocity, transform.up ) Vector2 RightVelocity() return transform.right Vector2.Dot( GetComponent lt Rigidbody2D gt ().velocity, transform.right ) this is working fine but the problem is that when I release the forward button the speed of vehicle is not getting slow down. Can anybody help me please


Complex Machine handling through VR controller I have a very Complex Machine which I want to operate through my VR controller (HTC Vive Controller). As you can see its short animated video here. I want to pull the machine cover through VR controller which is easy to do but i want to scale and pull some of the other related objects of the machine too (like spring, piston etc, you can see in the video) as i pull its cover through VR controller. The problem is that i am unable to do this using Joints and Animation play. I almost tried anything but nothing worked for me. My question how can i imitate animation all work through code or through physics. Like if i pull an object the rest related object should be stretched like chain. And piston should open or closed according to force.


Could not establish connection with local server process when opening or making Unity project Whenever i try to either create or open a Unity project, I get faced with this error. Does Unity need a proxy server, because I dont have one. (If so, how do I get one?) And apparently I need to add some environment variables, (HTTP PROXY, HTTPS PROXY and UNITY NOPROXY localhost,127.0.0.1) what values do i add to these? Unity Package Manager Diagnostics (v0.1.5) Ran 7 checks 1 succeeded 6 failed UPM registry reachable (FAIL) Make an HTTP request to the UPM package registry Connection error. This could be because a proxy is misconfigured. Ping UPM registry (FAIL) Measure the latency of the UPM package registry API No successful pings could be made in 0.062 seconds (30 failed) Ping UPM download (FAIL) Measure the latency of the UPM package download endpoint No successful pings could be made in 0.039 seconds (30 failed) UPM registry download speed (FAIL) Test the Internet connection using the UPM package registry Connection error. This could be because a proxy is misconfigured. Speedtest.net (FAIL) Test the Internet connection using Speedtest.net Connection error. This could be because a proxy is misconfigured. HTTP proxy environment variables (PASS) Detect whether proxy related environment variables are set (HTTP PROXY, HTTPS PROXY, ALL PROXY, NO PROXY, UNITY PROXYSERVER, UNITY NOPROXY) Proxy support has been configured through the following environment variables HTTPS PROXY C Program Files Unity Hub Unity Hub.exe HTTP PROXY C Program Files Unity Hub Unity Hub.exe UNITY NOPROXY C Program Files Unity Hub Unity Hub.exe UPM health check (FAIL) Start the UPM process and call its health endpoint Server started but did not respond to health requests Error Invalid protocol c How do I fix this?


Setup sub platforms inside Unity I want to automate some of my Unity build process. I know that setting up automatic builds for platforms is relatively easy, just start Unity headless and tell it to build platform X! This is fine for most things however I have some platform specific things for a given platform. For example I have achievements for Steam, GoG and my own thing if you are running truly standalone. I can easy switch between them by setting define STEAM BUILD to make a build with steam features enabled. This is setup for each platform that I support. At the moment I have to change the script manually and re build every time. I want to make a build server do this all for me but how do I tell Unity to build my PC version with a certain define X set?


Animating object, setting isKinematic false, and then letting physics take over I'm trying to create a "tree felling" effect, where the tree trunk falls over after being cut down by the player. I've used one prefab which contains my tree stump and tree trunk as children. In its default state, my tree trunk as a rigidbody with isKinematic true. When the player cuts down the tree, I begin an animation on the trunk which "tips it over". On the last frame, it sets isKinematic false at this point it should "fall over" because physicals gravity is in control and the center of mass is definitely over its base. However, the animation seems to be preventing it, like it's still "controlling" the transform. Adding a transition from the "fell" state to an "exit" state just resets the position rotation. Setting the animator to "animate physics" kind of works, but the tree just flies away, probably colliding with the stump or something. Disabling the animator after the animation kind of works, but this also causes the tree to go flying with some crazy physics. When left alone, OnCollisionEnter is called on the tree for colliding with my ground, yet the gameobject appears to still be stuck at 45 degrees and never touched the ground. It seems like the rigibody collider is not where the mesh transform is? Animating the object and then turning off isKinematic should work, it's been recommended to me on reddit and is the accepted answer on this question, so I'm not sure what could be wrong. Edit I can ease the physics problems by telling the trunk to ignore it's own stump (Physics.IgnoreCollision(Trunk.transform, Stump.transform) ), but the base of the tree still "jumps" away from the stump, rather than "continue tipping over". I'm not sure what else could be at play.


Unity2D How to save volume of audio source when game is restarted? How do I save volume of my audio source (clicking the mute button) when game is restarted. You see I have one scene in my game and once the player dies there is a button the user can click on that resets the game, however it also resets the audio source, so when I play the game and click my mute button, the audio source volume is at 0 but when I die and click the reply button (the restart reset button) the music is restarted as well, instead of staying muted (save the current volume). I tried using DontDestroyOnLoad(this) but my muted script is attached to my game over panel animation (the panel comes down when player dies) making the my game over panel animation not being destroyed when you restart the game. I tried other methods like putting my mute button script on a parent empty object and putting the object that has the audio source on under it as a child but it did the same thing. Anyway this is my mute button script private bool mute public void Muted () mute !mute if (mute) gameObject.GetComponent lt AudioSource gt ().volume 0 else gameObject.GetComponent lt AudioSource gt ().volume 1 And this is my restart level when button is pressed (p.s. I used the OnClick method activating methods) public void NavigateTo(int scene) Application.LoadLevel ("Game Level") Thank you in advance )


Unity scaling and animations In my Unity project I have a script that programmatically changes the scaling of an object during the game. Recently I wanted to add a spawning animation clip to my object, which modifies the object's scaling (but only during a short delay). So I added an animation controller to the object, containing the spawning animation clip. I can now successfully run the spawning animation but the in game programmatic scaling changes don't work anymore, even when my animation is not running. Any idea?


Mixamo Models not Importing Correctly in Unity Mixamo (now Adobe Mixamo) allows us to choose character and then animations from its website from free samples. I have done one simple animation and added the model to Unity. The animation works fine but the model is very changed once being imported, have a look here. I am using following import settings, Format Fbx for Unity Skin With Skin FPS 30 Keyframe Reduction Uniform I tried "Fbx" format only too, but no luck.I also applied "humanoid" in rigging, but I think it is not relevant here. Since I am not good with modeling that is why I am using this service, and I have no idea how to tackle this. Once it did worked well, but unfortunately I could not remember how, so I am stuck again.


Control convention for circular movement? I'm currently doing a kind of training project in Unity (still a beginner). It's supposed to be somewhat like Breakout, but instead of just going left and right I want the paddle to circle around the center point. This is all fine and dandy, but the problem I have is how do you control this with a keyboard or gamepad? For touch and mouse control I could work around the problem by letting the paddle follow the cursor finger, but with the other control methods I'm a bit stumped. With a keyboard for example, I could either make it so that the Left arrow always moves the paddle clockwise (it starts at the bottom of the circle), or I could link it to the actual direction meaning that if the paddle is at the bottom, it goes left and up along the circle or, if it's in the upper hemisphere, it moves left and down, both times toward the outer left point of the circle. Both feel kind of weird. With the first one, it can be counter intuitive to press Left to move the paddle right when it's in the upper area, while in the second method you'd need to constantly switch buttons to keep moving. So, long story short is there any kind of existing standard, convention or accepted example for this type of movement and the corresponding controls? I didn't really know what to google for (control conventions for circular movement was one of the searches I tried, but it didn't give me much), and I also didn't really find anything about this on here. If there is a Question that I simply didn't see, please excuse the duplicate.


canvas not found in game view with unity I am working on a GearVR app with Unity3D.I have an environement and I have placed a canvas in the scene.I have set the canvas Render mode to "World Space".But when I runned my project,the canvas is getting displayed on the scene view,but in the game view the canvas is not getting on the scene.But whereas in the camera view its showing the canvas.What will be the issue?. When I set me canvas Rendere mode to Screen Space Overlay the canvas is getting displayed in the scene but as the lookup change,the canvas is also moving along with the camera Can anybody please help me out.


How does Speed in Animator Window in Unity work? If speed 1 is considered normal playback, is it by a second? So animation play once in a second? If I have my animator speed set as 100, would it make the speed become 0.06 then ?


Unity UI Button not working on PC build but working on Android mobile build I am using Unity to build a game that is going to be used on PC and Android mobile devices. The problem I have is that when I use a UI Button, it works perfectly on mobile, but on PC and in the editor, is not working. Why could this be happening?


How to use Left Shift to run Unity? So, I need to use LShift to run, but I can't exactly figure out how to do so.... I don't know what to use.... Here my code using UnityEngine using System.Collections This script moves the character controller forward and sideways based on the arrow keys. It also jumps when pressing space. Make sure to attach a character controller to the same game object. It is recommended that you make only one call to Move or SimpleMove per frame. public class Move MonoBehaviour CharacterController characterController public float speed 6.0f public float jumpSpeed 8.0f public float gravity 20.0f public Transform charBody private Vector3 moveDirection Vector3.zero public float mouseSense 11f public float runSpeed 12f public bool isRunning false void Start() characterController GetComponent lt CharacterController gt () void Update() if (characterController.isGrounded) We are grounded, so recalculate move direction directly from axes moveDirection transform.forward Input.GetAxis( quot Horizontal quot ) transform.right Input.GetAxis( quot Vertical quot ) moveDirection speed moveDirection transform.right Input.GetAxis( quot Horizontal quot ) transform.right Input.GetAxis( quot Vertical quot ) moveDirection speed if (Input.GetButton( quot Jump quot )) moveDirection.y jumpSpeed Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below when the moveDirection is multiplied by deltaTime). This is because gravity should be applied as an acceleration (ms 2) moveDirection.y gravity Time.deltaTime Move the controller characterController.Move(moveDirection Time.deltaTime) float MOUSEY Input.GetAxis( quot Mouse Y quot ) mouseSense Time.deltaTime float MOUSEX Input.GetAxis( quot Mouse X quot ) mouseSense Time.deltaTime charBody.Rotate(Vector3.up MOUSEX) So, when left shift is clicked I want the speed to change to runSpeed... Can I please have some help doing so? Thanks


Move camera from wherever camera is to pinned point So, I need to switch move animate camera from point X (not point A,as I don't know where the camera is at that momemnt) to point B (place where you want your camera to move). This is for cinematics...like when you press a button in game which does something (opens doors maybe) but you can't see where nor what did you activate, so you show the player with the camera where and what happened. I tried to animate camera to position, camera just goes crazy. Then I tried to make an empty object placed at the position where the camera should be and move camera with code to that objects position. I tried enabling Camera 2 and disabeling Camera 1 but it just doesn't work. Enable Disable Code public var door DoorAnim public var triggered boolean false function OnTriggerEnter() triggered true function OnTriggerExit() triggered false function Update() if (triggered amp amp Input.GetKeyDown(KeyCode.JoystickButton1)) Debug.Log("Door 1 built") camera1 GameObject.Find("Camera1") camera1.enable false camera2 GameObject.Find("Camera2") camera2.enable true door GameObject.Find("door1") door.animation.Play()


How to animate a bezier curve over a given duration I have created a bezier curve by adding the following script to an empty game object in the inspector. This draws to complete curve at once when I run the code. How can I animate it over a given period of time, say 2 or 3 seconds? public class BCurve MonoBehaviour LineRenderer lineRenderer public Vector3 point0, point1, point2 int numPoints 50 Vector3 positions new Vector3 50 Use this for initialization void Start () lineRenderer gameObject.AddComponent lt LineRenderer gt () lineRenderer.material new Material (Shader.Find ("Sprites Default")) lineRenderer.startColor lineRenderer.endColor Color.white lineRenderer.startWidth lineRenderer.endWidth 0.1f lineRenderer.positionCount numPoints DrawQuadraticCurve () void DrawQuadraticCurve () for (int i 1 i lt numPoints 1 i ) float t i (float)numPoints positions i 1 CalculateLinearBeziearPoint (t, point0, point1, point2) lineRenderer.SetPositions(positions) Vector3 CalculateLinearBeziearPoint (float t, Vector3 p0, Vector3 p1, Vector3 p2) float u 1 t float tt t t float uu u u Vector3 p uu p0 2 u t p1 tt p2 return p


Is it possible to use a string somehow converted to match name of a bool? I have a Json file holding data for my LineData type i created. Serializable public class LineData public string lineID public string lineDialog public float lineDuration public string condition Note the last one, 'condition', that is what I hope to use to hold a name of a specific bool in my code, so that the line can only be spoken when that bool is true. Is this a decent way to achieve this? Or is it even possible? I've read about making 'custom markup' on my Json things like (!!) and ( ) built in the text to mean stuff in my code, but I don't know where to start with it and cannot find any tutorials (I've only seen it on some Youtube GDC lecture style videos from professional game developers working for companies) But failing the custom markup thing, if I can somehow use the string of the name of the bool, and use that to check the state of it's corresponding bool in the code, that would be enough for me so far. Any ideas or help is fantastic and very welcome. Many thanks!!! (PS. The json looks like this (Im sure you don't need it, but just in case)) "lineDatas" "lineID" "BEDROOM DAVE 0001", "lineDialog" "Yaawwn, up i get for another fun packed day.", "lineDuration" 3, "condition" "" , "lineID" "BEDROOM DAVE 0002", "lineDialog" "Well I think I need a cigarette before I get to work!", "lineDuration" 3, "condition1" "notSmokedCig"


Limit Color Pallete Using Shader (Unity) Basically, what I want to do is take a primary input image texture (which is a render texture in game) and a secondary pallete texture (contains X number of colors, and is X by 1 pixels in size). What I want to do is replace all of the pixels in the image with the most similar color in the color pallete texture. I made a stab at producing the effect, but at the moment, it only seems to return the first color in the pallete. Below is my (nonfunctional) version. I'm new to shaders, so sorry for the potentially very sloppy basic shader code. Shader "Custom Limiter" Properties MainTex ("Texture", 2D) "white" PalTex ("Pallete", 2D) "white" SubShader No culling or depth Cull Off ZWrite Off ZTest Always Pass CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" struct appdata float4 vertex POSITION float2 uv TEXCOORD0 struct v2f float2 uv TEXCOORD0 float4 vertex SV POSITION v2f vert (appdata v) v2f o o.vertex UnityObjectToClipPos(v.vertex) o.uv v.uv return o sampler2D MainTex sampler2D PalTex fixed4 frag (v2f i) SV Target float4 baseCol tex2D( MainTex, i.uv) float4 palCol tex2D( PalTex, 0) float palDiff 1000 for (int p 0 p lt 37 p ) float baseColDiff abs(tex2D( PalTex, p).r baseCol.r) abs(tex2D( PalTex, p).g baseCol.g) abs(tex2D( PalTex, p).b baseCol.b) palDiff min(palDiff, baseColDiff) palCol (abs(palDiff baseColDiff) lt 0.001) ? tex2D( PalTex, p) palCol return palCol ENDCG Any help would be greatly appreciated! I feel like it's a relatively simple problem to solve, but I couldn't find any examples of existing shaders like it, or any resources describing it. Edit This shader works... sort of. It has been picking the nearest color, but it has only been picking two yellow colors out of the pallete. I tried removing those colors, and it then chose to use only an orange. I don't know if this will help anyone, but I thought it was at least mildly interesting.


How can I disable an NGUI button when I pause my game? There is an NGUI button in my game, which when pressed increases the player's power. When I press the escape key, my game pauses completely. But the button still functions normally. Here's how I check for pausing void Update () if(Input.GetKeyDown("escape")) if(isPaused amp amp Time.timeScale 1.0f) Time.timeScale 0.0f AudioListener.volume 1 else Time.timeScale 1.0f AudioListener.volume 0 I'd like the button to be deactivated when the game is paused. It should be visible, but not be clickable or anything. How can I achieve that?


Unity Car Rollover Protection I have a standart Unity car with Unity Car physics. What would be the best approach to protect my car from a rollover? I dont want to mess up and try and error 10 different approaches, so maybe here is an expert who really knows how to do it right? I couldnt find anything decent on the internet.


UnityEditor.SyncVS.SyncSolution putting wrong language version in generated files I'm working on getting our Unity projects building in bamboo for our build server. We have a cli step that runs through the Unity commands for creating a build. It works fine on several projects, but for some reason this particular project I'm working on I'm getting an error that states I need to use c version 7.2 or newer. If I log in to the build server and open the .csproj files in notepad and check the language version, it's setting them to 7.0. However, if I deactivate the cli step so that the build job only clones the project, then manually log in and open unity and go through the process so it generates the .csproj files, then check them, the language version is set to 8.0. The project works fine locally on my own pc. And it works when setup manually on the build server pc, but when ran through the cli step, it generates them at an earlier c version. This leads me to believe there is a problem with the UnityEditor.SyncVS.SyncSolution step in my commands. I'm just not sure what it could be, or why it's behaving differently for this project as opposed to other projects that are using the same code base (where the problem is said to occur), same Unity version, same build server, etc. Anyone else experience this issue or have any thoughts on a solution?


HDR bloom techniques using post processing in Unity3D I've seen many posts on how to accomplish HDR bloom effects in Unity3D using its (now legacy) Bloom component as part of the standard assets package. I'm trying to replicate it using the new post processing package, but I can't seem to get it to work. I have an an emissive material that's emitting at a value far 1 sitting at 10 Bloom is set in a Post Processing Profile, and the threshold is 1 Finally, HDR is enabled on my camera, along with a deferred rendering path. Yet this doesn't work. I only see the bloom effect if I set my bloom threshold lt 1, after which all my materials bloom. It's as if HDR is not actually enabled. Anyone know why?


Rotating gradually in response to input, instead of snapping I'm trying to replicate Silent Hill's mechanic where if you press a button, the character does a 180, but instead of getting a smooth turn around, my character is snapping from one rotation to another. This is the code I have so far if (Input.GetKeyDown(KeyCode.Tab)) transform.Rotate(0f, 180f, 0f) I also have a Sprint() function and I want to disable this feature if the character is sprinting. Here's the code for that private void Sprint() float newTurnSpeed turnSpeed 1.4f vertical Input.GetAxis( quot Vertical quot ) horizontal Input.GetAxis( quot Horizontal quot ) Vector3 direction new Vector3(0f, 0f, vertical) Vector3 movement transform.TransformDirection(direction) sprintSpeed transform.Rotate(0f, horizontal newTurnSpeed, 0f) add the new turn speed isGrounded characterController.SimpleMove(movement) Any help is appreciated!


Why this if logic isnot short circuiting? I've this script in UNITY to check if the hit RayCastHid2D variable has some gameobject with hole tag or a parent gameobject with hole tag when I Raycast... if (hit.collider ! null amp amp (hit.collider.gameObject.tag "hole" (hit.collider.gameObject.transform.parent.gameObject ! null amp amp hit.collider.gameObject.transform.parent.tag "hole"))) Everything is fine until if (hit.collider ! null amp amp (hit.collider.gameObject.tag "hole" but when I enter (hit.collider.gameObject.transform.parent.gameObject ! null amp amp hit.collider.gameObject.transform.parent.tag "hole") it throws a NullReferenceException.... But why? It supposed to short circuit here hit.collider.gameObject.transform.parent.gameObject ! null amp amp if there's no parent gameobject!


Issues accessing arrays in Unity I'm trying to make a mini quiz game, but I'm stuck. I'm showing questions, randomly, but the first question never comes up. Furthermore, when I set the size of the questionsNumberChoosen array to 10 and run the game, it crashes. public struct Question public string questionText public string answers public int correctAnswerIndex .. we also construct the Question, directly providing all values. public Text questionText public Button answerButtons private Question currentQuestion private Question questions new Question 10 private int questionNumbersChoosen new int 9 private int questionsFinished void Start () questions 0 new Question("1", new string "A", "A", "A", "A", "A" , 2) questions 1 new Question("2", new string "A", "A", "A", "A", "A" , 0) questions 2 new Question("3", new string "A", "A", "A", "A", "A" , 4) questions 3 new Question("4", new string "A", "A", "A", "A", "A" , 0) questions 4 new Question("5", new string "A", "A", "A", "A", "A" , 0) questions 5 new Question("6", new string "A", "A", "A", "A", "A" , 2) questions 6 new Question("7", new string "A", "A", "A", "A", "A" , 0) questions 7 new Question("8", new string "A", "A", "A", "A", "A" , 4) questions 8 new Question("9", new string "A", "A", "A", "A", "A" , 0) questions 9 new Question("10", new string "A", "A", "A", "A", "A" , 0) setQuestionIndex () assignQuestion (questionNumbersChoosen 0 ) void assignQuestion(int questionNum) currentQuestion questions questionNum questionText.text currentQuestion.questionText for (int i 0 i lt answerButtons.Length i ) answerButtons i .GetComponentInChildren lt Text gt ().text currentQuestion.answers i public void checkAnswer(int buttonNum) if (buttonNum currentQuestion.correctAnswerIndex) print ("Correct!") else print ("Incorrect!") if (questionsFinished lt (questionNumbersChoosen.Length 1)) moveToNextQuestion () void setQuestionIndex() for (int i 0 i lt questionNumbersChoosen.Length i ) int questionNum Random.Range (0, questions.Length) if (!isContain (questionNumbersChoosen, questionNum)) questionNumbersChoosen i questionNum else i bool isContain (int num, int numbers) for (int i 0 i lt num.Length i ) if (numbers num i ) return true return false public void moveToNextQuestion() assignQuestion (questionNumbersChoosen questionNumbersChoosen.Length 1 questionsFinished )


What is the best option to implement buttons as player controls? I am familiar with programming, but new to Unity. There seems to be a million ways to implement a right and left button for turning the plane. I'm wondering what the standard easiest best way to do this would be. Do I make a single script that references the two sprites "left" and "right" and then detects mouse clicks and figures out whether they are over the sprite? Should the buttons even be sprites game objects? Or is there a better option for UI objects? Should the left and right buttons both have their own scripts? ps. I absolutely can't stand video tutorials, and it seems like that's all there is for unity '( so if there is a good written tutorial on unity desgin patterns, let me know please )


Room lighting in Unity I am trying to make a plain white room in Unity. I used six planes for the walls, but I can't figure out how to get the lighting to not look so harsh and uneven. The top picture is my best attempt using two directional lights, and the bottom picture is the look that I am trying to replicate. It is from a demo scene in the Google VR SDK 1.50 for Unity. It uses only a single point light, but when I turn it off in the scene view, it doesn't change the appearance of the room at all. How can I make my room look more like the Google VR demo? EDIT I made a big improvement by changing all my walls to be static so that they receive indirect lighting, and adding a single point light above the roof.


How can I stop and resume a coroutine over and over again? I want a coroutine to enter by default and then to stop when any input is given to it but then after some code to return again as active. So basically to start and stop a coroutine as many times as it's needed.


Unity applying forces using animation I'm trying to make a croquet mallet swing to hit the ball using an animation that rotates the mallet mesh. The mesh appears correctly positioned to hit the ball in the center but the ball doesn't go straight. Using a script with rigidBody.AddForce works fine. I do have Animate Physics selected on the animator and have explored many other options. Is there a way to debug the physics in this situation? Am I going about it the wrong way to use an animation to apply a force? This is what it looks like now


With gravity enabled, how do you move a RigidBody forwards at a specific speed? I have a perfectly smooth cube on top of a perfectly smooth plane. I am applying a forward force of 1 unit per second, using rigidBody.AddForce(new Vector3(0, 0, 1), ForceMode.VelocityChange). I apply this force every FixedFrame(), taking into account Time.fixedDeltaTime, of course. When the "Use Gravity" checkbox on the RigidBody is not checked, the object behaves as expected after exactly 3 seconds, it has a speed of exactly 3 units per second. However, when I enable the "Use Gravity" checkbox, the object barely moves. Both the object and the surface are using Physic Materials with zero friction, and the moving object's RigidBody has zero drag and zero angular drag. Why does this happen? And more importantly, how would I apply a force to this object so that it moves forward at, say, exactly 3 units per second, with gravity enabled? Thank you.


Unity won't Instantiate() outside of Start(), even though code is the same I am trying to add a gameobject to my game using a socket connection. I have a SocketHandler class, which simply connects to my NodeJS socket server, which can also call a method on another class, which will add a new gameobject to the game. Here is how it basically works void Start () GameObject car Instantiate(CarGameObject) car.transform.parent this.transform car.GetComponent lt TestCar gt ().text.text "Volkswagen" This works fine and it adds the gameobject to the game upon starting. However, if I do something like this in my SocketHandler, it doesn't work var addCar new AddCar() socketio.On("addCar", (data) gt string str data.ToString() Car data2 JsonConvert.DeserializeObject lt Car gt (str) addCar.AddNewCar(data2) ) and then inside my AddCar class, I have the AddNewCar() method public void AddNewCar(Car input) GameObject car Instantiate(CarGameObject) car.transform.parent this.transform car.GetComponent lt TestCar gt ().text.text input.name it does not work. If I do a Debug.Log(input.name) inside the AddNewCar() method, it does log the name the server sends. It should do the exact same thing, but the AddNewCar() doesn't get added to the game. It simply does nothing. What could be wrong?


Building multiple android apps via script does not trigger Resolving Android Dependencies I have a Unity Project which builds a number of smartphone android apps Anytime I need to build an app I have a script (SetupApp) that move a bunch of assets in the Resources folder and changes the package name. As far as I understood changing the package name triggers the tedious process of Resolving Android Dependencies , because all the various libraries in Plugins Android need to be recompiled. So far so good. Recently I tried to create a multi builder, basically it s a script (MultiBuilder) that takes all the applications that need to be created and, before each, calls SetupApp and then calls BuildPipeline.BuildPlayer My issue is that when MultiBuilder calls SetupApp the Resolving Android Dependencies is not triggered, creating all the app with the same (wrong) dependencies. Some thoughts Is there a way to force by script the Resolving Android Dependencies process? Is there a way to wait for the resolving process to be finished and the continue the building process? Is there a better way to do so? This goes really beyond my understanding of Unity, any help is very welcome. Thanks


How do I use GetComponent on multiple children? I'm a beginner and I'm making a game in Unity where I set random colors for four enemies. I made an empty object called "enemies" for me to use it as a folder for the four enemies. I want to get the colors of the enemies and pick randomly one of them for my player. I wrote this piece of code and I wanted it to store the colors in a list, but whenever I try to print it I find out that it only stores the color of the first child in the "enemies" hierarchy. How do I fix this? enemies GameObject.Find("enemies") GameObject allenemies new GameObject enemies.transform.childCount List lt Color gt colors new List lt Color gt () foreach (Transform child in transform) allenemies i child.gameObject i foreach (GameObject child in allenemies) thecolor enemies.GetComponentInChildren lt Renderer gt ().material.color colors.Add(thecolor) finalcolor Random.Range(0, colors.Count) Debug.Log(finalcolor) mr.material.color colors finalcolor


Does Unity own my game? I made my first game in unity, and I was wondering if I can sell it without owing anything to unity?


Unity Mask shows black content in world space canvas (Vuforia) So I've built my scroll rect, like this reference tells me to do http docs.unity3d.com Manual script ScrollRect.html Scroll View (Rect Transform with scroll rect attached) Viewport (Image Mask attached) Content (Image attached) In scene view it looks like I want it to look like, but in play mode it looks like this, which is the correct shape, but obviously not the correct content Update My Canvas Update The Image is getting displayed normally, when I disable the mask. Update The source of this problem seems to lie in Vuforia (Image Object Tracking library) since Vuforia appends a ClippingMask to the cameras


Unity How to use delegates with EventManager ? and use variable number of arguments in listenners? As answered here, I would like to know how to implement an EventManager with delegate instead of UnityAction for pass arguments. I tried but I did not succeed. Also, can someone tell me if it's a better solution than following ? And is it possible to change this code for invoke listenners with a variable number of arguments? using UnityEngine using UnityEngine.Events using System.Collections using System.Collections.Generic namespace Assets.Scripts System.Serializable public class Event UnityEvent lt System.Object gt public class EventManager MonoBehaviour public static EventManager Instance private Dictionary lt string, Event gt eventDictionary private void Awake() ... public static void StartListening(string eventName, UnityAction lt System.Object gt listener) Event thisEvent null if (Instance. eventDictionary.TryGetValue(eventName, out thisEvent)) thisEvent.AddListener(listener) else thisEvent new Event() thisEvent.AddListener(listener) Instance. eventDictionary.Add(eventName, thisEvent) public static void StopListening(string eventName, UnityAction lt System.Object gt listener) if (Instance null) return Event thisEvent null if (Instance. eventDictionary.TryGetValue(eventName, out thisEvent)) thisEvent.RemoveListener(listener) public static void TriggerEvent(string eventName, System.Object arg null) Event thisEvent null if (Instance. eventDictionary.TryGetValue(eventName, out thisEvent)) thisEvent.Invoke(arg)


What's the size of library in unity for android? In unity3d what is the size of library compiled into apk. Is that affect when i make game without any physics(2d or 3d) or when making 2d or 3d game.


Resuming a previous scene from a current scene using the Unity3D I am building a first person shooter game using unity and I am facing the problem of resuming a scene from its current state. It would be easy to pause the scene by using the Time.timeScale 0.0 within the scene itself. But I am loading a pause scene to ask whether the user wants to restart, resume or quit. But when I click on resume, it loads the scene I want, but it is totally fresh (i.e when the Ammo is supposed to be half full, it is full. Or the enemy has lost a part of his life, but then it starts with life completely full) How do I resume the previous scene from where it left off using SceneManager? This could have been somewhat easy by using the Application.loadLevel() and making sure that application does not destroy the previously loaded state. Here is the script I made for the pause scene. using UnityEngine using UnityEngine.UI using UnityEngine.SceneManagement using System.Collections public class pauseScript MonoBehaviour Use this for initialization void Start () Update is called once per frame void Update () public void exitPressed() Application.Quit() public void restartPress() SceneManager.LoadScene("prototype1") public void resumePress() SceneManager.LoadScene("prototype1") Here is the code snippet for calling the pause menu scene. and this is in another script. SceneManager.LoadScene ("PauseMenu") Is there anyway to save the current scene before calling the PauseMenu scene as shown in the above statement? This may be a simple enough query to you but I am completely new to game development as a whole and I am using unity for the first time, so please go easy on me. Thanks


object reference not set to an instance of an object hello i have a error "object reference not set to an instance of an object" when my ball collide with the spikes.its supose to remove one heart but it doesnt. health code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class Health MonoBehaviour public int health public int numOfHearts public Image hearts public Sprite fullHeart Use this for initialization void Start () Update is called once per frame void Update () if (health gt numOfHearts) health numOfHearts for (int i 0 i lt hearts.Length i ) if (i lt health) hearts i .sprite fullHeart if (i lt numOfHearts) hearts i .enabled true else hearts i .enabled false public void Damage(int dmg) numOfHearts dmg spikes code using System.Collections using System.Collections.Generic using UnityEngine public class Spikes MonoBehaviour private Health Player Use this for initialization void Start () Player GameObject.FindGameObjectWithTag("Player").GetComponent lt Health gt () Update is called once per frame void Update () void OnTriggerEnter2D(Collider2D col) if (col.CompareTag("Player")) Player.Damage(1) here i have the error.


Camera bounds grow along with the game scene editor in Unity I am extremely confused by the Unity editor. Look I have an image, And I want my camera to fit it perfectly. I have achieved so by using a size property of 540 Notice how the viewport rect has 1 width and 1 height. If you run this game in a Samsung Galaxy S5, the sprite will fit perfectly in your device. Now, resize the game scene view a bit (drag the Unity window border outwards to make it grow). Let's make it bigger. Then this happens The camera "white bounds" grew bigger! And the sprite no longer fits perfectly in the Galaxy S5! My question is, then why did the camera's bounds grow along with the editor window, if the viewport rect property never changed (it is still at 1 width an 1 height)?


Draco encoder lossless, is it possible? I'm trying to use the draco library in a Unity project. I've a lot of obj files with models of a person in different positions. When I encode these models with the draco encoder command I obtain a lossy conversion, and a lot of parts of my original models get lost. I tried to play around the parameters qp and cl in order to change the quantization and the compression level, but also with qp at its maximum and cl to its minimum some parts get lost. In this image the left model is the original one. The right model is the one converted with draco encoder by using cl 0 and qp 21. As you can see some parts are missing. Do you have any suggestion on how can I obtain a lossless (as lossless as possible) conversion?


How can I randomly generate objects inside of a Complex Area? In my game, I want to generate randomize enemies inside of this green area that I made with a custom editor tool.


Changing color for each element in linerenderer not working I want to change color for each line (element) just like in color switch. But my code is not working. What I wanted is that the right line should turn blue then the down line should turn color red. What is wrong with my code? void Start() lineGeneratorPrefab new GameObject() DrawLine() private void DrawLine() GameObject myLine new GameObject() myLine.transform.position start myLine.AddComponent lt LineRenderer gt () LineRenderer lr myLine.GetComponent lt LineRenderer gt () lr.positionCount 4 lr.SetPosition(0, new Vector3( 2, 0, 0)) lr.SetPosition(1, new Vector3(2, 0, 0)) lr.SetPosition(2, new Vector3(2, 2, 0)) lr.SetPosition(3, new Vector3( 2, 2, 0)) lr.materials 2 .color Color.blue lr.materials 3 .color Color.red


Limiting interaction between certain RigidBodies I'm developing a 2D game in Unity and have been tasked with building a particular feature I'm not sure how to accomplish with Unity's physics engine. To simplify, a bunch of objects of type X and O are filled into a pit XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX XXoXXXoXXXoX Both objects have Rigidbody2Ds and colliders. Objects of type X have normal gravity and should settle into place. Objects of type O have inverse gravity and should float. However, O should not be able to push X, and X should not be able to push O. Another way of looking at it is that O should only be able to move upward, and X should only be able to move downward. If we remove some of the Xs directly above an O, the O should float upwards as the Xs fall downwards until the Xs settle on top of the O and everything stops moving XXXXXXXXXXXX XX XXXXXXXXX XX XXXXXXXXX gt XXXXXXXXXXXX XX XXXXXXXXX gt XXoXXXXXXXXX XXoXXXoXXXoX XX XXXoXXXoX (In the actual game Xs and Os can be different sizes their movement is continuous and they are not constrained into rows or columns). The Os should be able to support the weight of any arbitrary number of Xs without sinking. XXXXXXXXXXXX XXXXXXXXXXXX XooooooooooX X X Lastly, the Os should be able to float diagonally if there is a space available XXXX XXXXXXX XXX XX XXXXX XX gt XXXXX XXXX XXXX XXXX gt XXXXoXXXXXXX XXXo XXXXXXX XXXX XXXXXXX I can't solve this problem simply by adjusting the mass of the Xs or Os since the number of Xs on top of an O may vary. I can't use the built in RigidBody constraints since they don't allow you to disable only one direction along an axis (e.g. saying an object can move upward but not downward). What's the proper way to handle this? I could do something like this void FixedUpdate() if (movementDirection Direction.UP) if (transform.position.y lt lastYCoordinate) Vector3 position transform.position position.y lastYCoordinate transform.position position lastYCoordinate transform.position.y but that feels hacky to me and I suspect it will keep the objects from sleeping. Are there better solutions here?


The .apk file for my built game is much larger than expected Assets of my game are 15 MB, Player Settings are default, but my .apk file is 45 MB. I tried to change Player Settings and convert PNG images to JPEG, but this didn't work.