NullReferenceException until tile is spawned I have a tile and tile has enemies spawn positions, and spawner script in it. Everything works fine when tile is spawned, my ray hits the collider in tile and enemies get spawned, but my spawn script is in tile my ray script is in my player so im reaching from my PlayerMove script to spawner script, but until my tile is spawned i get this error NullReferenceException Object reference not set to an instance of an object because tile is not spawned yet after its spawned error stops, but after tile is deleted it starts again how can i get rid of this error. PlayerScript private Spawner spawner private RaycastHit hit private void Update() spawner GameObject.FindGameObjectWithTag("Spawner").GetComponent lt Spawner gt () DrawRay() private void DrawRay() Ray ray Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0)) if(Physics.Raycast(ray,out hit)) if(hit.collider.tag "SpawnerCollider") if(hit.distance lt 5) Destroy(hit.collider) spawner.Spawn() SpawnerScript public Transform spawnPos public GameObject fireBall public void Spawn() for (int i 0 i lt spawnPos.Length i ) Instantiate(fireBall, spawnPos i .position, Quaternion.identity)


Why is my player not giving a knock back when it stays at the right side of the enemy? So, I have this problem I am facing, for some reason my player does not get a knockback when it stays at the right side of the enemy but when it stays at the left side it gives a knockback. What's the problem? PLAYER MOVEMENT void Movement() THIS IS FOR WALKING if (isControlesEnabled) moveInput Input.GetAxisRaw("Horizontal") runSpeed myBody.velocity new Vector2(moveInput, myBody.velocity.y) PLAYER KNOCKBACK private void OnCollisionEnter2D(Collision2D collision) if (collision.gameObject.CompareTag("Enemy")) health 0 if (health lt 0) gameObject.SetActive(false) else ContactPoint2D contactPoint collision.GetContact(0) Vector2 playerPosition transform.position Vector2 dir contactPoint.point playerPosition dir dir.normalized myBody.velocity new Vector2(0, 0) myBody.inertia 0 isControlesEnabled false Invoke("EnablePlayerControles", controlesDisablePeriod) myBody.AddForce(dir knockBackForce, knockBackForceMode) private void EnablePlayerControles() isControlesEnabled true


How can the player select his weapon among many? I'm working on the prototype of my game, I want one of the options to have a very large amount of weapons. I have searched for tutorials, but I have only found weapons changes where the weapons have already been loaded in the scene from the inspector, like this https youtu.be Dn BUIVdAPg where they are only activated and deactivated. But I want a game like dofus where there are hundreds of weapons, I think I have a data file of the weapons and so, I can load the correct model of the weapon. How can I get the model loaded? I have read other tutorials regarding the AssetBundle, but I think that is when you need to download the models from a server for example, but I just want to load them from the same project. sorry for the bad english


Recognize that user has traced a path of vector points with mouse How can I check if a player has traced a closed vector shape from an arbitrary starting point all the way around to the beginning? Setup Given are the vector points A through E, which form a closed path. The created shape can be convex or concave and even have sharp elongated corners. P1 is the point where the player decides to start tracing. The point can be anywhere on the path and will be set as soon as the mouse or touch is first close to the path. Requirements The player starts moving along a visual representation and traces the entire shape until he reaches P1 again. If his mouse path differs too greatly, misses a point or goes outside of a given margin, I want to start over. The player may either have to trace around in the direction from which he first starts without backtracking or just have to fill the entire path even if going back and forth on the path. How can I approach this problem? Ideally, I would like to implement a vector math solution. I don't have any pixel data to sample from and it would be rather cumbersome in my real world implementation to generate a suitable image and map world space coordinates to it. My Attempt Consider each corner a waypoint with a collision area. Track each entered collider and when all were hit, solve. While valid colliders are pending, project mouse position onto the closest point on the path. If the distance between projected point and mouse is too great, abort. This approach however doesn't give me perfect results. Firstly, it's not entirely what I want, since in my ideal case the user "draws" or traces the path with the mouse, not just hits the corners. Also, when moving around a sharp corner, the project point will snap from one line segment to the next, giving me ugly visuals, when showing progress. Possibly Better Solution As soon as player comes close to path start sampling points from mouse. Build up a user drawn vector path every time step or distance step. Check if the draw vectors are similar to the given path. Problem user drawn path needs some sort of processing or more complex algorithm until it is comparable to given path. Thank you for any suggestions! I will post some of my own code as soon as my implementation gives me good results.


Unity third person controller and hills So I've been building a game and using the out of the box unity third person controller demo stuff. I found that even the tiniest of slopes seems to stop the "dude" dead in his tracks. Is there an easy way to adjust the sensitivity on the scripts somewhere? I tried messing with the sensitivity options in the input options setup thinking that it might help but it didn't and I don't really want to go messing about in the scripts unless I really have to because i end up complicating my life when I do that.


How to get direction and velocity of movement of an object dragged with the mouse in Unty (C ) I have an object that is dragged by the mouse (X and Z positions) over a table, with the following simple code Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) if(Physics.Raycast(ray, out hit)) pos new Vector3(hit.point.x,myobject.transform.localScale.y 2,hit.point.z) myobject.GetComponent lt Rigidbody gt ().MovePosition(pos) The dragging works as expected. What I am struggling with is how can one retrieve the direction and velocity of such a movement, i.e. the direction and the velocity of that object when moved by being dragged by the mouse (I use Unity, C ). I have searched online, but only found the common ways to retrieve velocity and movement when using standard Rigidbody movement, not when dragged by the mouse.


Performance problem when multiple enemies are grouped up I have enemy with simple behavior Reach the player's current position. In game are increasing waves, which are increasing the number of enemies. But when are more enemies (like 14), and they got too close to each other, there is big physics spike in profiler. There are significant drop of performance... And as Profiler says, it's because of Physics... Now I am little lost, I tried turn of the ignore collision on layer (which was turned on), so they don't overlap, but there is still little touch of course, when they group up, so still so much to process... What is the best solution here? I build it around rigidbodies for the use of Velocity, and detection of collisions with walls (edge collider), so when the object reaches there, it is easily stopped... But for this cases it seems now like not the best solution.


Raycast does not detect child layer if parent layer is set to ignore I have a LineRenderer that ignores certain Layers based on a Raycast using LayerMask. I have a cube with a collider on a Layer which is ignored because of the LayerMask. I have a smaller object inside the cube that is a child object of the cube and is on a layer that is not set to be ignored. I need the Raycast to hit the smaller object. When this smaller object is un parented from the larger cube, the LineRenderer behaves like I want it to the hit data informs me it is being hit by the Raycast, but this does not hold true if the smaller object is a child of the cube. Is there a way of having this behaviour without having to un parent the smaller object? It's like the smaller object is inheriting the parent's Layer, despite being on it's own Layer does this sound like what is happening?


Modifying z axis position of a canvas and adapting it to camera I have a camera with y rotation of 0. And i have a canvas with position value of (0f,76.29f,41.82f). The size value of the canvas is (194.1f,307.8f). I want to modify the z value of the canvas to 10. public Canvas textcanvas void Start () textcanvas.anchoredPosition new Vector3 (0f, 24.5f, 10f) But i get an error "error CS1061 Type UnityEngine.Canvas' does not contain a definition foranchoredPosition' and no extension method anchoredPosition' of typeUnityEngine.Canvas' could be found. Are you missing an assembly reference?" Also, when i succeed moving the canvas, does the size of it adapting to the camera automatically?


How do I download audio resources and save them in cache? I am developing a game in Unity3d 2019, the instructions of the game must be translated into several languages. Right now, they are part of the compilation, but this makes the compilation very large. I would like, according to the selected language, to be able to download the corresponding audio and save it in the cache.


How to trigger OnMouseX events on Kinematic Rigidbody2D object with a different collider than one used for collisions? I have a use case where I have an object with a Collider2D and a Kinematic RigidBody2D in order to do Kinematic movement. However, I also want to be able to select hover that object with a OnMouseDown OnMouseEnter etc, using a larger collider than I would use for the kinematic movement. My current attempt at a solution is to have Physics related scripts rigidbody2d collider2d as the top level game object, and to have a child object, with a larger collider2D which will respond to OnMouseX events. In order to ignore OnMouseX events on the parent, I'm putting it into its own user ignore raycasts layer (I need it as its own layer for the layer collision matrix). I'm also putting the child in its own user use raycasts layer. I'm passing that into a script that sets MainCamera's event mask using UnityEngine RequireComponent(typeof(Camera)) public class CameraEventMasker MonoBehaviour SerializeField private LayerMask cameraEventMask Start is called before the first frame update void Awake() GetComponent lt Camera gt ().eventMask cameraEventMask What I notice is that OnMouseX events on the child will work IF the RigidBody2D on the parent is deleted...however, if the RigidBody2D is there, I won't receive any events. Anyone know why this is the case, and if there are other workarounds or solutions?


Importing code from unityscripts To encourage code reuse i want to import methods and classes defined in my core unityscripts to be imported into other unityscripts. How do i go about this? Note An answer here seems too complicated for such a simple thing (i come from Python).


Optimizing file size of a sprite sheet for a 2D game I have a question regarding the method of creating a sprite sheet so that it will not consume to much disk space and still preserve graphics quality. I was researching about this topic and found that my sprite sheets should have sizes that are a power of two. So valid sizes would be 512x512, 1024x1024, 2048x2048 etc. Then I created two sprite sheets (one is 1024x1024 and the other is 2048x2048), they are exported as 16bit but they still use too much disk space. How can I optimize my sprite sheet to use the least amount of disk space possible? This is one of my sprites


Enable SteamVR hand collision for when holding objects Just getting started on a game project with SteamVR in Unity. I've run into an issue with the collisions though. The hands and the objects that can be held collide with everything in the scene as they should. But when an object is picked up, the hand and the object stop colliding with everything. How would I go about fixing this? I could leave it as is, but if an object is let go of inside another, it gets flung out of the object it was inside. The other odd behavior happens after you let an item go. The hand that was holding it continues to not collide with anything until you move the hand away. After that it'll collide with everything normally again.


Is the Microsoft recommendation to use C properties applicable to game development? I get that sometimes you need properties, like public int Transitions get set or SerializeField private int m Transitions public int Transitions get return m Transitions set m Transitions value But my impression is that in game development, unless you have a reason to do otherwise, everything should be nearly as fast as possible. My impression from things I've read is that Unity 3D is not sure to inline access via properties, so using a property will result in an extra function call. Am I right to constantly ignore Visual Studio's suggestions to not use public fields? (Note that we do use int Foo get private set where there is an advantage in showing the intended usage.) I'm aware that premature optimization is bad, but as I said, in game development you don't make something slow when a similar effort could make it fast.


