Client not executing commands in Unet Edit Okay, so I partially solved the problem by adding a rigid body component to the capsule. I read somewhere that apparently you have to have one in order to move on the server. Problem 2 The next problem I have is that I can now move a capsule that is spawned by the client fine and the host can move it as well as many times as they like. The problem I am getting now is that when the host spawns a capsule the client cannot move it at all and I get a sort of glitch effect on the client side and the capsule still doesn't move on the host side. Is there a reason why it would only work one way and not the other way around? I thought at first it might have to do with Spawn vs SpawnWithClientAuthority but that doesn't seem to make a difference. Project Summary I have a pretty simple multiplayer project, all I want to do is have one player host and the other join as a client. Once they are joined together the two players can spawn a capsule and then when the user clicks on a capsule. They should be able to pick it up and move it around the scene and the other player should be able to see this action. I can get both players to connect to the server and spawn their own capsule and both players can see this. The movement script is done as well. However, it is only transmitted on the host side. When the client picks up the object it does not update on the server. Problem I have done a bit of debugging and have found that when I call the command on the client it is not being executed at all through line breaks and simple debug statements. Code public void OnInputClicked(InputClickedEventData eventData) Debug.Log("clicked") if (isLocalPlayer) if (Physics.Raycast(transform.position, direction transform.forward, hitInfo out hit, maxDistance range)) Debug.Log("Hit capsule") objectID GameObject.Find(hit.transform.name) objNetId objectID.GetComponent lt NetworkIdentity gt () playerIDThatClicked player.GetComponent lt NetworkIdentity gt () CmdAssignAuthority(objNetId, playerIDThatClicked) Debug.Log("grabbed") else if we are releasing the object we want to unassign our authority if (objNetId ! null) CmdAssignAuthority(objNetId, playerIDThatClicked) objNetId null Debug.Log("released") Command void CmdAssignAuthority(NetworkIdentity target, NetworkIdentity player) Debug.Log("inside cmd") current target.clientAuthorityOwner playerconn player.connectionToClient if (current ! null amp amp current ! playerconn) Debug.Log("Had authority now removing and replacing") target.RemoveClientAuthority(current) target.AssignClientAuthority(playerconn) else if (current ! null) Debug.Log("removing authority") target.RemoveClientAuthority(current) else if (current null) Debug.Log("No authority, adding one now") target.AssignClientAuthority(playerconn) else Debug.Log("CmdAuthority error") target.RemoveClientAuthority(playerconn) Question Am I calling this command correctly? The script is attached to a player prefab and the capsule prefab contains a network id and a network transform. I am pretty new to Unet and this feels like a noob mistake.


Google Play exclude devices I have a game that I'm developing in Unity. The game will be released for Android, so I'm working with the Google Play Console. The thing here is that I don't know how to block (Made not available) some devices with certain properties. For example, I need to made my game NOT available for tablets and for devices that don't have at least 1 GB of RAM. Does anyone know how can I do this?


Separating scene generation and scene starting in Unity? I'm working on a game, where the map is generated, and The map is generated in an Awake(), so when an object's Start() is called, the map should be fully initialized. But the scene's physics world won't be updated till the next FixedUpdate. So when Start() is called, there is a high chance, that physics operations are done in an incorrect world (like raycasting) I tried using Physics.SyncTransforms, but it didn't solve the issue for some reason. (Why?) My next approach was to start the objects with a delay. Precisely after a FixedUpdate. So I started a Coroutine in the Start() method, which waits for a FixedUpdate, then starts the object. But this caused that for example ObjectA's Update() is called before ObjectB's Start coroutine finishes. How could I achieve that scenes won't be started until the scene is fully initialized? Is there a way to tell Unity to call every Start() i.e. 1 frame later? Or how else could I fix this? What is the best solution?


How should a Unity object control it's state? I've been using Unity's component based design, and the biggest problem I've faced is how to control an object's( not component's ) state. The problem is, some components must act differently based on the object's state. However, checking an object's state within a non specific component( imagine we have a "DamageEnemyComponent" ) won't work at all because it makes assumptions about the object it's attached to. The alternative is to make each component perform one, and only one function. The components are then disabled enabled or added removed depending on the object's state( probably managed by a more specific component. ) Imagine we have a "Boomerang" object. Assume it has only two states idle( being held by the player ) and firing. In the idle state, the boomerang would have very few components, because we don't want it to interact with the world while it's simply being held. It may have components to listen for a "throw", though. Once it is thrown, some state manager on the object needs to update the object to have components for moving, damaging enemies, maybe picking up items etc. When the boomerang is back in the hands of the player, it's component list would need to be restored. This would work, but it would basically be building a new game object for each state, which is incredibly tedious and messy without Unity's editor. Not to mention the inheritance and interfaces can't be used well here( since the state specific components will be built into the state manager script. ) I can't see a way to control state using Unity's components. How is this usually done? It feels as if Unity should provide a way to build different states in the editor, much like building an object.


Double jump, without allowing two jumps after falling down a cliff I created a script that allows the player to double jump, which works like a charm. The problem is if the player walks off a cliff, they will still be able to jump twice. But that isn't how double jump works, right? Can someone tell me how to make it so that if the player falls down a cliff, they will be able to jump only once? using System.Collections using System.Collections.Generic using UnityEngine public class PlayerController MonoBehaviour private Rigidbody2D rb private Animator anim private float movementInputDirection public float movementSpeed 10f public float jumpForce 16f public int amountOfJumps 1 private int amountOfJumpsLeft private bool isFacingRight true private bool isWalking private bool isGrounded private bool canJump public float groundCheckRadius public LayerMask whatIsGround public Transform groundCheck void Awake() rb GetComponent lt Rigidbody2D gt () anim GetComponent lt Animator gt () void Start() amountOfJumpsLeft amountOfJumps void Update() CheckInput() CheckMovementDirection() UpdateAnimations() CheckIfCanJump() private void FixedUpdate() ApplyMovement() CheckSurroundings() private void CheckMovementDirection() flips sprite if (isFacingRight amp amp movementInputDirection lt 0) Flip() else if (!isFacingRight amp amp movementInputDirection gt 0) Flip() if(rb.velocity.x ! 0) isWalking true else isWalking false private void UpdateAnimations() anim.SetBool("IsWalking", isWalking) private void CheckInput() movementInputDirection Input.GetAxisRaw("Horizontal") if (Input.GetButtonDown("Jump")) Jump() private void ApplyMovement() player movement rb.velocity new Vector2(movementSpeed movementInputDirection, rb.velocity.y) private void Flip() isFacingRight !isFacingRight transform.Rotate(0f, 180f, 0f) private void Jump() if (canJump) rb.velocity new Vector2(rb.velocity.x, jumpForce) amountOfJumpsLeft private void CheckSurroundings() isGrounded Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround) private void CheckIfCanJump() if (isGrounded amp amp rb.velocity.y lt 0.01) amountOfJumpsLeft amountOfJumps if (amountOfJumpsLeft lt 0) canJump false else canJump true private void OnDrawGizmos() Gizmos.DrawWireSphere(groundCheck.position, groundCheckRadius)


How to play GameObject (ParticleSystem) and stop? Have a game where you've to shoot somethings and when you hit the GameObject I've should play. I've tried with Instantiate but I can keep shooting even if the gameobject is destroyed. What should I do in order to fix it? public GameObject particlesystem void Start () particlesystem GameObject.Find("Effect") void Hit() Destroy(gameobject) Instantiate(particlesystem, transform.position, transform.rotation) This is how I handle it now, but as I wrote earlier I can keep activating the particle system.


How can I improve the current enemy spawning system for my strategy game I'm currently making an RTS game for mobile where mini battles would take place on tiny battlegrounds. The problem is that currently the player is spawning its units based on a currency system, whereas the enemy is spawning based on a timed system. The timed system would make sense in a tower defense game, but not here. Here is a short clip of it in action https twitter.com LewanayG status 1378009426808950794 This is my current spawn script void Start() start spawning waves StartCoroutine(SpawnWaves()) IEnumerator SpawnWaves() before spawning the first enemies, wait a moment yield return new WaitForSeconds(startWait) while (true) if not all characters of this wave are spawned, spawn new enemy and that wait some time before spawning next enemy in this wave for (int i 0 i lt startEnemyCount i ) int random Random.Range(0, enemies.Length) GameObject newEnemy Instantiate(enemies random , transform.position, transform.rotation) as GameObject newEnemy.transform.parent enemyParent.transform yield return new WaitForSeconds(spawnWait) to add some randomness between spawns make sure the next wave contains more enemies than this one startEnemyCount extraEnemiesPerWave wait before starting the next wave yield return new WaitForSeconds(waveWait) Under the current system, as long as the player has more units on the battleground than the current spawn rate of the enemy it will win, and its really difficult to balance this game based on the two spawn systems. How do you suggest I handle this problem and the spawn system of enemy units?


How can you detect object s using raycast from mouse cursor? using System.Collections using System.Collections.Generic using UnityEngine public class CameraRaycast MonoBehaviour public Camera cam void Start() void Update() Ray ray cam.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0)) RaycastHit hit if (Physics.Raycast(ray, out hit, 1000)) if (hit.transform.tag "Interactable") print("I'm looking at " hit.transform.name) else print("I'm looking at nothing!") This is working fine but this send raycast hit from the camera. I want to send the raycast from the mouse cursor so if the mouse cursor is moving over object it will detect it. Just instead the camera the mouse cursor.


Center attribute of BoxCollider2D not working? I've been trying to make a laser beam for my 2D shmup. I've set up a LineRenderer, along with a box collider 2D, and I've noticed that the center of the collider is positioned at one end of the line. My settings are Line 2 Elements (1)0x 0y 0z (2)0x 0y 10z Not using World Space Rotated 90 on the Z axis (to face the 2D camera) I thought the Center attribute would align the box collider, but changing the X value seems to do nothing. Is it possible to align the box collider such that it is around the beam, and not sticking outside of it? Image reference


