Voxel terrain generation performance problems I am trying to create a minecraft clone to practice some stuff in Unity including Raycasting, terrain generation and player controlls. Terrain is generating without any problem with a perlinNoise. My problem is the then following performance problems. The terrain is only 1 block high with no underlying blocks. Each block constist out of 6 quads with a 64x64 texture. I generate terrain at 200 x 200 size. I can't imagine why 4000 voxels with such simple textures can lag out whilst my pc runs objects with 50k tris and complex textures without any problem. My code ... public int xVoxels 200 public int zVoxels 200 ... for (int x 0 x lt xVoxels x ) for (int z 0 z lt zVoxels z ) voxel script parameter GameObject newVoxel GameObject.Instantiate(voxel) Vector3 position new Vector3() position.x xVoxels 2 x position.z zVoxels 2 z PerlinNoise stripped out for testing position.y 0f newVoxel.transform.position position Solutions I tried Combining meshes Combining all meshes to a single one per material worked wonderfully... until I wanted to interact with each voxel determined by Raycasting from the Camera, I had a raycast hit to the combined mesh and not to my determined voxel Generating the planes myself Instead of using the unity plane object I generated all vertecies myself, same performance problems


How can I simulate a "Hot Swap" betwen Audio Clips? I have a Unity project with 3 separate looping Audio Clips and a single Audio Source. Based on certain events, I swap between which of them are playing. This works fine, but whenever I swap between Audio Clips, the AudioSource stops playing, and must be restarted... which means it starts over from the beginning. As the Audio Clips are the same length, how should I handle the logic to pickup where the previous Clip last left off? Neither Unity's AudioClip nor AudioSource classes seem to have either a "PlayFromTime()" or "GetPercentPlayed()" method that would facilitate using a single Audio Source. What's the expected way to handle such a scenario? Simultaneously "play" from 3 AudioSources at once, muting 2 of them and leaving the last the only one that is actually heard?


Unity Mesh importing as child of armature I'm following along with this tutorial by Sebastian Lague https www.youtube.com watch?v yhPRkihs Yg amp list PLFt AvWsXl0f4c56CbvYi038zmCmoZ4CQ amp index 14 However, when I import my character from Blender into Unity, the sword and shield mesh are children of the armature instead of siblings like the shirt pants shoes etc. I'm fairly certain this is because the sword and shield are parented directly to bones on the hands, I'm just not sure why they import as children of the mesh unlike in the video.


Breaking up List into sublists by multiple values I'm trying to break up a C List lt InventoryItem gt into multiple lists based on two different values InventoryItem.name and InventoryItem.isStackable. I want the list to be broken up into multiple lists for the purpose of populating my UI with the data while keeping non stackable items in their own list (one item per item slot in UI terms.) If this is the input InventoryItem name apple, stackable true InventoryItem name apple, stackable true InventoryItem name carrot, stackable true InventoryItem name knife, stackable false InventoryItem name knife, stackable false I should get this output InventoryItem name apple, stackable true InventoryItem name apple, stackable true InventoryItem name carrot, stackable true InventoryItem name knife, stackable false InventoryItem name knife, stackable false I'm successfully separating by name alone (see below), but I'm not sure how to take isStackable into account. I'm also using LINQ which I'd prefer to avoid if possible. var itemsByType new List lt List lt InventoryItem gt gt () var inventoryByItem inventory.GroupBy(x gt x.name) foreach(var v in inventoryByItem) var itemList v.ToList() itemsByType.Add(itemList)


Text Pooling Optimizations In my game I have created popup text for gained points when enemies are killed. it pops up wherever the enemy was and will say something like " 32" float up a bit and fade away at the same time. This transition lasts for a few seconds if that. and hundreds could appear at a time when AoE attacks destroy a lot of enemies. That's all well and good. and it works! but I fear that this could become quite slow on mobile devices. So I did what any good game dev does. I pooled it! Then it occurred to me. I'll still be changing the display value of the text elements dynamically and libraries like TextMeshPro already, in surely an optimized way, instantiate actual meshes to render text. So is pooling these text elements really a big optimization? so here goes my question for experienced and knowledgeable devs. Is it more efficient to pool each character I need and assemble my short strings dynamically as sets of pooled gameobjects for these popups of just a few characters or should I simply pool text elements that will change their text just before appearing? Assume the memory usage difference is minimal. only worried about speed. This is on top of the game having possibly thousands of projectiles moving at any given time, so I believe it is a valid optimization question, but I ask this more for curiosity than practicality. For now, I already have a working solution. but I believe such an issue could arise in the future. and want to satisfy my curiosity now.


How to handle multiple enemies with the same script? i'm working on a basic Top Down Shooter, kind of like... Nuclear Throne or The Binding of Isaac, but since i'm new to Unity, and it's something i'm required to do for school, i'm quite in a rush so i didn't have enought time to look at all the documentation i should've, so i apologize if i'm asking too much. The thing is like this I have the Player that moves around, and a Sword that rotates in the mouse direction, clicking the mouse activates a Trigger Collider around the Sword, and it's suposed to Hit all enemies inside its range The problem How should i "plan" my Scripts? i mean, i have a Sword script that handles the click and the OnTriggerEnter, and it should, somehow (Working on it), check if it hit an enemy, and access the Enemy Script to modify its Life Points, but how do handle the GameObject Enemy GameObject.FindObjectWithTag("Enemy") ... ? since this just gives me one enemy... I apologize again since i'm really bad at focusing on one point, i dont think it's neccessary to provide all the code since i dont really need you to provide me with code, just... guidelines or a basic pattern of doing this kind of things. Thank you a lot!.


Custom List Editor dependent on data from separate class's data I want to make a custom inspector that I'm not really sure how to approach. The idea is I have a quest framework with a class that holds onto the quest data and another class that is intended to hold onto dialogue data. The quest system is agnostic of my dialogue system. I want to be able to display the quest and dialogue data this way QuestName0 DialogueGiveQuest (TextAsset field) DialogueQuestIsActive (TextAsset field) DialogueQuestIsComplete (TextAsset field) QuestName1 DialogueGiveQuest (TextAsset field) DialogueQuestIsActive (TextAsset field) DialogueQuestIsComplete (TextAsset field) etc... Here's a pseudocode class layout public class QuestData MonoBehaviour List lt Quest gt quests public class DialogueData MonoBehaviour public TextAsset dialogueGiveQuest public TextAsset dialogueQuestIsActive public TextAsset dialogueQuestIsComplete public class Interaction MonoBehaviour QuestData questData List lt DialogueData gt dialogueData CustomEditor(typeof(Interaction)) public class InteractionEditor Editor public override void OnInspectorGUI() var interactionData (InteractionData)target foreach interactionData.questData.quests draw quest name make sure there's a dialogueData element for each quest draw field for each DialogueData An obvious issue is dialogueData doesn't care about what's going on with questData.quests so if the inspector were to draw normally it would display 2 lists. I'd like the dialogue data to add and remove elements to itself depending on the quest data but that sounds like it be a real challenge to serialize.


How can I make the player(transform) to rotate once each time the player exist the collider and to rotate him slowly smooth? using System.Collections using System.Collections.Generic using UnityEngine public class PlayerSpaceshipAreaColliding MonoBehaviour private float timeElapsed 0 private float lerpDuration 3 private float startValue 1 private float endValue 0 private float valueToLerp 0 private Animator playerAnimator private bool exitSpaceShipSurroundingArea false Start is called before the first frame update void Start() playerAnimator GetComponent lt Animator gt () Update is called once per frame void Update() if (exitSpaceShipSurroundingArea) SlowDown() if (playerAnimator.GetFloat( quot Forward quot ) 0) transform.rotation Quaternion.Inverse(transform.rotation) private void OnTriggerEnter(Collider other) if (other.name quot CrashLandedShipUpDown quot ) exitSpaceShipSurroundingArea false Debug.Log( quot Entered Spaceship Area ! quot ) private void OnTriggerExit(Collider other) if (other.name quot CrashLandedShipUpDown quot ) exitSpaceShipSurroundingArea true Debug.Log( quot Exited Spaceship Area ! quot ) private void SlowDown() if (timeElapsed lt lerpDuration) valueToLerp Mathf.Lerp(startValue, endValue, timeElapsed lerpDuration) playerAnimator.SetFloat( quot Forward quot , valueToLerp) timeElapsed Time.deltaTime playerAnimator.SetFloat( quot Forward quot , valueToLerp) valueToLerp 0 When the player exit the collider area he slow down then stop. at this point I want the player to start rotating and start moving back inside the colliding area. The exit and the slow down are working but the rotation is not working and not sure how to make him start moving again slowly to max speed when entering back. The main goal is to prevent the player to leave the marked colliding area with some slow down and rotation. For the rotation I did transform.rotation Quaternion.Inverse(transform.rotation) but it keep rotating non stop and not slowly smooth like using Lerp.


Change velocity of CharacterController? I'm trying to change the velocity of a character controller component on a Third Person Controller, but when I try to change it, the console says the velocity is read only. This is my code. P.GetComponent(CharacterController).velocity 0 (P is my player GameObject variable) So, any ideas on how to change this? Thanks, Chris.


Pointers in C Unity Hey I've just learned about pointers recently and am wondering how I can use them in c (I just learned about them in c ) in unity. I do have some questions though. Pointers use low level programming to find positions of different values on the computer so does that mean that you can just access a the value of a variable from any script? If so how do I just call upon a location of a variable with just its location code? Are there any discernible differences between pointers in C and C that I should know? How can I use pointers with the variable types in Unity (Vector3s, Transforms, GameObjects, etc...)? There are so many more questions I probably should and would like to ask so if you have any additional info or sources.


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