How to search for all uGui scripts in scene in the Unity editor? I have many game objects whose properties I need to edit because of a bug error. However, this is very time consuming, because I need to check each game object one by one. Is there any way to search for all game objects that (for example) contain uGui Scripts in a scene?


Power up spawns 2 3 times after a restart, but enemies spawn normally I have two spawning objects that use the same behaviour. They are being called in the same function and in the same situations. The only difference is the variable of time that classifies what's an enemy and what's a power up. The spawning of enemy objects is working fine no matter how many times I restart the game, the behaviour is the same. But with the power up spawning object, it spawns the right way sometimes, but in other times it spawns like 2 or 3 times in the same place. This only happens when I restart the game. How can I fix this bug? I'm not fluent in english. File 1 public float enemySpawnSeconds 2.5f public float powerUpSpawnSeconds 6f public void Start() gameManager GameObject.Find( quot GameManager quot ).GetComponent lt GameManager gt () private void Update() GameSpeed() public void StartSpawnObjects() StartCoroutine(SpawnPowerUps()) StartCoroutine(SpawnEnemies()) public IEnumerator SpawnEnemies() yield return new WaitForSeconds(2f) while (gameManager.startGame false amp amp gameManager.gameOver false) Instantiate(enemies Random.Range(0, 2) , transform.position new Vector3(9.8f, yPosition Random.Range(0, 2) ), Quaternion.identity) yield return new WaitForSeconds(enemySpawnSeconds) public IEnumerator SpawnPowerUps() yield return new WaitForSeconds(2f) while (gameManager.startGame false amp amp gameManager.gameOver false) yield return new WaitForSeconds(powerUpSpawnSeconds) Instantiate(powerups Random.Range(0, 3) , transform.position new Vector3(11.1f, yPosition Random.Range(0, 2) ), Quaternion.identity) File 2 void Update() spawnPlayer() gameTimer() restartGame() public void spawnPlayer() if (startGame true) starting the game if (Input.GetKeyDown(KeyCode.Space)) Instantiate(player, player.transform.position, Quaternion.identity) spawned true startGame false uiManager.HideTitleScreen() spawnManager.StartSpawnObjects() public void gameTimer() if (startGame false) timer 0.0165447f game time public void restartGame() if (gameOver true) restarting the game timer 0f spawnManager.enemySpawnSeconds 2.5f if (Input.GetKeyDown(KeyCode.Space) amp amp uiManager.restart true) gameOver false uiManager.HideTitleScreen() spawnManager.StartSpawnObjects()


How can I achieve area fill in the video? I am trying to clone a game while learning Unity but I am stuck. How can I achieve area fill like shown in this Area Fill Example Video? When I searched for it I found the quot Flood Fill quot algorithm but I am also not sure is it the right solution for this or not. Because in flood fill we have to select a point and check neighbors with same value and convert them, however here how can I decide which point to select and fill? For example at 00 03 in video I close an area and game fills the area with cubes. With flood fill, if I select a starting point above that line, algorithm can travel through all outer tiles and very well can fill them with cubes also but game fills lesser area there. Why does the game pick a smaller area here? How do they decide which portion of the game field they should fill? And in 00.11 when cube hit white wall they completely fill the remaining area because I guess they assume it is fully closed. But again my question is how can you decide that? Which methods provide area fills like this? If someone has an idea or experience about this can points me to the right direction I'd really appreciate. Thanks in advance.


In Unity, how do I dynamically manipulate parts of a mesh? I'm trying to achieve mesh manipulation of any mesh based on user input (mostly sliders). Here's an example of what I want. I am not sure whether to call this "morphing", as I am trying to change one part of the mesh without modifying the other parts. How does this work?


How can I insert a prefab instance programmatically inside the Canvas, in the bottom left corner of the Canvas? I am trying to create the Snake game in Unity, based on this video tutorial. I have also viewed this tutorial. I have created the new project with the 3D template and manually added the Canvas. I created a prefab from an Image which loads a texture from the Assets. I have this code using UnityEngine using UnityEngine.UI public class GameManager MonoBehaviour public GameObject whiteCellPrefab int N 30, M 20, size 16 Start is called before the first frame update void Start() Transform p GameObject.Find("Canvas").transform for (int i 1 i lt N i) for (int j 1 j lt M j) GameObject g Instantiate(whiteCellPrefab, p) g.transform.localPosition new Vector3(i size, j size) Update is called once per frame void Update() If I manually add a prefab instance to the Canvas, it is positioned as I want in the bottom left corner. But the script above, attached to the Main Camera object, creates the Image objects starting from the center point of the Canvas towards the top right corner of the Canvas. In the example shown here, I also added a new prefab instance to the Canvas in the Unity editor. It is positioned correctly even when play testing but the ones added with the script are shown somewhere else. Screenshots Download my example I tried to explain all the steps involved in my problem above, but here is the repo with my problem. Thank you.


Missing UI options in Inspector window when I import FBX files I am missing all the animation options in the Animation tab in the Inspector Window when importing FBX files. In the picture below, there are only 2 checkboxes. I can't see the list of animations, options, animation events etc., but you can see on the lower left window that the animations we're imported. Also, the Materials tab is empty as well. This FBX was exported from Blender. If I directly drag the .blend file to Unity, all those tabs appear normally, but when dragging an FBX, they become empty. I am using Unity 2019.3.0f6.


How do I determine distance of a point within a ProBuilder mesh? As in the title, I have an effect prepped for my game which applies certain derived parameters to a post processing effect after the player enters a boundary I created with ProBuilder. Finding how far inside the bound the player is that is, how far the player would have to travel, at minimum, to leave it would help me scale this effect. It is not an axis aligned boundary, and its sloped shape is fairly important. Having the effect go full on on crossing the boundary would be jarring to the player. I'm tempted to resort to traditional edge testing with this, but I would like to highlight that it will be done at least once per frame on multiple objects, so I would like to keep it as simple, and non home rolled, as possible. The other possibility would be to keep track of time exposed and scale it by that but this isn't ideal and I'm seriously curious as to whether a penetration depth testing method exists out of box. A requested image of my setup It is laterally symmetric, and that is unlikely to ever need to change. However, future volumes are likely to have varying angles and heights. Depth is more or less irrelevant, as while I'm using 3D, this game has the physics of a 2D platformer so you can consider it to have infinite depth if you need to. As you can see on the right, I've added almost nothing to it, other than the MagneticField.cs custom script (which does not even reference the mesh, only whether it's been crossed) and a debug class, TriangleReport.cs, that I'm working on right now. One thought I had was to get triangles for the top, bottom, left, and right edges, use them to define planes, and then determine the distance from those planes but if you've got something better I am all ears!


Help needed, following Unity multiplayer Health Bar tutorial. Only working on Server Host instance of the game was really hoping someone can be good enough to look over my code, I've been trying to fix it for several days. I followed the Unity tutorial which is fairly basic but the bit that confuses me (and potentially where the problem lies) is the if (!server) return part at the top of my TakeDamage() function. The problem im seeing is that once I get to that part of the tutorial, the bullet fired by the Host is registered against the other player and I can see his health has gone down (great so far!) , but when I load the instance in the editor (i did running another standalone on my laptop and connect to internet matchmaking but the same thing occurs) his bullets are not registered (even though my debug log tells me the Ray did hit the player. The tutorial tells me to make it return if not server, it then uses SyncVar and a hook that is supposed to call the method "OnChangeHealth" whenever currentHealth is changed. This DOES NOT appear to be happening, and the TakeDamage code is only happening on the Server Client Host instance. I was trying to adapt the tutorial to my own game, so there are some slight differences in the function and class names, but to me it looks to be exactly the same functionality wise. I will have to just post my full code here as I don't know which part is causing the issue (MANY THANKS FOR READING AND OR HELPING) the Player class public class Player NetworkBehaviour private GameObject startScreen public const int maxHealth 100 SyncVar(hook "OnChangeHealth") public int currentHealth maxHealth private float playerHeight private AudioSource audioSource public AudioClip painBodySound public AudioClip painHeadSound public AudioClip painHeadSound2 public RectTransform healthBar void Start () startScreen GameObject.FindGameObjectWithTag("StartScreen") if (startScreen ! null) startScreen.SetActive(false) playerHeight GetComponent lt Collider gt ().bounds.size.y currentHealth maxHealth audioSource GetComponent lt AudioSource gt () void Update () if (!isLocalPlayer) return if (Input.GetKey(KeyCode.LeftControl)) transform.localScale new Vector3(1, 0.5f, 1) else transform.localScale new Vector3(1, 1f, 1) public void TakeDamage(Vector3 hitPoint, int bulletDamage) check that its Server so that damage only gets applied on the server if (!isServer) return currentHealth bulletDamage audioSource.PlayOneShot(painBodySound) if (currentHealth lt 0) currentHealth 0 Debug.Log("Dead!") private void OnChangeHealth(int health) healthBar.sizeDelta new Vector2(health, healthBar.sizeDelta.y) Inside the bullet class is this function private void CastBulletRay() ray new Ray(bulletSpawnPos, bulletSpawnDirection) if (Physics.Raycast(ray, out hit, bulletRayDistance)) if (hit.collider.tag "Baddie") Debug.Log("ray has hit a baddie") Destroy(gameObject) if (hit.collider.tag "Player") Debug.Log("ray has hit a player") hit.collider.gameObject.GetComponent lt Player gt ().TakeDamage(hit.point, bulletDamage) Destroy(gameObject) and inside The Unity RigidBodyController class I'm using, I added Command void CmdFireBullets() muzzleFlashObject.SetActive(true) audioSource.PlayOneShot(gunFireSound, 0.2f) Create a new bullet GameObject newBullet Instantiate(bulletPrefab, bulletSpawnPoint.transform.position, bulletSpawnPoint.transform.rotation) as GameObject Spawn the bullet on the clients NetworkServer.Spawn(newBullet)


How can I draw a specific GameObject into a texture in Unity? I need to draw only a few specific objects into a texture (with their material) and then use that RenderTexture as a texture for an another object. I think Graphics.DrawMesh() and Graphics.SetRenderTarget() would be helpful, but I'm not sure. Ultimately I'm trying to create refractive water, which will refract only specified GameObjects, not layers. How can I do this?