Should I do interactions between a new class and the main engine via a redirector class, or directly refer to only the classes the new class needs? I'm making an open source voxel engine, and there's an architectural problem that I would like an answer to. I have come up with 2 different solutions, and would like your opinions on When I'm creating a new class for a feature that uses the voxel engine, should the new class only refer to a big re director class called VoxelWorld that redirects the calls to whatever component is responsible for it (solution 1), OR should the new class directly refer to only the classes it actually needs. Simply put, should the new class refer to the entire voxel engine, or just the parts it needs to? This may be similar to a monolithic vs microservice problem? Solution 1 All interactions go through a single entry point (I shall call it the VoxelWorld class). It's a single class, which would redirect all calls to whichever component is responsible for it. Examples of those calls would be for example VoxelWorld.GetVoxelData(position) or VoxelWorld.UnloadChunk(position). These calls would be coming from wherever, maybe a custom class made by the user such as a TerrainDeformer. The TerrainDeformer would only have a reference to VoxelWorld, and nothing else (except for all the parameters it needs to deform the terrain, such as the deformation range). The TerrainDeformer would simply call VoxelWorld.EditTerrain(listOfModifications), and that's it. The VoxelWorld would be responsible for redirecting the EditTerrain call to whichever class is responsible for editing the terrain, for example, a VoxelWorldEditor. The VoxelWorld.UnloadChunk call would be redirected to ChunkManager, which is responsible for managing chunks. Here's a picture to better explain it The public VoxelWorld would be the only public class in assembly A. Everything else is internal, meaning they are only visible for other classes inside assembly A. The assembly A is also like a black box, it is mostly (except for the VoxelWorld) hidden from the outside project. It just works, that's not a good ideology, but sometimes a necessary one. Everything in assembly B is easily extensible and public to the user. It contains the code the user would be messing with. VoxelWorld would essentially by only a redirector of calls. It would have absolutely no logic, only redirections. A function in VoxelWorld.cs could look like this public void LoadChunk(int x, int y, int z) ChunkManager.LoadChunk(x, y, z) Solution 2 Everything that the user wants to add refers to only the classes it really needs. Now, forget all that public internal redirecting stuff from solution 1, but keep in mind the different classes. This is kind of like the interface segregation principle, but just without the interface part. The interface segregation principle (ISP) states that no client e.g. TerrainDeformer should be forced to depend on methods it does not use e.g. LoadChunk In solution 1, everything depends on everything. That's the blessing and the curse of solution 1. In solution 2, that's not a problem because a class only depends on what it actually needs. Solution 2 is more traditional and maybe cleaner gt easier to maintain. I feel like I like solution 2 more than solution 1, but both seem good. Here's the main benefits and disadvantages Solution 1 Easy to use API (VoxelWorld.DoWhatever()) It contains a black box, so it's harder for the user to extend the very core features. (Of course, it wouldn't be an actual black box, this is open source, it's just something that the user shouldn't mess with) Solution 2 Easier to maintain and extend More difficult API, everything is scattered so the user has to explicitly know if some feature already exists (in solution 2, the user can just scroll through the suggested functions for VoxelWorld. ()) So, which solution do you recommend, and why? Or is there some third solution that I haven't thought about? This was quite a long question, but I hope it can help others who might have the same problem. I tried googling but didn't find anything related to this kind of problem, but I didn't really even know what to search for.


Why is my canvas being rendered underneath everything? I'm currently trying to implement a UI that will overlay a scene and follow a scene's main camera, but I'm running into some issues. When I set canvas's mode to Screen Space Camera, the Z position of the canvas is always set to 89.5, which is behind all of the objects that are generated into my scene, making the canvas and the UI elements on it completely invisible to the player. This is the game preview before running the game, with the UI elements clearly visible This is the game while it's running in the editor, with the UI elements not visible at all This is what my hierarchy looks like This is what the properties for the canvas look like Why is my UI not visible when I run my game? How can I fix this?