Do Gradle 'implementation' replace Unity Jar Resolver dependencies? I have a project with several Dependencies.xml files which the Unity Jar Resolver resolves fetching the .aar files and storing them on Plugins Android. When installing Ironsource, I saw in the documentation that it says to add the dependencies to the mainTemplate.gradle file dependencies Your other dependencies compile fileTree(dir 'libs', include ' .jar' ) compile 'com.google.android.gms play services ads identifier 16.0.0' compile 'com.android.support support v4 27.1.1' DEPS Your other dependencies ... AdMob's dependency compile 'com.google.android.gms play services ads 17.1.1' Because one of my dependencies that the jar resolver imports is an older version of support v4 my build fails. Seeing this new alternative, can I move all the dependencies files to the gradle file and let Gradle auto resolve this problem on the post build process? Is there any pros cons that the jar resolver has that Gradle doesn't? For what I know the Jar Resolver uses gradle.


How to add time delay in Unity C So I'm trying to make a camera zoom in, but Thread.Sleep doesn't work. Here is the code void Start() for (int a 0 a gt 1000 a a 1) Debug.Log( quot Done! quot ) Thread.Sleep(100) The error code is this Assets StartScene CamScript.cs(12,13) error CS0103 The name 'Thread' does not exist in the current context


Is there a way to convert shader graph to shader code for older version? Editing Shader in a graph is brilliant feature, however it's only works in Unity 2018 with Lightweight RP template. So I want to use the shader made from shader graph in Unity 2018 to older versions, such as 2017 or 5.x. There is a button to compile the shader to code but unfortunately when I drag into 2017 it gives me syntax error so I can't use it. Is there a way to use the shader made from Unity 2018's graph editor to older versions of Unity?


Execute a function for ten seconds and disable it for two seconds I have a particular function which I am calling in Update function. For the first ten seconds, the function should get called in Update function, then it should get disabled for next two seconds, then again enable it for next ten seconds. This cycle should keep repeating? How can I execute it?


How to create "broken glass" animation? I have started making a 3D game in Unity5 that consists in avoiding obstacles. It is very easy but I want to add a collision effect when I collide on the wall. I would like to slice the screen into many parts (random pieces is better) that are falling down from screen with gravity. An example of what I mean How can I do this? I've tried using a lot of different images (shapes) but I'm sure that is not the best way... Thanks for any suggestions.


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 )


2D Boat controlling physics I'm working on a top down 2D boat game with Unity3D. I couldn't able to understand how to implement physics of rudder controlling. My physics knowledge is not enough to think how rudder dynamics work. How rudder dynamics works in water? Can you help me for finding a starting point for this? Since I'm not able to think any solution for this, I can't provide an example code. EDIT I'm trying to apply a force to rigidbody2D of the ship at the point of rudder with angle of the rudder. But I couldn't able to make something working Sample Code I draw a sketch. Red point is location of rudder. I'm trying to apply a force at that point with angle of rudder relative to ship heading on each Update. How can I do this?


Models keep turning white Unity 5.3.5p1 I'm using Unit 5.3.5p1 but for some reason my models randomly turn white after I build an exe to run outside the editor. The textures work perfectly fine within the editor, but as soon as I build and run outside they sometimes show with appropriate colour, but many times do not and end up blank white. Does anyone know what might be causing this in general? I've downloaded the latest unity shaders and replaced all current shaders. Currently I'm using the Standard shader only, and it is 100 unmodified.


How can I have my third person camera track slightly ahead of the player as he or she moves? I have a 3rd person camera controller in a top down game. I have my cameran following the player and I currently use linear interpolation to make the movement smooth and a little laggy. But I would like to do the opposite when the player moves in a certain direction the camera moves a little bit ahead, so as to reveal more of what is ahead of the player. void Update () var newX player.transform.position.x var newZ player.transform.position.z 17 var y transform.position.y var targetPosition new Vector3 (newX, y, newZ) transform.position Vector3.Lerp (transform.position, targetPosition, 0.01f)


Implementing online connectivity and multiplayer PVP for a newbie Background I'm a noob programmer looking to create a simple turn based mobile game as a side project. I've pretty much got the game logic down and am left with implementing the online multiplayer PVP portion. More specifically, i'm looking to implementing a system when the player clicks play and will be matched with an opponent in a 1 v 1 format, without any lobbies etc etc. I'm currently trying to develop my game in android studio(i'm new) but am also open to unity if it makes the development easier.(I have no experience in Unity). What i want to know From what i understand,i need to create and host my own server for the multiplayer to run(i.e matching of player to opponent). Do i also need the server to run the game itself or am i able to connect the player to the opponent and simply record the result of the game to my server database? Also, how would i go about creating and running hosting the server? I heard nodeJS is a good choice for writing the server. End Goal I just wanna publish my game onto the app store, IOS store, etc.


How do I use virtual joysticks in Unity2d ()top view? I want to use virtual joysticks for character movement, in a top down 2D game, that includes rotating the character. I tried an Easy Joystick Unity Package, but it doesn't work properly, so what do I do? Does anyone have a script (preferably in C ) that would use virtual joysticks to move a character?


Random scene manager in Unity This may be hard to understand because this is hard to explain I have 6 scenes and one 'start' scene. The start scene will be where my scene manager is. So I want function where when the player clicks on the the start scene it goes to a random scene (from the 6 scenes) and then it goes to start. Then when you click again it goes to random scene, but this time these random scenes will be between the remaining 5 (excluding the scene the player just went on) and then it goes back to start. Then it goes to a random scene time, this time these random scene will be between the remaining 4. And so one. I already know how to go a random scene and back but I don't know how to do the remaining


How to make multiple AI surround a player I am working on a top down RPG game and I have come across a problem. I am working on an AI system to allow the enemy AI to surround the player. I've been trying to keep my implementation really simple, however, I've been running into problems. Here is what it currently looks like X represents the player and Y represents the friendly AI. There are 42 waypoints in total that the enemy can potentially occupy. However, if any of the waypoints of the player object encounters an obstacle, or if another friendly AI is too close, it will disable those waypoints This poses a big problem because I do not have all 42 waypoints. From the looks of it, I might need something more dynamic in my case. Are there any alternative ways to allow a large number of AI to surround the player or its allies?


How can I convert screen space to GUI Space View Space? Is there any way available to convert screen space into view space as like in the following figure


Unity 3D Slow car (wheel colliders) My car is moving very slowly even though I apply high amounts of torque to the wheel colliders. The only thing I found to be helpful was to increase the wheel's friction stiffness, but that really messes up the braking and makes the car shake. The values I use for setting up the car and torque are realistic (1500 kg car, 20 kg wheels, a realistic torque value accounting for gear ratios etc.), so I don't understand the problem.


Play a sound on button click before loading the load scene in Unity3D I am trying to play the sound of the button click before loading the scene in unity. However, the sound is never played. Below is my code, help would be appreciated. public void RestartGame() audioManager.PlaySound(forwardSound) StartCoroutine(DelaySceneLoad("Gameplay")) IEnumerator DelaySceneLoad(string scene) yield return new WaitForSeconds(forwardSound.length) GameTracker.SetGameOver(false) SceneManager.LoadScene(scene)


How to add tiles randomly? I made a set of 10 different "ocean" tiles, all interchangeable with one another, and I'd like to randomly attach these 10 different tiles together in different combinations over a large rectangular area what would be the best way to do so? I've thought of just adding each sprite into a script and then calling a for foreach loop to add it into my world but that seems extremely expensive since I'd be adding over 1000 sprites. I don't want to reduce the number of sprites I have to add, I'm just seeing if there's a typical way people do this sort of thing.


How to display a GUI Texture for a certain amount of time Is it possible to make a gui Texture display for a certain amount of Time.


How can I fade player character when he goes inside or outside of the area? I want to fade the player when he goes out of the area. For example, suppose a person enters a building. When a person is outside of the building, he shouldn't be seen, but when he enters he gradually becomes visible (using fading effect). when elephant is inside green area his alpha should be 1 when elephant is outside of green area his alpha should be 0


Is there any way to bring animation into unity without a rig bones? I am developing for mobile and to make the game run on lower spec mobiles, I was only going to import bones rig for the main character. There are other humanoid characters in the scene which do move about and are rigged already in my 3d app but since they wont be controlled in anyway by the player in the game, I just wanted to bake and import their animations alone without the bones. I know unity can handle blendshapes but I am more comfortable with rigs and also cos these characters are already rigged properly.


Recommended data structure for storage and fast access of infinite chunk based heightmap terrain I'm aiming to create a chunk based heightmap terrain in Unity. I already have a basic multifractal simplex noise set up and working, able to generate heightfields and meshes at runtime... but only individually for the moment. I'm attempting to work out how best to store and access each chunk. I already have a couple of methods worked out to convert global positions to chunk coordinates and chunk local barycentric triangle coordinates, so I can interpolate heights. I've used that to build a method to march a camera space to world space ray across the mesh and iterate through x z plane intersections until it finds the height intersection for a fast way to look up mouse position on the terrain without having to attach physics collision meshes for each chunk and use Unity's raycasting. That's all working nicely. I'm just a bit stumped now on how to implement the main infinite grid storage that I'll generate chunk meshes from. This is planned to be in service of a game with an isometric perspective, revealing the world as units explore fog of war over time... with the ability to move the camera around the uncovered terrain fairly quickly, so I'm guessing there might be limited scope for unloading previously generated chunks... it'll be an ever expanding dataset (so I'll presumably have to be looking for ways to keep it light on memory) I figure I can either Create a 2 dimensional array of float (or perhaps short 64k height levels should probably be plenty) for the entire terrain, and dynamically resize the array as each x z boundary is pushed back. Generate just the terrain mesh in chunks, to keep each mesh chunk under the Unity 64k vertex limit. Create a grid manager class, which has some kind of dynamic data structure that stores map chunk objects, and instantiates them retains references to them as they're demanded, each of which would contain its own (res res) sized heightmap array. Something else? I'm assuming option 2 will have the most mileage, but what I'm most unsure about is what kind of dynamic data structure to use. I'd guess some kind of key object pair structure, where the key is built from the chunk coordinates? Assuming I'll want to access height values quickly and constantly, across chunk boundaries, for things like my mouse ray intersection method, and for pathfinding code, etc... I presume I'll need a way to access chunks that is nearly as fast as looking up arrays by indices, and O(1) complexity. Or perhaps some way of caching recently accessed chunks or chunks that the camera is near? Or pointers to them, or something? As you can probably tell I'm fairly new to the gamedev side of things, but I have a VFX background, and so know my way around 3D geometry math and basic scripting. In terms of designing structuring implementing a game, I'm a total novice though, so any pointers to relevant tutorials and such would be much appreciated.


