How to animate clouds in a plane? I'm building a top down strategy 2D game, and i'm stuck animating clouds that will float above the arena, hiding other elements. The effect i want to achieve is something exactly like this How would i go about implementing it in Unity3D?


How to add post process volume script in unity 2019? i have old unity 2018 project and imported standard character asset. The 3d player has this script post process volume and post process layer. In 2018 i can add this component but not in 2019 . This component is not available in 2019. What is the replacement for this ? or how to achieve the same result for 2019 ?


How to avoid overwriting a value in Unity? I'm working on a Tower Defence style game, and wondering how best to handle the quot resources quot part. I have multiple enemies on screen at a time, and when an enemy dies, it updates a resource that allows the player to build more towers var tower Instantiate(buildables 0 , center, Quaternion.identity) var controller tower.GetComponent lt TowerController gt () controller.OnKilledEnemy (sender, args) gt int.TryParse(goldAmount.text.Replace( quot , quot , quot quot ), out var curr) curr args.gold goldAmount.text quot curr n0 quot But if 2 enemies die in the same frame, wouldn't the value there miss an update? What ways are there in Unity C to mitigate this problem?


Switch scenes and continue to receive bluetooth stream from Update I have a scene where I'm connected to a BLE device and receive data in bytes. I want to switch scenes from the current Update and continue to receive the data without disconnecting. How should I do this. Here is my current code in Update case States.Subscribe HM10 Status.text "Subscribing to HM10" BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress ( hm10, ServiceUUID, Characteristic, null, (address, characteristicUUID, bytes) gt float floatprint EnterDataQueue(bytes) Debug.Log("floatprint" floatprint.ToString()) HM10 Status.text "Received Serial " floatprint.ToString() HM10 Status.text "Received Serial " Encoding.UTF8.GetString (bytes) ) And the method outside static float EnterDataQueue(byte bytes) ArduinoHM10Test aTest new ArduinoHM10Test() always load the data byte array in full for (int i 0 i lt bytes.Length i ) aTest.myQueue.Enqueue(bytes i ) Dequeue the queue and check if 4 bytes have been dequeued if (aTest.myQueue.Count gt 4) byte byteArray new byte 4 for (int i 0 i lt byteArray.Length i ) byteArray i aTest.myQueue.Dequeue() if (i 3) break aTest.floatnum BitConverter.ToSingle(byteArray, 0) Debug.Log("floatnum " aTest.floatnum.ToString()) return aTest.floatnum throw new NotImplementedException()


Activate object that have button component? I'm trying to activate the array object that have button component. public GameObject weapon carry pistol new GameObject 3 public int p1 carry,activeObjects Update is called once per frame void Update() p1 carry weapon carry pistol 0 .GetComponentsInChildren lt Button gt ().Length 6 objects for (int i 0 i lt activeObjects i ) weapon carry pistol 0 .GetComponentsInChildren lt Button gt () i .enabled true This script do activate the button component but not the whole game object. If I change "Button" to "GameObject" I get error .GetComponent requires that the requested component 'GameObject' derives from MonoBehaviour or Component or is an interface.


Is it better to load all of the scene at once or load small parts of it as the player moves? I want to create a lot of detail in my game but I don t want to kill the frame rate tracking all the models and movements (like all the grass). Will loading them in pieces save the frame rate or will constantly loading and unloading models with every step negate any benefits of loading in pieces? I want to only load what the player will see at that moment and nothing else until the player either moves the camera or walks. I also want to know if loading a scene on Unity uses the gpu or the cpu?


Getting and playing AudioClips by string name Is there anyway I can get an audioclip by the name it has in the assets folder? Or will I always have to make a reference to it by dragging and dropping the clip on a SoundClip in the inspector?