Convert Rainbow gradient Shader to 3 colors gradient I am attempting to convert this rainbow shader into just using three colors. I thought I would be able to set the three colors in the shader file, but I can't understand how to link them through the shader helper file. shader https hastebin.com uworiduluc.cs Shader helper https hastebin.com kifezufegi.cs fixed4 frag(fragmentInput i) SV TARGET fixed2 lPos i.localPosition Spread half time Time.y Speed Spread half timeWithOffset time TimeOffset fixed sine sin(timeWithOffset) fixed cosine cos(timeWithOffset) fixed hue ( lPos.y) 2.0 hue time while (hue lt 0.0) hue 1.0 while (hue gt 1.0) hue 1.0 fixed4 hsl fixed4(hue, Saturation, Luminosity, 1.0) return HSLtoRGB(hsl) I added these properties at the top Color3 ("Top", Color) (1,1,0,1) Color2 ("Middle", Color) (1,1,0,1) Color1 ("Bottom", Color) (1,1,0,1) But I am not sure where I can add them into the code to have them be the colors that are used.


How can I get the vector3's names to gameobject name? void DrawBox() SpawnLineGenerator(v3FrontTopLeft, v3FrontTopRight, color) SpawnLineGenerator(v3FrontTopRight, v3FrontBottomRight, color) SpawnLineGenerator(v3FrontBottomRight, v3FrontBottomLeft, color) SpawnLineGenerator(v3FrontBottomLeft, v3FrontTopLeft, color) SpawnLineGenerator(v3BackTopLeft, v3BackTopRight, color) SpawnLineGenerator(v3BackTopRight, v3BackBottomRight, color) SpawnLineGenerator(v3BackBottomRight, v3BackBottomLeft, color) SpawnLineGenerator(v3BackBottomLeft, v3BackTopLeft, color) SpawnLineGenerator(v3FrontTopLeft, v3BackTopLeft, color) SpawnLineGenerator(v3FrontTopRight, v3BackTopRight, color) SpawnLineGenerator(v3FrontBottomRight, v3BackBottomRight, color) SpawnLineGenerator(v3FrontBottomLeft, v3BackBottomLeft, color) And the gameobjects name void SpawnLineGenerator(Vector3 start, Vector3 end, Color color) GameObject myLine new GameObject() myLine.name start.ToString() myLine.transform.position start myLine.AddComponent lt LineRenderer gt () LineRenderer lr myLine.GetComponent lt LineRenderer gt () lr.material new Material(Shader.Find("Particles Alpha Blended Premultiply")) lr.startColor color lr.endColor color lr.startWidth 0.03f lr.endWidth 0.03f lr.SetPosition(0, start) lr.SetPosition(1, end) The method SpawnLineGenerator get two vector3 and a color SpawnLineGenerator(v3FrontTopLeft, v3FrontTopRight, color) In the SpawnLineGenerator i'm setting a name for each gameobject myLine.name start.ToString() This give me the name for example ( 2.1, 3.4, 4.9) Nut I want it be the name like this format v3FrontTopLeft ( 2.1, 3.4, 4.9) v3FrontTopRight ( 1.1, 3.4, 4.9) The problem is if there is a easy way to get the names v3FrontTopLeft and v3FrontTopRight and the rest from the method DrawBox instead typing each one. I want to know that ( 2.1, 3.4, 4.9) are the coordinates for v3FrontTopLeft


is edit tangent possible in 3dsmax? I have a custom hlsl directx shader, it takes vertex normals for rim light calculation. and vertex tangent(it stores unified normals) for edge render(enlarge model amp cull front). I can export one fbx with auto smooth normals, and one fbx with unify normals, combine them in unity, it works but the process is slow. I just wonder if I can do it directly in 3ds max, so 3d artist can preview the result directly in their tools. I tried storing unify normals data in texture coordinate or vertex color, but the data will be wrong once bone animation is running. So I believe normal tangent is the only way to go if I want to have rim lighting amp edge render together for a animated character model use in Unity3D. I guess FBX SDK will help, but I have no experience in using it. I wish someone could tell me a way to store vertex normals data into tangent. or tell me is it not possible so that I should consider another solution. thanks you.


Initializing Variables, Difference between Awake and in class initialization public class ExampleClass MonoBehaviour int exampleVariable 0 int exampleVariableForAwake void Awake() exampleVariableForAwake 0 What is the difference between initializing a variable at declaration vs. initilize in Awake? Which I understand is to be used in place of constructors in Unity C , welcome to correct me if I'm wrong. Which usage is considered a proper convention by the community, if any? Same question might also be in order for Properties, so I'll leave that open ended.


Moving IK target with Unity's New Input System I'm currently converting our 2D game from the old input system to the new input system in the hopes of making it available to more people in the future. Currently I am using the mouse position to aim a flashlight by moving the IK target of that arm to the mouse position by getting the vector of the mouse cursor and converting it using screentoworldpoint. My question is, how can I implement a similar function using the new input system with a joystick? Currently I am getting a vector2 from the joystick which ranges from ( 1, 1) to (1,1) depending on the position and angle of the joystick. I would like to have the same code for both inputs so I don't have to use an if else statement and determine what input is being used but if that is unavoidable I understand. I would just like to know the best way to go about aiming an IK target using a joystick with the new input system.


Clamping always returns 0 I have a class with three fields StartingAngleOnRotationPlane is 180 MinimumRotatedAngleX is 0 MaximumRotatedAngleX is 140 Here is the offending code public virtual float ClampRotatedDegreesWithinAllowedRange() float rotatedAngle this.transform.GetRotatedAngleOnXPlane() Debug.Log("Rotated " rotatedAngle) float clampedRotatedAngle Mathf.Clamp( AngleNormaliser.BetweenNegativeAndPositive180(this.StartingAngleOnRotationPlane rotatedAngle), this.MinimumRotatedAngleX, this.MaximumRotatedAngleX) return clampedRotatedAngle Here is the debug window As you can see, when the breakpoint was hit, rotatedAngle was 178.9446. To calculate clampedRotatedAngle, rotatedAngle is added to StartingAngleOnRotationPlane, supplied to a method called AngleNormaliser.BetweenNegativeAndPositive180(float input), and then clamped between MinimumRotatedAngleX (0) and MaximumRotatedAngleX (140). Here is the code for AngleNormaliser.BetweenNegativeAndPositive180(float input) public static float BetweenNegativeAndPositive180(float angleBetween0And360) while (angleBetween0And360 gt 180) angleBetween0And360 360 while (angleBetween0And360 lt 180) angleBetween0And360 360 return angleBetween0And360 Here is the debug window when AngleNormaliser.BetweenNegativeAndPositive180(float input) was invoked By the time the return statement was hit, the result 1.055389 should be returned and assigned to the variable clampedRotatedAngle, since 1.055389 is within the clamping range (0 140). However, that was not the case As you can see, clampedRotatedAngle was still zero. In fact, clampedRotatedAngle is always zero, regardless of what I feed into the Mathf.Clamp function How can I fix this?


How to create custom 3D "areas" at runtime I've been puzzled for a few days trying to solve this problem, so far with no results. On a map, currently a Terrain, I'd need to have some "areas" which can be controlled by a specific players. The shape of those areas can arbitrarily change during the course of the game, such as you add a marker in any point, and the area evolves (like a spline, say) to pass through that point too. The problem isn't drawing the boundary itself, of course, but having the GameObjects detecting the area they are in. Currently I have absolutely zero idea on how to make this exactly. I've thought about a nice approximation, which is splitting the terrain in fixed chunks, and having the player control them "chunk by chunk" every chunk can have its own collider, and that should be easy if not trivial. So the question is how to do it "properly", since I already have this workaround.


Auto key bones with controller helpers I have skinned and rigged a human character with IK FK and helper objects to control the position of the IK goals and the rotation of the bones. For example, the characters' left arm IK goal is parented to a point helper, to make it easier to select and move around and the arm IK solves accordingly. I have the skeleton (without the helpers) set up as an avatar in Unity and I want to use this rig to create and export animations to work with the avatar. I create animations by moving the helpers in Auto Key mode in 3DS Max, so that when the helpers move, their new transform details (pos, rot, scale) are recorded in key frames. My questions is this using Auto Key only records the transform of the helpers I'm moving, it does not record the bone transforms, even though they have been changed by moving the linked helpers. Is there any way to record bone positions using Auto Key with this rigging method, or do I have to select the affected bones every time a movement is made and use Set Key?


How to speed up script compilation? Is there a way to speed up script compile time when I change something in VS then click on Unity? It takes 15 seconds. Is this normal?