Avoiding singletons for puzzle system Say for instance I have a puzzle with 3 switches that need to be in some configuration (say all on) in one room, that opens a door in another, with a load screen separating, so I can't link the switches directly to the door. My first thought was to create a singleton that stored the state of each "solution element" which in this case is the switches, but could be a correctly turned knob, ect. then a given "Puzzle Gate" like a locked door would check the required solution elements to decide it's own state, but I'm hesitant to use singletons for all of the commonly given reasons. What alternatives do I have to singletons that would give me the same or similar control?


Why is my character jumping at different heights randomly? I have a character controller on my character's gameobject and I'm trying to make the character jump. This is working but sometimes he jumps way higher than other times. Does anyone know why this is happening? Here's the code using System.Collections using System.Collections.Generic using UnityEngine public class Movement MonoBehaviour CharacterController cc public float Speed float Forward float Sideways float vertical public float gravity public float Jump Start is called before the first frame update void Start() cc GetComponent lt CharacterController gt () Update is called once per frame void Update() Forward Input.GetAxis("Vertical") Speed Sideways Input.GetAxis("Horizontal") Speed if (!cc.isGrounded) vertical gravity Time.deltaTime else if (Input.GetKeyDown(KeyCode.Space)) vertical Jump Time.deltaTime vertical 8 Time.deltaTime Vector3 Delta transform.TransformDirection(Sideways, vertical, Forward) cc.Move(Delta Time.deltaTime)


FBX model for 2d sprite charachter I was following along the unity platformer tutorial. https www.youtube.com watch?v 9WhZ1svdC3Q It is great. After looking the animation I found that there was a fbx model for 2d sprite character. I just want to ask can you use 3d animation like motion capture animation once you rig a character using bone for 2d(fbx model). I search but unable to find any good tutorial of how to create fbx model for 2d character and creating maps for these 2d character. I am really confused. Thank you so much for helping.


My Earthbound like Movement Script works in Unity Gameview, but runs differently in Gamebuild First programming question I've ever made in my short journey. I'm trying to create a script which moves members of your party in a line behind you (think Chronotrigger or Earthbound). Here's a clip of what I want it to look like. Problem Everything looks fine in the Game window when I play, but when I build the game to test, the characters begin to stack one on top of each other. I assume it has something to do with Update() frames dramatically increasing the frequency with which I enqueue the positions of the leading character (although I'm not experienced enough to say for sure, clarification on this would be helpful). I've tried increasing the offset, but this solution is variable depending on the players computer fps so that wont work. I've tried running both scripts in FixedUpdate() but a lot of my other systems run on Update() and so everything stutters. I've tried enqueue'ing from an IEnumerator and waiting for .1 second between each enqueue but that stutters as well.. What I'm doing The leading character has a script called PlayerTrail which creates a Queue of Vector3s. In Update the game object's transform.position is enqueued. The following character has a script called PlayerFollower which looks at the Queue and Vector3.MoveTowards the position, then dequeues that position and repeats. Each character only looks at the trail of the character in front of it. Everything seemingly works fine and well in the Unity program, this issue only arises once I build the actual game. Code Supplied Bellow using System.Collections using System.Collections.Generic using UnityEngine public class PlayerTrail MonoBehaviour public Queue lt Vector3 gt LeaderTrail public Vector3 LastMovement private void Start() LeaderTrail new Queue lt Vector3 gt () private void Update() if (this.transform.position ! LastMovement) LastMovement transform.position LeaderTrail.Enqueue(this.transform.position) using System.Collections using System.Collections.Generic using UnityEngine public class PlayerFollower MonoBehaviour public GameObject leaderObject public int Offset public int moveSpeed private PlayerTrail leaderTrail private Animator animator void Start() animator gameObject.GetComponent lt Animator gt () leaderTrail leaderObject.GetComponent lt PlayerTrail gt () void Update() if (leaderTrail.LeaderTrail.Count lt Offset) animator.SetBool( quot isMoving quot , false) return else Vector3 direction (leaderTrail.LeaderTrail.Peek() transform.position).normalized this.transform.position Vector3.MoveTowards(this.transform.position, leaderTrail.LeaderTrail.Peek(), moveSpeed Time.deltaTime) animator.SetBool( quot isMoving quot , true) animator.SetFloat( quot moveX quot , direction.x) animator.SetFloat( quot moveY quot , direction.y) Debug.DrawRay(this.transform.position, direction) leaderTrail.LeaderTrail.Dequeue()


Loading an image from Disk to used to replace a source image for an image object I am working on a Unity project where I need to be able to grab an image from disk and then have it be replaced as the source image for an image gameobject. Currently I already have a filebrowser implemented that gives me the filepath. if (File.Exists(output)) GameOjbect imageselect GameObject.Find("ImageSelection") imageselect.GetComponent lt Image gt () I need to make the file location at path output be the sprite? sourceimage? for imageselect Sorry if this has already been asked, I have been looking at other examples this morning with no luck.


Can I clip a collection of geometry to render only inside a particular worldspace volume? I am making a VR app in Unity. I have a giant map that I want to display on a virtual table. The map is too large to fit on the table, and I cannot change its size. (It is a third party asset, and does not easily have that capability.) How can I tell the camera not to render the parts of the map that fall off of the table? Perhaps something along the lines of Camera.DoNotRender(new Vector3(100, 0, 0)) I have been looking into using some MonoBehaviour messages such as OnPreRender, OnRenderObject, etc. But I do not know which one can help me, if any. Ideally, the pixels behind the non rendered pixels should be rendered, but that is not my priority. The map is made up of 100s of little renderers How can I have my Camera not render specific world space pixels?


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


Why does adding a value to list makes list not editable in unity inspector I am adding elements from the first list to another similar list, but it makes first not editable in the Unity Inspector. Whenever I try to change values from the inspector it makes them again 0. While If I comment list.Add() I can change values in the inspector. Serializable public class Characterz public string Name public int Age public float Gold public class Actor MonoBehaviour public List lt Characterz gt kings new List lt Characterz gt () public List lt Characterz gt Actors new List lt Characterz gt () void Start() for (int y 0 y lt 30 y ) Actors.Add(new Characterz()) if (y lt 4) I need to comment following line to change Actors list value in editor kings.Add(Actors y )


How to communicate to an inventory item which character it's being used on? Currently, I have an Inventory that is a ScriptableObject, which means it's not tied to any specific game object or player character. I just drag it into a MonoBehaviour if I would like expose the data of the inventory. I have created an InventoryUI, which is a MonoBehaviour attached to a GameObject in my scene, and I assign the Inventory SO to it. The InventoryUI contains button GameObjects with an InventorySlot script, to which I assign the item each slot is holding. Everything works fine. When I click on one of the InventorySlot buttons, I'm able to call item methods, such as UseItem. My problem is if the the item is a potion, for example. How can i add health to the player? Of course I could add reference to the player to the slot. But that will reference player repeatedly over 25 slots.


Unity error "must have a body because it is not marked abstract, extern, or partial" I'm trying to setup a system where I pickup an object drop it into a zone, and then the object is destroyed. So far I have using UnityEngine using System.Collections using UnityEngine.UI public class TriggerZone2 MonoBehaviour public Text MyText private int score public bool CompareTag(string Player) Use this for initialization void Start () MyText.text "" Update is called once per frame void Update () MyText.text " " score void OnTriggerEnter(Collider coll) score score 1 if (other.CompareTag ("Player")) Destroy (other.gameObject) Everything works up until I try to destroy the game object. The console keeps saying Assets Scripts TriggerZone2.cs(11,21) error CS0501 TriggerZone2.CompareTag(string)' must have a body because it is not marked abstract, extern, or partial. I've looked up quite a few threads, but I'm still not sure what it wants me to do with it. How do I fix this?


Unity Animate Sprite Shape Sprite? Is it possible to animate a sprite shape? I don't see the Sprite Shape Profile in the animator properties, so I was just wondering if there's another way to do that. To clarify Our game is 2D animated by hand, and one level has conveyor belts that span the level. We can animate it normally, but that will end up taking more video memory than if we were able to animate the conveyors as tiled sprite shapes. It may not end up being worth the effort to save the memory, but I figured it was worth a shot. Because the sprites span the level, they end up taking up lots of space in a sprite atlas.


Long occluding geometries in Resonance Audio for Unity I'm currently looking into using resonance audio (https resonance audio.github.io resonance audio ) for accurately modelling the audio for an environment that approximates to a long corridor with a series of bends. I want to have a sound at the end of this corridor that the user can hear at any point in the corridor based on the sound reflections along the corridor. I have tried a few of the options presented by Resonance Audio Placing reverb probes along the corridor. This seems like the ideal option, however a reverb probe will only apply its baked in reverb profile to sound sources inside the probe. If I try to make the probes larger then they seem to take into account all of the geometry of the corridor at once and things get exceedingly echo ey and consistent regardless of where I am in the corridor. Turning the corridor model into an audio room. This isn't apropriate as it has many of the same issues as a large reverb probe, and also doesn't actually model the space itself. Has anyone had any experience with hearing distant sounds in Resonance Audio environments like this? At this point I have a feeling that Resonance Audio is just not built for this particular situation.