Unity project not communicating with my iPhone 11? Connecting to my iPhone 11 with a cool FaceTracking project called FaceCapOSCReceiverExample https github.com hizzlehoff FaceCapOSCReceiverExample works excellent on my laptop, but not on my PC (Windows 10 and ubuntu dual boot. I am using Windows 10 for this project). On my PC the only AntiVirus firewall I have is Windows Defender. On the Inbound and Outbound rules, I deleted everything that had the word 'Unity' in it. I then added custom rules, allowing everything, for the program paths of Unity Hub and all Unity Editor installations. But no luck. The program won't communicate with my iPhone. I even tried turning the firewall completely off and re launching Unity as admin. No luck. I then manually installed the latest drivers for my network adapters (I have both quot Killer E2400 Gigabit Ethernet Controller quot and quot Qualcomm QCA9377 802.11ac Wireless Adapter quot in Device Manager). No luck! I also connected my PC to a personal hotspot from my iPhone. This was a tethered (purely USB) connection that I had running. But, while the tethered Internet worked great on my PC, it still didn't make the Unity project communicate with my iPhone! O I then added a rule to my firewall where I created a TCP port number 60001 and set it so private and public could connect. (I'm very newbie about ports) Then I entered that as the Port number within the Unity project. Still no connection was made... I have no idea what to try from here! Like I said, it works great on my laptop, but my laptop is too dang laggy to use with it, so I would really love to get it running on my PC.


Why are Visual Studio and VSCode not giving me a dropdown list of methods and options etc? I am using VSCode but I have also tried Visual Studio 2019 to write code for Unity, but when I'm writing the lines I don't get dropdown menus with for example the methods this class holds. Or objects. Or it's properties. etc. basically, IntelliSense is not working. Is there a setting that I need to enable in order to get those? Since I've seen everyone who use VSCode and visual studio get these dropdown menus.


What are the advantages and disadvantages of exporting spritesheets instead of models from Spriter into Unity? I'm working on a simple 2D platformer in Unity and have been using the Spriter2Unity tool to import my Spriter animations directly into Unity. I have noticed that this creates large hierarchies of gameobjects within the imported prefabs, basically 1 per image piece. Since the animations are fairly simple, I am thinking it would be cleaner to import each of them as a spritesheet and hook them up with a spriterenderer on the player object rather than using the importer tool. Would this actually result in any performance benefit at runtime or are the impacts of animating a lot of game objects at once negligible?


Is it possible to not pack asset files into archives when building a Unity game? When I build a game in Unity, it packs the assets into strange data files with strange extensions like .split2 or .split1. But what if I want to give the player the ability to replace textures and modify the game without reverse engineering these files? I want the Assets folder as I see it in the editor to be accessible with the same files in the build.


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


Limit position rigidbody How can I limit the position of a rigidbody, between two values if I use this code public Vector3 dir Rigidbody rb void Awake() rb GetComponent lt Rigidbody gt () void FixedUpdate() rb.velocity new Vector3(0f, 0f, 6f) rb.AddForce(dir 1f, ForceMode.VelocityChange) If I use Vector3.Clamp then the object will shake


Check if coroutine crashed I can check if coroutine still running by setting boolean variable outside the coroutine and then letting the coroutine itself set the value to true when it runs and set it to false when it decide to stop . But this method of detecting whether coroutine still active or not doesn't work when the coroutine crashed due to error (invalid input, null reference , ect) because the boolean variable remain true while the coroutine itself has stopped due to error. How do i check if coroutine still running or not in current frame ? i can't spend my code checking for next frame . Preferably C , but answer in javascript also accepted.


Unity2D force of an impact I don't know how to name what I am searching for... Force, Impact? It's easier to explain with an image for me. We have two GameObjects with colliders, A and B. They can move in any direction (top down game with 360 movement possibilities). First case (left) A go to the right at a speed of 2, B to the left at a speed of 1 and they collide. How to calculate that A take 1 damage (from the speed of B in its direction) and B take 2. Second case A go to the right at speed of 2 and B to the right at speed of 1. A take 0 damage and B take 1. I am using Collision2D which doesn't have "impulse" property. I have no idea how to calculate thing like this manually.


How can I give a MonoBehaviour field a default value that depends on the object? In Unity3D, I have a MonoBehaviour which gets added to game objects. I'm adding a string "name" field to it. I'd like the default value for the name to be the name of the game object the component is added to. Is there an easy way to do this? Some more details The component is an existing one to which I'm adding the name field. In old versions, the name was always the name of the game object, and this is a new feature to allow them to be different. The common case is (still) for the name to be the name of the game object, so having that as the default would simplify the process of adding the component to a new object. Ideally, deserializing an old scene will fill in the default, so updating scenes takes zero effort. I'm less concerned about this than about newly created scenes objects. The component already uses a CustomEditor. I don't care about updating the name in the component if the game object's name is changed, or if the component values are pasted into a different game object. One way I can think of is to add a bool "override name" to the object. If the bool is unchecked, it uses the default name (the game object) if it's checked, it uses the new field. But I'd like to avoid adding complexity to the GUI to support it. The whole point of my request is to add the new functionality (overriding the name) without adding steps to the creation workflow.


How to trust a UDP Client I'm working on a Unity project with the Lidgren UDP library for connection. I'm new to networking, so I'm not sure on general "best practices" for this area. I'm trying to figure out a good way to be able to quickly trust and verify a received UDP message. I currently keep a dictionary of players with each player assigned an UID (uint) from the server when the player connects. This UID serves as the key in the dictionary. The player is told their UID. Nothing secret being communicated here, like usernames passwords, so I'm not worried about things like that. So I'm having a problem with wrapping my head around how to trust the messages. Things like position updates and user actions will be sent from client server via UDP. I was thinking of a quick way to process these messages is by including the UID at the start of each message, checking the UID, grabbing the corresponding player from the dictionary, and then updating the players position that way. But I'm worried that can be easily spoofed manipulated. All it'd take is some mischief maker to figure it out, and then start inserting random position updates (for themselves or others). Is there an efficient, more fool proof way to ensure the message is from who it claims to be? Do I have to just rely on comparing IPEndPoints to tell? Is there anything specifically to Lidgren I can or should use? Please don't respond if all you have is "don't worry about it" or "why would anyone want to do this?" I'd rather learn proper processes now than down the road when if it becomes a problem.


Where how should A Star tie breaking occur? I've recently written a path finding script that utilizes a basic implementation of the A Star algorithm. It works fine but is not very fast. This is due, at least in part, to the fact that it isn't optimized at all. Through a bit of searching through this site and others I've realized that at least one thing I need is a tie breaking procedure that updates the heuristic values of nodes in the open list. Currently, whenever the pathfinder function is initiated. The pattern the finder takes pretty much expands outward in all directions from the point of origin until the target node is found. I've seen several videos that show A Star almost immediately traveling towards the target node thus eliminating many checks and ultimately speeding up the process. I believe this is due to a tie breaking procedure. My question is... At what point in the process should I be applying the tie breaking procedure and is there a better modifier to add to the heuristic aside from the below code? Node.heuristic (Mathf.Abs((Node.x endNodeVector.z) (endNodeVector.x Node.z)) 0.001F) This seems to be the most common that I have found. However, for some reason, this doesn't seem to effect the algorithm at all. It still searches in all directions from the origin position. What am I missing to make my A Star favor open list nodes that are closer to the target?


Align UI element to gameObject in 2D I have a 2d game where I want to display UI element perfectly aligned to specific gameObjects. I have an ortographic camera and I used to Camera.main.WorldToScreenPoint() function giving it the gameobject position modified, for instance, by 1 on X component to get the UI element on its perfect right. My problem is that the element is not on the gameObject's perfect right, but sensibly above. See this schema Expectation G UI element Reality UI element G I tried also to use the WorldToViewportPoint() but it's not giving the desired result. So, I think this is the right way to go but I can't guess what I'm missing. Any clue? EDIT After a little bit more observations it seemed that the UI element alignment depends somehow on it's distance from the center of the screen (of the camera viewport I guess), so that if the gameObject is below half height the UI element y position won't be on the perfect right but slightly below it and if above half heigth will be slightly above the perfect right. Same for x coordinate. Is there a way I could control this?


How do i easily clamp my cameras rotation when using transform.rotate() I'm making a fps controller, and I'm trying to clamp my cameras x rotation. Here's my code so far using System.Collections using System.Collections.Generic using UnityEngine public class Player MonoBehaviour Start is called before the first frame update SerializeField Camera cam SerializeField float camSpeed SerializeField float walkSpeed SerializeField float jumpSpeed float yaw float camPitch Vector3 direction Vector3 worldDirection Rigidbody myrigbody void Start() myrigbody GetComponent lt Rigidbody gt () Update is called once per frame void Update() camPitch Input.GetAxis( quot Mouse Y quot ) camSpeed cam.transform.Rotate(new Vector3(camPitch, 0, 0)) yaw (yaw Input.GetAxis( quot Mouse X quot ) camSpeed) 360f direction new Vector3(Input.GetAxis( quot Horizontal quot ) walkSpeed, myrigbody.velocity.y, Input.GetAxis( quot Vertical quot ) walkSpeed) worldDirection transform.TransformVector(direction) if(Input.GetKeyDown(KeyCode.Space)) myrigbody.AddForce(new Vector3(0, jumpSpeed, 0), ForceMode.Impulse) private void FixedUpdate() myrigbody.MoveRotation(Quaternion.Euler(0, yaw, 0)) myrigbody.velocity worldDirection I know that I want to clamp my cameras X rotation within a range of 89 to 89, but no matter what I try I can't figure out how to clamp the rotation while using cam.transform.Rotate(). I don't think I can clamp camPitch, because it is reset every frame, and I can't figure out a way to directly clamp the cameras rotation. The cameras rotation is not resetting, so if I could somehow clamp it it would work. Is this possible, or do I need to try a different method? How do i get this to clamp correctly?


Implementing a 4x4 Game Board I struggle with efficiency in code, and I want to start my game off on the right foot. I have a game that I'm making a 4 x 4 map of 'tiles' that a user can build their 'town' on. To keep track of the tiles, I'm planning on simply having a size 16 array of the type of my 'mapTile' enum. EX enum MapTiles defaultTile, homeBase, farm1, farm2 ...and so on... static MapTiles playerMap MapTiles 16 ... default map setup ... Is there a way that is more efficient or more easy to extend way to implement such a map? I'm using Unity and C mostly, though i'm willing to work with any Unity capable language if you have a clever answer.


How can I look up an object given only the name of its type? This question came from a fellow developer on Twitter, and I figured StackExchange would be a better format for explaining amp sharing the answer. To paraphrase the question I'm setting up an in game dev console in my Unity game, where a user should be able to call any method on any MonoBehaviour in the scene. I want to use something like FindObjectsOfType lt gt , but because it's coming from a string input by the user, the class name is unknown at compile time. I also want this to work universally, on any MonoBehaviour, not just ones I've specially instrumented or registered with the console system. Is there a way to find instances of a type with a particular name, and call methods on them, using something like reflection?


Unity Editor equivalent of Playmode Start() I am attempting to draw gizmos for easy debug in the editor. The gizmos code uses an array that gets populated during the start function. The array only needs to be populated once and may cause issues if its modified during runtime. As such, I cant call the method to populate the array in the OnDrawGizmos() method. I could possibly use a singleton populate the array but that would require many other things to be changed as well. I am looking for an equivalent to Start() for when it is in Editor Mode. Is there a method in editor mode that execute once or an attribute for the Start() method to execute in editor mode?


How do I prevent floating and jittering when on the ground and using spherical gravity? TL DR My ship floats and jitters when it lands on a sphere. To elaborate on the title I'm experimenting with a 3D space game. I have created a sphere, which in turn has a larger sphere overlapping it, within which, gravity will take place. However, once my player's ship (currently using an arrowhead) lands on the planet, it doesn't actually make contact with the surface of the sphere, and then the ship begins to rotate erratically and jitter. Code below. private void OnTriggerStay(Collider other) if (other.CompareTag("SoI")) inSoI true This trigger checks to see if the ship is in the larger overlapping sphere. I have another identical block for OnTriggerExit which sets inSoI to false. I also have a OnCollisionEnter which sets another variable, landed to true, and a OnCollisionExit which sets it to false. private void FixedUpdate() if (inSoI amp amp !landed) gravityVector (planet.transform.position transform.position) rb.AddForce(gravityVector.normalized planetrb.mass rb.mass gravityVector.sqrMagnitude) Simply, if in the larger sphere, then accelerate towards the planet. I tried disabling gravity if in contact with the sphere. It removed a lot of the jitter, however it still floats, and it still rotates side to side. The sphere by the way, is the standard Unity sphere, scaled 10000x in every axis. I don't need code (though it would help), any solution is fine, even if it means abandoning the project.


Start Position Move Step Problem Swipe Motion Mobile Unity C i am currently trying left amp right, up amp down swipe motion in unity C . I have done the scripting, it all working, but after i debug the script, the object's position suddenly changed to a very weird number from ( 3, 0, 3) changed to ( 3.000004, 0.00000464, 2.99999). And i intend to move just 1 unit every time i swipe, but the unit seems different, it always move around 1 but not exact 1 (Ex maybe like 0.9954, or like 1.002931). How i set the initial position to be exact integer number, and also move only 1 unit every time i swipe? Thanks using UnityEngine public class Player MonoBehaviour private Vector3 startTouchPosition, endTouchPosition private Vector3 startRocketPosition, endRocketPosition private float flyTime public float speed 1f bool canMove void Start() transform.position new Vector3( 3, 0, 3) void Update() if (Input.touchCount gt 0 amp amp Input.GetTouch(0).phase TouchPhase.Began) startTouchPosition Input.GetTouch(0).position if (Input.touchCount gt 0 amp amp Input.GetTouch(0).phase TouchPhase.Ended) endTouchPosition Input.GetTouch(0).position float xDifference Mathf.Abs(endTouchPosition.x startTouchPosition.x) float yDifference Mathf.Abs(endTouchPosition.y startTouchPosition.y) if ((endTouchPosition.x lt startTouchPosition.x) amp amp xDifference gt yDifference amp amp transform.position.x gt 5.5f) StartCoroutine(Fly("left")) MoveLeft() else if ((endTouchPosition.x gt startTouchPosition.x) amp amp xDifference gt yDifference amp amp transform.position.x lt 0.5f) StartCoroutine(Fly("right")) MoveRight() else if ((endTouchPosition.y gt startTouchPosition.y) amp amp yDifference gt xDifference amp amp transform.position.z lt 5.5f) StartCoroutine(Fly("up")) MoveUp() else if ((endTouchPosition.y lt startTouchPosition.y) amp amp yDifference gt xDifference amp amp transform.position.z gt 0.5f) StartCoroutine(Fly("down")) MoveDown() if (canMove) transform.position Vector3.Lerp(startRocketPosition, endRocketPosition, speed Time.deltaTime) canMove false startRocketPosition transform.position endRocketPosition new Vector3(startRocketPosition.x 10f, 0, transform.position.z) canMove true void MoveRight() startRocketPosition transform.position endRocketPosition new Vector3(startRocketPosition.x 10f, 0, transform.position.z) canMove true void MoveUp() startRocketPosition transform.position endRocketPosition new Vector3(startRocketPosition.x, 0, transform.position.z 10f) canMove true void MoveDown() startRocketPosition transform.position endRocketPosition new Vector3(startRocketPosition.x, 0, transform.position.z 10f) anMove true


Error when using GetComponent (Object reference not set to an instance of an object) I'm using a textmesh to check variables in real time. Thing is if I use AddComponent within Update(), it obviously starts spamming and slows the game. If I try with GetComponent the error is the following NullReferenceException Object reference not set to an instance of an object DebugCombo.Update() (at Assets DebugCombo.js 9) which points to the text.text assignment. This is the script from DebugCombo.js, from which I call the Combo class (from Combo.js) pragma strict public class DebugCombo extends MonoBehaviour function Update () var text gameObject.GetComponent(TextMesh) var combo gameObject.GetComponent(Combo) text.text quot Current quot Time.time quot Limit quot combo.comboTime How do I get rid of this error?


2D Driving Game with Unity I'm trying to make a 2D car driving game in Unity and I'm having problems with my code. I am able to move forward,backward,turn left right using arrow key from my present code using UnityEngine using System.Collections public class CarControll MonoBehaviour Use this for initialization float speedForce 15f float torqueForce 200f float driftFactorSticky 0.9f float driftFactorSlippy 1 float maxStickyVelocity 2.5f float minSlippyVelocity 1.5f bool move false public bool forwardArrow false public bool backwardArrow false public bool rightTurn false Use this for initialization void Start () void Update() move true Update is called once per frame void FixedUpdate () Rigidbody2D rb GetComponent lt Rigidbody2D gt () float driftFactor driftFactorSticky if(RightVelocity().magnitude gt maxStickyVelocity) driftFactor driftFactorSlippy rb.velocity ForwardVelocity() RightVelocity() driftFactor if( Input.GetButton("Accelerate") Input.GetButtonDown("Forward") Input.GetKeyDown(KeyCode.UpArrow)) Debug.Log ("Uparrow....................................................") rb.AddForce( transform.up 20) if( forwardArrow true) rb.AddForce(transform.up 0.5f) if(backwardArrow true) rb.AddForce( transform.up speedForce 25f ) if(Input.GetButton("Brakes") Input.GetButton("Backword") Input.GetKeyDown(KeyCode.DownArrow)) rb.AddForce( transform.up speedForce 2f ) float tf Mathf.Lerp (0, torqueForce, rb.velocity.magnitude 2) rb.angularVelocity Input.GetAxis ("Horizontal") tf Vector2 ForwardVelocity() return transform.up Vector2.Dot( GetComponent lt Rigidbody2D gt ().velocity, transform.up ) Vector2 RightVelocity() return transform.right Vector2.Dot( GetComponent lt Rigidbody2D gt ().velocity, transform.right ) public void MoveForward() forward button forwardArrow true backwardArrow false public void MoveBackward() backward button backwardArrow true forwardArrow false public void RightTurn() right button rightTurn true I have added four button(Forward,backward,right,left).Now I need to move the car using this button. The car is moving Forward,backward using the button but when Press the right left button the car is not Turing left right while move.But its working perfectly on key press.Can anyboady help solving this issue


reseting timer unity So I have been trying to reset this timer but for some reason I can't figure out why it isn't resetting. Thanks, public class controlborder MonoBehaviour varibles public static int time lt here I create my timer public static int random public static bool boolreset true varibles get objects public SpriteRenderer m spriteRenderer get objects public void Start() m spriteRenderer this.GetComponent lt SpriteRenderer gt () StartCoroutine(Changecolortimer(2f)) IEnumerator Changecolortimer(float loopdaelay) while (boolreset) yield return new WaitForSeconds(1) time lt here is set a interval if(time 3) boolreset false resettime() public void changeColor() if (random 1 amp amp time 1) m spriteRenderer.color Color.blue else if (random 2 amp amp time 2) m spriteRenderer.color Color.red else if (random 3 amp amp time 3) m spriteRenderer.color Color.green else if(random 4 amp amp time 4) m spriteRenderer.color Color.yellow public void Update() random Random.Range(1, 4) changeColor() public void resettime() time 0 boolreset true Debug.Log(time)


What is a faster alternative to a GetComponent from a RaycastHit? I have a basic AI car script which needs to interact with other cars around it. I would like to access variables from the other cars to help one car identify what the other cars are doing so they can avoid jams and crashes better. One way to do this would be a raycasthit (ignore any errors there, you know what I mean) if(Physics.Raycast(...)) hitCar hit.transform.gameObject.GetComponent lt Car gt () However, I know that GetComponent can be very performance taxing especially if it's done every time there's an intersection with the raycast. Another way would be to save all of the cars in an array or list before hand, and then test the name of it against all the names in the array or list. if(Physics.Raycast(...)) for(int i 0 i lt listOfCars.length i ) if(carName listOfCars i .name) hitCar listOfCars i However, I've heard that string comparisons (again, especially if there's a lot of intersections with the raycast) can also be taxing on performance. What's the best way to do this?