How do you de serialize a monobehaviour class? It seems JsonUtility.FromJson does not work for MonoBehaviour classes (and I can't get Newtonsoft to parse strings to Vector3s) Suppose you have a MonoBehaviour class like this (so that the values can be easily specified in inspector in editor) public class PropertyClass MonoBehaviour public Vector3 location public string name Suppose you have json data downloaded as a string called text, that you try to convert to PropertyClass format via using an JSONHelper around JSONUtility.FromJson(text) How do you have it autopopulate? If you specify a FromJsonOverwrite solution how do you have that work with JSONHelper? using System using UnityEngine using System.Collections public static class JSONHelper public static T FromJson lt T gt (string json) Wrapper lt T gt wrapper UnityEngine.JsonUtility.FromJson lt Wrapper lt T gt gt (json) return wrapper.Items public static string ToJson lt T gt (T array) Wrapper lt T gt wrapper new Wrapper lt T gt () wrapper.Items array return UnityEngine.JsonUtility.ToJson(wrapper) Serializable private class Wrapper lt T gt public T Items


Paint with soft brush (logic) During the last few days I was coding a painting behavior for a game am working on, and am currently in a very advanced phase, I can say that I have 90 of the work done and working perfectly, now what I need to do is being able to draw with a "soft brush" cause for now it's like am painting with "pixel style" and that was totally expected because that's what I wrote. My current goal consist of using this solution Import a brush texture Create an array that contain all The alpha values of that texture When drawing use the array elements in order to define the new pixels alpha And this is my code to do that (it's not very long, there is too much comments) The main painting method theObject the object to be painted tmpTexture the object current texture targetTexture the new texture void paint (GameObject theObject, Texture2D tmpTexture, Texture2D targetTexture) x and y are 2 floats from another class they store the coordinates of the pixel that get hit by the RayCast int x (int)(coordinates.pixelPos.x) int y (int)(coordinates.pixelPos.y) iterate through a block of pixels that goes fro Y and X and go brushHeight Pixels up and brushWeight Pixels right for (int tmpY y tmpY lt y brushHeight tmpY ) for (int tmpX x tmpX lt x brushWidth tmpX ) check if the current pixel is different from the target pixel if (tmpTexture.GetPixel (tmpX, tmpY) ! targetTexture.GetPixel (tmpX, tmpY)) create a temporary color from the target pixel at the given coordinates Color tmpCol targetTexture.GetPixel (tmpX, tmpY) change the alpha of that pixel based on the brush alpha myBrushAlpha is a 2 Dimensional array that contain the different Alpha values of the brush the substractions are to keep the index in range if (myBrushAlpha tmpY y, tmpX x .a gt 0) tmpCol.a myBrushAlpha tmpY y, tmpX x .a set the new pixel to the current texture tmpTexture.SetPixel (tmpX, tmpY, tmpCol) Apply tmpTexture.Apply () change the object main texture theObject.renderer.material.mainTexture tmpTexture Now the fun (and bad) part is the code did exactly what I asked for, but by asking to draw anytime with the brush alpha I found myself create a very weird effect which is decreasing the alpha value of an "old" pixel, so I tried to fix that by adding an if statement that check if the current alpha of the pixel is less than the equivalent brush alpha pixel, if it is, then augment the alpha to be equal to the brush, and if the pixel alpha is bigger, then keep adding the brush alpha value to it in order to have that "soft brushing" effect, and in code it become this if (myBrushAlpha tmpY y, tmpX x .a gt tmpCol.a) tmpCol.a myBrushAlpha tmpY y, tmpX x .a else tmpCol.a myBrushAlpha tmpY y, tmpX x .a But after I've done that, I got the "pixelized brush" effect back, am not sure but I think maybe it's because I'm making these conditions inside a for loop so everything is executed before the end of the current frame so I don't see the effect, could it be that? Am really lost here and hope that you can put me in the right direction.


Head tracking stuttering lag blur issue with Google Carboard I am working on Virtual Reality app. I have created a city terrain and when I move around the terrain using keyboard it move smoothly but when using head tracking I feel a lag blur when I move or look around the scene using Google Cardboard. How can I improve the performance.Is there any method in unity?


How to get good movement synchronization in a networked game (action shooter) I've spent the last two days trying to get good movement interpolation with Photon in Unity but I can't get anything that I'm happy with. I've tried several methods but none satisfied me. My understanding is that I better use some kind of interpolation (as opposed to extrapolation dead reckoning) because in my game the players can change direction fast. I've tried lerping between the current position and the last received authorized position, I've tried lerping between the old and the new authorized position, but nothing gives me the right amount of responsiveness smoothness. What can I do? Sample code public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) if (stream.IsWriting) do we have authority over this object? stream.SendNext(transform.position) stream.SendNext(transform.rotation) else newNetworkTime Time.time oldPosition transform.position oldNetworkPosition networkPosition networkPosition (Vector3)stream.ReceiveNext() networkRotation (Quaternion)stream.ReceiveNext() void RemoteMovement() float t 1.0f ((newNetworkTime interpolationPeriod Time.time) interpolationPeriod) transform.position Vector3.Lerp(oldPosition, networkPosition, t) transform.rotation Quaternion.Lerp(transform.rotation, networkRotation, Time.deltaTime movementSpeed)


Unity, Which side of Collider2D was hit by raycast? I've got a player firing out 2d raycasts. If one of them hits a boxcollider2d I would like to know if it hit the top side, bottom side, left side, or right side. How would I go about doing this? I've tried using Bounds but that didn't work out very well.


2d ParticleSystem batching problem I have multiple ParticleSystems with TextureSheetAnimation pointing to the same texture, using different offsets rows to choose different textures. They seem to batch with each other, but they're also being split by Unity into multiple batches in a strange manner. Here's a Frame Debugger view These 4 Draw Dynamic are on the same atlas, using Mobile ParticlesAdditive shader. The reason of breaking batching is Objects have different batching keys. This is usually caused by using different vertex streams on ParticleSystems or by mixing Lines and Trails, or by mixing lit and unlit geometry. All of the ParticleSystems have a simple setup, some Color Over Lifetime, some Velocity Over Lifetime etc. The strange thing is that Unity breaks batching like it makes one batch, puts half of the stars and half of the smokes into that, and then, makes another batch from these two. So they do batch, and the don't o.O I couldn't find and help on the web about this issue. I'd be glad for help.


IronPython with Python in Unity How should I manage dependencies Python side? I am currently trying to get Python working in Unity, and I was wondering how would I manage dependencies on the Python end. For example, say I have a Python script with the following dependencies import tensorflow as tf import numpy as np import cv2 I would like to get these working in IronPython in Unity. Does IronPython have it's own package manager like pip for this, and if so, how would I go about integrating this in Unity? Is there other .dlls for specific packages? Thanks in advance.


What is the Unity 2019.3.5 version of UnityEngine.UI.Text ? I was following a tutorial on how to create a dialogue Box in Unity, and in one part of the tutorial the tutor imports UnityEngine.UI and creates an object of type Text, but my version of Unity is 2019.3.5f1 and I learned through searching a bit online that this UnityEngine.UI doesn't exist anymore in this version, and that it was replaced with UnityEngine.UIElements, and this Text type doesn't exist anymore as well. I couldn't find a replacement for Text or what is the new nomenclature, nothing from trying stuff that popped in the auto complete or searching for answers in the Internet gave me answers. Maybe I just searched poorly, but if anyone happens to know, could you kindly answer?


How to make Frame Independent Timer Clock I want to make a frame Independent Timer that it work consistently across different computer configuration.


Multi level 3D grid based pathfinding in Unity I'm trying to come up with a way to pathfind on multiple levels. See image The orange walls would be considered a ladder, connecting you to the upper levels. At first I thought of looking at it as though it were top down 2d, but I also need to be able to go under things at some point. How can I compute these paths?


Why Does unity LightPosition 0 Seem to Depend on Camera Position? I'm trying to write a fairly basic shader but I keep running into lighting issues with Unity. My first problem was trying to figure out which variable stored the light's position in world space. (I'm only working with one light, at least at the moment). I finally found something that responds to movement of my light source unity LightPosition 0 . However the shader still didn't do what I wanted it to do, so I did some debugging I have a basic vertex and fragment shader and what I'm currently doing in the fragment shader is float4 c float4(0, 0, 0, 1) float3 lp normalize(unity LightPosition 0 ) c.rgb lp return c This should just set the color of my object to the normalized position of the light source, correct? What I see in my scene is my object changes colors when I move my camera around it (I'm not moving the light source at all, it is a separate entity). The color also seems to increase in strength as I zoom in. To me, it seems as if unity LightPosition 0 is related to my camera's position, as well as orientation and zoom level, yet the documentation I've found says it should represent the position of the light in world space. I tried switching to using the following float3 lp float4( unity 4LightPosX0 0 , unity 4LightPosY0 0 , unity 4LightPosZ0 0 , 1.0 ) ...but that only colors my object red regardless of the light's actual position. Additionally, I've set the LightMode tag to Vertex. It seems like simply getting the world position of the light source shouldn't be this difficult. What am I not doing correctly? EDIT I've been playing around with the camera and light position and I think that unity LightPosition 0 actually puts out position in the projection space. If I place the light source in the lower left corner of the screen, the object is black. Upper left the object is green (0, 1), upper right is orange (1, 1), and lower right is red (1, 0). When I place it in the lower left (0, 0) and move the camera in front of it, it becomes blue. This is consistent with the depth value behavior. (0, 0, 0) would appear as blue. Now, how to get it from projection back to world?...or should I use a different variable?


How do I rotate the Camera around the player by Keypress in Unity? I want to rotate the camera around the player by pressing E and Q but it doesnt rotates around the player. I tried RotateAround but didnt worked. Code public Transform player public float smoothSpeed 0.125f public float rotateSpeed public Vector3 offset private Vector3 velocity Vector3.zero void LateUpdate () transform.position Vector3.SmoothDamp(transform.position, player.position offset, ref velocity, smoothSpeed Time.deltaTime) void Update() if(Input.GetKey (KeyCode.E)) transform.RotateAround(player.position, Vector3.up, rotateSpeed Time.deltaTime) if(Input.GetKey (KeyCode.Q)) transform.RotateAround(player.position, Vector3.up, rotateSpeed Time.deltaTime)


How can I evaluate varying conditions in a Scriptable Object? I'm new to using Scriptable Objects, so this might just be a bit of confusion. Let's say we have a Scriptable Object that defines the abilities a character might have in the game, and a character class that triggers these abilities public class Ability ScriptableObject public string Name "New Ability" public int ManaCost 10 public Sprite AbilitySprite public void Execute(ref Character character) if (character.Mana lt ManaCost) return Do something, like instantiating and moving the sprite character.Mana ManaCost public class Character Monobehaviour public int Health 100 public int Mana 100 public List lt Ability gt AbilityList new List lt Ability gt () private void Update() Crude implementation for example purposes if (Input.GetKeyDown(KeyCode.Alpha1)) Abilities 0 .Execute(ref this) if (Input.GetKeyDown(KeyCode.Alpha2)) Abilities 1 .Execute(ref this) Obviously we can make numerous abilities with different mana costs, and add them to each character in the scene as needed some characters may have a "Bolt" ability, while others might have an ability that casts "Fire." The Execute() method will then evaluate whether or not the character can use these ability based on the character's current mana. But what if some of these abilities, all of which have similar effects, needed to also check the character's health, or perhaps a collision state, like isGrounded? For instance, maybe a certain ability can only be executed when the character has the appropriate mana value, and is also airborne. Would it be necessary to make many different subclasses of the Ability class to accommodate these different conditions, each with its own logic? At first I tried changing the Execute() method to take in a bool, like this public void Execute(ref Character character, bool canExecute) if (!canExecute character.Mana lt ManaCost) return The problem with this is that I have to hard code the conditions for canExecute and compare the current ability against its Name, and that sort of defeats the purpose of Scriptable Objects. My goal is to be able to create abilities that might need to check varying conditions while performing the same functionality, and assign them in the inspector to each character as needed.


Unity 5.5 Android scaling The questions I've seen are outdated, explained, not to my liking, or just don't work. Problem I want to be able to create a game that can scale on all mobile devices with ease and with no pixelation. Extra Info I'm very new to unity and tackling the the software with all my might I'm sorry for being a noob. I already paired unity with my phone and set the build to android (Nexus 5). Aspect ratio is 10 16, The game is going to be portrait. I have no scripts or anything, Its legit a blank game with a camera that has a blue background. I have some pictures, if you need anything else for my assistance don't hesitate I'm here to learn and take, GULP, Constructive Criticism. PC Android


Directory.CreateDirectory() created a folder with name that was supposed to be a file i am experiencing some problem here , i have a path " folder folderagain file.xml" i tried to use Directory.CreateDirectory() to create all folder (in case one of them is missing) and then reuse the path to create a file in another place inside the script. But instead a folder named "file.xml" was created by Directory.CreateDirectory() and my script got blocked from creating the file . I managed to solve this problem by creating 2 different path , one of them end with file.xml and the other does not. But is there any better way to do it ? can i tell Directory.CreateDirectory() to create only folder ?? look at screenshot below , there's System.UnautorizedAccessException error because my script trying to create file named "keymap.xml" but a folder with the exact name already exist so it thrown that error .


Animation imported from Blender into Unity via FBX doesn't play? I started building this model in Blender and gave it a simple animation that rotates the board about the axel. ...I exported it as FBX and imported it into Unity. I can see the animation is stored in the file when I import, but I can't find an animation file after I drop it in the scene, and there is no controller for the Animator controller it generated, either. I can watch the animation play in the FBX preview thumbnail but nowhere else. How can I get my animation working?


Vision Cone for Enemy AI in Unity 2d I am trying to develop an Enemy AI with vision cone in unity 2d top down game, can you please suggest me some approach or sample script, so I can get an idea.


Why do my point lights disappear when another nearby light is above 1.85 range? I'm making a game with a dungeon setting in Unity 3D. Many torches line the walls. I'm using a point light over each torch to simulate the flame. However, when two torches are across from each other, and one goes above the 1.85 range, the other disappears completely, giving off no light. What might be causing this?


Best way to create icon for UI , based on 3d model player can use in game I'm trying to figure the best way to create icon (for UI) from my 3d model (object) that player can use in the game. Maybe this is a silly question, but how do you create icon ? Do you create a new scene, place object and use a "shift print" to take screenshots ? Others way ? Thanks


Leaderboard not working in Unity I'm trying to create a leaderboard for my game. I have the game created and added the leaderbaord using cloudonce. I have also created the app on google play console and linked the app to the game services. I have followed the following tutorial to create the leaderboard Leaderboard tutorial I have followed the exact same instruction as given in the tutorial. Once the game is over, the leaderboard button is activated. I have attached LeaderboardsButton script(this script comes with the CloudOnce package) to the leaderboard button. Here is the code in the game over panel for getting the score void OnEnable() DisplayGameOverScore() void DisplayGameOverScore() gameOverScore.text ((int)gameManager.playerScore).ToString() gameOverHighScore.text PlayerPrefs.GetInt( quot HighScore quot , 0).ToString() CloudOnceServices.instance.SubmitScoretoLeaderboard(PlayerPrefs.GetInt( quot HighScore quot , 0)) This is the CloudOnceServices script as per the tutorial public static CloudOnceServices instance private void Awake() TestSingleton() private void TestSingleton() if (instance ! null) Destroy(gameObject) return instance this DontDestroyOnLoad(gameObject) public void SubmitScoretoLeaderboard(int score) Leaderboards.HighScore.SubmitScore(score) I have attahced this script to an empty game object along with the InitializeCloudOnce script(this is provided with the CloudOnce package). I have also created an alpha test on googleplay. Once I open the link and start the game, the google play services console open and when I hit the leaderboard button, google play services console loads but after that nothing happens. It just goes back to the game. I read that other people ran into similar issues and the advise given was to check if the SHA1 certificate fingerprint is the same in app signing under release management and the credentials in GoogleApis. They both match. I'm not sure what the issue is?


Creating a planet out of an existing terrain I am creating a game that I have created a terrain for. I really like the terrain so I am wanting to keep it but I want to have the game take place on a full planet. Avoiding paying 200 for an asset already made, how would I develop something to allow me to "tile" this terrain to make a full planet and to make it round instead of flat? I know this has to be somewhat possible with the expensive assets on the asset store that are for round terrains. I just need to figure out how and I can't find anything online that is much help.


How to upgrade a project in Unity Hub Before Unity Hub, it used to be the case that if you opened up a project that was from an older version, you would be prompted to upgrade the project. I am now on the latest Unity Hub 2.0.0 and I am trying to open a project that was last saved with 2018.2.1f1 but I am unable to. From installs, I am able to download and install the closest available version, 2018.2.21f1, but anytime I try to open my project I get the message Missing editor version 2018.2.1f1 on this machine. Select another version from the list or install the missing one. How can I upgrade this project like we did in older versions?


Get Prefab Asset From Gameobject in Edit Mode I want to get a prefab asset (that resides in Project Window) and assign it to a field like the one you get when you manually drag the prefab asset from Project Window to GameObject field But when I try to do the same thing in code (and in Edit Mode) with this function GameObject prefab instance PrefabUtility.GetNearestPrefabInstanceRoot(gameobj) as GameObject I get a prefab instance but not a prefab asset How do I get a reference to prefab asset from the gameobject that was created from it?


How to move objects across a canvas with consistent speed on different screen resolutions? I am making a rhythm game in Unity. I have been using Transform.Translate for moving images on a canvas as the music notes. However, I cannot consistently use this method on different screen widths. The notes move the same amount each frame. I want to use interpolation for my music notes. I want to have the notes reach the center of the canvas at the same time despite the width of the screen. How can I write such a script?


Why does setting a static member value in MonoBehaviour child class constructor have no effect? I am following a tutorial for Unity. I don't know C but I know other similar languages. I got the tutorial to work. Here is the script I used. using System.Collections using System.Collections.Generic using UnityEngine public class PlayerMove MonoBehaviour private Rigidbody rb public float speed Use this for initialization void Start () speed 3.5f rb GetComponent lt Rigidbody gt () Update is called once per frame void Update () float fx Input.GetAxis ("Horizontal") float fz Input.GetAxis ("Vertical") rb.AddForce (new Vector3 (fx, 0, fz) speed) This goes slightly against my C instincts, which are to put initialization values in a constructor. public PlayerMove () speed 3.5f void Start () rb GetComponent lt Rigidbody gt () This doesn't work. In Unity, the speed field has an initial value of 0. Why does setting the initial value in a constructor not work?


I have a problem rotating a 2D game object after collision I'm developing a simple flip game where a cube flips and the bar a it collides with should start rotating after collision. Most snips involve destroying an object, but that's not my case. Here is my code using UnityEngine public class CheckI MonoBehaviour float x public Rigidbody2D rb2d void OnCollisionEnter2D(Collision2D col) if (col.gameObject.tag "bar") x Time.deltaTime 10 transform.rotation Quaternion.Euler(0, 0, x) How do I start rotation after collision?


How to add a volume bar like YouTube for iOS? I am almost done with my game in Unity 5. However when the player presses Volume Up Down, the iOS (version) shows the standard UI to show volume. Android has it's own (looks better on Stock). I want to make my game consistent on either platform and different variations of Android. So I want to recreate how YouTube (for iOS) handles the change in volume. I can't figure this out. Any help would be awesome!!!


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


Unity 2018.4.25f1 Errors error CS0118 error CS0234 I am getting 2 errors in my c script. Assets scripts playerMovement.cs(8,5) error CS0118 'PlayerControls' is a namespace but is used like a type Assets scripts playerMovement.cs(4,19) error CS0234 The type or namespace name 'InputSystem' does not exist in the namespace 'UnityEngine' (are you missing an assembly reference?) playerMovement.cs using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.InputSystem public class playerMovement MonoBehaviour PlayerControls controls Vector2 move void Awake() controls new PlayerControls() controls.Gameplay.move.performed ctx gt move ctx.ReadValue lt Vector2 gt () controls.Gameplay.move.canceled ctx gt move Vector2.zero void Update() Vector2 m new Vector2(move.x, move.y) Time.deltaTime transform.Translate(m, Space.World) I am using the new Input System 0.2.1 in unity 2018.4.25f. The PlayerControls script is auto generated from an Actions Input object, and it is in the main root quot Assets quot .


Why does my tile palette not arrange nicely? I made my own Hex Point Top Tile sprite sheet, ensuring it's pixel perfect and align well. Slicing in Sprite Editor has no problem too. However, when I drag the sprite sheet to a new Palette in the Tile Palette panel, the tiles show up with random spaces. See screenshot below What did I miss? The sprite sheet is here, 30 x 30px offset, 24 x 24px padding, 66 x 66px tile size I'm using Unity 2019.3.10f1.


Using crittercism with Unity I want to use crittercism with my Unity project. In Unity I am developing a game for iOS and Android platform. I did enough Google searching to come to the conclusion that Unity doesn't support this by itself and there aren't much tools out there to help me. Can someone suggest a way to do it? If not, is it possible for me to get access to the editor logs of Unity programmatically so that I can send these logs to my server directly. (I'll however still need to know when a crash occurs.) I was thinking of a "hack". Please tell me if it is doable. On building the project, Unity creates an xcode project for iOS. I was thinking of opening the xcode project itself and putting the relevant commands to send the logs to crittercism, in case a crash occurs. However I am not able to think of a way to do this with Android.


Getting warning after importing plugin to unity5 project I am getting following warning when I import any plugin to my unity5 project.Whats the solution for this warning? Is there any problem with that which will affect my project.


Check Supported Platforms for Editor How can I find out from script(c ) did I download specific platfrom support for current Unity version?


Maintain Vuforia tracking during Unity Ad My game uses Vuforia pos and ground plane tracking. During gameplay players are given the option to watch a video to gain additional health. When 'No' is chosen gameplay resumes fine. However when 'yes' is chosen Vuforia tracking is lost during the video and afterwards all gameobjects are locked in a static position in relation to the AR camera. Is there anyway to maintain pos tracking during the video?


How can I stop transform.position from being modified when adding a child object? I suspect there is a well known and easy to explain reason for the behavior I'm seeing, but I am having difficulty explaining it (and likely not able to Google for the answer). When adding a child GameObject to a translated parent, the child's localPosition is modified so that the child's position stays the same after the parent's transformation is applied. Is there a way to not have this be the case? In the following example, I create a parent object and move it to (1,1,1), and then attach the child. I would like the child's position to be (1,1,1), that is (0,0,0) relative to the parent. However, the child's position is modified to be ( 1, 1, 1) so that it is (0,0,0) relative to the world. Here is a repro Create parent. GameObject parent new GameObject() parent.name "Parent GameObject" parent.transform.parent foregroundObject.transform Move the parent. parent.transform.Translate(1, 1, 1) Add a child under the parent GameObject. GameObject child (GameObject) GameObject.Instantiate(guildiePrefab) child.name "Child GameObject" child.transform.parent parent.transform PROBLEM localPosition is set so that the "global" position is (0,0,0). How can I add the child object and have its position be (1,1,1)? this.Assert(child.transform.localPosition.ToString() "( 1.0, 1.0, 1.0)") this.Assert(child.transform.position.ToString() "(0.0, 0.0, 0.0)") Is there a different way I should be adding child as a child of parent? Or, should I always zero out the position of parent before adding a child? If that is the case, any reason why I need to do this? What is the rational for this design choice?


Text mesh scaling camera distance relative I am searching a fromula that can maintain my text mesh size according to the distance from camera. I want that no matter my camera is near or far from text mesh my text show always with same width an height. I have tried this but the problem is still persist somehow float size (activeCam.transform.position transform.position).magnitude newLocalScale new Vector3(size 108, size 108, size 108) transform.localScale newLocalScale


Exclude a certain folder from Unity? I work with a small team of three people, and we use the collaborate service within Unity to share our progress. One of the folders we have inside our Unity project is an "OffGame" folder, which includes a tool I created specifically to help with the creation of certain assets. It's not actually supposed to be part of the game, but since I'm often making changes to it, I figured I'd include it in the Unity project. The Unity project temporarily makes use of certain files inside said OffGame folder, however, once the game is done, those files will be moved outside of that folder and integrated into the game proper. Since that OffGame folder is not supposed to be part of the game and I only included it there to share it to my teammates over the collaborate service, I don't want it to be treated like a normal folder for the game. Specifically, I don't want Unity to create a bunch of useless meta files for each file in that folder, or to act like a stray .js file in there is part of the project. I actually got compile errors because Unity kept thinking it had to include all the .js files in that folder. How can I make Unity ignore that folder?


Calling functions that needs to be on update() So I have a function DialogueRun() for a Dialogue System that changes the line on the dialogue box whenever you click. Which means it has to be in Update(). My test works so far but my next problem is how to make the whole dialogue box only appear whenever I click on a character. I tried making the characters as buttons and it does make the dialogue box show up whenever clicked, but it won't change the dialogue lines because that function has to be in an update method. I'm looking at OnMouseDown() right now but the result will be probably the same. Any ideas? public void DialogueRun() dialogueBox.SetActive(true) dialogue.text textLine nextLine if (nextLine lt textLine.Length 1) if (Input.GetKeyDown(KeyCode.Mouse0)) nextLine 1 else counter dialogueBox.SetActive(false) return


Unity Mobile How can we safely store our API key? We're making an app in Unity. We're building it for Android and iOS. We also have a server. In order to use our server you need to present our api key for the server. So, we need to store that key in the build somewhere (eg. APK file) But how can we put it anywhere where people wont be able to get it? Eg. they can get the APK and decompile it. SDKS for unity for facebook and so on, store an api key in the client. What do they do?


Jump script using AddForce not working I am making a simple jump script by adding a separate script to the character. I got the character from the Asset Store and I have left it untouched. I have searched the solution and similar problems to this, and I changed the force or JumpHeight to a pretty high value. But it is still nothing. The logs are printed out just fine. public class JumpScript MonoBehaviour public Rigidbody rb public float JumpHeight 7.0f Update is called once per frame void Update () if (Input.GetKeyDown (KeyCode.Space)) Debug.Log ( quot PRESSSED quot ) GetComponent lt Rigidbody gt ().AddForce (Vector3.up JumpHeight) Debug.Log (GetComponent lt Rigidbody gt ())


How long does one have to pay the 125 per month subscription fee for Unity pro? I'm a bit confused by how the subscription for Unity Pro works. If I were to get Unity Pro, do I have to keep paying 125 per month for as long as I'm using Unity pro? Or do I have to keep paying 125 per month until certain period, after which I am no longer required to pay anything? Furthermore, if I developed a game with the personal version of Unity and the game made over 100K, would that result in an immediate penalty or will Unity give me a deadline before which I must get Unity Plus Pro?


Effects of collisons broken glass, damaged cars, how are they created? My question is related in particular to achieving the effects of collision in game engine, how is this done? I have searched a bit, read from the internet and went through a few tutorials, and saw that one way to create one of the effects, explosion, or something breaking is to create the model in pieces, and apply force (in a game engine such as Unity 3D) to make the pieces fly off. It seems to be a solution, but it doesn't address the problem of items that are vaporized in a big explosion, with so many pieces. How is this done? Basic methods and tricks etc would be helpful. Secondly, the problem of things bending and getting damaged on impact, such as a car's front end destroyed when it hits a wall? How is this done? One thing that comes into my mind is to create each component of a car in a different state as an animation in 3Ds Max or Maya, and then in the engine, according to the collision, switch the model state in the time bar. Is this how it is done? Finally, what about materials, such as net of a basketball net, or a soccer goal net for example? Effects of ball hitting it can be calculated and applied in a script, but how to make the net bend and stretch with it? Is it done through models or materials? Also what about a flag fluttering in the wind? My questions are specific to game engines, particularly Unity3D. Some good links on the subject would also be helpful.


UI looks different between editor and in game I am very confused about Unity's UI system. This is how my inventory menu looks in the Editor And this is the view in game Settings Can someone please explain why this happens?


How do I change a value gradually over time? I'm using Unity3D 5 point something, and I'm planning on making a game where the player travels through a hot, dry desert, and so the heat causes the player's energy to deplete. The object of the game is to reach a certain point before the player's stamina runs out. What I was planning on doing is having different landmarks in the game world that the player can visit, and these will help replenish their Health or Stamina.


Do I have to commit the downloadable assets for Unity to the repo? Or a reference for the team to download them? QUESTION (Short version) I am going to use the Unity Test Tools asset to do unitary testing. Q Do I have to commit the Unity Test Tools to my repo? (using git, by the way). CONTEXT Team Workflow We are an indie team of 10 people (of which 4 coders, 2 graphics, 1 music, 2 marketing, 1 automation test QA), remotely located. We built the team 2 weeks ago, have explored Unity, decided that unity shall be our devel framework, and finally we did an internal silly tic tac toe internal for us to check the workflow. Now we want to start developing our 1st game. Clean code. Clean repo. Using git for version control. We configured Unity to write all forced in text and visible metas. We are using Unity5 free edition. Coding Up to now, I've managed to create a MVC schema. MonoBehaviour acts as the Controller and then we have non dependant classes that act as the Model of our game. The controller calls methods of this model. The model throws events to notify the changes in its state. We want to unit test the model. Assets Yesterday I discovered the Unity Test Tools. This is the only downloaded asset, the rest of the assets are made by us. The wonderings presented by this question may happen again if we download other assets or if we want to keep a common own made library across several games. QUESTIONS (Long version) As far as I've seen, assets get "copied" into your project. Okey for working. But... comitting?? I'm feeling uncomfortable. The same way in PHP you may use composer to handle "dependencies" so if you need a library you do not commit it inside your project, you just commit a text file saying "I want this library, this specific version" for the sake of example, you can tell composer to install PHPUnit for unit testing, and you commit the composer text file, you do not commmit a full copy of PHPUnit , these are our questions wonderings Q1) Do I have to commit all the Unity Test Tools in my repo? It is 10 Megas may seem an overkill or not, depending on your optics... but, as it carries "examples" and I don't know how to filter what is needed and what not, it seems so overkill to me to commit all of it but worse this might happen with another asset that is 500 Megas for example. Committing downloadable assets seems anti pattern. Do I have to commit? Q2) Or it is better that I don't, and have all the members in the team to manually download the Unity Test Tools? Q3) If they delete that repo and download it again, the Unity Test Tools seem to be kept local to the project, then a new download is imposed if it's not kept in the repo? Or Unity may store "local in your computer still global to your projects" things like "the testing library" you are likely going to use in several projects? Q4) Case one thinks "maybe each project needs its own version of libraries, best practice is do not keep anything global" then, committing them to the project still seems overkill... is there any standard of "config file" that I can place and then once the "git repo" is cloned, run some kind of "dependency installer" or so (much like the composer install action is to a recently cloned repo in PHP)? I've seeked for information, but I'm still confused on this. I've seen it exists something like an "asset manager" but I'm not sure if this is what I need. Any pointer to documentation I must read will be highly appreciated. Note that the documentation in Unity website, as for example this one Mastering Unity Project Folder Structure Version Control Systems does not address my specific question. Thanks!