Why does the code in Unity affect objects differently? There are 2 objects made in a blender and imported into Unity. Eye of the Cyclops.blend Flask.blend The problem is that after using the code, which should create an object in the hand body area (I'm still working on it), one object is created far from the character. Example Everything is OK. It's not ok. Code PlayerInteraction using System.Collections using System.Collections.Generic using UnityEngine public class PlayerInteraction MonoBehaviour public GameObject target null public KeyCode interactKey public GameObject itemHolder private void Update() if (Input.GetKeyDown(interactKey)) if (target null) return FoodBox food target.GetComponent lt FoodBox gt () if (food ! null amp amp itemHolder null) food.Interact(this) TableBox table target.GetComponent lt TableBox gt () if (table ! null) table.Interact(itemHolder, this) public void SetItem(GameObject c) if (c ! null) Debug.Log(" !") itemHolder Instantiate(c, transform.position new Vector3(0f, 2.15f, 0.65f), Quaternion.Euler( 90f, 0f, 180f), transform) else Destroy(itemHolder) private void OnTriggerEnter(Collider col) if (target ! col.gameObject amp amp target ! null) return else target col.gameObject Debug.Log(" " target.name) private void OnTriggerExit(Collider col) if (col.gameObject target) target null TableBox using System.Collections using System.Collections.Generic using UnityEngine public class TableBox MonoBehaviour public GameObject itemHolder private void Start() if (itemHolder ! null) itemHolder Instantiate(itemHolder, transform.position new Vector3(0f, 1.9f, 0f), Quaternion.Euler( 90f, 45f, 0f),transform) Debug.Log(" !!") public void Interact(GameObject i, PlayerInteraction player) if ((i null itemHolder null)) player.SetItem(this.itemHolder) Destroy(this.itemHolder) Debug.Log(itemHolder) this.itemHolder i if (this.itemHolder ! null) this.itemHolder Instantiate(this.itemHolder, transform.position new Vector3(0f, 1.9f, 0f), Quaternion.Euler( 90f, 0f, 135f),transform) Debug.Log(" !") else return FoodBox using System.Collections using System.Collections.Generic using UnityEngine public class FoodBox MonoBehaviour public GameObject ingredient private Animator anim Use this for initialization void Start() anim GetComponent lt Animator gt () anim.SetBool("openFoodBox",false) public void Interact(PlayerInteraction player) anim.SetBool("openFoodBox", true) if (anim.GetBool("openFoodBox")) anim.Play("Opening") player.SetItem(ingredient) Debug.Log(" !") anim.SetBool("openFoodBox",false) There is also an assumption that this is due to the initial position of the models. Because for me, some models are stored normally vertically, and some lie horizontally. I also add the prefab inspector Eye of the Cyclops Flask


Lerp UI Color outside update method? I'm able to Lerp the color of a UI panel within the Update method. However I'd like to trigger behavior a single time when needed. If I put it in a method and call it it only changes for a brief time and doesn't fully complete. I could probably set a bool flag within the update method but that seems sloppy.


What's wrong with my food generating code? This script is intended to produce amount of (food) objects for the players over the network. What should happen is that when a player eats one food, another food object gets created in another random place. Somehow it doesn't do that. Here's the script. public class FoodManager Photon.MonoBehaviour SerializeField GameObject smallCirclePrefab SerializeField float widthOfBoard 100 SerializeField float heightOfBoard 100 SerializeField int amtOfSmallCircle 100 SerializeField int sizeOfCircle 5 Use this for initialization void Start() if(PhotonNetwork.isMasterClient) produceSmallCircle(amtOfSmallCircle) Update is called once per frame void Update() void produceSmallCircle(int n) Vector2 position GameObject circle float positionX, positionY int ratioOfSize 5 for (int i 0 i lt n i ) positionX Random.Range( widthOfBoard 2, widthOfBoard 2) positionY Random.Range( heightOfBoard 2, heightOfBoard 2) position new Vector3(positionX, positionY,0) circle PhotonNetwork.InstantiateSceneObject(smallCirclePrefab.name, position, transform.rotation, 0,null) as GameObject circle.transform.localScale new Vector3((float)sizeOfCircle ratioOfSize, (float)sizeOfCircle ratioOfSize, (float)sizeOfCircle ratioOfSize) and here's the other script using UnityEngine using System.Collections public class FoodCollision Photon.MonoBehaviour public static float amtOfIncreaseSpeed 1f public static float amtOfIncreaseHealth 1f public static float ratioOfSpeed 150.0f public static float increaseSize 0.001f PhotonView photonView BoxCollider2D boxCollider SpriteRenderer sp void Awake() photonView PhotonView.Get(this) boxCollider GetComponent lt BoxCollider2D gt () sp GetComponent lt SpriteRenderer gt () Use this for initialization void Start() Update is called once per frame void Update() public void DestroyGO() photonView.ownerId PhotonNetwork.player.ID boxCollider.enabled false sp.enabled false photonView.RPC("DestroyRPC", PhotonTargets.MasterClient) PunRPC void DestroyRPC() PhotonNetwork.Destroy(gameObject)


Unity 2D Current object force I'm working on a game with an entity firing a shot. This shot could destroy other entities as well as the entity who generated the shot. My first step was to apply a force to the rigidbody2D of the shot, but when my entity is too fast the shot destroy it (the speed does not match). I tried adding the speed to the force but the values mismatch by far (the force is a vector of like 150 magnitude, whereas the speed as a magnitude of 1). I wonder how one can achieve this, to add the current speed of the entity to the shot fired, and i wonder if there's any litterature concerning the way physics is actually handled in Unity, i find very little documentation on the Physics. Thanks.


Conditional Variables in Scriptable Objects While using ScriptableObjects, how can I make some variables conditional? Example Code System.Serializable public class Test ScriptableObject public bool testbool public string teststring public int testint Goal When testbool true then teststring is available to edit, when testbool false then testint is available to edit while the other one is "grayed out".


Overriding the sprites in a Animation clip Right now we are in the process of adding seasonal content to our game. I would like to know of a way to override animation clips. Specifically I want to change the sprites being show at each key frame. Looking from the text of a animation clip I found the following m PPtrCurves curve time 0 value fileID 21300000, guid 1fa82f3b0bb4e1f49ab9a9ffd4e891b1, type 3 time 0.6 value fileID 21300000, guid ae9111d826eb24442b21523b30b748bd, type 3 time 0.6666667 value fileID 21300000, guid 88840e4f59c4a6040922d9b6eed3dec3, type 3 time 1.2333333 value fileID 21300000, guid 88840e4f59c4a6040922d9b6eed3dec3, type 3 time 2.0001667 value fileID 21300000, guid ae9111d826eb24442b21523b30b748bd, type 3 time 2.05 value fileID 21300000, guid 1fa82f3b0bb4e1f49ab9a9ffd4e891b1, type 3 time 3.1166666 value fileID 21300000, guid 502fc97a961e4424ea008c0e546c83ef, type 3 time 3.45 value fileID 21300000, guid 1fa82f3b0bb4e1f49ab9a9ffd4e891b1, type 3 attribute m Sprite This corresponds to the key frames and amount of sprites in the animation clip but I have no idea from where to get the data for the new sprites. I'm guessing the guid is a hashed path to the png files. can someone explain where to find this data so I can write myself a neat little parser to do the job?


Why does Unity use HLSL instead of GLSL? I am beginner in shader programming. I got my introduction (few minutes ago) to shader programming via Unity. I didn't know what HLSL was. So, I Googled and found this post Difference b w HLSL amp GLSL I can't understand one thing. Unity was initially developed for OSX amp introduced at WWDC. Also DirectX is windows only API amp HLSL is the shader programming language for DirectX. However, Unity3D for OSX is written in OpenGL. OpenGL uses a standard shader programming language called "GLSL". So, I'm confused how Unity3D uses HLSL on OSX amp why Unity didn't pick GLSL instead of HLSL. NOTE I might be wrong somewhere. So please correct if something is wrong as I told I'm a beginner


Smooth Camera Follow I am using a fixed static background. I have a gameobject(Current ref. image) which is moving with the help of waypoints. I have made camera to follow the Current. The camera is stuttering while moving. Can anyone help me to solve the camera stuttering and make it follow the Current smoothly? This is my code attached to camera following the star public class CameraController MonoBehaviour void Start () GameObject.FindGameObjectWithTag("OptionCamera").GetComponent lt Camera gt ().orthographicSize (20.0f Screen.width Screen.height 2.0f) void LateUpdate() if (GameObject.FindGameObjectWithTag ("Current") ! null) if (GameObject.FindGameObjectWithTag ("Current").GetComponent lt CurrentController gt ().Greenblast false amp amp GameObject.FindGameObjectWithTag ("Current").GetComponent lt CurrentController gt ().Redblast false) Vector3 pos GameObject.FindGameObjectWithTag ("Current").transform.position transform.position new Vector3 (transform.position.x, pos.y, transform.position.z)


Help with OnTriggerEntered Canvas UI This seems like it should be incredibly easy and I know there are other posts out there with a similar title, but I promise you I have looked at all of them. All I want is for my canvas that simply says "you win" to appear when I enter an invisible box collider that I have . My canvas is by default set to disabled. public class YouWin MonoBehaviour public Canvas myCanvas private void Start() myCanvas GetComponent lt Canvas gt () void OnTriggerEnter (Collision Collider) myCanvas.gameObject.SetActive(true) This script seems incredibly simple and straightforward, but for whatever reason, when I enter my box, nothing at all happens. Why might this be? What am I missing? As per an answer I also tried public class YouWin MonoBehaviour public GameObject canvas void OnTriggerEnter (Collider Collider) canvas.gameObject.SetActive(true) But had no luck with this either. I've been tinkering to no avail, can you please give me some suggestions?


Raycasting to AddForceAtPosition goes to the wrong direction I'm trying to get my coin object's Rigidbody to move whichever way it was swiped on by the user through RayCast void Awake() coinRigidBody coin.GetComponent lt Rigidbody gt () void Update() foreach (Touch touch in Input.touches) if (touch.phase TouchPhase.Began) firstTouchPos new Vector3(touch.position.x, touch.position.y, Camera.main.nearClipPlane) if (touch.phase TouchPhase.Moved) lastTouchPos new Vector3(touch.position.x, touch.position.y, Camera.main.farClipPlane) if (touch.phase TouchPhase.Ended) Vector3 firstTouchWorldPos Camera.main.ScreenToWorldPoint(firstTouchPos) Vector3 lastTouchWorldPos Camera.main.ScreenToWorldPoint(lastTouchPos) Vector3 diffWorldPos lastTouchWorldPos firstTouchWorldPos direction3D diffWorldPos.normalized power diffWorldPos.magnitude (force Time.deltaTime) Ray firstTouchRay Camera.main.ScreenPointToRay(firstTouchPos) Ray lastTouchRay Camera.main.ScreenPointToRay(lastTouchPos) RaycastHit hit Debug.DrawRay(firstTouchRay.origin, lastTouchRay.direction firstTouchRay.direction, Color.red, 50.0f) if (Physics.Raycast(firstTouchRay.origin, lastTouchRay.direction 100, out hit)) Vector3 hitLocation hit.point if (hit.collider.tag "Coin") projectedVector Vector3.ProjectOnPlane(direction3D, plane.normal) coinRigidBody.AddForceAtPosition(projectedVector power, hitLocation 5) throwCoinObject.throwWithForce(power, hitLocation, direction3D) The Code is working but my only problem is that it goes only in a certain direction? And it seems that direction is manipulated by how the camera is facing the objects. I just want it to hit the first touch origin then move to the direction the swipe was made. Help would be really appreciated


Why can't I use the operator ' ' with Vector3s? I am trying to get a rectangle to move between two positions which I refer to as positionA and positionB. Both are of type Vector3. The rectangle moves just fine. However, when it reaches positionB it does not move in the opposite direction, like it should. I went back into the code to take a look. I came to the conclusion that as the object moved, the if statements in the code missed the frame in which the rects position was equal to positionB. I decided to modify the code to reverse direction if the rects position is greater than or equal to positionB. My code is not too long, so I will display it below using UnityEngine using System.Collections public class Rectangle MonoBehaviour private Vector3 positionA new Vector3( 0.97f, 4.28f) Start position private Vector3 positionB new Vector3(11.87f, 4.28f) End position private Transform rect tfm private bool atPosA false, atPosB false public Vector2 speed new Vector2(1f, 0f) private void Start() rect tfm gameObject.GetComponent lt Transform gt () rect tfm.position positionA atPosA true private void Update() NOTE Infinite loops can cause Unity to crash Move() private void Move() if ( atPosA) rect tfm.Translate(speed Time.deltaTime) if ( rect tfm.position positionB) atPosA false atPosB true if ( atPosB) rect tfm.Translate( speed Time.deltaTime) if ( rect tfm.position positionA) atPosA true atPosB false When I changed it, however, it warned me of the following error message Operator cannot be applied to operands of type Vector3 and Vector3. This confuses me for two reasons first, both values are of the same data type. Second, using the comparison operator( ) on the two values works without error. Why can't I use the operator gt with Vector3s?


Corgi Engine Character glitches with "jump" animation on top of a ladder I'm new to Corgi Engine and Unity in general. I have an issue that I could find a way to resolve. I'm using CorgiEngine's quot RetroLadder quot prefab and extended quot Rectangle quot character with custom animations from quot MinimalLevel quot The problem is that when character finishes climbing the ladder, for a very short amount of time, jump animation appears. As in my case jump animation is very different from idle animation, this feels like an unpleasant glitch to me, so that's why I want to fix it. You can see it on the GIF below (at first I jump near the ladder to show how animation looks and then start climbing the ladder and on the top jump glitches) I checked some other demos (e.g. RetroVania, which uses some ladders there) and they also have this quot glitch quot with Corgi demo character, but as the character's idle and jump animations are not very different, it doesn't seem wrong (GIF below) I suspect that this glitch happens because quot CharacterLadder.cs quot script disables gravity during ladder climbing and then enables it back which triggers fall of the character Do you think it's possible to workaround it somehow? Thanks!


All Materials are pink (Unity URP) Version Unity 2020.2.0f1 I started my project with Universal render pipeline template but I don't know why all materials are pink. i even tried to upgrading but nothing happened. This error was coming after upgrading And when I am creating new materials then I still getting pink materials and I am also not able to upgrade them


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


The more appropriate way to find GameObject in the scene Which way is the more appropriate to find GameObject in the scene. I know that GameObject.FindGameObjectWithTag is faster than GameObject.Find but i wondering whether FindGameObjectWithTag is better solution than this public GameObject someObject public void SelectObject() someObject.SetActive(true) or whatever i want


In Unity, how can I render borders of provinces from a colored province map in a grand strategy game? I am kind of a beginner of Unity and I am trying do work on a grand strategy game. I already have a province map, colored by unique rgba for each province, looks like something below I know that the province map is kind of a look up map for province id. But when I obverse the paradox strategy games, I notice that they have render borders differently for the provinces and nations. For example, in the CK3, the Baron collars are separated with dotted lines, and the kingdoms are separated with enhanced yellow lines. I thought they have some other maps or files containing those information, so I went to read their dev diary, and I find that all province shape information are stored in the province map. So, my question is Is there any way in Unity3D to create those different borders with some shader and some province map such those given above? I think what I wish to accomplish is something as this link Render border on 3D map Which is


Translating object from y to y smoothly in Unity 2D I am trying to make a game that has an object on screen, which moves from one Y coordinate to another. Right now, I do it through translations, but that does it instantly. I want to do this as a kind of animation, where it transitions smoothly from one Y coordinate to another. What should I do? Here is an image of what I'm talking about


Bold black bar on right side of game in Unity (Android) I am trying to create an endless runner. I have already created a system to generate infinite backgrounds from an array of some. However, on running the game, I get huge black bar on the right side of the screen, both on PC and on Android phone. Here are the screenshots One more thing, on Android, it doesn't even display the left side of the game, i.e, where the character is. It looks like the things are displaced towards left. Also, the game is a scrolling on and everything is scrolling but behind that bar. It just doesn't go. I hope I can get some help. Ask me if you need any piece of code. EDIT "CameraFollow" script using UnityEngine using System.Collections public class CameraFollow MonoBehaviour public GameObject targetObject private float distanceToTarget Use this for initialization void Start () distanceToTarget transform.position.x targetObject.transform.position.x Update is called once per frame void Update () float targetObjectX targetObject.transform.position.x Vector3 newCameraPosition transform.position newCameraPosition.x targetObjectX distanceToTarget transform.position newCameraPosition My "GeneratorScript" using UnityEngine using System.Collections using System.Collections.Generic public class GeneratorScript MonoBehaviour public GameObject availableRooms public List lt GameObject gt currentRooms private float screenWidthInPoints Use this for initialization void Start () float height 0.0f Camera.main.orthographicSize screenWidthInPoints height (Camera.main.targetDisplay) Update is called once per frame void Update () void FixedUpdate() GenerateRoomIfRequred () void AddRoom(float farhtestRoomEndX) int randomRoomIndex Random.Range (0, availableRooms.Length) GameObject room (GameObject)Instantiate (availableRooms randomRoomIndex ) float roomWidth room.transform.FindChild ("floor").localScale.x float roomCenter farhtestRoomEndX roomWidth 3.0f room.transform.position new Vector3 (roomCenter, 0, 0) currentRooms.Add (room) void GenerateRoomIfRequred() 1 List lt GameObject gt roomsToRemove new List lt GameObject gt () 2 bool addRooms true 3 float playerX transform.position.x 4 float removeRoomX playerX screenWidthInPoints 5 float addRoomX playerX screenWidthInPoints 6 float farhtestRoomEndX 0 foreach(var room in currentRooms) 7 float roomWidth room.transform.FindChild("floor").localScale.x float roomStartX room.transform.position.x roomWidth 6.0f float roomEndX roomStartX (roomWidth 13.0f) 8 if (roomStartX gt addRoomX) addRooms false 9 if (roomEndX lt removeRoomX) roomsToRemove.Add(room) 10 farhtestRoomEndX Mathf.Max(farhtestRoomEndX, roomEndX) 11 foreach(var room in roomsToRemove) currentRooms.Remove(room) Destroy(room) 12 if (addRooms) AddRoom(farhtestRoomEndX) (I tried playing with the numbers on GeneratorScript, but nothing seemed to help.


What is the purpose of the Allocation Callstacks button in Unity's Profile window? I have an idea of what this button does, but I cannot find any specific information in the documentation. What information does this button add to the profiling data? How can I see this extra information?


Make a glass cup look like it's full of water I've been struggling to figure out a way to make a glass cup full of water, and since the cup is made of glass a plane on the top of the glasse won't really do it, so how can i go around making the glass looks like it's full of water?


CrossPlatformInput Prefabs Button handler to move? I am currently trying to put two buttons on my UI that move a character left and right if touched down (Held). I would like to use the cross platform input, and would like the buttons to change the value of the Horizontal axis as my "A" and "D" keys would... And my code for moving my character is as follows private void Update() isGrounded Physics2D.OverlapCircle(groundChecker.position, .15f, groundLayer) float move CrossPlatformInputManager.GetAxis("Horizontal") moveSpeed playerRB.velocity new Vector2(move, playerRB.velocity.y)


I'm trying to write a randomly patrolling AI for my 2D Platformer I'm trying to write a randomly patrolling AI for my 2D Platformer. The AI already has a ground checker function which checks if there are tiles nearby or not. What I want to do is randomize its actions and create an illusion of a somewhat quot sentient quot enemy. What I tried to create below is using the built in RNG to make the enemy either jump, change direction, or keep moving. The problem is, it doesn't seem to work properly. The enemy just jumps every second I want it to change behaviour. The change direction functions, however, don't occur as frequently. I need to know what I've done wrong here. Thanks. void Update() RNG behaviour Random.Range(0,3) jumpSpeed Random.Range(1,5) clock timer Time.deltaTime time private float waitTime 2.0f private float timer 0.0f void MoveRandomizer() if((Mathf.Round(timer waitTime)) 0) if(behaviour 0) movingRight false if(behaviour 1) movingRight true if(behaviour 2) rb.velocity new Vector2(rb.velocity.x, jumpSpeed)


How can I use different fonts for different objects in Unity? In Unity 3.5, I have a font that is strangely linked to four game objects. I want to put separate fonts on each object. In the Inspector, when I click on the circle icon next to the "Text" attribute, I can select a font. But, then it changes the font on the other three objects as well. I was hoping Unity would have something like a material ID from 3DS Max. If I could put a new material ID on the other objects, hopefully I could assign a new font to the text mesh. Regardless, is there a way to assign a different font to each of my objects?


How to automatically scroll vertical text? I've a GUI, and a panel with a Text control. I simply want to do an automatic vertical scroll effect (circular). Problems I've to solve How to identify if text on my textbox is "too much" and overflow vertical How to move Text and not textbox transform Y Can you help me find the correct solution ? Thanks


Unity3D Sudden lighting change in a scene Sorry if this is a duplicate question, but I have no idea what this would be considered. Hello, I have recently been creating an FPS game, but while researching some things on the internet, the lighting changes within only one scene. I actually want to keep this change, but I am not sure what changed to make it look like this. It unusually changed from this To this I want to keep the new one, but have this same lighting effect on a different scene, however, I am not sure what can cause this change. I have searched high and low for anything that could've changed, but I couldn't find anything. Any help is greatly appreciated. Thanks!


How can I make all the objects to move between the waypoints? using System.Collections using System.Collections.Generic using UnityEngine public class MovementSpeedController MonoBehaviour public List lt Transform gt objectsToMove new List lt Transform gt () public List lt Vector3 gt positions new List lt Vector3 gt () public int amountOfPositions 30 public int minRandRange, maxRandRange public bool randomPositions false public bool generateNewPositions false public float duration 5f public bool pingPong false private void Start() if (generateNewPositions (positions.Count 0 amp amp amountOfPositions gt 0)) GeneratePositions() StartCoroutine(MoveBetweenPositions(duration)) private void GeneratePositions() for (int i 0 i lt amountOfPositions i ) if (randomPositions) var randPosX UnityEngine.Random.Range(minRandRange, maxRandRange) var randPosY UnityEngine.Random.Range(minRandRange, maxRandRange) var randPosZ UnityEngine.Random.Range(minRandRange, maxRandRange) positions.Add(new Vector3(randPosX, randPosY, randPosZ)) else positions.Add(new Vector3(i, i, i)) IEnumerator MoveBetweenPositions(float duration) for (int i 0 i lt positions.Count i ) float time 0 Vector3 startPosition objectsToMove 0 .position while (time lt duration) objectsToMove 0 .position Vector3.Lerp(startPosition, positions i , time duration) time Time.deltaTime yield return null objectsToMove 0 .position positions i Now only the first object in objectsToMove is moving between the waypoints but I need all of the elements of objectsToMove to move between the waypoints. If I try this objectsToMove i .position Vector3.Lerp(startPosition, positions i , time duration) I will let out of bound index exception because the size of objectsToMove is not the same the size of positions i


Unity Texture huge areas with decals I'm using 1024 textures for smaller buildings and 2048 for larger one's. Basic workflow 1) Unwrap in Blender 2) Smack a concrete texture on it 3) paint some dirt here and there. Result This only works for small buildings. Here is an example from Battlefield 2, they put a small 128x128 brick texture and tiled it across the entire building and added Dirt on top of that. Is there a way to do this using Unity or do I have to create my own custom shaders? (God forbid)