How do I slow down my character while running? void Movement() transform.Translate(Vector3.forward 10 Time.deltaTime) if(Input.GetKey(KeyCode.S)) transform.Translate(Vector3.forward 3 Time.deltaTime) if(Input.GetKeyUp(KeyCode.S)) transform.Translate(Vector3.forward 10 Time.deltaTime) I tried this code but seems to me, it didn't work as I expected it to. What I expect my character moves along at a speed of 10 automatically when the S key is held, the character slows down to a speed of 3 instead when the S key is released, the character goes back to their default speed of 10 What I observe the character does not slow down when the S key is pressed How can I fix this?


SpriteRenderer.flipY not functioning The problem I'm having is that my script, which has access to the spriterenderer on my gameobject, won't flip the sprite when I directly type quot sprite.flipY true quot at the end of my FixedUpdate() function. if (transform.position.x lt player.transform.position.x) facingright false if (transform.position.x gt player.transform.position.x) facingright true sprite.flipY !wasfacingright Heres all of the code if you need it using System.Collections using System.Collections.Generic using UnityEngine public class GunController MonoBehaviour public Transform player public CharacterController2D playercontroller public float smoothness 0.125f public float winglength 2 private Vector2 difference private bool facingright true bool wasfacingright true public GameObject bullet public int maxammo public int ammo public Transform rightNozzle public Transform leftNozzle public SpriteRenderer sprite public Sprite normalGun public Sprite emptyGun public GameObject emptyBottle public Animator reloadAnim Start is called before the first frame update void Start() player transform.parent.transform sprite.sprite emptyGun Update is called once per frame void Update() private void FixedUpdate() doMovement() tryShooting() tryReloading() private void tryReloading() if (Input.GetKey(KeyCode.R) amp ammo lt 0) Instantiate(emptyBottle, transform.position, Quaternion.identity) StartCoroutine(reload()) ammo maxammo private void tryShooting() if (Input.GetMouseButton(0) amp ammo gt 0 ) ammo 1 if (facingright) Instantiate(bullet, rightNozzle.position, transform.rotation) else Instantiate(bullet, leftNozzle.position, transform.rotation) private void doMovement() wasfacingright facingright if (transform.position.x lt player.transform.position.x) facingright false if (transform.position.x gt player.transform.position.x) facingright true sprite.flipY !wasfacingright if (wasfacingright ! facingright) playercontroller.Flip() difference Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.position float rot Mathf.Atan2(difference.y, difference.x) Mathf.Rad2Deg Vector3 pos Camera.main.ScreenToWorldPoint(Input.mousePosition) player.position pos.z 0 Vector3 desiredpos player.position (winglength pos.normalized) Vector3 smoothpos Vector3.Lerp(transform.position, desiredpos, smoothness) transform.position smoothpos transform.rotation Quaternion.Euler(0, 0, rot) IEnumerator reload() sprite.sprite emptyGun reloadAnim.Play( quot Reload quot , 0, 0) yield return new WaitForSecondsRealtime(0.5f) sprite.sprite normalGun public void die() gameObject.SetActive(false)


How to set rotations to 0,0,0 in 3ds max for exporting in unity? I'm a modeler in 3ds max and the unity programmer ask me that the object must have pivot with Y up rotations at 0,0,0 but every object that I export in fbx he says don't have rotations at 0,0,0. I tryed different solutions as reset xform freeze rotation rotation to zero .rotation eulerangles 0 0 0 but in unity he have values like this 4.577637e 05, 1.525879e 05, 0 or 90, 1.525879e 05, 0 and so on It's a problem that can I fix in max or the programmer has to fix it in unity? Thanks


Converging at position and angle using motor based rigidbody movement I am given a rigidbody positioned in mathbb R 2 . It is a box of length l and height epsilon . The position of the box's left center is described by vec p , and its angle from the x axis is theta . The body is in a vacuum (no friction), and its mass is m (uniformly distributed). Here's a quick diagram. Next, I am given a target position and angle to reach. It is not guaranteed that the body will reach the target position and angle the next time frame. I need to calculate the necessary force F and torque T that will push the body closest to the target. I am given constraints for max force and max torque. To make things complicated, the body might be affected by external forces. One of them is gravity F g , which will always remain constant. Sometimes, normal forces exist as well. The applied forces or the total force is unknown, but the velocity or the angular velocity is available. I tried to solve this problem using steering behaviors. However, the angle seems to fluctuate constantly. Here's part of my code in C (Unity). vec p 0 transform.position theta 0 transform.eulerAngles.z vec p t position theta t angle private RigidBody body public float SlowDownRadius 2f public float MaxVelocity 50f public float MaxForce 10000f public float SlowDownDelta 15f public float MaxAngVelocity 180f public float MaxTorque 10000f public void Next(Vector3 position, float angle) angle in degrees force Vector2 to position var from (Vector2) transform.position var desired to from var dist desired.sqrMagnitude desired desired.SetMagnitude(dist lt SlowDownRadius SlowDownRadius ? MaxVelocity Mathf.Sqrt(dist) SlowDownRadius MaxVelocity) Vector2 vel body.velocity var steering desired vel var mass body.mass Vector2 force mass UnityEngine.Physics.gravity var time Time.deltaTime var newForce (time lt 0 ? new Vector2() (mass time steering)) force body.AddForce(newForce.Clamp(MaxForce)) limits magnitude of newForce to MaxForce torque var toAngle angle var fromAngle transform.eulerAngles.z var desiredAngle AngleDistance(fromAngle, toAngle) var distAngle Mathf.Abs(desiredAngle) if (distAngle lt 1f) transform.eulerAngles new Vector3(0, 0, angle) return desiredAngle Mathf.Sign(desiredAngle) (distAngle lt SlowDownDelta ? MaxAngVelocity distAngle SlowDownDelta MaxAngVelocity) Mathf.Deg2Rad var angVel body.angularVelocity.z in radians var steeringAngle desiredAngle angVel var newTorque (time lt 0 ? 0f (mass time steeringAngle)) body.AddTorque(0, 0, Mathf.Sign(newTorque) Mathf.Min(Mathf.Abs(newTorque), MaxTorque)) public static float AngleDistance(float from, float to) var dist (to from 180f) 360f 180f return dist lt 180f ? dist 360 dist If I made any errors, please let me know. Thank you in advance!


Help with a snake like movement I am looking for an algorithm that moves an object at a regular speed in a snake circular like movement. This movement should look pseudo random and smooth, later on I am going to add other body parts, but so far this is the essential. My try so far has consisted in having a random value t that chages each frame t Random.Range(t 20f,t 20f) and according to it I was employing a direction. The result should be more directions that are smoothly different, so that the movement itself is smooth. I would score the solution with 7 10, and moreover, it doesn't describe like short circles, but rather larger ones and the negative result is that the object exits the scene quite fast. What is your algorithm solution? On the internet I found solutions where the player moves the head of the snake, but here the object acts like an autonomous object.