How can I rearrange layers in Unity 2D? I'm new to using Unity (2019.30a2) and am currently learning by watching Brackey's (youtube) "How to make a 2D Game in Unity" At 6 58 he is able to rearrange his layers easily. On my hand, I can create but am unable to change the order of the layers. Looking at other questions on similar subjects hasn't provided me with a solution yet. I'm currently working around it but feel this will hinder me in the future. The screenshot of the unmovable layers is included below


Why is my CameraCrop script blurring the screen slightly in Unity? I've been trying to enforce a 4 3 aspect ratio in my Unity game, in order to give a nostalgia feeling to it. But whenever I add this script to my camera and compile my game, it blurs slightly. I am using a 4 3 aspect ratio in the game view and have Fullscreen Window chosen in my Window Option and in Supported Resolutions I have only 4 3 ticked. Also, I am used Pixel Perfect Camera with Pixel Snapping enabled. Here's what my game looks like without the CameraCrop script added And here is what it looks like when the script is added Here's the script I add to my camera using UnityEngine using System.Collections using System.Collections.Generic Requires that the camera component is on the GameObject RequireComponent(typeof(Camera)) public class CameraCrop MonoBehaviour Sets the aspect ratio to whatever you want public Vector2 targetAspect new Vector2(4, 3) Camera camera void Start() camera GetComponent lt Camera gt () UpdateCrop() Call this method if your window size or target aspect change. public void UpdateCrop() Determine ratios of screen window amp target, respectively. float screenRatio Screen.width (float)Screen.height float targetRatio targetAspect.x targetAspect.y if (Mathf.Approximately(screenRatio, targetRatio)) Screen or window is the target aspect ratio use the whole area. camera.rect new Rect(0, 0, 1, 1) else if (screenRatio gt targetRatio) Screen or window is wider than the target pillarbox. float normalizedWidth targetRatio screenRatio float barThickness (1f normalizedWidth) 2f camera.rect new Rect(barThickness, 0, normalizedWidth, 1) else Screen or window is narrower than the target letterbox. float normalizedHeight screenRatio targetRatio float barThickness (1f normalizedHeight) 2f camera.rect new Rect(0, barThickness, 1, normalizedHeight) I am using Unity 2019.4.17f LTS and using Windows 10.


How to check version of Unity package in project through script I'm writing an asset that will be used by many people, but it depends on TextMeshPro (TMP). I ran into a bug in TMP that can only be fixed by upgrading to a preview version. I want to warn users that install my asset that they need to upgrade their TMP version if they are using a prior version. Surprisingly, I can't find this anywhere online or in the docs. just something like if (TextMeshPro.version lt MyAsset.RequiredTMPVersion) Debug.LogError("Need to upgrade TMP")


Unity 5 light reflection on the water surface How to adjust reflection in Unity 5 to show up it on the water surface. So I have few light elements in the scene. So I want my water pro to reflect this lights. As example you can see red and yellow lights from the Shanghai's build on the water, that's what I am trying to achieve I've added water pro and setup flare Looks liker here some small reflection on the rect I market as red. But if comparing with real reflection it's more vertical reflection I've marked it as red well If you can see it unity example does not look natural. So if we compare distance from sun to the beach border on real photo, there is a huge sun line over the water surface, but there is not the same line on water pro in unity. Here is a video link with what I did http screencast.com t bq8Ocl24ZAJH


How can I duplicate a GameObject with the correct number of copies? using System.Collections using System.Collections.Generic using UnityEngine public class FormationsManager MonoBehaviour public GameObject squadMemeberPrefab public int numberOfSquadMembers 20 public int numberOfSquads 1 public int columns 4 public int gaps 10 public Formations formations private int numofmembers private int numofsquads private GameObject squadToClone private List lt GameObject gt SquadMembers new List lt GameObject gt () Use this for initialization void Start() squadToClone GameObject.Find("Squad") numofmembers numberOfSquadMembers numofsquads numberOfSquads formations.Init(numberOfSquadMembers, columns, gaps) GenerateSquad() Update is called once per frame void Update() if (numofmembers ! numberOfSquadMembers) numofmembers numberOfSquadMembers formations.Init(numberOfSquadMembers, columns, gaps) GenerateSquad() if (numofsquads ! numberOfSquads) numofsquads numberOfSquads for (int i 0 i lt numberOfSquads i ) Instantiate(squadToClone) private void GenerateSquad() GameObject go squadMemeberPrefab List lt GameObject gt newSquadMembers new List lt GameObject gt () int i 0 for ( i lt formations.newpositions.Count i ) if (i lt SquadMembers.Count) go SquadMembers i else go Instantiate(squadMemeberPrefab) go.transform.position formations.newpositions i go.tag "Squad Member" go.transform.parent gameObject.transform newSquadMembers.Add(go) for ( i lt SquadMembers.Count i ) Destroy(SquadMembers i ) SquadMembers newSquadMembers In the Update I duplicate the squad if (numofsquads ! numberOfSquads) numofsquads numberOfSquads for (int i 0 i lt numberOfSquads i ) Instantiate(squadToClone) The problem is that if for example when running the game there is 1 squad and then I'm changing the value of numberOfSquads to 3 then instead duplicating more 2 squads it will duplicate more 3. And then if I will change the value of numberOfSquads from 3 to 4 it will add more 4 squads instead only 1. And I also want to make that if I change the value of numberOfSquads to be lower then destroy the last squad s.


Upper Lower angular limits on Y and Z axes My Task I'm trying to replicate this project. I'm using unity as my physics engine. Currently I'm still learning how to work with the different joints unity has to offer. The type of movement I'm looking for is where a body is connected to only one other body and its relative movement can be limited based on angles on different axes. My Problem I'm using Configurable joints for my movement restrictions. The Low Angular X Limit and High Angular X Limit does exactly what I'm looking for since it can have a different uppper and lower rotation limit. Looking at the documentation, it seems that this can only be done on the X axis. The Y and Z axes only have a Angular Y Limit or Angular Z Limit which set the upper as the opposite of the lower limit. My Question Is it possible for the Y and Z axes to have the same lower upper limit system that the X axis has? Is the use of configurable joint good for this task? Thanks in advance )


How to stop rendering a gameObject that has no rendering component in unity I want to stop rendering this gameObject. But the all available renderer.enabled false is not working. Is it because it has no rendering component attached? If so, how can I see it when it is not rendered?!


Start Broadcast Unity Network Discovery I am using the unity NetworkDiscovery component, and I am wondering how I can auto start broadcasting when the server starts, instead of the client having to click on the gui Initialize Broadcast Start Broadcasting. I would like to be able to put some C in my start host function so that the user does not have to do anything.


Unity Issue applying Render Texture to object imported from Blender I'm new to Unity and am trying to create a sort of CRT computer monitor terminal with text. To draw the text, I set up a Text Mesh Pro with its own camera, which renders to a Render Texture. I then designed a simple computer monitor model in Blender split into two objects one for the glass part of the screen, and another for the 'rest' of the monitor exterior case. I saved a copy of the .blend file into the Assets folder and imported this into Unity. My blender model (two separate objects, with the separate "screen" piece moved out of the screen) When I try to apply the Render Texture onto the screen object, the texture is rotated 90 degrees anti clockwise and is too zoomed in I can't seem to rotate the texture so that it is the right way up to read the text, and only some of the text is visible. I have tried rotating the object 90 deg. clockwise in Blender and "applying" the transform so unity then thinks the object is oriented correctly. this still caused the texture to be rotated. I also tried exporting as an .obj file, with "Up" set to "Y Up", but this didn't work. I then tried applying the Render Texture to a material, which I then applied to the screen object which didn't work either. If I apply the texture to a standard cube in Unity, it works fine and is rotated and scaled correctly to fit the cube. How can I get the blender object oriented correctly so that the Render Texture applies in the correct orientation and scales so the whole of the Render Texture fits and is not zoomed in? I'm using Unity 2019.3 and Blender 2.82.


Capture Video without Third Party SDK's I am trying to capture the game play and store it on local memory without using any third party sdk's. I tried This Video Capture Script but i didn't get the recorded file even i don't know whether it's recording or not. anybody please help me to complete the task. Thanks in Advance


Exposing type definitions to modders in Unity Note that this question is not about modding assets data and not about security, I plan to rely on community trust. I don't know much about DLL's and I was wondering how I can provide interface and attribute definitions for modders. For Kerbal Space Program modders only have to reference the Assembly CSharp.dll, UnityEngine.dll and UnityEngine.CoreModule.dll files of a games build, to create and compile their own DLLs. Are there certain things I have to do, to mimic this behavior, or does this work out of the box? Are there gotchas to this approach? Will a mods DLL, that was compiled using an older version of Assembly CSharp.dll, break if the Assembly CSharp.dll is updated, even though no types relevant to the mod changed? Will modders be able to use Visual Studios debugging features for their DLLs? Is there a better approach to provide type definitions? My question is related to this question. But I would argue that that question is kind of broad, while mine is about one specific aspect. Might not be needed for the question, but here are the two levels of modding that I would like to support for my game 1. Easier modding I want to compile .cs files of modders that implement special interfaces like IAbility, IItem, etc. I will use Roslyn or cs sript to do so. 2. More advanced modding I also want to load .dll's that modders compiled, allowing them to register their own Types in the games DI Framework, mark methods classes with attributes like CallMethodOnLevelLoad and use Harmony.