How does layer based collision affect performance In Unity3D, and others, there are Layer Based Collision System which makes collisions only happen between specified Layers. It defaults to all layers colliding with all others. Does making use of these setting decrease performance, or increase performance? I could imagine it decreases it if every potential collision had to be checked for it's layer. Or are those collisions completely bypassed?


What is the cause of this lighting artifact on my dynamic terrain mesh? I am generating my own terrain mesh in Unity, using pseudo random noise to determine the height. I construct the mesh using quads, each quad is composed of two triangles. All seems to be going well, except the terrain does not look right the quads are very visible. You can see the outline of them on the surface, but I haven't seen this effect before elsewhere. I feel that something is wrong with either my normals or my UV's. I am using just one white directional light. Dynamic Terrain http www.spannerworx.com images terrain.png I thought the issue was with the normals, so I stopped calling RecalculateNormals and manually calculated the normal for every vertex using the averaged normal of the sum of each triangle touching that vertex. This was a lot of effort, but made no effect and ended up looking just the same. Has anyone else seen this dynamic mesh effect before and maybe make some suggestions as to how I could try resolve this? Just to clarify, I am already generating the triangles myself, two per quad. I do it like this for (int t 0 t lt quadCount t ) int x t (Samples 1) int z t (Samples 1) Calculate quad corner indexes int indexBR CalculateIndex(x 1, z) int indexBL CalculateIndex(x, z) int indexTL CalculateIndex(x, z 1) int indexTR CalculateIndex(x 1, z 1) Assign indexes for triangles Triangle 1 triangles 6 t 0 indexBR triangles 6 t 1 indexBL triangles 6 t 2 indexTL Triangle 2 triangles 6 t 3 indexBR triangles 6 t 4 indexTL triangles 6 t 5 indexTR Normals stuff...