How to call animation event from another GameObject I have an animation event but I want it to call a function from a script that is attached to a different GameObject that I'm not animating. Is this even possible?


2 cameras that each player sees through a different one Im very new to Networking in Unity 5. Im trying to bring the finished basis for my 2 player, 1 vs 1, turn based game I made for local multiplayer (both players on same computer) to an online matchmaking system. In the game currently (for local), there are 3 cameras. 2 centered on separate canvases for selecting attacks for each player. that once p1 chooses his attacks and presses continue, the camera is deactivated and the 2nd camera for p2's attacks is activated. Once p2 presses to continue the 2nd cam is also deactivated and the 3rd cam is put on, this camera is set on the battle arena and plays out in turns the moves picked by the 2 players through a turn determining system. What I want to do for the online is have both canvas cameras activated at the same time and each player to be assigned to a different camera. So is there a good way i should do this? NetworkView on one of the cams? Hope I explained the premise enough P


Transparent objects in the scene only get lit half way by point light I have encountered a weird graphics problem, where all of our transparent objects in the scene only get lit half way (only from the y position downward) by a point light. This happens with all of our grass and tree shaders. Also, when looking through translucent objects, they become really desaturated and gray is which is an undesired effect. Does anyone know how to deal with this problem? Please refer to the screenshots below. I'm are using Unity 2020.1.14f, built in render pipeline with a forward renderer. For grass and trees we are using the Fantasy Adventure Environment, but all other grass shaders from other packages have the same problem.