Unity 5.3 with C Toggle Sound On Off I'm working with Unity 5.3 with C as code editor These are what I have I have 2 scenes in my project home and options. I have bg object on both scenes. Both bg objects have Audio Source component, which contains same background music that play on awake. I don't use any codes for these background musics, I only click the Add Component button from Unity and add Audio Source. This is what I want Options scene can toggle the background music on off for all scenes. Therefore, there are btnOn and btnOff in Options scene. This is my code in Audio Manager.cs using UnityEngine using UnityEngine.UI using System.Collections public class AudioManager MonoBehaviour public Button btnOn public Button btnOff Use this for initialization void Start () btnOn GetComponent lt Button gt () btnOff GetComponent lt Button gt () btnOn.onClick.AddListener(() gt PlayAudio()) btnOff.onClick.AddListener(() gt StopAudio()) void PlayAudio() AudioSource.volume 0.5f void StopAudio() AudioSource.volume 0f This is the problem I have this error An object reference is required to access non static member UnityEngine.AudioSource.volume. Maybe, this is because I don't write public AudioSource audioSource in my code. But, if I write this, I have to add another audio in Get Component box, and I will have double Audio Source in one scene. What should I do? Thanks


Unity Import a mesh that only has vertex and edge data but no faces I am working on a game that requires meshes that only have edges and vertices but no faces. In blender, you can make a mesh with only edges and vertices, but if you export it to FBX or OBJ, once it is imported into Unity, the resulting prefab has no mesh data linked to it. The prefab has no MeshFilter. It's as if I imported an mesh with absolutely no mesh data. For example, if I create a plane in Blender and then delete the face but leave the edges and vertices, and then export as OBJ, I can open the OBJ in a file editor. This is a square with no faces Blender v2.78 (sub 0) OBJ File '' www.blender.org mtllib egdes.mtl o Plane v 1.000000 0.000000 1.000000 v 1.000000 0.000000 1.000000 v 1.000000 0.000000 1.000000 v 1.000000 0.000000 1.000000 l 3 1 l 1 2 l 2 4 l 4 3 So it appears that OBJ actually does export with the correct mesh data, however, it seems that Unity does not know how to import an OBJ if there are no faces. Does anyone know if anyone has come up with a solution to this problem yet? If not, I guess I'll just have to write my own parser. If that's the case, does anyone know if there is a way to extend or override Unity's built in OBJ parser?


Is Update() called on the very first frame in Unity? I'm calling Time.frameCount inside Update() and then immediately Debug.Break() to pause the simulation before Update() is finished. This of course happens (supposedly) on the very first frame, and yet Time.frameCount returns 1, as if one frame had already been rendered by at that point. Also, I'm calling Time.deltaTime the same way, on the first frame inside Update(), and it returns a value too, as if a previous frame had been rendered and took X milliseconds. Considering Time.deltaTime returns the value of the "time it took to complete the last frame", and I'm calling it on the first frame and it's returning a value, is there an "invisible" first frame that Update() doesn't run on? I couldn't find any reference to this specific issue on the Unity docs.