Calling and functions methods from different Classes in Unity I am learning some of the basics with Unity and am running into calling sending code to a different script. For example, the code below is a basic menu of options. I have a different Scene set up in Unity for each one of the menu options. As you can see from the if else if statements, depending on which option a user checks, will take them to a different portion of the program. At this point it will obviously not compile because the 4 methods for each menu option are not referenced anywhere. Lets say the user selects option 1 which is the StudyScreen() method. Now in the StudyScreen.cs script that I created, how do I link those so when option 1 is selected, it goes to the StudyScreen.cs and runs what I need it to run. using UnityEngine using UnityEngine.UI using System.Collections public class MainMenu MonoBehaviour public Text menu Use this for initialization void Start () menu.text "Main Menu Options r n r n" "1. Study r n" "2. Quiz r n" "3. Test r n" "4. Exit r n" Update is called once per frame void Update () if (Input.GetKeyDown(KeyCode.Alpha1)) StudyScreen() else if (Input.GetKeyDown(KeyCode.Alpha2)) QuizScreen() else if (Input.GetKeyDown(KeyCode.Alpha3)) TestScreen() else if (Input.GetKeyDown(KeyCode.Alpha4)) ExitScreen() I hope I was able to make it clear as to what I was trying to accomplish. Please let me know if anything is unclear. Thanks in Advance. Curtis


Is there a way to use Post Processing Effects on Mobile? I tried to use the built in unity Post Processing stack, I simply just want a vignette effect for my game, but it when I tested it on my phone it ran lt 25 fps, which is too low in my opinion. Is there a way to recreate the effect for better performance?


snap an object to another object? so I have some walls which are cubes stretched along a direction.and I have some windows and doors that are suppose to snap to a wall and don't let go until the desired location is out of the snapping range.and in the meantime I want the Objects to move along the wall but never detach from it. if I wasn't clear enough let me know.


Design basics for Unity game sport management type I am planning the classes for my game and I am having problems to figure out the best way to connect them. In my game I do not have the classic structure of say a FPS where you have the player class with stats, and AI class with enemy AI. my game is more like a sport simulation manager type so there are various entities The player which take over a team (or play in a team) The NPC other players, managers, people that work in the club. The team (club) itself where either the player take control of it, so NPC will join it, or will play in it, so the team will have both player and NPCs. Competitions self explanatory team participate in it. I was thinking to make different base classes, one for team, NPC, player and competitions, but then I need to establish relations between them. This look more like a DB with relation between tables, compared to a standard FPS game, where everything is strictly divided and you don't get class that "belong" to some other class. I am using Unity BTW, so far I ahve the GameManager class which initialize the main menu, the scene manager and UI manager. Then I have 4 different class (player, NPC, competition and team), and this is where I am stuck. Should I create references to other classes, so when I instantiate for example a team class then I will put in it a dataset to represent the NPC classes and the player class? Or should they not know about each other at all, and all the interaction and logic should go in the gamemanager class?


How do you unzip a Texture2D from image or string from txt from a zip file using SharpZipLib How do you unzip a Texture2D from image or string from a txt file contained in a zip file using SharpZipLib or System.IO.Compression?


AudioSource not working. Empty Exception I'm trying to load and play an wav file that exists in my Application.dataPath but when the game gets to the line GoAudioSource.PlayOneShot(audioLoader.audioClip) It justs throws a empty exception and no sound is played. I've already checked if the path is correct and it is. I've also tried uploading this wav file to an FTP and loading it via HTTP instead of File but nothing changes. This is my full code private IEnumerator WriteResponseAudio(ResponseModel res) File.WriteAllBytes(Path.Combine(Application.dataPath, FILENAME RESPONSE), Convert.FromBase64String(res.intent.audio.content)) string path "file " Application.dataPath " " FILENAME RESPONSE WWW audioLoader new WWW(path) yield return audioLoader try GoAudioSource.PlayOneShot(audioLoader.audioClip) catch (Exception ex) Debug.LogError("Erro " ex.Message) This is the version with HTTP request private IEnumerator WriteResponseAudio(ResponseModel res) File.WriteAllBytes(Path.Combine(Application.dataPath, FILENAME RESPONSE), Convert.FromBase64String(res.intent.audio.content)) string path "http www.raphaelrosa.com response.wav" WWW audioLoader new WWW(path) yield return audioLoader try GoAudioSource.PlayOneShot(audioLoader.audioClip) catch (Exception ex) Debug.LogError("Erro " ex.Message) This is the console


In Unity, what's a better solution than having a bunch of singleton static managers? (SceneManager, UIManager, SfxManager, PfxManager) I always hand a bunch of public static manager classes in my game GameManager (singleton) for reading and writing persistent data and gamestate across scenes SceneManager for holding scene data (coins picked up, score, are we in a cutscene) UIManager for dealing with HUD stuff SfxManager for sound effects PfxManager for particle effects On the gameobject that holds these manager classes, there are also subordinate classes (e.g. HUDManager, a smaller class that managers tasks specific to HUD, and then delegate those tasks into other smaller scripts) in order to avoid monolithic manager classes. Is this method frowned upon in Unity game development and if so, what are some better solutions than this approach?


Does Unity have a built in pathfinding system? I know that there a lot of plugins available for pathfinding in unity but I was just wondering if unity has a built in pathfinding system ?


Baking lights causes weird seams on meshes. How to avoid it? I'm trying to bake lightning in the simple scene with some imported geometry. The result is weird seams near the edges of the meshes even there is no free space between them. How to avoid it and just simply bake that lightning? This is just something that should not be.


How to prevent Dynamic Rigidbody2d with large mass pushing another Rigidbody2d into BoxCollider2D I'm making a prototype for a game idea but hitting a problem ( Quite new to Unity and feel like this should be relatively easy to solve, but keep going around in circles, and hoping to get some help ) Video https gfycat.com candidplushemeraldtreeskink GameObjects Red box has BoxCollider2D Duck has BoxCollider2D, Rigidbody2D (dynamic), some scripts Wall has BoxCollider2D, Rigidbody2D (dynamic), some scripts Rules Red box doesn't move, everything should stop when colliding with it Duck moveable by player, can't push quot Wall quot Wall moveable by player, can push quot Duck quot To get quot Wall can push Duck, but Duck can't push Wall quot working, I set the Mass for Wall to be Infinity. However, this seems to have a side effect where Wall can now push Duck through Red box. Note even increasing mass to something like 500 has this side effect too If the mass for Wall is smaller, then it won't push Duck through Red box. However, with the smaller mass, Duck can then push Wall (which I don't want). The script for moving Wall is private void FixedUpdate() https learn.unity.com tutorial world interactions blocking movement?uv 2019.2 amp projectId 5c6166dbedbc2a0021b1bc7c 5ce3cdabedbc2a3ce61754e8 Vector2 position rigidbody2d.position position.x speed horizontal Time.deltaTime position.y speed vertical Time.deltaTime rigidbody2d.MovePosition(position) Question What should I do so quot Wall can push Duck, but Duck can't push Wall quot holds true, without Duck being pushed into the Red box. Should I be using Dynamic Rigidbody (sort of physics with collisions and pushing), or Kinematic Rigidbody (and handle collisions and pushing manually)? Thanks in advance!


Is there a way to turn collision detection system off completely in Unity? My world setup is 2D Top Down. All collisions are disabled from the collision matrix. There are no collisions in the scene as I wanted, but as I perceive, Unity is still trying to calculate collisions in the background. So I'm experiencing serious frame rate drops because of Physics2D.Simulate when I have about 2k colliders moving over each other on the scene. I followed the suggestions about colliders and rigidbodies on the API exactly (so I know the stuff about not to move static colliders without rigidbody, that's not the case here), but I somehow can't manage to tell Unity that I don't want her to calculate "possible" collisions. I only want colliders for Raycast2D, OverlapCircle and making movements a bit realistic. Thanks in advance for all suggestions.


How can i use StartCoroutine to set the speed for each scaling step of the walls? using System.Collections using System.Collections.Generic using UnityEngine public class WallsTest MonoBehaviour using a GameObject rather than a transform public GameObject prefab public Vector3 wallsStartPosition public float width 0 public float height 1 public float length 2 public Camera wallsCamera void Start() wallsCamera.transform.position new Vector3(wallsStartPosition.x, wallsStartPosition.y 100, wallsStartPosition.z 235) StartCoroutine(BuildWalls()) IEnumerator BuildWalls() for (int i 2 i lt 2 i ) GameObject go Instantiate(prefab) go.transform.parent transform Vector3 scale Vector3.one Vector3 adjustedPosition wallsStartPosition float sign Mathf.Sign(i) if ((i sign) 2 0) adjustedPosition.x (length sign) 2 yield return new WaitForSeconds(0.1f) scale.x width scale.y height scale.z length width else adjustedPosition.z (length sign) 2 scale.x length width scale.y height scale.z width adjustedPosition.y height 2 go.transform.localScale scale go.transform.localPosition adjustedPosition What it does now it's creating two walls at once it's just waiting 0.1 millisecond before creating them. But instead i want it to show the scaling of the walls how they scaling and moving same for the else part for the adjustedPosition.z and not only the adjustedPosition.x The problem is it's just waiting until it's placing the walls at once. I want to see the walls being building step by step like it's placing cube after cube.


Quaternion.slerps resets camera rotation to (0,0,0) when i go to play mode help! i am building a camera rotation script like in fps. Everything is setup and working except that camera rotation resets to zero at the start of game which i dont want. This is the camera rotation i have set This is rotation of character my script is attached to And after hitting play it resets camera rotation to (0,0,0). i want it to remain how i have set it in inspector. i am using quaternion.slerp to rotate camera around to rotations on the basis of touch inputs. After reset to (0,0,0) everything works fine.please help, i have always had a hard time understanding quaternions. this is the script public class ScreenCharacterController MonoBehaviour private Camera mainCamera private CharacterController character private int leftFingerID 1 private int rightFingerID 1 private Vector2 leftFingerInput private Vector2 rightFingerInput private float xAxisRotation private float yAxisRotation SerializeField private float minXRotation SerializeField private float maxXRotation SerializeField private float minYRotation 25f SerializeField private float maxYRotation 25f SerializeField private float cameraRotationSpeed 20f void Start() mainCamera Camera.main void Update() for touch TouchInput() for calculating rotation vaues CalculateAndClampRotation() RotateCamera() void TouchInput() foreach (Touch touch in Input.touches) if (touch.phase TouchPhase.Began) Left Touch if (touch.position.x lt Screen.width 2) leftFingerID touch.fingerId Right touch else rightFingerID touch.fingerId else if (touch.phase TouchPhase.Moved) Left Touch if (touch.position.x lt Screen.width 2) if (leftFingerID touch.fingerId) Right touch else if (rightFingerID touch.fingerId) rightFingerInput touch.deltaPosition Time.smoothDeltaTime else if (touch.phase TouchPhase.Ended touch.phase TouchPhase.Canceled) if (touch.fingerId leftFingerID) leftFingerID 1 else if (touch.fingerId rightFingerID) rightFingerID 1 rightFingerInput new Vector2(0, 0) void RotateCamera() Quaternion currentRotation mainCamera.transform.localRotation Quaternion targetRotation Quaternion.identity targetRotation Quaternion.Euler((mainCamera.transform.localRotation.x yAxisRotation), (mainCamera.transform.localRotation.y xAxisRotation), 0f) mainCamera.transform.localRotation Quaternion.Slerp(currentRotation, targetRotation, 0.5f) void CalculateAndClampRotation() xAxisRotation rightFingerInput.x cameraRotationSpeed yAxisRotation rightFingerInput.y cameraRotationSpeed xAxisRotation Mathf.Clamp(xAxisRotation, minXRotation, maxXRotation) yAxisRotation Mathf.Clamp(yAxisRotation, minYRotation, maxYRotation)