Why the spotlight is working only in scene view window but not in game view? What i did is disabled in the Hierarchy the Directional Light. The Spotlight is child of the character so it will move with it. Then in Window Lighting Settings In the Spotlight i just changed the range and rotation a bit. It's strange since it's showing the light in the scene view but not in the game view not even when running the game. And this is the Spotlight config


How can I instantiate and sync a LineRenderer in multiplayer network? I am trying to make a laser that will be visible to all clients in a multiplayer networked game on Unity. I've tried using a Command Attribute but that hasn't worked. I also found some ideas to use RpcClient but I am not quite sure how to implement that. The code I'm using for the laser (I just run the method in Update) is public void CmdActivateLaser(bool laserState) if (laserState false) return pointer.SetPosition(0, transform.position) RaycastHit endCommand if (Physics.Raycast(transform.position, transform.forward, out endCommand)) finalPos new Vector3(0f, 0f, endCommand.distance) pointer.SetPosition(1, finalPos) else pointer.SetPosition(1, transform.forward 500f)


Unity why game app on Android takes up much more memory than Unity Profiler reports? We are profiling a game app on Android 4.4.2 device via Unity s ADB profiling. We have set up ADB profiling following the official guide http docs.unity3d.com Manual Profiler.html The ADB profiling works fine, when the app is running, Unity Profiler reports its memory usage as following Used Total 100.4 MB Unity 40.5 MB Mono 10.1 MB GfxDriver 34.9 MB FMOD 3.9 MB Profiler 14.8 MB Reserved Total 112.8MB Unity 47.0 MB Mono 15.4 MB GfxDriver 34.9 MB Profiler 15.5 MB Meanwhile, we are also running another performance test tool (i.e. Emmagee, https github.com NetEase Emmagee) to monitor the app, which can monitor CPU, memory, network traffic, battery current and etc. However, the memory usage of the app reported by Emmagee tool is much larger As shown above, Unity Profiler reported 112.8M memory is totally reserved for running the app, but Emmagee tool reported 200M PSS memory is used. Obviously, more than 90M memory taking up is happened somewhere by something that Unity Profiler does not take into account. (We also tried other performance monitoring tool for Android apps, e.g. APT, and the result is similar to what Emmagee reported. The extra memory usage problem remains.) We noticed that the Unity Profiler itself would take up 15M memory, which is included in the profiler s report. Also, we knew that PSS memory includes proportional shared libraries with other processes, but 90M extra is such large amount considering that Unity Profiler only reported 112.8M totally. Our puzzle remained Where does the 90M memory come from? How are they used by the app? Why Unity Profiler does not report the extra memory? What can we do for reducing the extra memory and the total PSS memory of the running app, and or get it close to what Unity Profiler reports? Any help could be appreciated!


Why in the dialogue system it's showing in the conversation only 2 sentences and not the whole 3 sentences? The first script the manager is attached to new empty gameobject I want the conversation to start automatic when running the game so i'm calling the method TriggerDialogue in the manager using System.Collections using System.Collections.Generic using UnityEngine public class DialogueManager MonoBehaviour public DialogueTrigger dialoguetrigger private Queue lt string gt sentences Use this for initialization void Start () sentences new Queue lt string gt () dialoguetrigger.TriggerDialogue() DisplayNextSentence() public void StartDialogue(Dialogue dialogue) Debug.Log("Starting conversation with " dialogue.name) sentences.Clear() foreach(string sentence in dialogue.sentences) sentences.Enqueue(sentence) DisplayNextSentence() public void DisplayNextSentence() if (sentences.Count 0) EndDialogue() return string sentence sentences.Dequeue() Debug.Log(sentence) void EndDialogue() Debug.Log("End of conversation.") Next the DialogueTrigger using System.Collections using System.Collections.Generic using UnityEngine public class DialogueTrigger MonoBehaviour public Dialogue dialogue public void TriggerDialogue() FindObjectOfType lt DialogueManager gt ().StartDialogue(dialogue) Last the Dialogue using System.Collections using System.Collections.Generic using UnityEngine System.Serializable public class Dialogue public string name TextArea(3, 10) public string sentences In the editor I filled the all 3 TextAreas each one with a sentence. Hello world Hi everyone I have woke up When running the game it's showing only to the Hi everyone it's not showing the I have woke up. And it also not showing the "End of conversation." in the log.