Is it bad form to use singletons in unity I've heard a lot of people say singletons are bad practice and an 'anti pattern', like here, this answer this article and here. However, a lot of the reasons I've read about seem to be to do with dangers in their creation, them not being thread safe, difficult to destroy safely etc. But in unity where there are functions such as awake() and start() which are (as far as I'm aware) guaranteed to only be called once, are they unsafe to use?


How To Find Child Object and set is own criteria condition? I am Making 2D Game. I Apply a Two Tag On Multiple Child Game Object.. Crate A Empty Game Object and Put Script Obstacle.cs and Rigidbody2d. Child GameObject Static OnTriggerEnter2D Obstacle.cs void Start() foreach (Transform item in GetComponentsInChildren lt Transform gt ()) if (item.tag "someobstacleslow") 7 child game object find successfully Debug.Log("someobstacleslow " item.tag) if (item.tag "someobstaclefast") 4 child game object find successfully Debug.Log("movefastobstacle " item.tag) Referance https imgur.com a ozcJcO4 I want to some obstacleslow is going slow and someobstaclefast is going fast but nothing happens. Output all obstacle going very fasy?? what i miss my programme?? But Child GameObject not working its own condition? Obstacle.cs float speed 2.5f normal speed float movefastobjectspeed 3f fast spped void Update() goTopToDown() void goTopToDown() foreach (Transform item in GetComponentsInChildren lt Transform gt ()) if (item.tag "someobstacleslow") issue here move top to down object normal speed transform.position Vector3.down speed Time.deltaTime Debug.Log("GameObject obstacle object " item.tag) Debug.Log("inside obstacle object") if (item.tag "someobstaclefast") issue here move top to down object fast speed transform.position Vector3.down movefastobjectspeed Time.deltaTime Debug.Log("GameObject movefast object " item.tag) Debug.Log("inside movefast object") When My Obstacle Touch My Player then Ontrigger2d Is fire Obstacle.cs void OnTriggerEnter2D(Collider2D other) foreach (Transform child in GetComponentsInChildren lt Transform gt ()) if (child.tag "someobstacleslow" child.tag "someobstaclefast") Debug.Log("chiildtag " child.tag) gameovertext.SetActive(true) StartCoroutine(gameover()) Debug.Log("inside triggerfire") But Issue Is all obstacle going very fast(See in referance).I want to some obstacleslow is going slow and someobstaclefast is going fast but nothing happens.??help


Security of Unity Rpc calls Im just starting to code my game in unity and have been reading up that rpc calls are not validated and can run havoc on the server. For example a modified client can connect to your server and just disconnect everyone by sending networkView.RPC("disconnecteverybody", RPCMode.All) RPC void disconnecteverybody () Network.Disconnect() Is there a way to validate packets?


Instantiate and launch prefab that's overlapping player? I m very new to Unity and C . I m trying to create my first game and I have now invested about 15 hours trying to find solutions to this issue...I m stumped! My player sprite (blue square) needs to launch a prefab sprite (red circle) of similar size appearing to originate from itself. Here is a GIF of what I have so far...I don t want the blue cube to collide and go flying. After clicking and dragging on Player (drag to aim) via OnMouseDrag to set the target vector, I m trying to Instantiate a prefab sprite (Dynamic RigidBody2D, CircleCollider2D) using the Player sprite s position (a Dynamic RigidBody2D, BoxCollider2D) and have it APPEAR to be originating from inside the Player object. Launch is triggered via function called in OnMouseUp. Both objects should immediately come under control of Physics to collide with the environment which will include other moving RigidBody2D objects later. Targeting should allow 360 degrees to include straight into an obstacle allowing rebound effect. Here is some excerpts of my code using System.Collections using UnityEngine public class Teleportation Grenade MonoBehaviour This script is attached to Player and requires projectile prefab. tested with thrust set between 100 and 200. public float thrust public Transform prefab public LineRenderer playerShotLine private Vector2 playerToMouse private Vector2 targetVector ... void OnMouseDrag() Vector3 mouseWorldPoint Camera.main.ScreenToWorldPoint (Input.mousePosition) Vector2 playerToMouse mouseWorldPoint transform.position mouseWorldPoint.z 0f playerShotLine.SetPosition (0, transform.position) playerShotLine.SetPosition (1, mouseWorldPoint) playerShotLine.sortingOrder 3 opposite direction of line renderer targetVector playerToMouse void OnMouseUp() SpawnPrefab () void SpawnPrefab() Instantiate(prefab, new Vector3(transform.position.x, transform.position.y, 0), Quaternion.identity) prefab.GetComponent lt Rigidbody2D gt ().AddForce (targetVector thrust, ForceMode2D.Impulse) This is only one of many, many iterations. It's the gist of it though. I appreciate any insight from the community.


How do I show a camera's field of view area through another camera? I have a side camera that can be set on run time with changeable field of view with GUI. I am searching for a way to show the field of view of the side camera using my main camera. I am thinking about custom mesh creation through code so that it can be generated alongside the camera rectangle, but it seems too complex. Should I proceed with this method or are there any other solutions? !


Help deciding data structure for spatial partitioning, using only value types in c I simply want to implement some sort of grid where I can sort units in an RTS into cells, and then for each unit check to avoid other units and attack other units, in 2d. My map grid is currently 10 000 x 10 000 cells, with 20 thousand units. To be specific, my grid is sparse but the units move together in very dense groups of about 300 each (like an ancient army type of formation). So cells will either be extremely dense, or completely empty, no in between really. My issue in deciding is that I am using Unity job's system and burst compiler. If you do not know, jobs is a multithreading system, and burst is an LLVM based compiler outputting very fast assembly. The limitations of these systems is you can only use value types. So no classes. I have looked at using a MultiHashmap, but from what I read this can be very slow because I need to run a hash function for every unit. Then when I want to iterate al units in a cell, this is much slower than iterating an array. Especially, because I will also be checking the 8 neighbour cells for each unit as well. That's a lot of hashing being done. Finally, I have to clear the map every frame. The advantage here is Unity provides a container NativeMultiHashMap which is thread safe, so I can build and query it in parallel. I have looked into quad trees. But quad tree does not seem suited to multithreading, especially without using references. So if I did this, it would most likely be single threaded. My question is, are my above statements correct in thought? Is there a faster way to organize my data? If I go with a hashmap, how can I query it most efficiently?


Unity3d zooming with orthogonal camera like in Google maps I am implementing 2d orthogonal zoom. As far as I know in Unity3d there are no translations like in OpenGL. Taking this into consideration, I work with camera size camera position (center) real world mouse position I have no issues implementing simple zoom in zoom out operations, combined with camera position changes ( drag'n'drop ) But I have some issues calculating camera zoom shift in this case camera size (4,4) camera position (0,0) real world mouse position (1,0) A double zoom in (2x) is applied, as a result camera size (2,2) camera position (0.5,0) real world mouse position (1,0) User shifts real mouse position to (1.5,0) and applies a double zoom out ( 0.5 ). In this case camera size is again (4,4) camera position ??????? real world mouse position (1.5,0) What should be the camera shift so the mouse doesn't visually move ? What is the formula for calculation in this case ? Thank you in advance. P.S. Any suggestion regarding current method of handling zoom are welcome Update So I resolved this issue with Blue's help. The basic idea about shifting is right. The main reason it didn't work was incorrect zoom factor. Example Initial camera size is 5. User zooms in by 1, camera size is now 4 ( it displays less content on the same 'screen'). User changes mouse position and zooms out by 1. Camera size is 5 again, but the amount of zoom is actually different initially the change was 20 ( 1 5 ) in the second time, the change was 25 ( 1 4 ) My fault was that, when zooming out, I tried to restore position by 20 , not 25 .


Unity SphereCast HitInfo Give me an interpolation of the normal surface? I'm doing a SphereCast for a GroundCheck of a player. I have my Raycast hitInfo, and here in the picture at the left, I Debug.drawRay in black the direction of the hitInfo.normal every frame It seems like hitInfo.normal give me an interpolation of the normal, not the real normal of the surface... I only want the real normal of the surface... (red normals I have draw on the right), and may be the green one (the perfect normal between 2 surface), but if I can have only the red one, it would be great How can I do it ? Thanks !


Unity animations not transitioning properly I am currently trying to animate transitions between four different directions. I have four total animations for walking, and another four for the idle state. I cannot seem to figure out why when I try to transition from a walking state to another walking state in a different direction (not the direction I am idling in) it must wait for the walking animation to finish, and then play the walking animation in the new direction. You can see my sprite begin to walk forward, and then when I attempt to turn south the animation it continually plays the north animation until the animation is finished. What I am trying to achieve is a smooth transition that switches immediately. I know very little about animating and much more about programming. My list of attempted solutions is very short, and limited to only changing the length of each animation.


How to Steer a Moving Object Away From Another Object(s) I'm working with C in Unity, and I'm making a top down space shooter game in which there are many different AI controlled ships flying around. The problem is that these ships often fly on top of one another in passing, and sometimes even will fly the same route on top of one another if given the same waypoint. I want to add a system to steer my AI ships away from each other as well as other obstacles so that instead of overlapping one another when flying the same path they will fly side by side, and will also try to avoid things that pass in front of them. My current system essentially works like this The AI looks at all of the current objectives, points of interests, etc, and decides where it wants to be on the map (a coordinate). The AI then sends an input direction to the ship, which then applies acceleration in that direction and changes the velocity. Therefore, any solution to alter my ship's pathing would need to alter this input direction somehow. So my first idea was to check if there are any obstacles (ships, asteroids, structures, etc) within a radius of the ship, increasing this radius based on the ship's velocity (higher velocity larger "view" radius) Collider2D hits Physics2D.OverlapCircleAll(transform.position, ship.velocity.magnitude) If there is something nearby, calculate the direction to that collision, then calculate the opposite direction and scale it to the reciprocal, which also has the added effect of making the aversion stronger the shorter the distance to the collision is foreach (Collider2D hit in hits) if (hit.gameObject gameObject) continue exclude self from the search Vector2 v hit.ClosestPoint(transform.position) (Vector2)transform.position v (1 v.magnitude) v.normalized I would perform this for every nearby obstacle and add all of these together to get the avoidance vector avoidanceVector v continue Then I add the total avoidance vector to the AI's input direction and normalize the result inputDirection avoidanceVector inputDirection.Normalize() However, when i add this avoidance vector to my input direction, my ships exhibit a strange behavior where sometimes they will simply stop moving completely. commenting out the line where i add them together stops this behavior. I'm really not sure what could be going wrong here, but I think it has to do with my approach altogether. Can anyone help me figure out a clean, simple way to make my ships steer away from other objects?


Where's Anti Aliasing in LWRP? In Unity 2019.2 LWRP (lightweight render pipeline project) the default Game Output(Quality High) is rendering with jaggies. Inorder to get a clear render ,while looking for the Anti Aliasing option it doesn't seem to be under the default location (Edit Project settings Quality )for LWRP projects. Where is the Anti Aliasing option in LWRP and is there any other way to get a clear game render?


Why does Unity think my RectTransform has changed? I am working with UI. I want to know when my RectTransform changes its position. I am using transform.hasChanged void Update() if (transform.hasChanged) Debug.Log("Updated Position") transform.hasChanged false However, it thinks it has always changed. "Updated Position" is constantly printing out. If I remove and then readd the component while in play mode, the issue resolves itself. However, I don't want to have to do this, as it is very hacky. I could just throw a bunch of if statements in there to check, but I'd prefer to make use of the build in transform.hasChanged property. How can I check to see if my RectTransform has changed its position efficiently and elegantly?


Change Unity 3d viewport shortcuts to match Blender? The shortcuts in Unity are more similar to Maya (Alt Middle for 3d orientation, LeftClick select, etc). I've looked into Edit gt Shortcuts but couldnt find them. Is there any way to do this?


Programmatically generated mesh vertex colors not showing up in Unity? I'm sorry if this is an obvious thing to solve but I just can't figure it out...did I miss something...I've generated a mesh and during vertices generation I've also set its colors (and colors32 just in case) by reading those values from a ply file, and afterwards I've added a number of vertex color shaders but none of them will show the vertex point colors in play mode, it's either solid black or just like I added no material to the mesh (which I've tried doing manually in play mode too). Did I miss something please?


Google Play Game Services (Unity Plugin) Turn Based Multiplayer List of Open Matches I took a closer look at Google Play games services Turn based multiplayer, and I cannot find out if I am somehow able to just get a list of all open matches, so that I can implement my own GUI. It seems really weird to me that they would not let you do such a simple task. Is this just a problem with the Unity implementation or is it a general problem? Using the Google UI would make a clunky feel which I would like to avoid.


Android black screen with Unity app in subview I've exported an Unity app game I have made to Android Studio. In Android Studio I made a layout and within it I have a framelayout. However, when I run the app the framelayout is completely black, why? Here is my Java code public class UnityPlayerActivity extends Activity protected UnityPlayer mUnityPlayer don't change the name of this variable referenced from native code FrameLayout fl forUnity Button bt groen, bt gul, bt sort Override protected void onCreate(Bundle savedInstanceState) requestWindowFeature(Window.FEATURE NO TITLE) super.onCreate(savedInstanceState) getWindow().setFormat(PixelFormat.RGBX 8888) mUnityPlayer new UnityPlayer(this) if (mUnityPlayer.getSettings().getBoolean("hide status bar", true)) setTheme(android.R.style.Theme NoTitleBar Fullscreen) getWindow().setFlags(WindowManager.LayoutParams.FLAG FULLSCREEN, WindowManager.LayoutParams.FLAG FULLSCREEN) setContentView(R.layout.main) this.fl forUnity (FrameLayout) findViewById(R.id.fl forUnity) this.fl forUnity.addView(mUnityPlayer.getView(), FrameLayout.LayoutParams.MATCH PARENT, FrameLayout.LayoutParams.MATCH PARENT) this.bt groen (Button) findViewById(R.id.bt groen) this.bt gul (Button) findViewById(R.id.bt gul) this.bt sort (Button) findViewById(R.id.bt sort) this.bt groen.setOnClickListener(new View.OnClickListener() Override public void onClick(View v) UnityPlayer.UnitySendMessage("Main Camera", "ReceiveRotDir", "G") ) this.bt gul.setOnClickListener(new View.OnClickListener() Override public void onClick(View v) UnityPlayer.UnitySendMessage("Main Camera", "ReceiveRotDir", "Y") ) this.bt sort.setOnClickListener(new View.OnClickListener() Override public void onClick(View v) UnityPlayer.UnitySendMessage("Main Camera", "ReceiveRotDir", "B") ) mUnityPlayer.requestFocus() Here is my XML lt ?xml version "1.0" encoding "utf 8"? gt lt RelativeLayout xmlns android "http schemas.android.com apk res android" android layout width "match parent" android layout height "match parent" android rowCount "3" android columnCount "10" gt lt FrameLayout android layout width "match parent" android layout height "400dip" android id " id fl forUnity" android background " 00FFFF" android layout centerHorizontal "true" gt lt FrameLayout gt lt Button android layout width "wrap content" android layout height "wrap content" android text "Gr n" android id " id bt groen" android layout column "4" android layout row "2" android layout alignTop " id bt sort" android layout toRightOf " id bt sort" android layout toEndOf " id bt sort" android layout marginLeft "30dp" gt lt Button android layout width "wrap content" android layout height "wrap content" android text "Gul" android id " id bt gul" android layout column "9" android layout row "2" android layout alignTop " id bt sort" android layout toLeftOf " id bt sort" android layout toStartOf " id bt sort" android layout marginRight "30dp" gt lt Button android layout width "wrap content" android layout height "wrap content" android text "Sort" android id " id bt sort" android layout below " id fl forUnity" android layout centerHorizontal "true" android layout margin "10dip" gt lt RelativeLayout gt


Having trouble with foreach loop affecting anything past the first object found I have been trying to disable isTrigger in unity c script on all GameObjects containing a certain tag. Currently my code works and disables the isTrigger part of the box collider, but it only does this for the first object with the tag I am looking for do this for all objects. Here is the code using System.Collections using System.Collections.Generic using UnityEngine public class DefenseCollisionTrigger MonoBehaviour public static Rigidbody rb public bool CanBePlaced public GameObject defenseTriggers void Start () CanBePlaced true defenseTriggers GameObject.FindGameObjectsWithTag("Defense") public void OnTriggerEnter (Collider other) if (other.tag "Defense") CanBePlaced false public void OnTriggerExit(Collider other) if (other.tag "Defense") CanBePlaced true public void IsTriggerFalse() foreach (Object dt in defenseTriggers) Debug.Log("working on it") GetComponent lt Collider gt ().isTrigger false That is what is currently looks like. The public void IsTriggerFalse() is called on each time I go to instantiate an object with my mouse button. The Debug.Log is working and printing to the console. This is the closest I have came to making it work, but it only works for the first object. I have searched for hours and watched videos looked at unity docs on foreach statements with no luck to my issue. I have also tried using foreach (GameObject dt in defenseTriggers) instead of just Object. Anyone know how to solve my issue?


Procedurally generate with different sized cubes I am trying to procedurally generate my world like in Minecraft with tons of blocks. I have watched lots of videos about this but they all use a single fixed size cube. I would like to achieve the same as in Minecraft but with different sized cubed for example. How could this be done? I am using Perlin Noise for generation.


Why does Avatar Mask not work as expected? I have 2 layers The base layer, and an upper body layer. On the upper body layer, I have an avatar mask because I only want to affect the upper body. However, this mask doesn't work as expected. Here is what it looks like This is what is looks like when the upper body layer has a weight of 0 And this is with the upper body layer with a weight of 1 and with the Avatar Mask As one can see, the lower body is affected. The avatar mask doesn't seem to have an effect. Is that a bug in Unity, or is there anything I could still check? Thank you!


Improving Rigidbody collision between real time movable object and other Rigidbodies I have a cube that has been scaled to be rectangular (controlled by a remote Raspberry Pi gyro accelerometer magnetometer) and am translating its orientation into Unity via calls to transform.localEulerAngles new Vector3(...). This works wonderfully (the cube object modeled to be a Pi rotates perfectly), however now I'm running into issues with the actual physics. GIF of successful roll Initially the ball will land on and roll around the Pi object, however when I start to increase the speed of my movements the ball will sometimes fall through the Pi. The cube has a Rigidbody (no gravity, is kinematic) and Box collider (not triggered), and the sphere has a Rigidbody (has gravity, not kinematic) and Sphere collider (not triggered) attached. I've tried varying the collision detection from discrete to continuous on both objects and have noticed similar behaviors. The intent is to turn this into a marble maze type game, and the issue that I have is similar. If I roll the ball into the joint between a wall and the floor (both stretched cubes), rotate it down, and then rotate it up, the ball will fall through the joint. I have the same movement code attached to the GameArea object below. Again, same issue with various types of collision detection applied. My assumption is that this is a quickness of movement thing, as the cubes overlap each other (there's not a space for the ball to sneak through). For reference, in the physics colliders section of the project preferences, all relevant layers are supposed to collide with each other. I don't mind getting into code based collision detection, but this seemed fairly trivial for Unity to take care of so I was wondering if I was missing something obvious.


How can I improve my touch slide mechanic to be more smooth and fluid? I have the following C code, but it leaves me with two problems void FixedUpdate() if (Input.touchCount 1) this.transform.Translate(Input.touches 0 .deltaPosition.x 0.009f, 0, 0) Firstly, the gameobject (which is a sphere in my case), has a tendency to leave the ground and fly into the air. Additionally, it is not as smooth and snappy but fluid as I would like it to be. If you look at some of the following gameplay videos, you will see the kind of movement I am looking for. "Splashy!" Gameplay "Sky Ball" Gameplay "Balls Race" Gameplay More specifically, from actually playing each of the above games, there is a certain "ratio" that seems to be operating in regards to each swipe gesture and the actual movement of the ball. That is, the ball does not go exactly where the finger goes, for it is slightly ahead, if that makes sense. What I mean is, the device is only so wide, yet for that width, the ball can always reach it's required destination on either end of the horizontal axis. This must mean that for every pixel the finger moves, the ball moves a little bit more to fit that pixel density of the screen. In other words, in the case of "Splashy!", it's clear that even if the finger moves the entire distance across the screen, the ball moves more than double that distance. By "smooth", "fluid", and "snappy", I mean that the swiping gesture is very responsive. It moves where you want it to and does not over or undershoot. Additionally, the "snappy" effect is present when you stop swiping. The ball seems to "snap" into it's end position. My question, then, is what is the best way to improve my script as to achieve the polished mechanic I am looking for, as is depicted in the above videos? Also, how can I keep the sphere on the ground without constraining any axes on the rigidbody? I am using Unity3D with C . I would appreciate any help you could provide. Thank you.


All GameObjects and Models are Transparent Whenever I create a new game object its completely transparent, with the Mesh Renderer selected. This is really frustrating as I am new to Unity and Google offers no solutions.


Typedef redefinition error when running Unity iOS project in Xcode 9 simulator I was able to run my Unity 2017.1.0b10 iOS project successfully on my iPhone 6S (Using Xcode 9). I changed the Target SDK to Simulator SDK to try it out on other device simulators then I got the following errors in the UnityMetalSupport.h file. Below are screenshots of my player settings


Setting SteamVR Camera Target Eye before SteamVR installed in Unity I'm writing a plugin that can be used in both VR and non VR projects. I have a Camera that is used to display UI containing some game info on a secondary monitor. My problem is that when the end user adds my plugin and then imports steam vr, this UI camera's Target Eye is set to "Both" by default. I can't have any SteamVR code in my plugin. But I can't adjust Target eye property of the camera without it. I just want it so that the camera doesn't change when a user imports SteamVR. I want it to always render to the main display (target eye none) So just to clarify, I have my plugin, written in a non vr project with a standard Unity camera. There is no Target Eye setting for this standard camera. User wants to use it in VR project, imports plugin into SteamVR Project Camera used to render UI gets automatically converted (wrongly) into SteamVR camera Defaults to Target Eye Both Need it to be Target Eye None At the moment to avoid users submitting countless bug reports, I have to provide warnings in like 6 places telling users to dig way into my built in prefabs to adjust this setting manually if they use SteamVR. It's not easy for new Unity users, and I want to make adoption as easy as possible.


18.5 9 Android ratio force to 16 9 problem in Unity I want to my game build in devices with 18.5 9 ratio like Samsung S8 forced to be displayed as 16 9 ratio. I already set Aspect ratio mode to Custom and set it to 1.86 in Player Settings. I also overrided Android Manifest like this lt ?xml version "1.0" encoding "utf 8"? gt lt manifest xmlns android "http schemas.android.com apk res android" package "com.unity3d.player" xmlns tools "http schemas.android.com tools" android installLocation "preferExternal" gt lt supports screens android smallScreens "true" android normalScreens "true" android largeScreens "true" android xlargeScreens "true" android anyDensity "true" gt lt application android theme " style UnityThemeSelector" android icon " drawable app icon" android label " string app name" android isGame "true" android banner " drawable app banner" gt lt activity android name "com.unity3d.player.UnityPlayerActivity" android label " string app name" android screenOrientation "sensorLandscape" android launchMode "singleTask" android maxAspectRatio "1.86" android resizeableActivity "false" android configChanges "mcc mnc locale touchscreen keyboard keyboardHidden navigation orientation screenLayout uiMode screenSize smallestScreenSize fontScale layoutDirection density" android hardwareAccelerated "false" gt lt intent filter gt lt action android name "android.intent.action.MAIN" gt lt category android name "android.intent.category.LAUNCHER" gt lt category android name "android.intent.category.LEANBACK LAUNCHER" gt lt intent filter gt lt meta data android name "unityplayer.UnityActivity" android value "true" gt lt activity gt lt meta data android name "unity.build id" android value "633a700a 7389 4a19 972c ac1f177788f8" gt lt meta data android name "unity.splash mode" android value "0" gt lt meta data android name "unity.splash enable" android value "True" gt lt meta data android name "android.max aspect" android value "1.86" gt lt application gt lt uses feature android glEsVersion "0x00020000" gt lt uses permission android name "android.permission.INTERNET" gt lt uses feature android name "android.hardware.touchscreen" android required "false" gt lt uses feature android name "android.hardware.touchscreen.multitouch" android required "false" gt lt uses feature android name "android.hardware.touchscreen.multitouch.distinct" android required "false" gt lt manifest gt And as you see add attributes like android maxAspectRatio amp android resizeableActivity to AndroidManifest manually. But by installing the app on devices with that specific ratio, the game still running full screen and out of the bounds. I am using Unity 2018.1.4f1 (64bit).


Unity 5.1 audio issues (no sound in back channels) I've trying to bring in surround sound audio into my project. I've set my computer up to run in 5.1 and when I play a 6 channel audio through windows media player (it's a test audio that does left speaker, right speaker etc) it works fine. However, when I run it through Unity, all I get is the front 3 channels. I've set it in the Edit project settings audio to be 5.1 in there. I even set it in code with following void Start() AudioSettings.speakerMode AudioSpeakerMode.Mode5point1 How ever, when I run a debug line of print ( AudioSettings.driverCaps) It tells me that Unity is only playing in stereo. Is there something I'm still not doing? I should also add I've ran 10 different tests using the 3D audio pan and spread options. I've set both to either being fully off, half way on and full. Still the same results.


How to check strings from multiple lines in one input field? I need help with input fields. I already set the line type to 'Multi Line NewLine' in inspector, but I have problem with submitting the string. Here's the code using UnityEngine using System.Collections using UnityEngine.UI public class GameController MonoBehaviour public string code public string code1 SerializeField public InputField input public void Check(string guess) if (string.Equals (guess,code)) Debug.Log ("correct") else Debug.Log ("wrong") public void GetInput(string guess) Check (guess) input.text "" I want to have both 'code' and 'code1' strings to be inserted in different lines inside the same input field but I don't know how to check both 'code' and 'code1' string value inside the Check(). Any help would be appreciated.


Worker threads are not being utilized in Time rewind system, is this job system really multi threaded? I am trying to make a simple time rewind mechanic. It's working but it becomes slower as number of game objects increases. I decided to give Job System a shot. My idea is to interpolate between positions and rotations for N game objects in parallel. It is certainly running faster than single thread execution. However, when I see the profiler, the worker threads are sitting idle. Here's the screenshot And here's the IJob code using System using System.Collections.Generic BurstCompile struct RewindJob IJob public int RewindableIndex ReadOnly public NativeArray lt Vector3 gt positions public NativeArray lt Vector3 gt finalPositions public float currentTime public void Execute() rewind code for interpolating b w positions and this is how I schedule RewindJob for each entity like this in main thread NativeArray lt Vector3 gt finalPositions new NativeArray lt Vector3 gt (m Objects.Count, Allocator.TempJob) for (int i 0 i lt m Objects.Count i ) NativeArray lt Vector3 gt positions new NativeArray lt Vector3 gt (count, Allocator.TempJob) TimeRewindable rewindable m Objects i for(int yo 0 yo lt count yo ) positions yo rewindable.m Transforms yo .position RewindJob rewindJob new RewindJob() rewindJob.finalPositions finalPositions rewindJob.positions positions rewindJob.RewindableIndex i JobHandle handle rewindJob.Schedule() handle.Complete() positions.Dispose() for(int i 0 i lt m Objects.Count i ) m Objects i .transform.position finalPositions i m Objects i .transform.rotation finalRotations i finalPositions.Dispose() finalRotations.Dispose() What I can understand is it's not real multi threading but context switching. Can anyone just explain a little bit what's happening? Thanks.


How to create an Editor class for a generic class For all my MonoBehaviour scripts, instead of them inheriting from MonoBehaviour they inherit from a generic class like so public abstract class MonoBase lt T gt MonoBehaviour where T MonoBase lt T gt public class Example MonoBase lt Example gt Now, I would like to make an editor script for all those MonoBase classes, and the closest I have gotten to a solution that will compile is CustomEditor(typeof(MonoBase lt gt )) public class MonoBaseEditor lt T gt Editor where T MonoBase lt T gt public override void OnInspectorGUI() this.DrawDefaultInspector() MonoBase lt T gt myScript (MonoBase lt T gt )this.target if (GUILayout.Button("Build Object")) But of course it doesn't really work. Am I missing something or is there really no way to make a generic editor class like it's mentioned in an answer here.


How do I slice a 3D object at runtime in Unity? I'm specifically looking for some sort of algorithm or way that can "cut" a 3 dimensional mesh with some other game object. How would I implement this?


Collision with supposedly aligned box colliders I am quite new to game development, and I am trying to create a top down game with 2D sprites, but with a 3D feel to it. I managed to do so with the 2D engine by setting Transparency Sort Mode to Custom Axis with the axis values set to (X 0,Y 1,Z 0). I then moved the pivot of GameObjects to bottom center and used the pivot as sorting point for the sprites. I am now trying to create the environment, but my character 'clips' against the Box Colliders, even though I did all I could think of to align them (same pivot coordinates, same collider offset and size). See the attached GIF for an example I think that the cause is mentioned here, but there are no solutions mentioned there. My two solutions Remove the colliders, group the objects in a parent object, and add the collider there. But then I would get the same issue if I place two of those instances next to each other. I am still pondering to drop this approach altogether and try the same in the 3D engine, but with a fixed camera angle. I lack experience to estimate if that would be a better approach, so if someone thinks that approach would be better suited to this game style, I am happy to hear it. Can anyone give me advice on this issue, or point me towards resources that might be useful? Thanks in advance, Florian Some pictures of the settings I used


Access Single Pass RenderTexture I'm trying to achieve a mirror effect where a second camera renders to a render texture, which is then passed into a shader using SetGlobalTexture. Everything works fine outside of VR, but in Steam VR it seems like the render texture only stores the texture for one eye (left), even with single pass stereo enabled in player settings. How can I access the texture for the second eye? Or rather, how can I access the texture where both eyes have been drawn, one on each half of the screen? What I'm doing at the moment void Awake() mirrorCameraRenderTexture new RenderTexture(vrCam.pixelWidth, vrCam.pixelHeight, 24) mirrorCamera.targetTexture mirrorCameraRenderTexture Shader.SetGlobalTexture(" MirrorCameraRenderTexture", mirrorCameraRenderTexture)


Physics.IgnoreCollision not working right after invoked When invoking Physics.IgnoreCollision in Unity, it seems work but it still have collision detection right after creation. I have this issue with ejecting empty case after gun fire, it's spawning position located inside of character controller(collider), so when ejecting case created, it immediately hit to my character controller and makes my character slows. First I thought that it's coming from something else, but it's not, because when I just not spawning the empty case, it never happens. This is the code GameObject ejectedCase Instantiate(emptyCasePrefab, caseSpawnPoint.position, caseSpawnPoint.rotation) Collider caseCollider ejectedCase.GetComponent lt Collider gt () Physics.IgnoreCollision(caseCollider, playerCollider) Note that playerCollider is Collider. I also tried with CharacterController(because it's extended from Collider class) but result was same. Why I said something like "it's not working right after invoked" because it's actually working after passed some time. If it's not work, character controller step on the empty case and makes camera jittering issue on vertical axis. This is totally gone after ignoring collision detection with above code, however it still works right after creation and makes my character really slow. How do I avoid this weird glitch, makes IgnoreCollision works right after it invokes? In addition I don't want to fix this issue with using Layer Collision Matrix. I didn't tried but it will work sure, however I don't want to spend Layer for this purpose only, because it's number is limited and already using lots of layers in other logics so it makes game logic more complicated if I use Layer to avoid collision detection. I want to know why "Physics.IgnoreCollision" not works because literally it saids "ignore collision" but it wasn't.


Sending a shot left right up down based on directional key press I am trying to make a top down shooter game with similar combat to the Binding of Isaac when I press the up key the shot goes up when I press the right key the shot goes to the right I have all the rest of the code such as the point where the projectile is instantiating and the if statement to check for the button press I just want to know where I should put the vector 2 to allow me to set the direction and what to write into the vector 2 private void Update() if (Input.GetKeyDown("up")) if (Time.time gt shotTime) Instantiate(projectile, shotPoint) shotTime Time.time timeBetweenShots This is my Projectile script (at least the parts that I think would be useful) void Update() transform.Translate(Vector2.up speed Time.deltaTime) I realized that if I change the Vector2.up to make it say Vector2.down it would now shoot down But I need that to be able to change depending on which direction I am shooting.


gazing and lip syncing in Unity 5.2 Is it possible to achieve gazing or lip syncing in Unity 5.2 at all, similar to Locomotion done through MecAnim?


Why am I getting a down arrow in my Unity scene when using Oculus Rift and how do I get rid of it? In Unity, I have set up a scene to try out in Oculus Rift. When I hit play in Unity, everything works fine until about 5 seconds later when I get an arrow (Assets OVR Textures out.png) that appears in the center of my screen and won't go away. What does this arrow mean and how can I get rid of it? It is obstructing my view of the level that I am trying to view.


Touch to continue (coroutine) in unity When the object gets destroyed in my game, I want a touch to continue function after a delay. This is what I tried. this is the SceneManager class which is attached to the Main Camera public bool ttc public void NextLevel() StartCoroutine(Delay()) IEnumerator Delay() yield return new WaitForSeconds(2) print("touch to continue") ttc true My Object class void OnDestroy() Camera.main.GetComponent lt SceneManager gt ().NextLevel() if (Camera.main.GetComponent lt SceneManager gt ().ttc true) if (Input.GetKeyDown(KeyCode.V)) Application.LoadLevel("TheGame2") I also tried this IEnumerator Delay() yield return new WaitForSeconds(2) print("touch to continue") if (Input.GetKeyDown(KeyCode.V)) Application.LoadLevel("TheGame2") side note I will change the 'KeyCode.V' to a mouse button later


Changes to one Unity trail renderer causes all of them to flicker I'm using Unity. So I have a prefab, and this prefab has a trail renderer component attached to it. However, for some of the game objects I want to stop the trailer renderer at certain points in time. But doing so seems to make all of the trail renderers blink flash off and on. I've tried changing time, disabling the component, and using Clear() while hiding the trail renderer behind the background before needing to be used. All of these makes all trail renderers flicker on the frame the change happens. I believe providing the code won't be helpful, it's just if(x) disable action, if(y) enable action. What can I do?


Technique to find a mesh intersecting with a primitive solid without using colliders? For what it's worth I'm using Unity3d, but I believe the problem is more general. There are hundreds if not thousands of meshes with hundreds of vertices each. There is one sphere that can be intersecting any of those meshes and is constantly moving. Are AABB colliders approximating the mesh's volume the best way to go about this? Or is there a more specific technique that can be used here? (A limitation I have is that my colliders need to be rotated, so they're each stored in a game object, so the number of game objects becomes absurdly large for my meshes(tens of thousands) which is slowing down my game.) I have a couple of properties unique to my situation I believe might allow me to ditch colliders I don't care about the meshes colliding with each other. Just the one sphere. I only need to know that the intersection exists, I don't care about the point of the intersection or any other metadata. Just a boolean of the intersection occuring and what mesh it happened with. I don't need to know the exact moment frame when the intersection occurs. If I can find out an intersection occurred within 100 200ms 20 30 frames of it happening it'll be fine.


Third Person Highlight "Usable" Objects I'm trying to figure out a good solution in a third person RPG to determine if the character is facing and close enough to an object for it to highlight and be shown as a usable item a door, or a chest, or any other usable object in the scene. I imagine the best approach is ray casting, but I've yet to figure out how this would actually work. I plan to have a usable script on all usable objects that defines what happens during use (a door or chest opens, a coin goes into your inventory, etc), but I need to know whether the player can use the item, highlight it, and also determine which object is the "best choice" based on facing direction and distance if multiple items are in range.


(unity) move the world or the character I'm making a game like this https www.youtube.com watch?v hO7573lphqI wherein a 3D ship is flying around on a 2D plane. From the player's perspective, the ship will stay stationary in the center of the screen. The question I have is whether it's better to have to ship stay stationary and the world move around the ship? Or should I have the camera follow the ship as it moves around? Notes assume the ship can go infinitely in any direction this is in Unity, though I'm curious if that differs from other tools like Unreal I will be culling items that are offscreen either way Obviously, having the camera follow the ship is easier from the programming side of things, but I'm wondering if there's a good reason not to do that (if the player moves far enough in one direction does it hit an internal limit that would break the game)? Thanks!