How can I customize remove the caret from Input Fields in Unity? Goal Change the caret to a non blinking asterisk. Description I'm using the TextMeshPro variant of the InputField, and my Unity ver. is 2019.3. Potential Solutions Remove Caret I could remove the caret and manually add an asterisk at the end and remove it upon submission. Problem I don't know how to do that. Caret width doesn't go below 1, and I've yet to see an option to disable it. Change Caret Self explanatory. However, it doesn't appear that customizing the caret character is an option. Shove The Input Field Off Scree And Copy Its Value To Text On Screen I can still use the Input Field (and I need to), but hide it off screen and put a simple Text field in its place, which will display the Input Field's text the caret ( ). This could work, but I'm hoping there's a less hacky solution.


How to temporarily increase the speed of a character in a Unity game As the title would suggest, I want to give a character a speed boost for x amount of seconds, while increasing their Gameobject's mass. During this little speed boost, I also want to add a script to another player that disappears when the speed boost dies out I am new to C , and Unity in general, any help would be appreciated. using System.Collections using System.Collections.Generic using UnityEngine public class PlayerAddMass MonoBehaviour Start is called before the first frame update void Start() Update is called once per frame void Update() if (Input.GetKey(KeyCode.Q)) rb GetComponent lt Rigidbody gt () rb.mass 10 rb GetComponent lt Rigidbody gt () rb.speed 5 The code above was found on a unity website of some sorts, and I modified it to set the speed and mass numbers (I changed the 0s into a 10 and a 5) The errors I get are "rb does not exist in the current context" x 4


Unity Applying Global Light Settings fog to a non main camera Is it possible to apply fog to a non main camera?


Can I create realtime textures with text? I have a large number of items in my game, that will eventually have a texture associated with them. The problem is, for right now, I have nothing. I would really like to do something with, say, the first 2 letters of the object's name. As my main system will be pure textures, I really don't want to add a text object to the texture, I would really like to just create a texture with the object's first two letters. Is there a way I can create a texture, realtime, with font rendered on that texture? Preferably without a camera render texture, unless I can create them once. I really want to create a unique default texture for each item at runtime, preferably with some kind of font. Can I do this?


How do mobile games implement time gates unhackably? Is it possible in offline games? I'm thinking about porting my game to Google Play, and it would be free to play with time gates which are skippable if you watch an ad. What are the ways of implementing an unhackable time gating? Is it possible without internet connection? If yes, how? If no, is there a way to implement it without custom backend, using Google Play's services? Or should I care about this at all? Because... It doesn't affect other players... Most of the audience couldn't do it anyway, and if the game stays small, hacks couldn't really spread. Then maybe I should just let them hack those time gates, it's a marginal revenue loss. What do you think?


Do editor errors affect device performance? Do errors that come up in the Unity editor affect a game's performance on a device (on Android in particular)? I'm talking about errors that keep coming continuously during Update() such as NullReferenceException and "Debug.Log".


How can I make a level generator script run in Edit Mode? Description I've a script that takes in a PNG bitmap (e.g. 8x8) and, reading from that, populates the grid with cells where alpha gt 0. Problem The script runs in Awake(), so it can only be seen in Play Mode. I want it to always appear in the scene, even in Edit Mode. Potential Solutions I know of the ExecuteInEditMode attribute, as well as the OnValidate() callback. I don't know which is better to use, though, or what pitfalls to avoid. Additionally, in the past, I created a level generator that created a mesh, which I saved as an .asset with a custom editor button. The .asset was then loaded from inside the script. However, if possible, I'd like a more elegant and automatic solution. Other I'm using Unity 2018.4, and the grid is isometric. (I'm not using Unity's built in Tilemap.)


How do I make Unity halt on exceptions? I'm trying to debug a Unity project using the Unity Editor and Visual Studio. A runtime exception keeps popping up, but the debugger doesn't halt when an exception occurs, making it impossible to debug my code efficiently. In Visual Studio, I've gone into Tools Options Tools For Unity and set "Exception Support" to "True". I've also enabled all types of exceptions in the Exception Settings panel. I am connecting the debugger to Unity using the "Attach to Unity" button. Breakpoints are working, but the debugger isn't halting on Exceptions. What do I need to do to get Unity VS to actually halt on Exceptions? Note I've tried closing and re opening both Unity and VS many times but that doesn't make any difference.


Jerky Character movement after adding mouse orbit script I added a custom mouse orbit script to my project. When the right mouse button is clicked, the camera can be rotated around the player. The issue, after this change, is my player movement has become jerky choppy and not smooth. If I remove my mouse orbit script, player moment is back to normal i.e smooth. I can't seem to pin point what is causing this jerky movement withing MouseOrbit script Video demo Code This is where we initialize our script void Start() Initialize() This is where we set our private variables, check for null errors, and anything else that needs to be called once during startup void Initialize() h this.transform.eulerAngles.x v this.transform.eulerAngles.y cameraTransform this.transform cam Camera.main smoothDistance distance timerot TimeSignature((1 rotationDampening)) 100.0f NullErrorCheck() We check for null errors or warnings and notify the user to fix them void NullErrorCheck() if (!viewTarget) Debug.LogError("Please make sure to assign a view target!") Debug.Break() if (collisionLayers 0) Debug.LogWarning("Make sure to set the collision layers to the layers the camera should collide with!") This is where we do all our camera updates. This is where the camera gets all of its functionality. From setting the position and rotation, to adjusting the camera to avoid geometry clipping void Update() if (!viewTarget) return if (Input.GetMouseButton(1)) Cursor.lockState CursorLockMode.Locked h Input.GetAxis("Mouse X") horizontalRotationSpeed Time.deltaTime v Input.GetAxis("Mouse Y") verticalRotationSpeed Time.deltaTime h ClampAngle(h, 360.0f, 360.0f) v ClampAngle(v, minVerticalAngle, maxVerticalAngle) Debug.Log ("value of h " h) newRotation Quaternion.Euler(v, h, 0.0f) else Cursor.lockState CursorLockMode.None if (Input.GetKeyDown(KeyCode.D)) h transform.eulerAngles.y 90 newRotation Quaternion.Euler(transform.eulerAngles.x, h, transform.eulerAngles.z) if (Input.GetKeyDown(KeyCode.A)) h transform.eulerAngles.y 90 newRotation Quaternion.Euler(transform.eulerAngles.x, h, transform.eulerAngles.z) We set the distance by moving the mouse wheel and use a custom growth function as the time value for linear interpolation distance Mathf.Clamp(distance Input.GetAxis("Mouse ScrollWheel") 10, minDistance, maxDistance) smoothDistance Mathf.Lerp(smoothDistance, distance, TimeSignature(distanceSpeed)) We give the rotation some smoothing for a nicer effect smoothRotation Quaternion.Slerp(smoothRotation, newRotation, TimeSignature((1 rotationDampening) 100.0f)) newPosition viewTarget.position newPosition smoothRotation new Vector3(0.0f, height, smoothDistance) Calls the function to adjust the camera position to avoid clipping CheckSphere() smoothRotation.eulerAngles new Vector3(smoothRotation.eulerAngles.x, smoothRotation.eulerAngles.y, 0.0f) Vector3 dir new Vector3(0, 0, distance) cameraTransform.position newPosition cameraTransform.position viewTarget.position smoothRotation dir cameraTransform.rotation smoothRotation Time Signature with speed as input private float TimeSignature(float speed) return 1.0f (1.0f 80.0f Mathf.Exp( speed 0.02f))


can i show logs in unity with different colors or different icon signs? I'm working on a project that has a lot of logging messages that pass very fast. I can use error logs or warning logs but is there any way to log something with different colors so it is easier to find? Right now, I just use something like this Debug.LogError("show missing gold popup accepted")


Sea is higher than land when importing large real world terrain I am trying to import some real world terrain into Unity with the help of Global Mapper. The data I am using is download from CGIAR SRTM(http srtm.csi.cgiar.org ,http srtm.csi.cgiar.org srtmdata ). The land part works well but I am having trouble with the sea part. This is a larger view of that weird thing in the first image. This strange is actually the sea. This is happening because I am using the gradient shader. Lokks like The sea is represented with white, but when Unity reading the .raw file, the white means the highest part. Does anyone know how to deal with problems like this? Thanks very march.


How do I duplicate the functionality of ugui's onClick (button component) in inspector (Unity)? I'm trying to create the same functionality that occurs when you are working with a button in uGui in Unity. I know that I have to create a custom inspector, but i'm not sure where to go from there. Essentially the functionality allows you to drag and drop a script to it's on click portion in the inspector, and then it gives you a list of functions for that script to select. This may sound a little confusing, so here are a few pictures demonstrating the functionality i'm trying to replicate. As you can see above the functionality allows you to drag in a script, select a function to link, and do this for as many or as little scripts as you want by pressing the or buttons on the bottom right. Thanks for any help in advance!


Hide part of the GUITexture in Unity I have a Health Bar in my Unity game and it's implemented as a GUITexture with gradient image from red to green. Now I can reduce it's width from max width to 0, but is still scaled gradient. public void UpdateHealthBar(int hitPoints) healthBar.pixelInset new Rect( healthBar.pixelInset.x, healthBar.pixelInset.y, 3 hitPoints, healthBar.pixelInset.height) But I want to hide (make transparent) the right part of this health bar in game progress. How can I do this? Thanks!