Overcoming float limitations for planet sized worlds in Unity As far as I know, going further than 1M units from the world origin in Unity is hardly possible due to floating point precision issues. Making a world more than 1M units in radius would require either using double vars for coordinates or utilizing some space division technique to divide a massive scene into hierarchical chunks with the smallest of them being around 10 000 units, i.e. each world space position would be expressed by the chunk hierarchy the object's in and a bunch of float vars representing its local position (and possibly rotation and scaling) inside the last chunk. Either way, doing this would require implementing a completly new coordinate system, so I'd like to know whether or not that is possible in Unity, and if so, how may I make it work with existing Unity systems like physics and so on. P.S I can't just move the world into origin as the player moves since I want to have things going on simultaneously around the planet. Thanks!


How is entering cover animation done for cover system? I am trying to create a cover system for my 3rd person shooter game in Unity. My implementation is a basic one On Player enter Trigger Player move to preset cover position Player play Enter Cover animation (eg dash to cover) This is fine without root motion enabled, when it is enabled (so the movements look natural), instead of dash amp stop behind the cover, the Player will dash and stuck himself inside the cover (due to root motion). So I am curious, what is a good way to do the animation for cover system?


Draw GUI.Button on certain position on a scrollable background Problem is in a 2D game I have a large background around 2 screens wide. And on there I got 4 buttons placed on top of background all over complete width. Now when I swipe of move my mouse around I scripted that the camera will move with it. So for the GUI.Buttons (Unity4.5) to stick on their place I used a variable drawX drawX Camera.main.transform.position.x 100 The 100 is for calculating it to pixels. I then add this to my buttons when drawing. scaleX Screen.width 1920f scaleY Screen.height 1200f if (GUI.Button(new Rect((500 drawX) scaleX, 700 scaleY, 325 scaleX, 425 scaleY), "")) Now the problem is that under 1920x1200 my target resolution everything works exactly pixel perfect. But when changing the resolution or aspect ratio to something else the drawX increases to much or not enough so the buttons don't move on the same pace as they did in the 1920x1200 version. Somebody got the solution for me?


How I randomise a list of audio clips in Unity and remove it from the list once the clip is finished? I have 4 audio clips. When I play a press a certain button in Unity, the data is sent to MAX MSP and the audio is played. I created a list a signals (As shown below in the code). What I want is that, the signal list is randomised. The user presses a button to listen to the audio (which works fine). Once the clip is finished the user presses Next Trial button. Once the Next Trial is pressed. The previous clip is removed from the list. Once all the clips are finished. A message is displayed in the Debug.Log( quot All trials finished quot ). I have the following problems One of the audio clips is repeated again. It appears that the audio clips are not removed from the list. How do I write the audioclip index to a csv file? Code public class SignalToMax MonoBehaviour private static int localPort private string IP define in init public int port 8050 define in init quot connection quot things IPEndPoint remoteEndPoint UdpClient client experiment case public string experimentCase quot A quot string strMessage quot quot public List lt int gt signals public static int stimIndex void Start() NextTrial GameObject.FindGameObjectWithTag( quot NextTrial quot ).GetComponent() signals new List lt int gt 1, 2, 3, 4 define IP quot 127.0.0.1 quot port 8050 Senden remoteEndPoint new IPEndPoint(IPAddress.Parse(IP), port) client new UdpClient() NextTrial.onClick.AddListener(Advance Trial) void Advance Trial() int signalIndex Random.Range(0, signals.Count) int currentSignal signals signalIndex stimIndex currentSignal signals.RemoveAt(signalIndex) string text signalIndex.ToString() byte data5 Encoding.ASCII.GetBytes(text) client.Send(data5, data5.Length, remoteEndPoint) Debug.Log( quot lt color magenta gt Current source signal is lt color gt quot currentSignal) if (signals.Count gt 0) Debug.Log( quot lt color blue gt Signal count before removal was lt color gt quot signals.Count) Debug.Log( quot lt color yellow gt Source signal removed lt color gt quot ) else Debug.Log( quot lt color green gt All Trials finished lt color gt quot )


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


How to draw a 2D cross section of a 3D object? I am creating a game where I only want the user to see the 2D intersection of a plane with a 3D object. The goal of the game is to move this plane to a certain position and rotation, which gives a certain 2D shape. Here is a link to a website which illustrates the 2D slices of a 3D object. How do I approach this if I only want the player to see the slice. Just to be clear, the solution does not necessarily have to be in 3D, since the ui for the player is going to be 2D anyway


RigidBody or Character Controller for Zero Gravity first person shooter I am developing a single person, first person shooter that takes place in space. I want to be able to simulate zero gravity. Should I use a Rigid Body or a Character Controller?


Create a 2d circular maze How can I create a 2d procedurally generated circular maze like the following picture


Slowmotion except main player? My script works fine except I don't know how to not let the slow motion affect the main player. public GameObject player void Update () if (Input.GetKeyDown(KeyCode.A)) Time.timeScale 0.5 Time.fixedDeltaTime 0.02F Time.timeScale if (Input.GetKeyDown(KeyCode.Z)) Time.timeScale 1.0f


Unity Editor Scene View does not match built executable I'm trying to make my game resolution independent. I'm using Unity's 4.6 UI, and I've got custom resolutions defined at 1280 x 720, 1600 x 900, and 1920 x 1080. In editor, if I swap between any of these resolutions, the observed scene doesn't change. It looks like this I then build an executable (set to only allow 16x9 resolutions), and run this scene. On 1280 x 720 (as selected from the resolution dialog), I get this While on 1920 x 1080 (as selected from the resolution dialog), I get this Which matches the editor view. (Ignore the character sprites those are in worldspace on a separate camera and aren't relevant to this question). What is it about the executable that causes lower resolutions to be "zoomed in" like this, even if that lower resolution is the Reference Resolution for the Canvas Scaler?


Small health bar above entity is drawn differently when the entity is rotated differently Here is a simple positioning code for my health bar transform.position Camera.main.WorldToScreenPoint(target.position 0.2f target.up) Here is the prefab HealthBar is middle center anchored, and 0.5, 0.5 pivoted, Background and Fill are stretched and 0.5, 0.5 pivoted, but background is Left, Right, Top, Bottom 1 positioned. Here is how it should look (all images are zoomed in) And here is a video about the entity rotating around https i.imgur.com EOzFEvt.mp4 2 example rotations, in which the health bar is drawn incorrectly (see the border of the bar) Why? Edit Another interesting artifact If I'm moving the camera up, the healthbars are offsetted up a bit, and if I start moving down, it's instantly offsetted down, with left and right the same, etc. As soon as I stop, it's at the correct position, but as soon as I start moving, it becomes offsetted to the direction I'm moving. See gif https i.imgur.com K8mwzTW.mp4 Fix for this Place it in LateUpdate.


How do you write an unlit shader which supports Ambient Occlusion? For performance reasons, a scene might use Unlit shaders only. Is there an Unlit shader which supports Ambient Occlusion? What is the best way to achieve this look, for moving and static objects, while prioritising performance?


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


When serializing a class, can its fields take their defaults from the Unity editor? Can I have a custom serialized class whereby I set a value in the editor and that value persists into runtime, as happens with serialized monobehaviour fields? Currently it sets itself to 0 or a default hard coded from within the class. I noticed that using a struct actually works but using a struct breaks the events used in my actual use case (included below). Example code public class Class1 MonoBehaviour this variable can be set in the editor and persist into run time SerializeField private float testVar1 this variable can not SerializeField private Class2 class2 private void Start() class2 new Class2() Serializable public class Class2 SerializeField private float testVar2 My use case Serializable public class EditorFloat SerializeField public float value public EventProperty lt float gt eventProperty public EditorFloat(EventProperty lt float gt eventProperty) this.eventProperty eventProperty Object.FindObjectOfType lt CentralParams gt ().OnUiChange Update this.eventProperty.OnChanged UpdateEditor public void Update() eventProperty.Value value public void UpdateEditor(float valueFromEventProperty) value valueFromEventProperty Thanks!


Storing Type Game Data Within A Unity 3D Game Using An Offline Flatfile Database I've read several documents on how to manage game type data Would it be better to use XML JSON Text or a database to store game content? How to choose how to store data? Im developing an offline RPG game in Unity3D. I've made online games before, but with online we had an edge for the database. For the online game we used a MySQL database each time the player loaded the game, they would download the database (JSON setup) and we would parse it on the client side and it would be good to go. However for an offline RPG I don't have the luxury of storing my game type data online. To be clear when I say type data I mean things like Monster tables Item tables Ability tables etc What I liked about the MySQL database was that it was tabluar and I could edit rows and columns easily and not need to create hundreds of classes subclasses to manage the type data. My question is how can I mimic the MySQL database in Unity3D? I considered using an excel file but I feel that would be so easy for the user to hack. Just change the excel data and boom, you've hacked the game. Is there a way I can create an offline (secure ish) flatfile database that will let me avoid having to create tons of type data class files to manage all my game data?