Quality deterioration on a device I am using Unity. When I try the game out in the IDE everything looks pretty good But when I am trying to play the same game on a device the quality becomes a great deal worse and you can see it for yourself I am using Xiame Redmi 4X and I do not think that it is because of device. So, how can I fix it? How can I preserve the quality? I would like to try out this solution, but there is no Android settings in my Inspector for quality I would like to preserve at least colors. And here are setting for my player sprites


Unity plane that is normal to Z axis I want to create a plane that will be normal to the Z axis, but I am having difficulty visualizing what rotation it needs to have. I want to have a top down view upon the plane such that I can use the X and Y coordinate system for position, and the Z axis for height. It seems intuitive for me to point the camera in the same rotation as this plane, and give it an orthogonal view and a positive Z value (and set gravity to have a negative Z value), but I seem to be fighting against the grain and running into more issues than I should be, so I would like to ask what rotations I should be using for this. What rotation should I use for the plane? can the camera share the same rotation? (assuming I want the top to be y and the right to be x as seen from the camera.


Dynamic rigidbody and kinetic with simplectic integration for trajectories 2d Okay, I have the following situation I want to launch a GameObject into orbit of a planet and using the dynamic rigidbody everything is working as I want. I simulate gravity and as it hits the surface again it bounces around nicely using the Box2D system. However, I want to calculate the trajectory and visualise it on screen. I thought about it and came up with two solutions, but I run into some problems 1 Simplectic integration for the trajectory I simulate the trajectory using simplectic integration. However, as can be expected, the results are different for the dynamic rigidbody movement and the simplectic integration. This became very obvious when I launched two identical objects and simulated one dynamically and the other one simplectic. The code is as follows (all in FixedUpdate) if (rb.isKinematic) velocity forces mass Time.fixedDeltaTime Vector2 newPosition (Vector2)transform.position velocity Time.fixedDeltaTime rb.MovePosition(newPosition) else rb.AddForce(forces) The simplectic kinematic one is slower than the dynamic one. Weird. 2 Use Physics2D.simulate According to https docs.unity3d.com ScriptReference Physics2D.Simulate.html I can simulate it via code. However, this means that I have to set everything that is not to be simulated as disabled and simulate it for a given amount of time to calculate the trajectory. Not really what I was looking for, because I want to have a live trajectory update 3 Full simplectic That seems to be easy, but I want to have realistic collisions and bounces. Don't want to reinvent the wheel when Box2D should be sufficient. 4 Simplectic for simple movement, dynamic at collision This seems to be the logical candidate, but don't know if it is clever. Had no time to implement this yet, but should not be that difficult. Feels a bit icky... So, question? My questions are Can I reduce or eliminate the offset from solution 1? If not, what whould be the most logical solution and or am I missing one? EDIT It was asked how I calculate the forces. This is simply Newton's law with squared distance public Vector2 CalculateForce(GameObject a, GameObject b) AUComponent is an interface type I have... not very special in itself. float mA a.GetComponent lt AUComponent gt ().Mass float mB b.GetComponent lt AUComponent gt ().Mass Vector2 r b.transform.position a.transform.position return gravityConstant mA mB r.sqrMagnitude r.normalized However, the ever increasing offset is also happening with a constant force applied in a direction. The masses of the AUComponent are equal to those of the RigidBody.


How can i make fade in out of the alpha color of a material from black to none black? This is script is attached to a black plane. I have a plane and i added to it a material and the plane is in black. When running the game the alpha color of the plane material is changing slowly. The script is working it's getting slowly from dark black to none black. But i want to make some changes It's not my script i took it from the youtube and did some changes the first one converted from js to c second added the fade bool variable. First of all i don't see any meaning setting the variable timer to 10 at the top. Any ideas what is the point ? Second is how can i check when the alpha color value is high enough to do some stuff Enabled true the fpc again. Once it's not black again the fpc is still enabled false. If i want when the alpha color value reached it's max to make automatic fade back to black Now i'm using manual fade bool variable but i wonder how to do it automatic fade in out. using System.Collections using System.Collections.Generic using UnityEngine using UnityStandardAssets.Characters.FirstPerson public class FadeScript MonoBehaviour public float timer 10.0f public FirstPersonController fpc public bool fade true Use this for initialization void Start() Color tempcolor GetComponent lt Renderer gt ().material.color tempcolor.a 1f GetComponent lt Renderer gt ().material.color tempcolor fpc.enabled false Update is called once per frame void Update() timer Time.deltaTime if (timer gt 0) Color tempcolor GetComponent lt Renderer gt ().material.color if (fade true) tempcolor.a 0.1f Time.deltaTime else tempcolor.a 0.1f Time.deltaTime GetComponent lt Renderer gt ().material.color tempcolor


Raycast only specific layer and ignore other collider I am willing to raycast specific layer and ignore other layers no matters its colider is above to my navPoint layer object? int specificLayerMask LayerMask.GetMask("NavPoint") raycast only this layer ignore others if (Physics.Raycast(raycastObject.transform.position, fwd, out objectHit, specificLayerMask)) 50 the above code raycasting to navpoint layer but unable to bypass other layers colliders. is there any way available to ignore all other collider and raycast to desired layer only no matter colliders are behind any other collider


Clipping speed when turning without using aggressive drag I have a Unity project in which I want to control a player in a similar way to Source games, and so far I am clipping each input to the speed in the player's coordinates, by using transform.InverseTransformDirection( GetComponent lt Rigidbody gt ().velocity ) after which I pass each of the player's input vector direction through this function private float FLSMF ( float aInputVelocity, float aMaximumVelocityOnAxis, float aSpeedOnAxis ) if ( Mod( aSpeedOnAxis ) gt aMaximumVelocityOnAxis ) if( Sign( aSpeedOnAxis ) ! Sign ( aInputVelocity ) ) if ( Mod( aSpeedOnAxis aInputVelocity ) gt aMaximumVelocityOnAxis ) return Sign ( aInputVelocity ) ( aMaximumVelocityOnAxis Mod( aSpeedOnAxis ) ) return aInputVelocity return 0 if( Mod( aSpeedOnAxis aInputVelocity ) gt aMaximumVelocityOnAxis ) return Sign( aInputVelocity ) ( aMaximumVelocityOnAxis Mod( aSpeedOnAxis ) ) return aInputVelocity There is only one problem whenever I turn and strafe and walk forwards or backwards, the speed increases dramatically. I tried solving it by comparing each processed velocity axis to the velocity rotated by the difference in the rotations between the last 2 FixedUpdate's. So far nothing worked, aside from driving the drag factor through the roof. My best guess is that when turning, the unclipped X axis of the vector bleeds into the Z axis when turning, which can't add anything, but cant stop the X axis from interfering because the forward key is pressed. There is no issue when only one of the input axis are used, the speed remaining consistent when turning. I tried to implement this function especially so I don't have to use any drag, to allow the player to be flung by other things, like grapples and explosions (this issue is present irrespective of said external factors). If you want to, I will share the entire code, but it's messy and I don't think it would help. Any ideas how to solve it? Edit yes, I have normalized the input vector. The speed increases to more than triple of the maximum, in as few as 2 turns.


How can I find a bounding box for a bezier curve I am using the code from the question Adding functionality to make individual anchor points of bezier continuous or non continuous to create bezier curves (I added a line renderer). How can I find the center of the curve for multiple cubic B zier segments, where the centre of a bounding box is the centre of the curve (as in the image below)?


Moving object along X and Z plane relative to camera Using keys, I'm trying to move a cursor object across the X and Z plane, keeping it relative to a camera that I can orbit around the playfield. This is my code so far, and apologies...I'm about 2 days into learning Unity. This code is on my cursor object. if (Input.GetAxis("Horizontal") gt 0f) transform.position transform.position Camera.main.transform.right moveSpd Time.deltaTime if (Input.GetAxis("Horizontal") lt 0f) transform.position transform.position Camera.main.transform.right moveSpd Time.deltaTime if (Input.GetAxis("Vertical") lt 0f) Vector3 dir Camera.main.transform.forward dir.y 0.01f dir.Normalize() transform.position transform.position dir (moveSpd 1.5f) Time.deltaTime if (Input.GetAxis("Vertical") gt 0f) Vector3 dir Camera.main.transform.forward dir.y 0.01f dir.Normalize() transform.position transform.position dir (moveSpd 1.5f) Time.deltaTime transform.position new Vector3(transform.position.x, 0.01f, transform.position.z) It works, but the vertical axis affects the Y plane so I had to do another transform at the end. What is the best way of doing this? I'd also like the cursor to snap to grid co ords. I've tried turning them to int but it doesn't do what I want.


Convert Minimap render texture to 3d space position I am using Render Texture to make a Mini Map it is working fine. Now I want world space position from render texture click point. Is there any way available that I get the world space position from the render texture's specific click point? If I click somewhere in render texture then, how can I get that point in 3D world space? For example, I click a car object on render texture How can I highlight or get it in 3D world space.? Update Actual Scenario is One Main Camera Rendering the Scene. NGUI Camera Rendering the GUI. That GUI contains the Render Texture(minimap) which rendering the scene on texture using GUI Camera. Now how can I get 3D position from 2D render texture!


Google Admob GDPR compliance Unity I have created a unity game that uses admob to show only rewarded video ads and there are no banner interstitial ads in my game. Is it mandatory to take user consent (for EU countries) for showing the rewarded ads and if so how do I go about implementing it. I followed some online tutorials to implement admob ads but there was no mention of gdpr in any of those. Can someone please help?


Drawing a 1 pixel thick line in Unity I'm trying to get a cross at the center of the screen (Two lines will do as well). I have a 2048x2048 Texture which I have thrown into a canvas. Filtering is set to point. The image is set to be in the middle of the screen no matter the resolution. The image is set to 2048x2048 no matter the screen resolution which works as well. However when I change the Screen Resolution I get results like the following, no matter what I do, the line refuses to stay at the same thickness. When I enable Bilinear filtering the lines constantly fade and thicken. This is what I get when I use a 16x16 image EDIT i tried using a black square and setting its width to 1 and height to 2048, and another one with width to 2048 and height to 1. The result i got is not what i expected Can someone help me to fix this please?


Most efficient way to get the world position of the 8 vertexes of a Box Collider (C ) What I am looking for is the most efficient way to get the world position of the 8 vertexes of the Box Collider of a freely rotated Gameobject. I cannot use collider.bounds since object is rotated, not axis aligned. As for the framework I am working within, it's Unity 5 with C . Would you know how could I achieve that? Thanks in advance.


The camera does not capture movements in z axis I want to make a simple drag and drop card in Unity, where the card pops up a bit towards the screen when the drag begins (lifting effect), and then drops down back on the table when the drag ends. My script looks like this public class Draggable MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler void IBeginDragHandler.OnBeginDrag(PointerEventData eventData) this.transform.position new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z 10) public void OnDrag(PointerEventData eventData) this.transform.position new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10) public void OnEndDrag(PointerEventData eventData) this.transform.position new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z 10) The card is an image, and it is child of the canvas. The render mode for the canvas is Screen Space Overlay. The drag works correctly, but I cannot capture the movements in the z axis. It does capture the movements in the z axis when I change the render mode. However, then the card is too far away in the z axis, and it moves with an offset with respect to the mouse pointer. As far as I understood, I need to do something about realtive distances, but I how can I force the mouse pointer to be on z 0 plane.