Box2D Soft Body Wheel in Unity3D I was watching this video made with IForce2D, its about creating soft bodied wheels in box2D. http www.youtube.com watch?v F aDMZUVw0c I wanted help in being able to increase the Radius of the Wheel gradually. I tried increasing the natural distance of spring joint (Distance Joint) between central body and outer body. But since outer bodies are connected by revolute joint, which force the outer bodies to not change their positions. I then changed the Anchor Points of Revolute Joint to match the increase in Radius of Wheel. Now, the outer bodies start moving away from center body towards their natural Distance. But gradually some outer bodies rotate and move away from each other. Check out this video i made showing what i have done https drive.google.com file d 0B CQHvLBg5TQNlBEZXpRaVc5MDQ edit?usp sharing Note I am using Unity3D 4.3.4 with 2D Physics, Gravity is Off. Any ideas?


Get all supported resolutions for a monitor I've been receiving complaints from users that my game doesn't support the 16 10 aspect ratio. Currently I list everything in Screen.resolutions in a dropdown and allow the user to pick from that. I have since come to the understanding that the first element is not necessarily the native resolution of the monitor. I've found the Display class but this appears to only give the native resolution, not all scaled resolutions. E.g. if the monitor is 1920x1080 then I need a list of 1600x900, 1280x720, 640x360 etc. I thought about just multiplying by some scale factor but then I'm afraid I'll get something obscure like 885x497.8. And if I have a pre determined list of resolutions for a specific aspect ratio, how do I support obscure aspect ratios like widescreen for example.


Raycast a ray to the tip of another ray I'm using unity to raycast a line from the center of my camera viewport to a world position (yellow line). I also want to cast a ray from the center of my character to this same point (blue line). I have tried two methods to get this to work, however neither has worked. The two methods are the following if (Input.GetKey (KeyCode.Mouse0)) if left click is held down Ray crosshairPoint viewCamera.ViewportPointToRay (new Vector3(0.5f, 0.5f, 0.0f)) Vector3 crosshairEnd (crosshairPoint.origin crosshairPoint.direction 15) Debug.DrawRay (crosshairPoint.origin, crosshairPoint.direction 20, Color.yellow, Time.deltaTime, false) Vector3 intersect crosshairPoint.GetPoint (20) Debug.DrawRay (Vector3.zero, intersect, Color.red, Time.deltaTime, false) Debug.DrawRay( charFace.position, intersect, Color.cyan, Time.deltaTime, false) The red line being drawn is a line from the origin, which has no problem intersecting my camera ray line. The one from my character just refuses to point at the given point. The second method is the same as above, but using vector math (origin direction distance) to get the same point. Any ideas why the ray from my character won't point the right way, but one from the origin would? Something to do with world vs. local coordinates? Thanks 1


Why is my TextMesh always on top? I have a 2 d game that I am making, using 3 d assets, including TextMeshes for text. I have decided that in some instances, I would like to have the TextMesh appear behind objects in the foreground. The below is one such example. It seems that the TextMesh is always in front. I have tried a number of things to get the text between the map and object layers, with no success. These include Moving the text between the map and object. Changing the SortingLayers and SortingOrder. The map, objects, and labels are on 3 different layers, with the Objects being the highest layer, the map the lowest, and default and label in between. Using a perspective camera, not orthographic. Any ideas as to what else could be going on? Thanks! How can I make the TextMesh appear that isn't on the top layer? Thanks!


How to use the BillboardRenderer in Unity? Since version 5 (?) Unity has a new component type BillboardRenderer. Unfortunately the documentation is quite poor. It can be added in the inspector by clicking on "Add Component Misceallaneous Billboard Renderer" but apparently it requires a Billboard Asset to do anything. There doesn't seem to be any way to create one from the Unity interface. One of the few sentences from the equally poor documentation of BillboardAsset reads imageCount Number of pre baked images that can be switched when the billboard is viewed from different angles. My newest project will have sprite polygon mix graphics, so a component which renders a billboard with a different sprite depending on the view angle is something I could really make use of. But there doesn't seem to be any method to add such images. So I wondered if you could post an example how this component is used.


Unity3d Rigidbody movement along slope slowdown I have a Rigidbody character controller (Unity, C ) which I'm trying to make work seamlessly when walking on sloped ground. I've got it working fine walking up and down a slope by changing the forward direction to always be parallel to the ground (using the surface normal). But a strange thing is happening when walking sideways on that same slope (and not up and down it)...the character slows to a crawl. Anyone have any idea why this might happen, or how to solve it? private void Walk() isMoving false if (!inChatwithNpc amp amp !ledgeChecker.isGrabbingLedge) isMoving true playerRigidbody.AddForce(moveDirection moveSpeed multiplier Time.deltaTime) if (playerOnGround) playerRigidbody.velocity Vector3.Lerp(playerRigidbody.velocity, moveDirection playerRigidbody.velocity.magnitude, Time.deltaTime 0.5f) if (!isRunning) playerRigidbody.velocity Vector3.ClampMagnitude(moveDirection playerRigidbody.velocity.magnitude, 12f) if (isRunning) playerRigidbody.velocity Vector3.ClampMagnitude(moveDirection playerRigidbody.velocity.magnitude, 18f) if(!isMoving amp amp playerOnGround) playerRigidbody.velocity Vector3.Lerp(playerRigidbody.velocity, Vector3.zero, 0.2f) private void CalculateForward() if (!playerOnGround) forward transform.forward return forward Vector3.Cross(transform.right, touch.normal)


On key press, spawn a collider where my player is facing? I'm trying to create an attack mechanic to my player hero in my 2D Tower Defense game. When I press the Q button I want my hero to do an animation and spawn a temporary collider shaped as a cone at where the hero is looking at. If this collider collides with a GameObject called "Stone" it will decrease its hpValue with a script I made. If there is multiple Stones in the cone I want it to only effect one Stone, chosen either by random or and closest to the hero. How would I go about doing this and how can I detect the direction of where my hero is facing? This is my movement script public float speed Movementspeed Rigidbody2D rbody void Start () rbody GetComponentInChildren lt Rigidbody2D gt () rbody.freezeRotation true void FixedUpdate () Vector2 movement vector new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")) rbody.MovePosition (rbody.position movement vector speed Time.deltaTime) A picture visualising what I mean


Map video texture to a half sphere in Unity I'm new to unity3D. and am trying to play a 360 degree video. But instead of mapping the whole 360 degree (equirectangular) video to the whole sphere, I need to map the half video to a half sphere object. How can I do that? So basically we'll have two half sphere, tied together, each playing the half of 360 degree video, as if a single video is mapped to a whole sphere. An example or tutorial for a beginner would be great. e.g. So the top half of this 360 video should be textured on such mesh UPDATE No worries...we not cropping the video on the go! It is already cropped as two separate videos)


Customizing Unity WebGL index.html Hey everyone just some css and styling tips needed! i want to use a game as a 404 page. so i would need on top to be either text or a contact form then some spacing and then the actual game window. iframes dont work that good on mobile devices and by doing a simple div in unity index although on mobile it works rather crude but nice, on desktop the text is going behind the unity game window. any tips please? Note that im adding the style in the index.html and not using the separate css file in the template folder. So to sum up how can i make another div centered in the page and well responsive for mobile above the game container and add a margin on the bottom of that div! Thank you!!


Make platformer character stay in the air at the top of a jump I have a player who can jump. I want the character to stay in its position and not fall to the floor. This is the code I am using so far private void FixedUpdate() if(moveup) rigid.AddForce(new Vector3(0, 1f, 0) speed, ForceMode2D.Impulse) moveup false How can I stop the character from falling?


I try to make a Unity Curved Shader with shadow Effect? I try to make a curved shader with shadow effect I got a existing curved shader in github and it has no shadow effect i try to modify it but i couldn't find any appropriate solution. The shaderor helping script link https gist.github.com g0ody 5550039 Curved.shader Shader "Platogo Curved" Properties MainTex ("Base (RGB)", 2D) "white" QOffset ("Offset", Vector) (0,0,0,0) Dist ("Distance", Float) 100.0 SubShader Tags "RenderType" "Opaque" Pass Lighting Off CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" sampler2D MainTex float4 QOffset float Dist uniform float4 MainTex ST struct v2f float4 pos SV POSITION float2 uv TEXCOORD0 v2f vert (appdata base v) v2f o float4 vPos mul (UNITY MATRIX MV, v.vertex) float zOff vPos.z Dist vPos QOffset zOff zOff o.pos mul (UNITY MATRIX P, vPos) o.uv TRANSFORM TEX(v.texcoord, MainTex) return o half4 frag (v2f i) COLOR return tex2D( MainTex, i.uv) ENDCG FallBack "Mobil Unlit" CurvedAlpha.shader Shader "Platogo CurvedAlpha" Properties MainTex ("Base (RGB)", 2D) "white" QOffset ("Offset", Vector) (0,0,0,0) Dist ("Distance", Float) 100.0 Alpha ("Alpha", Range(0.0,1.0)) 1.0 SubShader Tags "Queue" "Transparent" "IgnoreProjector" "True" "RenderType" "Transparent" LOD 100 ZWrite On Blend SrcAlpha OneMinusSrcAlpha Pass Lighting Off CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" sampler2D MainTex float4 QOffset float Dist float Alpha uniform float4 MainTex ST struct v2f float4 pos SV POSITION float2 uv TEXCOORD0 v2f vert (appdata base v) v2f o float4 vPos mul (UNITY MATRIX MV, v.vertex) float zOff vPos.z Dist vPos QOffset zOff zOff o.pos mul (UNITY MATRIX P, vPos) o.uv TRANSFORM TEX(v.texcoord, MainTex) return o half4 frag (v2f i) COLOR return tex2D( MainTex, i.uv) float4(1,1,1, Alpha) ENDCG FallBack "Platogo Unlit Texture Alpha"


Unity "Convert To Entity" does not work (Render) with "Skinned Mesh Renderer" for Animations I'm trying to make a game with Unity's ECS and Job System. I came across the issue where, Convert To Entity does not support Skinned Mesh Renderer. It does not render the mesh. I need it for animations. On the bright side, Game Object Entity does render Skinned Mesh Renderer. The downside is that, it does not support Physics Shape and Physics Body. Convert To Entity does. I am using Physics Shape and Physics Body for physics. Would anyone mind telling me what options are open to me?