Displaying Trajectory Path How can I display trajectory path exactly as in this image? I have used void OnDrawGizmos, but that only displays trajectory in the editor and without any arrows like shown below. Trajectory with void OnDrawGizmos Script public Transform someObject object that moves along parabola. float objectT 0 timer for that object public Transform Ta, Tb transforms that mark the start and end public float h desired parabola height Vector3 a, b Vector positions for start and end void Update () if ( Ta amp amp Tb ) a Ta.position Get vectors from the transforms b Tb.position if ( someObject ) Shows how to animate something following a parabola objectT Time.time 1 completes the parabola trip in one second someObject.position SampleParabola( a, b, h, objectT ) void OnDrawGizmos () Draw the parabola by sample a few times Gizmos.color Color.red Gizmos.DrawLine( a, b ) float count 20 Vector3 lastP a for ( float i 0 i lt count 1 i ) Vector3 p SampleParabola( a, b, h, i count ) Gizmos.color i 2 0 ? Color.blue Color.green Gizmos.DrawLine( lastP, p ) lastP p region Parabola sampling function lt summary gt Get position from a parabola defined by start and end, height, and time lt summary gt lt param name 'start' gt The start point of the parabola lt param gt lt param name 'end' gt The end point of the parabola lt param gt lt param name 'height' gt The height of the parabola at its maximum lt param gt lt param name 't' gt Normalized time (0 gt 1) lt param gt S Vector3 SampleParabola ( Vector3 start, Vector3 end, float height, float t ) float parabolicT t 2 1 if ( Mathf.Abs( start.y end.y ) lt 0.1f ) start and end are roughly level, pretend they are simpler solution with less steps Vector3 travelDirection end start Vector3 result start t travelDirection result.y ( parabolicT parabolicT 1 ) height return result else start and end are not level, gets more complicated Vector3 travelDirection end start Vector3 levelDirecteion end new Vector3( start.x, end.y, start.z ) Vector3 right Vector3.Cross( travelDirection, levelDirecteion ) Vector3 up Vector3.Cross( right, travelDirection ) if ( end.y gt start.y ) up up Vector3 result start t travelDirection result ( ( parabolicT parabolicT 1 ) height ) up.normalized return result


How to play sound in WebGL build in Unity? I have a project that works fine when I build for windows, but doesn't work when I switch platform to WebGL. The SerializeField AudioClip variables in the inspector are all 'missing', even after I check 'override for WebGL' convert to AAC. And when I try to link any audio file to an AudioClip within a WebGL build in the inspector, it doesn't seem to work. How do I get sound to play within WebGL? To recreate the problem Switch platform to WebGL. Create a new Script in any recent unity version, then add a SerializeField AudioClip x. Put that script on a new gameobject and try to link an audio asset to it (default import settings, however don't forget to check 'override for WebGL' to AAC, otherwise you will get compiler errors when you switch platform).


Add picture in the Hierarchy view in Unity How can I add a picture in the Hierarchy view in Unity? For example, Dragon bones does it automatically. Here it is As you can see there is a picture on the right of the gameObject name.


Getting player cube to move left or right in relation to camera based on camera's rotation Right now I'm trying to make the player cube move left, right, up and down in relation to the camera's rotation and position. I figured what I could do is create an empty game object, make the main camera the parent, and then get the vector pointing from the camera's child to another game object that follows the cube's exact position, and that would give me the direction the cube should roll towards. I have my example in profile view, but in 3D view the camera should be facing the cube with the cube at the center. So I have the following line of code code Vector3 forwardVector (position1.transform.position position2.transform.position).normalized If you look at the image on the right hand side, I Debug.GetLine'd the resulting vector from the cube's position and ended up with a vector pointing down. In theory though, it should be pushing off to the right hand side. Here's the rest of the code Vector3 perpendicularVector Vector3.Cross (Vector3.up, resultant).normalized if (Input.GetKey (KeyCode.UpArrow)) cube.rigidbody.AddForce ( forwardVector moveSpeed) if (Input.GetKey(KeyCode.DownArrow)) cube.rigidbody.AddForce ( forwardVector moveSpeed) if (Input.GetKey (KeyCode.LeftArrow)) cube.rigidbody.AddForce ( perpendicularVector moveSpeed) if (Input.GetKey (KeyCode.RightArrow)) cube.rigidbody.AddForce ( perpendicularVector moveSpeed) As a result, when I press the up arrow key, I end up with the cube flying upwards toward the sky, and the down key brings it back down towards the plane, but my intention is for the vector to move along the XZ plane. Also, with this line of code, I was hoping to get the line perpendicular to my intended vector and Vector3.up, but I naturally get wonky results from that. Vector3 perpendicularVector Vector3.Cross (Vector3.up, resultant).normalized If there's an easier method to achieving my goals, that's fine, but it would be nice too to figure out why the vector is pointing down instead of to the right. It's also might be worth noting that the camera already successfully rotates around the player cube.


What's a viable way to get public properties from child objects? I have a GameObject (RoomOrganizer in the picture below) with a "RoomManager" script, and one or more child objects, each with a 'HasParallelagram' component attached, likeso I've also got the following in the aforementioned "RoomManager" void Awake () Rect tempRect HasParallelogram tempsc foreach (Transform child in transform) try tempsc child.GetComponent lt HasParallelogram gt () tempRect tempsc.myRect blockedZoneList.Add(new Parallelogram(tempRect)) Debug.Log(tempRect.ToString()) catch( System.NullReferenceException) Debug.Log("Null Reference Caught") HasParallelgram is an empty script with a public Rect set in the editor and nothing else. Unfortunately, attempting to assign tempRect tempsc.myRect causes a null pointer at run time. I've done some more digging, and the reason for the null pointer is relatively simple the RoomManager script gets woken ("Awake") before the HasParallelagram script gets instantiated ("Start"). It's an issue of timing I need to wait until all objects have been instantiated before calling the RoomManager. Does Unity support a means of doing that? What's the proper way to get a child's component?


How can I move an object over linerenderer lines positions? I have 4 cubes the first 3 cubes connected with two lines one of the lines is curved. The fourth cube I want to move over the lines. The lines is built using linerenderer and in the linerenderer there are 397 positions. I created a small script that move an object over the positions. I checked and I have in the array 397 positions and the loop get to 397 but the object (Cube (3)) never moving all the positions only some. Or maybe the positions I get are not the same in the linerenderer ? This screenshot show some of the positions in the linerenderer this is the positions I want the object to move on Why the object is not moving over all the positions , only on some ? And this is the script I created that should move it using System.Collections using System.Collections.Generic using UnityEngine public class MoveOnCurvedLine MonoBehaviour public LineRenderer lineRenderer public GameObject objectToMove public float speed private Vector3 positions new Vector3 397 private Vector3 pos private int index 0 Start is called before the first frame update void Start() pos GetLinePointsInWorldSpace() Vector3 GetLinePointsInWorldSpace() Get the positions which are shown in the inspector var numberOfPositions lineRenderer.GetPositions(positions) Iterate through all points, and transform them to world space for (var i 0 i lt numberOfPositions i 1) positions i transform.TransformPoint(positions i ) the points returned are in world space return positions Update is called once per frame void Update() if(index lt pos.Length 1) objectToMove.transform.position pos index Time.deltaTime speed index Now I checked using a breakpoint the first position in the linerender at index 0 is X 30.57, Y 6.467235, Z 4.98 But in my script in the pos array I see that in index 0 the position is X 30.6, Y 6.5, Z 5.0 And the result is that the object that move Cube(3) is moving only some of the way and also it's not exactly on the line Why the object is not moving over all the positions , only on some ? Something is wrong in my script with getting the right positions from the linerenderer and maybe also the loop and the move is wrong. I can't figure out ho to do it.


problem on enable and disable GameObject I'm trying to enable and disable GameObject (canvas) using this code public int canvaslevel 1 public GameObject one public GameObject two public GameObject three void Update() if(canvaslevel 1) one.SetActive(true) two.SetActive(false) three.SetActive(false) if(canvaslevel 2) one.SetActive(false) two.SetActive(true) three.SetActive(false) if(canvaslevel 3) one.SetActive(false) two.SetActive(false) three.SetActive(true) but it doesn't work!!! error Cannot implicitly convert type int' tobool'


How to make a game object scale up from another game object I have a GameObject. I'm trying to make another GameObject grow in scale from touching this GameObject, and when a set amount of scale is reached, destroy this GameObject. My problem is that when I access ScaleUp, it dosn't add any scale to the other GameObject. How do I scale another GameObject? Here is my ScaleUp script using UnityEngine using System.Collections public class ScaleUp MonoBehaviour public GameObject Player public PlayerMovement PlayerScript private float playerScaleX private float playerScaleY public float scaleUp 10.0f void Start() Player GameObject.FindGameObjectWithTag ("Player") PlayerScript Player.GetComponent lt PlayerMovement gt () playerScaleX Player.transform.localScale.x playerScaleY Player.transform.localScale.y void OnTriggerEnter2D (Collider2D other) if (other.tag "Player") playerScaleX scaleUp playerScaleY scaleUp Debug.Log ("GROW")


Can both High poly model go with a low poly scene? I'm in the process of developing a game, and I've found a model that would go perfectly for the character. However, the scentre I already have is low poly and I can't find a good enough high poly to go with it. So tell me whether or not I should I should carry on with the art I have or find a low poly model.


How to create a wavy beam? I want to implement a wavy laser beam similar to the Proton Backpack in Enter the Gungeon. https youtu.be wl o6gbMqFM?t 58 It's easy enough to draw a line from one point to another, but how to get the undulating curviness and the lighting effects? I am working in Godot, but I could easily adapt techniques from Unity, if you know them, since Godot has similar resources. I asked a version of this question in a Godot forum, but am also asking it here


Lightmapped prefabs for procedural content I'm doing a game with procedural content from handmade prefabs, but I ran into a problem as Unity bakes the scene instead of objects when lightmapping with Beast. So when the prefabs are instanced they are without lightmaps. Is there a way to get lightmaps for dynamically created prefabs with Unity's built in lightmapper?


How can I change the script so it will not be with a while loop inside Update or using coroutine instead? The script is working fine as it is and I don't fell any performance problems and yet I wonder if it's a good idea to run a while loop inside the Update function ? The idea is to be able to move an object over a curved lines with a lot of positions in any speed. So I'm calculating how much positions there is next each time and it's working fine I just wonder about the while in the update. using System using System.Collections using System.Collections.Generic using System.Linq using UnityEngine using UnityEngine.AI public class MoveOnCurvedLines MonoBehaviour public LineRenderer lineRenderer public float speed public bool go false public bool moveToFirstPositionOnStart false private Vector3 positions private Vector3 pos private int index 0 private bool goForward true private List lt GameObject gt objectsToMoveCopy new List lt GameObject gt () Start is called before the first frame update void Start() pos GetLinePointsInWorldSpace() if (moveToFirstPositionOnStart true) transform.position pos index Vector3 GetLinePointsInWorldSpace() positions new Vector3 lineRenderer.positionCount Get the positions which are shown in the inspector lineRenderer.GetPositions(positions) the points returned are in world space return positions Update is called once per frame void Update() if (go true) Move() void Move() Vector3 newPos transform.position float distanceToTravel speed Time.deltaTime bool stillTraveling true while (stillTraveling) Vector3 oldPos newPos newPos Vector3.MoveTowards(oldPos, pos index , distanceToTravel) distanceToTravel Vector3.Distance(newPos, oldPos) if (newPos pos index ) Vector3 comparison is approximate so this is ok when you hit a waypoint if (goForward) bool atLastOne index gt pos.Length 1 if (!atLastOne) index else index goForward false else going backwards bool atFirstOne index lt 0 if (!atFirstOne) index else index goForward true else stillTraveling false transform.position newPos


How does Unity's QualitySettings.masterTextureLimit work? I'm trying to get to the bottom of how masterTextureLimit works, but my results have been inconsistent so far. I created a massive sprite (8192x8192), and I'd like to resize it at runtime to save performance. The idea is to start with large sprites and then resize based on the monitor's resolution. Here's what happens at different settings Texture import size 8192, masterTextureLimit 0, mipmaps off 2ms Texture import size 8192, masterTextureLimit 0, mipmaps on 1.5ms Texture import size 8192, masterTextureLimit 1, mipmaps on 1.5ms Texture import size 4096, masterTextureLimit 0, mipmaps off 0.9ms Texture import size 4096, masterTextureLimit 0, mipmaps on 0.9ms Texture import size 4096, masterTextureLimit 1, mipmaps on 0.83ms Looking at these results, I have a couple of questions If masterTextureLimit is supposed to halve the texture resolution, why did it not affect performance while setting texture size to 4096 did? Why did turning mipmaps on improve performance at 8192 texture size but not at 4096? My camera is orthographic, and it's only 1 unit away from the sprite.


Zoom into character upon collision When a character collides with an object in my game, there is a slow motion effect. That's coool, but how would I zoom into a sprite when it collides with another object? Here is my code currently... using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class GameManager MonoBehaviour public float slowness 2f public int index private AudioSource hitSource public Vector3 Target public Camera Cam public float Speed 0.012f public void Start() Cam Camera.main public void EndGame() Application.targetFrameRate 300 StartCoroutine(RestartLevel()) hitSource GetComponent lt AudioSource gt () IEnumerator RestartLevel() Cam.orthographicSize Mathf.Lerp(Cam.orthographicSize, 3, Speed) Cam.transform.position Vector3.Lerp(Cam.transform.position, Target 1 , Speed) Time.timeScale 1f slowness Time.fixedDeltaTime Time.fixedDeltaTime slowness yield return new WaitForSeconds(1.5f slowness) Time.timeScale 1f Time.fixedDeltaTime Time.fixedDeltaTime slowness SceneManager.LoadScene(2) private void OnCollisionEnter(Collision collision)


Why does Unity let you install iOS Build Support on Windows? When installing Unity on a Windows machine, you are allowed to select "iOS Build Support" as one of the components to install. However, it is not possible to make an iOS build from Windows. Why is this package available on Windows? What does it offer?


How to store information into the tile? I have made a map via TilePallete tool. Now I want to store information in certain tile. How I can do this? ForEx I'm hittin a certain tile and I need it to have info about health remaining. For first hit I change a tile. For second I set it to null.


Separate data tables for different item types? I have two types of items in my game, consumables, and equipment. For my database, should I store them in two different tables, or all in one big items table?


90 CPU on Profile Editor Throttle mainMessageLoop I have a big problem in my Unity game, in almost every sc ne of my game, my editor is laggy, when I record Porfile Editor deep profile editor, here is the result I have no idea what is this throttle MainMessageLoop, what can I do ? Thanks you !


How to convert Blender rotation angles to Unity rotation angles? I add news cameras in my game. I have a problem with rotation, the result is not alway the same as in Blender. I tried lot of ideas but today I do not have anymore. Cameras 1, 2, 4 good rotation Cameras 3, 5 bad rotation Cam 1 (Blender) Cam 1 (Unity) the fov is different Cam 4 (Blender) Cam 4 (Unity) the fov is different Cam 3 (Blender) Cam 3 (Unity) rotation is very different Cam 5 (Blender) Cam 5 (Unity) rotation is very different This problem appears if camera orientation is "vertical" Do you have a turn arround, a solution for me? My code using System.Collections using System.Collections.Generic using UnityEngine public class rotation cams MonoBehaviour private Vector3 cams loc private Vector3 cams rot void Start() cams loc new Vector3 5 cams rot new Vector3 5 cams loc 0 new Vector3(79.7771f, 21.7574f, 109.795f) cams rot 0 new Vector3(95f, 45f, 200f) cams loc 1 new Vector3(78.0048f, 21.9854f, 110.314f) cams rot 1 new Vector3(87.0958f, 1.34464f, 160.515f) cams loc 2 new Vector3(78.3154f, 18.9402f, 111.654f) cams rot 2 new Vector3(169f, 59.3947f, 110.242f) cams loc 3 new Vector3(78.023f, 18.7094f, 111.375f) cams rot 3 new Vector3(89.4105f, 16.7202f, 128.303f) cams loc 4 new Vector3(79.5798f, 19.7249f, 111.743f) cams rot 4 new Vector3(55.0461f, 74.0926f, 220.475f) int i 0 foreach (Vector3 vector loc in cams loc) string camName "cam" i.ToString() GameObject currentCam AddCamera(camName) currentCam.GetComponent lt Transform gt ().position new Vector3(cams loc i .x, cams loc i .z, cams loc i .y) Vector3 objRotation new Vector3(cams rot i .x 1, cams rot i .z 1, cams rot i .y 1) objRotation.x 90f currentCam.GetComponent lt Transform gt ().eulerAngles objRotation i 1 void Update() private GameObject AddCamera(string name) GameObject gizmoPhoto GameObject.Instantiate(GameObject.Find("cam")) gizmoPhoto.name name return gizmoPhoto


Unity3D Button Slicing Problem I'm having trouble getting my button to appear correctly, as you can see in the image below, the right and top sides are stretched out and not displaying properly. I cannot figure out if this is a problem with the image itself or something wrong in the way I'm setting up the button. Here are the settings in the inspector window Here is the original image UPDATE So everything looked fine when I just opened up Unity, so I tried to figure out what I did last time for it to make this switch. It happens when I build and export the scene to my Android device.


How to open two Animator views in Unity? How can I open two Animator views in Unity editor? What I tried so far is to lock an Animator view and go to Window Animator. That did not help.


(Unity) Shortest way to instantiate an object and obtain it script Normally I use ScriptName script ((GameObject)Instantiate( Resources.Load("Prefab"), new Vector3(x, y, z), Quaternion.identity )).GetComponent lt ScriptName gt () It is a little too long and too much of brackets, so I wondering if there is any other way to get instantiated object's script without break it in two statements.


Unity RTS Single Selection Problem I am trying to build an RTS game and I have managed to form a way to select a unit using Raycast and the tag system. I made it so that if the object the ray falls onto is of tag "TankUnit" Make so and so variable true and allow it to move to another place. However, Units of the same tag even when not selected also move. How do I fix this problem? The script is bound to each unit. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.AI public class UnitController MonoBehaviour bool clicked false public float speed 10f public float rotationSpeed 10f public LayerMask groundLayer public NavMeshAgent playerAgent Update is called once per frame void Update() if (Input.GetMouseButton(0)) Debug.Log("Clicked") FindClickPos() if (Input.GetMouseButton(1) amp amp clicked true) Debug.Log("I clicked right mouse") Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit)) MoveTo(hit) private void FindClickPos() RaycastHit hitInfo new RaycastHit() bool hit Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo) if (hit true) Debug.Log("I hit " hitInfo.collider.name) if (hitInfo.collider.tag "TankUnit") Debug.Log("I hit" hitInfo.collider.tag "!") clicked true else Debug.Log("I didnt hit a unit ") clicked false else Debug.Log("I didnt hit anything...") clicked false void MoveTo(RaycastHit hit) Debug.Log("Position " hit.point) playerAgent.SetDestination(hit.point)