Experiencing strange behavior in Unity when rotating a 2D GameObject according to the slope it is standing on I am trying to rotate a square GameObject, so it appears to be standing perpendicular to the slope underneath it. However, when above a slope, the square constantly quot spins quot it seems like the rotation is set and then immediately set back to 0, causing it to jitter. I am currently using a RayCast based character controller instead of rigidbody. To change the rotation, I added the follow line of code following the vertical RayCast if ( raycastHit) transform.rotation Quaternion.FromToRotation(transform.up, raycastHit.normal) transform.rotation ... It calculates and rotates the square correctly, but I am not sure why it resets back to 0 every other frame. To avoid taking up too much space, the character controller I am using is hosted on GitHub here. Specifically, this is in the moveVertically() method.


If statements seem to act as though the condition is always true I have other scripts in the same project using boolean if statements that work fine, but I've tried multiple methods of testing if the if statements below are working and none of them worked! I don't really know what to ask because I don't know whats going on. I've tried placing theae statements in Update and Start, and in both instances the if statement completely ignored the check and just executed the contents of the block as though the check evaluated to true. void OnTriggerEnter(Collider other) if(other.gameObject.CompareTag("Player")) working true Extremity false if(Extremity) Instantiate(Cannon, transform.position, transform.rotation) Extremity !true The false statement is only in there to show that even when the bool is set to false immediately before the check, it still runs the Instantiate method inside as though it were true.


Optimizing spawning 500 objects every 3 seconds Using Object Pooling, assuming I'll like to spawn 500 cubes once every three seconds. How do I make it performance friendly? I need ideas, not the code itself.


Unity Canvas blocking objects in Editor I think I am missing something really basic here..., I'm creating a 2D game in unity, and the UI Canvas (with the setting "Screen Space Overlay") is blocking exactly a quarter of my workspace. I can not select any objects on the top right part of the screen. Is there any fix to this?, or do I have to move the camera down half of the screen? Thanks


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