Unity Custom aspect ratio in build I have made a game that was supposed to be for mobile but now I need to build it for PC. I want the aspect ratio to be 2 3 but as you can see on the image that doesn't exist. How do I add a custom aspect ratio for the build?


GUI Layering (Enemy health bars appear above Inventory) I have set up an enemy prefab that gets instantiated during Start. Each enemy object has a health bar GUI object attached to a Canvas which is a child of these spawned enemy objects. So, when I spawn 10 enemies, 10 health bars get spawned as well. I have another GUI object for the inventory which I can open and close at the press of a button. When I open my inventory and there are enemies behind it, their health bars show on top of my inventory. I would like to layer the GUI objects such that these enemy health bars do not appear above my inventory. How do I do this? I have tried ordering them differently in the hierarchy as per someone's suggestion in a forum post, but that didn't seem to work. Again, every enemy object has its own Canvas of which the health bar is a child. The inventory GUI object is attached to a different Canvas which has no parent.


Do I have to use new keyword for unity single game object? I'm using Unity4. Do I have to use new keyword for single game object? look at the following code. 1. GameObject obj new GameObject() obj Resources.Load("Prefabs Ball", typeof(GameObject)) as GameObject 2. GameObject obj obj Resources.Load("Prefabs Ball", typeof(GameObject)) as GameObject is it the same?


How to make score counter independent of framerate I have a score counter, but I've noticed that the lower the framerate is, the slower it counts. How can I make it so it ignores the framerate? using System.Collections using UnityEngine using UnityEngine.UI public class Score MonoBehaviour private Text scoreText private static int score private static int finalScore private static bool count public static int scoreMultiplier private void Start() scoreText GetComponent lt Text gt () count false scoreMultiplier 1 public static void StartCounting() count true public static void StopCounting() count false public static void Reset() count false score 0 public static IEnumerator MultiplyBy(int scoreMultiplier) Score.scoreMultiplier scoreMultiplier yield return new WaitForSeconds(6f) Score.scoreMultiplier 1 private void Update() if (count) score scoreMultiplier Slice the score so the number doesn't get too big finalScore score 4 scoreText.text finalScore.ToString("00000") Edit Fixed by adding Time.deltaTime and putting it in FixedUpdate instead of Update private void FixedUpdate() if (count) score scorePerSecond Time.deltaTime scoreMultiplier finalScore Convert.ToInt32(score) scoreText.text finalScore.ToString("000000")


Restrict object movement inside irregular shaped container I want to restrict object movement inside an area. My object follows cursor position. I have already done that for the area border using Mathf.Champ to the translate because the borders are square shaped (got the idea from Unity Restrict movement inside a gameobject (2D)). The thing is that inside the box area there can also be other shapes (colliders) which I don't want my object to go over. I know people suggest using physic collisions, but my game needs a unit perfect positions so I can't use physics due to physics' default contact offset (the one physics use to detect collisions). Here is a short video of what I have https gfycat.com cookedsmartannelid As you can see, movement is restricted (clamped) inside the box area but I want the movement to also be restricted to not go over the black area. Is there a way to be able to do this with just clamping or do I need a raycast system or something like that?


Unity only rendering certian parts of 3d building model from certian angles So I made a couple modular building sections in blender, modular in the sense that I can insert build a floor at a time. I transferred them into Unity and then I got a rendering error that I have gotten many times before. I will put the object in the game world and then certain chunks of the building will only be visible from on direction and the other it will be completely invisible. I have been having trouble with this bug for a long time and I really would like if someone could point out what's causing this problem. I will include pictures below to help show my problem. Thanks, Nova


Stop animation playing automatically I've created an animation to animate a swinging mace. To do this I select the mace object in the scene pane, open the animation pane, and key it at a certain position at 0 00. I'm prompted to save this animation in my assets folder, which I do, as maceswing I then rotate the mace, move the slider through time and key it in a different position. I move the slider through time again, move the object to the original position and key it. There are now three things in my assets folder maceswing appears to be my animation, but I have no idea what Mace Mace 1 and Mace 2 are. (I've been mucking around trying to get this working so it's possible Mace 1 and Mace 2 are just duplicates of Mace. I still want to know what they are though) When I play my game, the mace is constantly swinging, even though I didn't apply maceswing to it. I can't stop it. People say there's some kind of tick box to stop it constantly animating but I can't find it. My mace object only has an Animator component Unticking this component doesn't stop the animation playing so I have no idea where the animation is coming from. Or what the Animator component actually does. I don't want this animation constantly playing. I only want it to play once when someone clicks a certain button var Mace Transform if(Input.GetButtonDown('Fire1')) Mace.animation.Play('maceswing') Upon clicking the 'Fire1' button, I get this error MissingComponentException There is no 'Animation' attached to the "Mace" game object, but a script is trying to access it. You probably need to add a Animation to the game object "Mace". Or your script needs to check if the component is attached before using it. There is no 'Animation' attached to the "Mace" game object, and yet I can see it swinging away constantly. Infact I can't stop it! So what's causing the animation if the game object doesn't have an 'Animation' attached to it? My maceswing animation object


Flexible and extendable system of level objectives (victory failure conditions) in Unity I'm trying to come up with a flexible system of level objectives for a Unity game. What I'd like to achieve is to have a system that on each level (scene) can accept a different set of (configurable) success failure conditions. Conditions can be repeated between levels but on every level a given type of condition should accept different parameters. For example on one level success conditions would consist of destroying all enemy units and on the other level success conditions would require destroying a specific enemy unit and escorting a friendly unit to a specific place on map. Failure conditions would for example be player death (on all levels) or not reaching a specific destination within a given time. First I've tried to approach this problem by using ScriptableObjects but abandoned this idea as it's not possible to save scene object references in a ScriptableObject. So I've come up with a kind of polymorphic system like this (pseudocode) public interface Condition bool IsFulfilled() public abstract class VictoryCondition MonoBehaviour, Condition public virtual bool IsFulfilled() public abstract class AllUnitsKilledCondition VictoryCondition public List lt Unit gt units public bool IsFulfilled() foreach (Unit unit units) if (unit.IsAlive) return false return true public abstract class FailureCondition MonoBehaviour, Condition public virtual bool IsFulfilled() public abstract class TimeOutCondition FailureCondition public float timeLeft void Update() timeLeft Time.deltaTime public bool IsFulfilled() return timeLeft lt 0 The idea here is to have a level manager that is given a set of victory failure conditions in the editor and have it continuously monitor all those conditions. In a simplest scenario a level is won if all victory conditions are fulfilled and lost if any failure condition is fulfilled. Unfortunately, I'm not sure how to create a LevelManager component that would expose those lists letting me add various conditions and configure them (for example letting me add a list of units from scene to AllUnitsDestroyedCondition). I think it would be doable with a set of custom property drawers for each type of condition but I'm wary of digging into this until I'm sure there is no other, easier way. I've come up with a way of adding various conditions by adding multiple condition components to a GameObject and then dragging those components to victory failure conditions lists in LevelManager. But this solution seems awkward and inflexible because it's not possible to dynamically add and configure new conditions in runtime and creating more complex conditions (for example some condition activating only after some other condition is fulfilled) seems like a sure way to create a huge pile of unmaintainable condition component mess. Please, let me know if I'm approaching this problem correctly and if not, what are other, simpler, more flexible solutions.


How to make an object destructible? I have some 3d models that I have downloaded from Unity asset store. Most of the time, these objects are not "separatable" so I can't apply a destructible effect. Is there a way to separate a model into small pieces, whether by using Blender, or a Unity script, or something else?


Unity Event Register Deregister and Scene Unload From what I understand in C , normally when you register an event, it maintains a reference to the object of the containing method, so in order for garbage collection to pick up an object, you need to first deregister it. My question In unity when one scene is loaded and another is unloaded, do I need to first clean up and deregister any registered events, or does the scene unload process destroy objects and remaining references?


A.I. dependencies based on components I'm working on a turn based game in Unity. I need to perform field grid analysis(2D grid) when i'm iterating trough each unit "entity". The A.I. should be able to plan ahead and therefor needs to consider the components each unit have. Not every unit will have the same ability. These abilities are defined as components. I want to make it flexible in the sense that I can plug in new abilities and my A.I. will take it into consideration. While user control is somewhat implemented, A.I. hasn't even been written. So I'm open to any suggestion. Q What is a way for the A.I. system to collect all abilities of one unit and make decisions depending on each component? edit I know there is the "null" checking method to see if the gameobject contains a component. But this is highly inflexible because you are hard coding a stack of if else. Something I want to prevent.


What's the scope of RPCs in unity? I can define several RPCs in unity and I can call them via the networkView component. But it seems that it gets the RPC called regardless where it is defined. So I was wondering to know how do the scope of RPC works in Unity. Am I able to call whatever RPC in whatever script which share the same networkView? Or is there any other logic behind? As a corollary can I define a unique structured file gathering every RPC in my project?


Impossible rooms in 3D games recently I was playing The Stanley Parable, and noticed that there are several impossible spaces in the game in this example, a pair of pillars in the middle of the room, which from each side appear to open onto a long corridor between them, which would have to cut the room in two if it were present in the same space. I hadn't seen this in a game since the Marathon Trilogy. The marathon games used a 2.5d engine that due to a quirk in its programming allowed for non Euclidean geometry. I was not aware it was even possible with fully 3D engines until I played The Stanley Parable. How does it work? how would I do that in Unity 5?


How is actual object size in a scene calculated? I've got stuck with 'pixel per unit' parameters and object scale. I've created two different sprites. A background picture, 1000x1000 pixels, and another one for a 'player', 200x200 pixels. I've added two empty game objects, with default transform, so positions are (0 0 0) and scale is (1 1 1). I added a sprite renderer to both of them, and assigned the required sprites. Both sprites have 1 pixel per unit. And the 'player' in the scene looks much more bigger than the background. I expect that if ppu 1, then the background would have a size of 1000 units, a player 200 units and it would be 5 times smaller. What am I doing or understanding wrong? What is an actual object size?