GameObject not exiting through leftScreen I'm trying to wraparound game object so that, it exits through right screen and enters through left and vice versa. The code snippet below is what I'm working on. Vector3 Pos mainCam.WorldToScreenPoint(transform.position) Vector3 LS mainCam.ScreenToWorldPoint(new Vector3( 1, 0f, 0f)) Vector3 RS mainCam.ScreenToWorldPoint(new Vector3(1, 0f, 0f)) if (Pos.x gt Screen.width) transform.position new Vector3(LS.x, transform.position.y, transform.position.z) if (Pos.x lt 0) transform.position new Vector3(RS.x, transform.position.y, transform.position.z) So far, exit through right and re enter through left works, but the gameObject does not exit through the left screen, there seems to be a barrier preventing it, or maybe my parameters for the second if statement are wrong.


Unwanted rotations with transform.RotateAround I didn't tough i would have issues with this, but unfortunatly I did. I have a Character (which is more a pile of cube) with a body, a empty GameObject for each leg attached to the body with a join and 2 cubes for leg too. The body and the two empty gameobject are child of a Empty gamebject. The 2 cube that represent leg are both child of one of the empty gameObject. What I want to achieve is to rotate the leg around the position of its empty parent by doing this if(Input.GetKey("l")) l leg.transform.RotateAround(l leg.transform.parent.transform.position, new Vector3(1,0,0), 75 Time.deltaTime) unfortunatly, I only want it to rotate on x, but all of the axis are changing, which lead to unwanted rotation. Now, I know rotations aren't independant like translations, but I don't know how to fix this. If possible, i'd prefer to rotate locked joint via script but I have now idea how, I haven't seen anything about it when I looked up 2