SteamVR locks position of dynamically created cameras I'm having trouble tracking down a problem with SteamVR. Here is a quick way to set up an MWE Create a new Unity project. Import the SteamVR package from the Asset Store. Create the following script using UnityEngine public class CameraCreator MonoBehaviour private GameObject cameraObject private void Start () cameraObject new GameObject("CameraObject") cameraObject.AddComponent lt Camera gt () cameraObject.transform.position Vector3.one Create an empty game object and add this script to it. SteamVR seems to lock this object's position (and that of any other game object with a dynamically created camera component) to the origin. No matter what I try to do to change it (inspector set it inside update set it in a coroutine), it always ends up back at the origin at some point during the frame (I believe somewhere between LateUpdate and OnRenderObject, but I'm not entirely sure). Without data breakpoints I find this really hard to track down. This behaviour isn't really a problem for my actual project, but I need to be able to create cameras and modify their positions in my unit tests, where I'm having the same issue. Does anyone know what's causing this, or have any advice on how to track down the cause?


FixedUpdate or Subroutine So Update is called every frame while FixedUpdate is called on Physics time, which can be modified. Is it better to depend on FixedUpdate to have optimized game loop so that everything doesn't get called so much. OR Is it better to write a coroutine to Update FixedUpdate and set things there? public void Start() StartCoroutine(MyIntervalMethod()) void MyIntervalMethod() for( ) yield return new WaitForSeconds(.2f or whatever time interval is suitable here )


How I add gap between Instantiated objects? using System.Collections using System.Collections.Generic using System.IO using UnityEngine using UnityEngine.Networking using UnityEngine.UI public class SavedGamesSlots MonoBehaviour public GameObject saveSlotPrefab public float gap private Transform slots private string imagesToLoad Start is called before the first frame update void Start() imagesToLoad Directory.GetFiles(Application.dataPath quot screenshots quot , quot .png quot ) slots GameObject.FindGameObjectWithTag( quot Slots Content quot ).transform for (int i 0 i lt imagesToLoad.Length i ) var go Instantiate(saveSlotPrefab) go.transform.SetParent(slots) Texture2D thisTexture new Texture2D(100, 100) NOW INSIDE THE FOR LOOP string fileName imagesToLoad i byte bytes File.ReadAllBytes(fileName) thisTexture.LoadImage(bytes) thisTexture.name fileName GameObject ChildGameObject go.transform.GetChild(1).gameObject ChildGameObject.GetComponent lt RawImage gt ().texture thisTexture var raw go.GetComponent lt RectTransform gt () raw.anchoredPosition new Vector3(1 1 gap, 6, 0) Update is called once per frame void Update() The way I'm doing it now is not working it's moving all the objects to the same position and not adding equal gap's between them. In the loop I tried to do it this way in this line raw.anchoredPosition new Vector3(1 1 gap, 6, 0)


Mathf.Round returning wrong values I want to check if the Y position is changing or not for the player and the enemy. If it has changed in the frame I want it to return true and if it didn't I want it to return false. I round because the enemy's position alternates between 0.8 and 0.800001 . I tried to do Mathf.Round(transform.position 100) 100 and I compare is to the enemyOldPosition which I assigned using enemyOldPosition Mathf.Round(transform.position 100) 100, but it says it's not equal. I tried to check Debug.Log(enemyOldPosition Mathf.Round(transform.position 100) 100) and it returned 1.192093E 08. void Update() if(Mathf.Round(player.transform.position.y 100) 100 oldPosition) isChangingY false oldPosition Mathf.Round(player.transform.position.y 100) 100 else Debug.Log(oldPosition Mathf.Round(player.transform.position.y 100) 100) isChangingY true oldPosition Mathf.Round(player.transform.position.y 100) 100 if(Mathf.Round(transform.position.y 100) 100 enemyOldPosition) enemyIsChangingY false enemyOldPosition Mathf.Round(transform.position.y 100) 100 else Debug.Log(enemyOldPosition Mathf.Round(transform.position.y 100) 100) enemyIsChangingY true enemyOldPosition Mathf.Round(transform.position.y 100) 100 This script is placed my on enemy, and they both have rigidbodies


What is the difference between WaitForSecondsRealtime and a counter? I am making my own button using the Unity UI code, but now I got to the OnFinishSubmit () coroutine private IEnumerator OnFinishSubmit() float fadeTime base.colors.fadeDuration float elapsedTime 0f while (elapsedTime lt fadeTime) elapsedTime Time.unscaledDeltaTime yield return null this.DoStateTransition(base.currentSelectionState, false) yield break But I want to use a different code to delay time IEnumerator FinishSumbit() yield return new WaitForSecondsRealtime(colors.fadeDuration) DoStateTransition(currentSelectionState, false) Will this also work? Why didn't the Unity developers use WaitForSecondsRealtime?


Profiling unity games on Android devices I would like to profile our Unity mobile game on Android devices in a way similar to profiling Unity games on iOS with Instruments. I am aware of how to do this using Unity's profiler, I would however like to use a third party profiler for the following reasons to validate Unity's profiling data to have more visibility into how the app is running, including Unity's functions, etc. the largest lag spikes cause unity's profiler to run out of samples. I'm however very interested in precisely these spikes I'd like to have profile data for longer periods than unity records for I'd like to do analysis over time (not just detailed data for each frame, but also aggregated over a time span) Essentially I'd like as much visibility as possible to make Android on device profiling as comprehensive as possible. As close to Instruments on iOS as possible. So far I've tried with DDMS, but could only get visibility into Andoid OS functions and seeminly nothing in the actual apk at least nothing I recognised. I tried with mono2x and il2cpp, with all debug features that I'm aware of in build and player settings enabled. The game is developed with Unity 5,4 with Mono2x. All help is appreciated. I've listed my intents above, so even if profiling on device is not possible in this way on Andoid, alternate solutions to the listed intents are still very appreciated. Thanks!


Unity3d iOS build restarts when regaining focus from browser I have an app made in Unity3d for android and iOS. In it, the user has the ability to link their accounts with Facebook and Twitter. For Facebook I use their Unity plugin, for Twitter, I open an external browser page that lets them accept or decline Twitter integration that then redirects to a php page the calls the app URI to return focus to Unity. On Android this all works perfectly using an Intent in the Manifest. In IOS I'm running into issues though and I don't really know my way around XCode. I'm using the newest version, XCode 7 Beta 2. The App runs as expected but for both the Facebook and Twitter authentications, upon returning focus to the App from the Browser, it completely restarts the App as if just launched rather then returning from a suspended state. In the Unity build I have "Run in Background" selected. I setup the URL Scheme in XCode. Its a pretty basic app so I don't think its being closed due to Memory usage. Any ideas or any settings I can change in XCode that might be preventing it from resuming? Note, if I just hit Home and send the App to the background it will properly resume, its only when called by the URI from the browser that it seems to completely restart.


How to make camera smooth when following player When my character moves through my cameras 'FollowPlayer' script, the background just looks really glitchy and bad Is there anyway to fix this? This is my script using UnityEngine using System.Collections public class FollowPlayer MonoBehaviour Transform bar void Start() bar GameObject.Find("PlayerMovingBar").transform void Update() transform.position new Vector3( bar.position.x, transform.position.y, transform.position.z)


Load custom resources in Unity The situation is I work in my free time on one study project. I have resources of one game packed in it's own format. My intent was to use those with Unity without converting them into Unity's inner format. But with brief analysis of Unity Api Reference I did not find anything that would help my in my efforts. Like I have custom binary files I would need to parse with Unity and upon that data create geometry, lights and so on using Unity's classes. So I wonder if it's even possible? I would really appreciate if anyone would show make a hint on this subject


How to vary the initial velocity of a jump based on hold time? What I want to do is, the longer player holds the screen, the longer distance the object will jump when they release the hold. Here is my code private float timeBeginTap switch (touch.phase) Finger start touching the screen case TouchPhase.Began print("Start tapping") timeBeginTap Time.time break Finger leaving the screen case TouchPhase.Ended when finger release,the object jump float timeHolding Time.time timeBeginTap Debug.Log( "The player1 touched the screen for timeHolding seconds.") Vector2 jumpVelocity new Vector2(timeHolding, timeHolding) rb.velocity rb.velocity jumpVelocity break So with the code above I can get the value like 0.6324167, or 0.423567 for timeHolding, which is the amount of time that user hold the finger on screen. And I able to make the object jump by using this code below Vector2 jumpVelocity new Vector2(timeHolding,timeHolding) rb.velocity rb.velocity jumpVelocity But the distance traveled or "force" with which the object jumps is very small and it doesn't make sense. Therefore I make an attempt with the code below float right 5 float up 10 Vector2 jumpVelocity new Vector2(right timeHolding,up timeHolding) rb.velocity rb.velocity jumpVelocity With the code above, the distance is of course longer. But it feels constant and not dynamic, because the relationship between the Vector2's X and Y value is always constant. Therefore my question is, What is the correct way to define the values of X and Y for a Vector2 object based on the value of Time? If I missed anything, please guide me in the right direction. Desired Outcome For example,the velocity added to the box is to let the box jump from pole to another pole and stand on it. The velocity is define by using the time user hold on the screen,the longer the user hold on screen,the greater the velocity,means the x,y value of Vector2 is define by the timeHolding. Now when I hold the screen for the long time,the box will jump to the 3rd or 4th pole,and it not guarantee will reach the pole.Like everything is by chance. What I want is,the box will jump from 1st pole to 2nd pole,from 2nd to the 3rd and continuously.At the same time,the velocity to go higher or lower and the distance is depends on the time user hold the screen. This is what I want and my limited understanding of the problem.


Response to form triggers creation of zero or more duplicate scenes I've got two scenes, one with room 1 and one with room 2. In room 1 I've got one table with two 3D assets on top of it. This room also has a door that connects to room 2 through a door but it's closed. Once going near the 3D assets a dialog pops up saying to click "E". This pops up a 2D form one needs to fill. Only after filling both forms I'm able to go into room 2. Now what I would like to do is, depending on the response in the form, one or more duplicate room 2 scenes should be created and dynamically added to the scene. If with scenes isn't possible, what's the way to do such thing? Know about SceneManager.CreateScene but this creates an empty scene, not exactly what I want to.


Generate random position within object I have a plate object which is generated somehow (I don't care how), now I want to put another object within this object on random position. Lets say that I want to put random trees on this plate. How can I achieve this in Unity. I had read for bounds but I don't know how to use it to generate position for the tree.


Calculate required position to keep object centered when camera is rotated I always want to keep an object in the center of view of a camera. When the camera's rotation X value is 45, the object should still be centered. Therefore I need to calculate the new position of the camera. How could the "required camera position Y value" be calculated? Thank you.


Unity 2D collisions imprecise I am trying to make a platformer. For the player character I am using a kinematic rigidbody because I want to calculate the jump curve myself (including physics amp gravity). The platforms are also kinematic because I want them to move. I am having issues with the collision detection being imprecise causing the sprite to not stand exactly on the platform after jumping (as seen in the three images taken after three different jumps). This issue also causes the sprite to get stuck in the ground sometimes. The left image is the character inspector and the right is the platform inspector. The jump movements are done with movePosition, and I tried many things to fix this. I tried the following decreasing the timestep from 0.02 to 0.01, using onCollisionStay to keep it exactly on the platform, adding a physics material with zero friction, using edge colliders amp capsule colliders, using interpolate and extrapolate. https imgur.com a Kech2Qy


problem using OnStartServer() for unity multiplayer networked game UPDATE i am still scratching my head over this. The way i see it, the Awake() function is only invoked when I load it in the Editor, but if I put the prefab Loading line into OnStartServer() it just doesnt load anything, presumably because it hasnt managed to load the prefab yet ... i think it is something to do with when it switches Scenes from the offline to online in NetworkManager, i think this script and others are being dropped because the DontDestroyOnLoad command wasnt called due to Awake not being called. Hello everyone I am making a football game which you control one player from the team. It will connect 11v11 players per server (using a "Host" acting as server and client, and other clients connecting to them) I believe I have followed the examples and information provided by Unity to the letter, but I can't seem to get it working properly. The problem My code seems to work fine, provided I open the 'Host' instance from the Unity Editor, but if I make the full build version the Host it doesnt work. Strangely all my player objects will all spawn and act exactly as I intended, but the ball will not spawn unless the 'Host' instance is the one opened inside Unity Editor. I've made the Ball a Network Identity, NetworkTransform etc and Registered Prefab in the NetworkManager in inspector. Here's the code I am using to spawn the ball on the server, what could be the problem as I really have no ideas, thanks using UnityEngine using UnityEngine.Networking public class MatchdayManager NetworkBehaviour GameObject ballPrefab private void Awake() DontDestroyOnLoad(this) ballPrefab Resources.Load lt GameObject gt ("Prefabs Ball") public override void OnStartServer() Debug.Log("on server start called") GameObject go Instantiate(ballPrefab) NetworkServer.Spawn(go)


How can i check when rotation is ended? At the top of script public Quaternion lookRotation In Update void Update() transform.rotation Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime RotationSpeed) I want to know when the transform rotation ended and is at lookRotation Maybe using some flag ? This is my code using System.Collections using System.Collections.Generic using UnityEngine using UnityStandardAssets.Characters.FirstPerson public class FadeScript MonoBehaviour public UnityStandardAssets.ImageEffects.Blur blur public UnityStandardAssets.ImageEffects.BlurOptimized blurOptimized public FirstPersonController fpc public float fadeDuration 5 public float startAcceleration 0.6f public float endAcceleration 0.6f public float maxSpeed 1.0f public float rotationSpeed 0.6f private Material material private float targetAlpha 0 private float lerpParam private float startAlpha 1 private bool rotated false private Quaternion clampedTargetRotation void Start() material GetComponent lt Renderer gt ().material SetMaterialAlpha(1) fpc.enabled false void Update() lerpParam Time.deltaTime float alpha Mathf.Lerp(startAlpha, targetAlpha, lerpParam fadeDuration) SetMaterialAlpha(alpha) if (alpha 0) fpc.enabled true if (rotated false) fpc.GetComponent lt FirstPersonController gt ().enabled false rotationSpeed Mathf.Clamp(rotationSpeed startAcceleration Time.deltaTime, 0, maxSpeed) if (fpc.transform.localRotation Quaternion.Euler(0,0,0)) fpc.GetComponent lt FirstPersonController gt ().enabled true rotationSpeed Mathf.Clamp(rotationSpeed endAcceleration Time.deltaTime, 0, maxSpeed) blur.enabled false blurOptimized.enabled false rotated true clampedTargetRotation Quaternion.RotateTowards(fpc.transform.localRotation, Quaternion.Euler(0, 0, 0), rotationSpeed Time.deltaTime) fpc.transform.localRotation clampedTargetRotation public void FadeTo(float alpha, float duration) startAlpha material.color.a targetAlpha alpha fadeDuration duration lerpParam 0 private void SetMaterialAlpha(float alpha) Color color material.color color.a alpha material.color color What i want in the rotation part is to start the rotation slowly and then accelerate a bit and then in the end when it's getting "close enough" to 0,0,0 so start accelerate down until complete stop. Complete stop not must be at 0,0,0 but close to it. Th way i'm doing it now is wrong i'm not using the t 0 1 solution and not courtine. The rotation now in my script is almost working as i want. It start slowly and accelerate but in the end it stop at once without smoothly accelerate down.