How to Get VR Controller's Velocity in Unity with SteamVR? Back when I used Unity 2017 and controller bindings weren't a thing, I simply attached a rigidbody to my Vive controller and read out the velocity of the rigidbody to know how fast the player was swinging the controller. Now, I've updated to Unity 2021.2.0a14, I went through all the effort of modifying my code to work with bindings, and it doesn't seem like I can get velocity anymore. The rigidbody always reports zero velocity. I can see the World Center of Mass vector changing so I know it registers motion, but it's just not reporting the velocity anymore. Is there a new setting in Unity I need to turn on to measure things that it doesn't personally control? Or do the new bindings options have a way to get velocity as an input? Am I forced to calculate it myself now? Thanks! Edit Base assumption was wrong, I did not get velocity from the rigidbody attached to the hand controller like I thought I did. I got it directly from SteamVR Controller. So Unity is probably acting like it ever did.


How can I prevent clicks from going through a GUI.Box? I have a GUI.Box that I slide in from the side of the screen. How can I prevent mouse interaction from going to any objects under it (another GUI.Button for instance, or for that matter an GameObject)?


Using a Compute Shader in Unity to convert a texture to a float array I have a fairly simple requirement for a compute shader (DirectCompute through Unity). I have a 128x128 texture and I'd like to turn the red channel of that texture into a 1d array of floats. I need to do this very often so just doing a cpu side for loop over each texel won't cut it. Initialization m outputBuffer new ComputeBuffer(m renderTexture.width m renderTexture.height, sizeof(float)) m kernelIndex m computeShader.FindKernel("CSMain") Here is the C method lt summary gt This method converts the red channel of the given RenderTexture to a one dimensional array of floats of size width height. lt summary gt private float ConvertToFloatArray(RenderTexture renderTexture) m computeShader.SetTexture(m kernelIndex, INPUT TEXTURE, renderTexture) float result new float renderTexture.width renderTexture.height m outputBuffer.SetData(result) m computeShader.SetBuffer(m kernelIndex, OUTPUT BUFFER, m outputBuffer) m computeShader.Dispatch(m kernelIndex, renderTexture.width 8, renderTexture.height 8, 1) m outputBuffer.GetData(result) return result and the entire compute shader Each kernel tells which function to compile you can have many kernels pragma kernel CSMain Create a RenderTexture with enableRandomWrite flag and set it with cs.SetTexture Texture2D lt float4 gt InputTexture RWBuffer lt float gt OutputBuffer numthreads(8, 8, 1) void CSMain(uint3 id SV DispatchThreadID) OutputBuffer id.x id.y InputTexture id.xy .r the C method returns an array of the expected size, and it usually sort of corresponds to what I expect. However, even if my input texture is uniformly red, there'll still be some zeroes.


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?


why child class can access object while parent can't I have Block class which is the parent and StandardBlock the child , the prefab block have StandardBlock script attached to it, and according to my small knowledge in inheriting I though this would work public class Block MonoBehaviour HUD HUDscript Start is called before the first frame update void Start() HUDscript GameObject.FindWithTag("Canvas").GetComponent lt HUD gt () public void OnCollisionEnter2D(Collision2D col) HUDscript.addPoints() Destroy(gameObject) and child class public class StandardBlock Block some code but this is the error that i got NullReferenceException Object reference not set to an instance of an object Block.OnCollisionEnter2D (UnityEngine.Collision2D col) (at Assets Scripts Gameplay Block.cs 24) while writing OnCollisionEnter2D in the child class worked fine


Rotating game object without using localEulerAngles I'm building a player controller. While aiming, the player can rotate the chest bone. This looks as if the character aims in different directions. The chest bone should only be allowed to rotate within a certain range. If this range is exceeded (either to the left or to the right), the chest bone should stay at its current rotation, and the player should be rotated instead. I'm having problems applying the desired rotation to the parent game object instead. I'm trying to work with the localEulerAngles in order to applying an additional Y rotation to the gameobject, but the Y rotation value tells me for example "359.9" while I expected to work with a value of 0. private void pHandle LateUpdate Aim() Quaternion oldNeckRotation Neck.transform.rotation Fade old input before capturing new, so we don't dull the freshest data. float yawBlend Mathf.Pow(1.0f Aim yawInputFalloff, referenceFramerate Time.deltaTime) A Lerp toward zero is just the same as a multiplication by the blend factor. Chest yawRate yawBlend Accelerate by mouse movement over the past frame. (May need adjustment for display resolution). Chest yawRate Input.GetAxis("Mouse X") float yawDelta Chest yawSpeed Chest yawRate Time.deltaTime float offCenterYaw Chest currentYaw Chest yawCenter float fDesiredChestYaw Chest currentYaw yawDelta float fHeroRotation 0f if (fDesiredChestYaw gt Chest rotateRange) the allowed chest rotate range would be exceeded. Instead, move the gameobject the parent. fHeroRotation (fDesiredChestYaw Chest rotateRange) fHeroRotation this.transform.localEulerAngles.y this.transform.Rotate(0, fHeroRotation, 0) return else if (fDesiredChestYaw lt Chest rotateRange) fHeroRotation (Chest rotateRange fDesiredChestYaw) fHeroRotation this.transform.localEulerAngles.y this.transform.Rotate(0, fHeroRotation, 0) return else If we're moving away from the center, slow down as we approach the edge. if (yawDelta offCenterYaw gt 0) float extremityYaw offCenterYaw Aim yawMaxRange yawDelta 1.0f extremityYaw extremityYaw fHeroRotation yawDelta Ensure we never overshoot the allowed range. Chest currentYaw Mathf.Clamp(Chest currentYaw yawDelta, Chest yawCenter Aim yawMaxRange, Chest yawCenter Aim yawMaxRange) Vector3 nNewChestRotation new Vector3(Chest.localEulerAngles.x, Chest currentYaw, Chest.localEulerAngles.z) Chest.localRotation Quaternion.Euler(nNewChestRotation) Quaternion newNeckRotation Neck.transform.rotation the neck should not rotate with the chest. So I first counter rotate it against the new chest rotation, then rotate it a little towards the chest rotation Neck.transform.rotation Quaternion.Lerp(oldNeckRotation, newNeckRotation, neckFollowChest)


Unity Animation makes object spawn at x0 y0 z0 I was making an animation for a coin in my game in Unity, and when I was testing the full game, I saw that the coin is spawning at x0 y0 z0 and is doing the animation there. Then I realized that it was the animation, that increases and decreases y position and y rotation, starting at 0. So, I need to make the animation, that increases and decreases position y and rotation y, without affecting the actual position, because it will be different the position of the coins each time. In a while I will upload a screenshot for describing better the problem. Any clue?


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


Why is my game object generated by a custom Unity editor script missing its sprite? I have a number of sprites that I generate outside of Unity. I'd like to automate the process of importing these sprites into Unity as fully configured game objects. I'm trying to do this through a Unity editor script, but I'm having some difficulty. When I run my script, my game object is saved as a .prefab as expected. However, the Sprite I'm assigning to my game object's SpriteRenderer component is missing In my script, I'm assigning my SpriteRenderer's sprite property to a Sprite object that I dynamically create in the script. Here's the relevant excerpt from my editor script GameObject gameObject new GameObject(fileName) SpriteRenderer spriteRenderer gameObject.AddComponent lt SpriteRenderer gt () texture size will be replaced during the LoadImage() call Texture2D texture new Texture2D(1, 1) texture.LoadImage(File.ReadAllBytes(Path.Combine(generatedOutputPath, fileName ".png"))) spriteRenderer.sprite Sprite.Create( texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.0f, 0.0f) ) PrefabUtility.CreatePrefab("Assets Prefabs " fileName ".prefab", gameObject) DestroyImmediate(gameObject) I can verify through logging that the image path to my .png is correct and that the Texture2D and Sprite objects seem to be instantiated correctly. For example, I can do this logs "580" as expected Debug.Log(texture.width) What am I doing wrong? How can I save this game object as a .prefab without losing its sprite information?


"Unfortunately game has stopped" error on Android device In Unity 2018.4.3f1, I am able to build my APK successfully, but when I try to launch it on my mobile device, it shows "Unfortunately game has stopped". I don't know the problem is. Here are the project settings I'm using


how to check mouse is not over any object in unity Im working on a way to check mouse is not over any object on scene to put my object in there. i know i can use OnMouseOver function but i have to add it on all objects script. Is there any other way to check my mouse position is not on any object collider? Its a 2d project. thank you for helping


Load Material from file path or parse .mat file to Material Unity Is it possible to load a material from a file path? Or, otherwise parse a .mat file saved on disk to a Material usable at runtime? I had naively thought it would be possible to assign the bytes from a .mat file, as read by File.ReadAllBytes to a Material object, but that does not seem to work.


Missing references in built bundles The following is a copy of our post in Unity Forum (https forum.unity.com threads missing references in built bundles.1103689 ) Hello, We have a bundle for our scenes and another one to store our prefabs (actually we have around 10 bundles but let's keep it simple). In every scene we have unpacked prefab instances. We have no problem in playmode using the AssetDatabase but once we use built addressables some unpacked prefab instances in our scenes are broken. Sprites and or scripts are missing in a inconsistent way in some scenes those objects are fine and sometime they are not. This comes along multiple warning messages quot The referenced script (Unknown) on this Behaviour is missing! quot . Note that the issue also happens when we fully deploy our player. Unity version 20193.3.13 Addressables version 1.16.1 Solution 1 We tried to remove addressable prefabs (A,B,C in the diagram) from their bundle since we don't really have to instantiate them at runtime for now and it worked. Solution 2 We also tried to put scenes and prefabs into the same bundle and it worked too. Solution 3 Switch to 1.18.2 and 1.15.1 version of addressable package and it didn't work. Solution 4 Finally we tried to use the Duplicate Bundles Dependencies analyzer multiple times in order to have no more issues of this type and it didn't work. Questions 1 As far as we understand, when addressable groups are built, Unity computes all dependencies and build them inside the bundle along the orignal assets (in my diagram quot Scenes quot bundles is packed with D'). What we don't understand is why having our prefabs in a separated bundle break references link in the scenes. Our guess is that Unity doesn't know which version of those dependencies to use (the one in the scene bundle or the one in the prefab bundle) and somehow fails to load them properly. Question 2 Is splitting our content is a good approach, we did it mostly for visibility but it appears to be more a problem in the long term, what are your guidelines regarding this matter ? Question 3 Why Duplicate Bundle Dependency rule has to be processed multiple times to properly fix every issue ? We think that running this rule creates duplication issues itself but we can't really tell.. Thanks.