Unity Seamless Terrain I am programmatically generating terrain using unity's terrain object and assigning height maps to it via the terrainData, the problem is that there are seams even when using the GroupingId(which is used for auto connect). I even tried creating a terrain object in the editor with neighbours, and modified their terrain data via script, seams still there. I have also tried SetConnectivityDirty after applying terrainData. Most people who have reported this seemed(lol) to have issues with their normals at the edges, I cant see that being the issue here, but if it is, how do i approach solving it given I am using unity terrains. If there is no good answer I will have to resort to custom meshes and lose all the nice terrain tool functionality. Edit Here is how I'm setting heights. var terrain GameObject.Find("test").GetComponent lt Terrain gt () var terrainData terrain.terrainData var noiseMap Tool Generators.GenerateNoiseMap(chunkSize, seed, scale, octaves, persistance, lacunarity, 0f, 0f) terrainData.SetHeights(0, 0, noiseMap) Then the actual noise generation is just a 2D array of heights, i have been using a simplified version with only 1 pass for testing. public static float , GenerateNoiseMap(int chunkSize, int seed, float scale, int octaves, float persistance, float lacunarity, float offsetX, float offsetY) float , noiseMap new float chunkSize, chunkSize for (int y 0 y lt chunkSize y ) for (int x 0 x lt chunkSize x ) float noiseHeight 0 float sampleX (x offsetX) scale float sampleY (y offsetY) scale noiseHeight Mathf.PerlinNoise(sampleX, sampleY) noiseMap y, x noiseHeight return noiseMap


Health zone heals player but I have a problem Hello I am creating a special health zone that gives the player health and my current scripts health is going up super fast and I want it to go up by 2 hp per second. How would I do this? Here is the health zone script. public PlayerHealth playerHealth public float healthGain 2f void OnTriggerStay2D(Collider2D other) if (playerHealth.currentHealth lt playerHealth.maxHealth) playerHealth.currentHealth (int)healthGain playerHealth.healthBar.SetHealth(playerHealth.currentHealth) if (playerHealth.currentHealth gt playerHealth.maxHealth) playerHealth.currentHealth playerHealth.maxHealth playerHealth.healthBar.SetHealth(playerHealth.currentHealth)


pragma target 3.0 or 3.5? What is gained. What is lost for compatibility with older systems I've just designed an image based layering system shader. Multiple textures with Alphas overlay to create a fully dressed character, using 1 material. pragma target 3.0 is where I had started (suggested default in UnityProjects). After creating so many transparent overlay layers in my code, I got this Shader error in 'Custom Test' Too many texture interpolators would be used for ForwardBase pass (12 out of max 10) The fix seems to be to upgrade to pragma target 3.5 My game is going to be a Steam distributed game, PC only. What do I lose by using pragma target 3.5? Will only super dvanced PCs be compatible? Or should a fairly good average PC be able to run this? I don't know the intricacies of this subject.


How can I make a health bar a UI element part of a character prefab? Description I want my character prefabs to come with their own health bar, but I can't simply add one as part of the prefab, because it's a UI element and therefore goes into a Canvas. Potential Solution I could write a script that takes in a separate health bar prefab and instantiates it when the character prefab's instantiated, but it's one extra script. Is there a more conventional way to do this? I'd think this is a common problem.


Entity Interpolation (Lost Packets?) I'm working on a networked game for a while. I'm aware of client side prediction and lag compensation (shooting) but I'm not sure about entity interpolation client side. I'm sending update sync packets at 10fps from server and client interpolates from current position to newly received position. Interpolation takes 100ms (because of 10fps) to reach target position but what if new position arrives late or 2 3 packets drop? There will be no target position and sync'd (client side) entity will be idle until new position packet but entity continuously moving forward server side. Basically, I don't know what to do in this situation.


Unity Smoothing between two floats which are continuously changing I'm looking for some help with smoothing between an original float and a target float, where the original float is consistently changing (potentially interfering with interpolation techniques and or Mathf.SmoothDamp) I tried Mathf.SmoothDamp with the below (float rocketBoostPower is a global variable) float yVelocity 0.0F float tempForce rocketBoostPower Input.GetAxis("Mouse Y") shiftSpeed 5f rocketBoostPower Mathf.SmoothDamp(rocketBoostPower , tempForce, ref yVelocity, 0.5f) This doesn't change the force at all however, it just stays locked in place. I'm currently using the below to change my power, however I want to smoothly change the power instead of just incrementing sharply on each Update frame rocketBoostPower Input.GetAxis("Mouse Y") shiftSpeed 5f Please can someone help? I need the assumption that every update will receive a new rocketBoostPower value, whilst still smoothing its previous value.


How can I speed up Unity3D Substance texture generation? I'm working on an iOS Android project in Unity3D. We're seeing some incredibly long times for generating substances between testing runs. We can run the game, but once we shut down the playback, Unity begins to re import all off the substances built using Substance Designer. As we've got a lot of these in our game, it's starting to lead to 5 minute delays between testing runs just to test a small change. Any suggestions or parameters we should check that could possibly prevent Unity from needing to regenerate these substances every time? Shouldn't it be caching these things somewhere?


Why is there a difference in frame rate between my fps calculation and Unity's calculation So I wrote my own script for calculating framerate but it consistently comes out with a different value than Unitys idea of current framerate. This is my implementation void UpdateFPSStats() double frameTime new double() frameTime Time.deltaTime m times frameIndex frameTime frameIndex if (frameIndex m numberFrames) frameIndex 0 int numberSamples 0 double averageFrameTime 0.0f foreach(double t in m times) numberSamples averageFrameTime t if (numberSamples gt 0) averageFrameTime averageFrameTime numberSamples m frameRate 1 averageFrameTime where m frames is a list of the last 60 frames frame times and UpdateFPSStats is called in Unitys Update(dt) function. On average in my scene my fps calculation gives a steady 50fps, while Unity calculates a steady 80fps. Which is right and why?


Enemy clones don't target player In a small game that I'm making enemies multiply when you kill them, however when clones are instantiated they don't chase the player like the original prefabs do (example http gfycat.com VastActualElver) Here is relevant part of my code pragma strict var moveSpeed int 3 var player Transform var MaxDist 10 var MinDist 1 function Update () if(curhealth lt 0) Dead() transform.LookAt(player) if(Vector3.Distance(transform.position, player.position) gt MinDist) transform.position transform.forward moveSpeed Time.deltaTime function Dead () Destroy(gameObject) var posx Random.Range( 10, 10) var posz Random.Range( 10, 10) Instantiate(enemys, Vector3(posx, 0.5, posz), transform.rotation) What am I missing?


Admob is load failing by No Fill error I m using official admin plugin for Unity implementing Reward video. But it s only working for test unit id, when I replacing it to my own unit id, it just failing load by error No Fill . Even when I add test device, still happening the issue. How can I fix this?


How do I draw lines to a custom inspector? I have a custom editor to which I want to be able to draw a basic line graph. I have much of the functionality down, but I have only been able to test as much via the debug. I am yet to figure out how to draw the actual lines to the inspector. How do I draw lines to a custom inspector? I have found plenty of online resources, in regards to custom drawing to the editor. However, everything I find pertains specifically to drawing in the scene view nothing seems to work inside of an actual inspector. The two general methods I have found involve using Handles.DrawLine and the GL library. Neither appear to work however, I have only been able to test functionality with blind coordinates, so far. I can not find anything in regards to actually determining the local coordinates of the area on the inspector where I wish to draw. Perhaps I need to start with an initial "origin" position, Perhaps I need to start with a local area defined by a Rect. I simply don't know. It has also been a while since I had to use OpenGL, directly. It is entirely possible I am simply doing it wrong, to begin with. Here is my current graph method private void DrawVelocityGraph(float velocityValues, float minimumVelocity, float maximumVelocity) float velocityValue velocityValues 0 float increment 0 Vector3 lineStart Vector3.zero Vector3 lineEnd new Vector3(horizontalIncrement, velocityValue verticalIncrement) GL.Begin(GL.LINES) for(int i 1 i lt velocityValues.Length i ) if(velocityValue velocityValues i amp amp (velocityValue minimumVelocity velocityValue maximumVelocity)) Handles.color VelocityGrapherColours.outOfRangeColour else velocityValue velocityValues i Handles.color VelocityGrapherColours.lineColour lineStart lineEnd lineEnd.x increment lineEnd.y velocityValue verticalIncrement GL.Vertex(lineStart) GL.Vertex(lineEnd) GL.End()


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.


Why do I have to set my Unity app to full screen manually on my phone When I open my unity app it doesn't go full screen until I change it in the settings, isn't there a way to do that... it actually isn't a scaling problem or an aspect ratio.... Because you can see how in the phone settings it is turned off Thanks in advance


How to generate mesh at runtime using raycast points? I'm trying to make a clone of the trail line renderer with the difference that everything is perfectly flat, i.e. the faces are not designed to face the camera. I'm using two raycasts to get the position of the edges of where I want those faces but now I'm struggling to generate the mesh...I've gone through the mesh docs but I don't really understand it. Could someone help me do this? Here is my code so far public Transform probes public float probeDistance public Vector3 newVertices public Vector2 newUV public int newTriangles void Update () Generating the mesh Mesh mesh new Mesh() GetComponent lt MeshFilter gt ().mesh mesh mesh.vertices newVertices mesh.uv newUV mesh.triangles newTriangles Defining the rays Ray l ray new Ray(probes 0 .position, probes 0 .forward probeDistance) Ray r ray new Ray(probes 1 .position, probes 1 .forward probeDistance) RaycastHit l hit RaycastHit r hit Debug.DrawRay(probes 0 .position, probes 0 .forward probeDistance, Color.blue) Debug.DrawRay(probes 1 .position, probes 1 .forward probeDistance, Color.red) Getting the position of the left ray point if(Physics.Raycast(l ray, out l hit)) print (l hit.point) Getting the position of the right ray point if(Physics.Raycast(r ray, out r hit)) print (r hit.point)


How to use NGUI with Unity I feel like Im missing something really simple, but Ive read about all the events NGUI can generate from an object and just dont get where to recive (or handle) the event. Do I just attach it to a script on the object?


Can I Debug.Log() on Android without all the callstack spam? I get this I Unity ( 1908) Serialized file length 754 bytes. I Unity ( 1908) UnityEngine.Debug Internal Log(Int32, String, Object) I Unity ( 1908) UnityEngine.Debug Log(Object) I Unity ( 1908) SerializeTest Test() (at Z Pong Devel2010 Src UnityGames BhvrDemo BinarySerialization Assets Script SerializeTest.cs 64) I Unity ( 1908) UnityEngine.Events.InvokableCall Invoke(Object ) I Unity ( 1908) UnityEngine.Events.InvokableCallList Invoke(Object ) I Unity ( 1908) UnityEngine.Events.UnityEventBase Invoke(Object ) I Unity ( 1908) UnityEngine.Events.UnityEvent Invoke() I Unity ( 1908) UnityEngine.UI.Button Press() (at C BuildAgent work d63dfc6385190b60 Extensions guisystem guisystem UI Core Button.cs 36) I Unity ( 1908) UnityEngine.UI.Button OnPointerClick(PointerEventData) (at C BuildAgent work d63dfc6385190b60 Extensions guisystem guisystem UI Core Button.cs 45) I Unity ( 1908) UnityEngine.EventSystems.ExecuteEvents Execute(IPointerClickHandler, BaseEventData) (at C BuildAgent work d63dfc6385190b60 Extensions guisystem guisystem EventSystem ExecuteEvents.cs 52) I Unity ( 1908) UnityEngine.EventSystems.ExecuteEvents Execute(GameObject, BaseEventData, EventFunction 1) (at C BuildAgent work d63dfc6385190b6 but I would like this I Unity ( 1908) Serialized file length 754 bytes.


Detecting a mouse click While in a Trigger Why does the following code not working? (weird, sometimes it works sometimes not ) I want to move player by touching on the screen and change the color of gameObject when detect trigger and release mouse click. quot Drag and move quot script works correctly I just add following code and sometimes it works sometimes not private void OnTriggerStay2D(Collider2D colider) if (Input.GetMouseButtonUp(0) amp colider ! null) colider.gameObject.GetComponent lt SpriteRenderer gt ().material.color Color.blue There is a full script private Camera cam private Vector3 daragOfset SerializeField private float speed 4.55f private bool isEntered false void Update() if (Input.GetMouseButtonDown(0)) daragOfset transform.position GetMousePos() private void OnTriggerStay2D(Collider2D colider) if (Input.GetMouseButtonUp(0) amp colider ! null) colider.gameObject.GetComponent lt SpriteRenderer gt ().material.color Color.blue void Awake() cam Camera.main void OnMouseDrag() transform.position Vector3.MoveTowards(transform.position, GetMousePos() daragOfset, speed Time.deltaTime) Vector3 GetMousePos() var mousePos cam.ScreenToWorldPoint(Input.mousePosition) mousePos.z 0 return mousePos


In Unity, what does the camera script's "Behaviour missing" error mean? I started in Unity few days ago and made a cube with a tank control style. Now I'd like to create controls similar to 3D fighting games (Gunz, Blade Symphony, ) Control body direction with the mouse and walk with WASD. However, the Camera is giving me a error called "Behaviour missing" each time I try, with all the cameras scripts I saw. I think that is a error with tagging the character movement in the camera, but I don't know how to do that. What might be the problem?


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


Pixel art sprite distortion with 1 1 pixel ratio So I've been studying the Unity's PPU, pixel density, camera settings topic to make my game pixel perfect. I've set everything in a way that my screen pixel to sprite texel ratio equals 1. The art looks very good and crisp overall on the game view... But! There are still some minor distortions and I don't know where it comes from. Take a look at this example In this example my settings are Screen 870x510 PPU 100 Camera size 2.55 Pixel snap on Sprite material on The issue happens when I move the sprite manually by 0.001 values on the Y axis. Same happens on the X axis. Any ideas what's the problem?


Unity how to put a target under a character's feet that follows ground model contours? In my current projects, one of the power ups needs to place a target marker centered on the position of the player triggering it the actual design for this is TBC, but will be a circle with a radius of 10 units. The ground for the playing arena is a model, and not flat. Assuming that I use a texture to show this target area, how can I have this texture render following the contours of the ground? Alternatively, any other approach to solving this would be appreciated. Thank!


Switch Vector 3 x,y,z Components Based on Rotation I have a cube that moves by rotating on its edge. I want my code to also work for cuboids. The following code is what I'm using to rotate my cube turnPoint transform.position new Vector3(0.5f direction x, 0.5f, 0.5f direction z) Location of edge (resets every 90 degrees) transform.RotateAround(turnPoint, axis, rotateSpeed direction) Turn around the edge It works fine, however I want to get this to work when the cube is scaled to be a cuboid. I tried multiplying the new Vector3's x, y and z components by the objects respective x, y and z scale. This works, but only for the first rotation. Is there a way this could work for all future rotations without using if else for all 4 rotations?


How to access Lit shader properties through code? Currently i'm using HDRP in my project, so i have a question. How can i access Lit shader properties through code ? Or where i can see names of variables in this shader ? For example


How to simulate car drivetrain (in Unity)? One of my hobby projects involves cars. Up until now I had a quick and dirty "one class" implementation of engine gearbox wheels, but I thought that this is ugly, and I want to go a bit more realistic. Sadly I couldn't find much on Google (either wrong search terms or there really isn't anything that is what I want). It seems like Setup in scene Four wheelcolliders attached to a big boxcollider. Things that I want in the system Separate classes for engine, clutch, gearbox, differential and wheels (and whatever else does stuff with torque). Throttlecontrol with revlimiter (works!), steering (works too!), brakes (not yet made, but also not very complex and will likely work). First thing I tried Mainly this rotates around how I tell the engine that the wheels are actually using or giving (engine braking) power to the system. so first I created all the classes each with their own updatemethod (not called directly by mainloop, but from a fixedupdate of a controllerclass). updatemethod of engine calculates engine torque from throttle, torque curve (animation curve) and engine friction. This is then used to speed up the virtual crankshaft which has its own inertia. But before speeding up the shaft, I decided to put some feedback torques on the engine torque, so if the wheels can't keep up, the engine can't speed up, or even slows down. Such a feedback torque is added for example by the gearbox, which in turn also has feedback forces from the differential and with that the wheels. The wheels calculate the torque needed to spin up to the speed of the shaft coming out of the gearbox and then it propagates all back to the engine over a few updates. Problem was, the torque feedback didn't really do engine braking, but catapulted it to several million RPM in a split second. Dividing the feedback torque by 1000 did work, but then the car didn't move at all. So this is fail number 1. Fail number 2 Okay screw this, I thought, and tidied up all the stuff. This doesn't use several updatemethod anymore, but recursive updating. Basically I call update on the engine, which in turn then calculates what torque it has available. With that it tells the transmission that it has t torques at r RPMs. The gearbox changes the values according to the current gear and then again puts the values into the differential. The differential SHOULD split the torque between its outputs. To do this I calculate how much torque the output (in this case wheels) would need to speed up to r RPMs. I do this for each output and make a list of it for each output. I also save the sum of these values. With this I can get a value of 0...1 for each output, that determines how much torque each output gets in its updatemethod. Its basically an intelligent differential that gives the output which needs more torque, more torque. I guess modeling a real differential would involve some more complex stuff. Now the torque is at the wheels and gets put into the motorTorque property of the wheelcollider. Up until here it works. If I throttle up and then let go of it the wheels start turning backwards. It's basically another feedbackloop just like with the first try. So also fail And fail 3 Instead of returning the torque that's left, I tried backpropagating the RPMs to the engine instead. So I apply torque, and get RPMs back. But again everything tries to move the car in the opposite direction that I want it to go. Here is where I'm out of ideas. I want a relatively realistic drivetrain, that is modular and can do enginebraking. A bought asset will most probably not solve my problem, and I also want to understand how it works, and not just use it. Does anybody have experience with how to properly model a drivetrain? If I forgot to mention something, please ask.


How should asset bundles be divided? The only way to load an asset from an asset bundle into memory is to load the entire thing, decompress and pull out the asset you want, then unload the entire thing, except the assets you want. This seems impractical for sharing assets between bundles. For example, if asset bundle A wants a single asset from asset bundle B, it must load all of B, pull out the asset, then destroy B. The alternative to this is to extract the shared assets and create a new bundle call asset bundle C. The problem with this is that B must have been designed this way before being built, which it won't be if it was built before A (it has to be since A depends on B). Using the resources folder results in a huge blob of bytes that, from what I understand, cannot be changed after build, and is certainly not differ able for patches. Putting the pros of asset bundles and the resource folder together, I figure that having an asset bundle for every asset is the best of both worlds. Is there problems with this? Is my understanding of asset bundles or the resource folder flawed?


Asset opening wrong unity version I'm trying to open one of my assets in unity via my browser, but when I click open in unity it opens the 2017 version, when I want to add it to my newest one. How do i get this to work? (I need the 2017 version, so deleting it is not an option.)


Making only one side of a object receive light in Unity So I want to achieve a visial asthetic in my game that looks like this Meaning I dont want the outer parts of my dungeon walls to be affected by light. Now I know this is posible if the object itslef is created with 2 materials that way I can make the back material solid black. But I was wondering if there is a easy way to achieve this with a shader.


Unity Record real time game play in high quality using offline rendering? I'm looking to record Unity gameplay at really high quality (360 Stereo 8k 120 fps). I can't do this in real time due to the GPU resources required so I need to do offline rendering (frame perfect rendering). The problem is offline rendering by its nature doesn't accept user input, so I can't record live gameplay footage. I'm looking for a solution that lets me record live gameplay and then render it out at this higher quality. I considered recording the user input or the gameobjects properties and then playing them back while rendering the footage. I tried a number of assets like Ultimate Replay 2.0, Record and Play, GameObject Recorder, even tried Unity Recorder to an animation but none of them record all of the changes to components on a gameobject. I think I'll have to write my own code, although I'm not sure what the best method would be, I'm reluctant to sink to much development time into this if there's an easier solution that I've overlooked? Initially I'm looking for a solution that works inside the Unity editor but would love to be able to give this ability to end users.


Unity3d Delay between animation cycles trying to create simple 360 rotation animation on 2d object but can't understand delay between animation cycles, please check youtube video with issue https www.youtube.com watch?v JlLJLHvnkgo


how to prevent stretched vertical shadow in blob shadow which projected by Projector of Unity I feel it's a ridiculous because projector's rotation of X is 90. the projector is a orthographic. how can i prevent that long stretch shadow in vertical side of a platform?


How can I launch Visual Studio via a double click on a C script in Unity? This is my first time using Unity and I am following the tutorial for the 2D RogueLike Game. Everythings seems to be working properly, apart that I cant get Visual Studio to launch, if I'm double click my c scripts. What I have tried so far Checked my preferences, that External Script Editor says "Visual Studio 2017" Reinstalled Unity and Visual Studio. Unity Version 2019.3.0a2 Personal Hope somebody can help me. Additional information After double click, nothing seems to be happening, even my mouse doesnt show a load icon When I create a new project, the bug (dont know if bug, or my fault) is still there. I can open the .sln file from my project in Visual Studio. Visual Studio can even autocomplete unity based code then, before it was a "miscellaneous file" and didnt autocomplete code like for example "Transform" or "Rigidbody2D".


What's a simple way to send statistics from my game back to me? For example, I set up my game to keep track of how many times people play x, y, and z game modes, and also to keep track of how often players reach a certain point. What's a simple way to send this data to me so that I can see it?


Camera Movement Snap Camera back to origin in relation to the player object I am trying to implement camera movement like it is done in Guild Wars 2. Scenario is when A and D keys are pressed, the player rotates right left and the camera follows and stays behind the character player like this (Starts at 23 seconds) https www.youtube.com watch?v XkHJ2uSrLjE I can get the basic working fine, and I did it this way private void KeysRotateCameraAndPlayer() float keysOrbitingSpeed 120 this.player GameObject.FindWithTag("Player").transform if (Input.GetKey(KeyCode.A)) Debug.Log("Rotate Left") CenterPoint.eulerAngles new Vector3(0, 360 Time.deltaTime keysOrbitingSpeed, 0) player.eulerAngles new Vector3(0, 360 Time.deltaTime keysOrbitingSpeed, 0) else if (Input.GetKey(KeyCode.D)) Debug.Log("Rotate Right") CenterPoint.eulerAngles new Vector3(0, 360 Time.deltaTime keysOrbitingSpeed, 0) player.eulerAngles new Vector3(0, 360 Time.deltaTime keysOrbitingSpeed, 0) Now the next part I am trying to achieve , when the camera is rotated orbited around the player using the mouse and is left in a position that is not the origin i.e behind the player (in relation to player) when A and D keys are pressed, what happens in GW2 is the camera seems to snap back to the origin and then continue to follow the player from the back ( or its relation origin with regards to the player Object if that makes sense) This is what the game does (which I hope to achieve) https www.youtube.com watch?v qTTDaeuHl80 so at present moment with my current code https www.youtube.com watch?v a53lZ 0BDtg camera and player will continue to rotate (with A and D), from where the camera was last left during orbit. How can I add to this, to force the camera to snap back to origin like they have in Guild Wars 2?


unity3d Fire bullet using AddForce is very slow This is a top down view but in 3D coordinates, I would like to instantiate and fire a bullet from the player's gun. This script is on a spawner object at the end of the barrel. void Fire () float speed 80 GameObject projectile Instantiate (bullet, transform.position, transform.rotation) as GameObject projectile.GetComponent lt Rigidbody gt ().AddForce(transform.forward speed) coolDown Time.time I also tried this but in this case the bullet always moves in a fixed direction (North) projectile.GetComponent lt Rigidbody gt ().velocity Vector3.forward speed Bullet is an empty object and the actual bullet is it's child ( did that to overcome a rotation issue ), the problem is nomatter how high I turn up the speed the bullet travels very very slow. Both the parent and the bullet have Rigidbody.


Unity build shows wrong date I made a 3D game in Unity named Sniper Shot. I am facing a problem when I build the project at the end it shows the wrong date of build. I have tried many scripts resolving this issue but I did not find any accurate way to fix it. I completed this project on 4 march 2019 but this is showing me a wrong date, 23 July 2017.


How to use TensorFlow in Unity I am trying to implement a deep reinforcement learning IA with TensorFlow for a checker game in Unity. How can I do this? I've searched for it on Google and found a lot of videos and tutorials on how to use machine learning agents with Unity, and other people who explain how to import a TensorFlow trained neural network in Unity, but I didn't see anything related to using directly TensorFlow in Unity to create (and train) neural networks. If someone knows another package to create CNNs with C , I am interested.


How to obtain a camera stream from Unity without rendering it to the player's screen? I'd like to stream the output of two cameras to a separate process. Right now, it looks like the best way to do that is to grab the rendered camera views from the screen via platform specific screen capture hooks then compress them real time with h.264. Is there a way to grab the input of the cameras within unity and avoid rendering them to the screen? One solution I'm considering involves using Unity's multiplayer capability to run the game on a separate machine and grab it from that screen buffer, unbeknownst to the player.


Why does this code not update my object's position? I am trying to move the object in my frame in Time.deltaTime. I have not taken care the speed yet but the problem is, the object is almost at position (0,0) after I have multiplied the x amp y axis with Time.deltaTime. I want it to appear randomly on the screen in a given range. The update function is given below function Update () var x Random.Range( 4.37,4.34) Time.deltaTime var y Random.Range(4.45, 4.66) Time.deltaTime var velocity Vector3(x, y, 0) transform.position velocity


In Unity, How to format Old RPCs into new "PunRPCs" In older unity versions you could simply used RPC. With newer verisons of Unity my code now doesn't work and it says that it needs to be transformed into "PunRPC" , Pun being "Photon Unity Networking." I am not sure how to reformat it to work with current unity versions. Can anyone shed light on this? My Code FXManager.cs 1 using UnityEngine 2 using System.Collections 3 4 public class FXManager MonoBehaviour 5 6 RPC 7 void SniperBulletFX( Vector3 startPos, Vector3 endPos ) 8 Debug.Log ("SniperBulletFX") 9 10 11 PlayerShooting.cs 1 using UnityEngine 2 using System.Collections 3 4 public class PlayerShooting MonoBehaviour 5 6 public float fireRate 0.5f 7 float cooldown 0 8 public float damage 25f 9 FXManager fxManager 10 11 void Start() 12 fxManager GameObject.FindObjectOfType lt FXManager gt () 13 14 if(fxManager null) 15 Debug.LogError("Couldn't find a FXManger.") 16 17 18 19 20 Update is called once per frame 21 void Update () 22 cooldown Time.deltaTime 23 24 if (Input.GetButton ("Fire1")) 25 Player wants to shoot...so. Shoot. 26 Fire () 27 28 29 30 void Fire() 31 32 if (cooldown gt 0) 33 return 34 35 36 Debug.Log ("Firing our gun") 37 38 Ray ray new Ray (Camera.main.transform.position, Camera.main.transform.forward) 39 Transform hitTransform 40 Vector3 hitPoint 41 42 hitTransform FindClosestHitObject (ray, out hitPoint) 43 44 if (hitTransform ! null) 45 Debug.Log ("We hit " hitTransform.name) 46 47 We could do a special effect at the hit location 48 DoRicochetEffectAt (hitPoint) 49 50 Health h hitTransform.GetComponent lt Health gt () 51 52 while (h null amp amp hitTransform.parent) 53 hitTransform hitTransform.parent 54 h hitTransform.GetComponent lt Health gt () 55 56 57 Once we reach here, hitTransform may not be the hitTransform we started with! 58 59 if (h ! null) 60 This next line is the equivalent of calling 61 h.takeDamage( damage) 62 Except more "networky" 63 PhotonView pv h.GetComponent lt PhotonView gt () 64 if (pv null) 65 Debug.LogError ("Freak out!") 66 else 67 h.GetComponent lt PhotonView gt ().RPC ("TakeDamage", PhotonTargets.AllBuffered, damage) 68 69 70 71 if (fxManager ! null) 72 fxManager.GetComponent lt PhotonView gt ().RPC ("SniperBulletFx", PhotonTargets.All, Camera.main.transform.position, hitPoint) 73 74 75 else 76 We didn't hit anything (except empty space), but let's do a visual FX anyway 77 if (fxManager ! null) 78 hitPoint Camera.main.transform.position (Camera.main.transform.forward 100f) 79 fxManager.GetComponent lt PhotonView gt ().RPC ("SniperBulletFx", PhotonTargets.All, Camera.main.transform.position, hitPoint) 80 81 82 83 cooldown fireRate 84 If anymore information is needed, please let me know, I would love to figure out how the new "PunRPC(Photon Unity Neworking)" works so I can use it in future projects. Edit This is the error I get "PhotonView with ID 2 has no method "SniperBulletFx" marked with the PunRPC or PunRPC(JS) property! Args Vector3, Vector3 UnityEngine.Debug LogError(Object)"


Accesing child GameObjects of GameObject I have already tried really much with all "GetChildren" and similar functions, but I haven't found out how to do it yet. I have a GameObject named "koffer". I have added several other GameObjects as children to it. I have added a script to "koffer" in which I try to retrieve the children. In this script I have stated this line string sThis this.name just for testing. "sThis" becomes "koffer", so it looks perfectly fine. foreach (GameObject g in this.GetComponentsInChildren lt GameObject gt ()) doesn't retrieve anything. So obviously I'm not doing it correctly. However this doesn't retrieve anything. Is this not the correct function for such a case? Is there any built in function to retrieve theses game obects? I have found several custom made functions from some years ago, and I don't know if they are still needed or if Unity has integrated some functions for that. What really bothers me is that there are so many custom made functions that deal with "Transform" instead of "GameObject". Why would somebody need Transform instead of GameObject? Thank you.


How to properly interact with game objects in Unity3D? I am trying to make a game where player will be placed in the scene and the goal is to explore it. He can interact with game objects that player can find in the environment, like picking object, examining, dropping and putting back. Basically it is something like first person exploration... So the problem is how to properly implement code regarding interaction. One way I see and saw it on the internet is Raycasting. So the idea would be to in Update() method place Raycast fire code and see what it hits. Also all game objects with which player can interact are placed on separate Layer and also limit length of Raycast (which is obvious thing to do as player cannot interact with objects that are like 10 meters from him)... So as I understand, game objects should have at least some kind of collider (I know box and sphere colliders are simple, but sometimes I will need to use more complex one)... That being said, I wonder is this right approach Separate layer for interactable objects Raycast that checks objects in that layer Raycast length limited to like 1 meter This approach should not be that much CPU consuming or is there any other way? I am also thinking to putting some invisible box area (trigger) where raycasting would make sense, but I am not sure will this be overhead or not.... So, at the end what would be the right approach to this?


Detect collisions for each instantiated objects I want to instantiate cube at a random position when I click mouse and do something (change color or freeze position ..) for each cube when detect collision on the plane. I tried first few steps public Rigidbody cube void OnCollisionEnter(Collision collision) if (collision.gameObject.name quot Plane quot ) Do somthing for each cube cube.constraints RigidbodyConstraints.FreezePositionY void Update() Vector3 position new Vector3(Random.Range( 5f, 5f), 8,Random.Range( 5, 5)) if (Input.GetMouseButtonDown(0)) Rigidbody clone clone Instantiate(cube,position, Quaternion.identity)


A field initializer cannot reference the non static field, method, or property 'CinemachineFreeLook.Variable' engine unity coding language c I am trying to control CinemachineFreeLook maxSpeed from another script in the struct AxisStat public AxisState(float minValue, float maxValue, bool wrap, bool rangeLocked, float maxSpeed, float accelTime, float decelTime, string name, bool invert) It only accepts to type a number, but not a variable. Whenever I create a public float variable and place it in maxSpeed, it keeps sending the error error CS0236 A field initializer cannot reference the non static field, method, or property 'CinemachineFreeLook.rSpeed' Here is the default unity CinemachineFreeLook script code the added code which I declare a float variable quot rSpeed quot at the beginning and added my variable in the AxisStat maxSpeed public class CinemachineFreeLook CinemachineVirtualCameraBase public float rSpeed 300f lt summary gt Object for the camera children to look at (the aim target) lt summary gt Tooltip( quot Object for the camera children to look at (the aim target). quot ) NoSaveDuringPlay public Transform m LookAt null lt summary gt Object for the camera children wants to move with (the body target) lt summary gt Tooltip( quot Object for the camera children wants to move with (the body target). quot ) NoSaveDuringPlay public Transform m Follow null lt summary gt If enabled, this lens setting will apply to all three child rigs, otherwise the child rig lens settings will be used lt summary gt Tooltip( quot If enabled, this lens setting will apply to all three child rigs, otherwise the child rig lens settings will be used quot ) FormerlySerializedAs( quot m UseCommonLensSetting quot ) public bool m CommonLens true lt summary gt Specifies the lens properties of this Virtual Camera. This generally mirrors the Unity Camera's lens settings, and will be used to drive the Unity camera when the vcam is active lt summary gt FormerlySerializedAs( quot m LensAttributes quot ) Tooltip( quot Specifies the lens properties of this Virtual Camera. This generally mirrors the Unity Camera's lens settings, and will be used to drive the Unity camera when the vcam is active quot ) LensSettingsProperty public LensSettings m Lens LensSettings.Default lt summary gt Collection of parameters that influence how this virtual camera transitions from other virtual cameras lt summary gt public TransitionParams m Transitions lt summary gt Legacy support lt summary gt SerializeField HideInInspector FormerlySerializedAs( quot m BlendHint quot ) FormerlySerializedAs( quot m PositionBlending quot ) private BlendHint m LegacyBlendHint lt summary gt The Vertical axis. Value is 0..1. Chooses how to blend the child rigs lt summary gt Header( quot Axis Control quot ) Tooltip( quot The Vertical axis. Value is 0..1. Chooses how to blend the child rigs quot ) AxisStateProperty public AxisState m YAxis new AxisState(0, 1, false, true, 2f, 0.2f, 0.1f, quot Mouse Y quot , false) lt summary gt Controls how automatic recentering of the Y axis is accomplished lt summary gt Tooltip( quot Controls how automatic recentering of the Y axis is accomplished quot ) public AxisState.Recentering m YAxisRecentering new AxisState.Recentering(false, 1, 2) lt summary gt The Horizontal axis. Value is 180...180. This is passed on to the rigs' OrbitalTransposer component lt summary gt Tooltip( quot The Horizontal axis. Value is 180...180. This is passed on to the rigs' OrbitalTransposer component quot ) AxisStateProperty public AxisState m XAxis new AxisState( 180, 180, true, false, rSpeed, 0.1f, 0.1f, quot Mouse X quot , true)


How can I set up a 3D camera for a top down game like Enter the Gungeon? DodgeRollGames, the developers of Enter the Gungeon, tweeted that the game was in fact made in 3D They tried to explain how they set their camera in this reddit post. Basically what they said was so the walls are tilted 45 degrees toward the camera, and the floors are tilted 45 degrees away from the camera, meaning that each should experience sqrt(2) distortion because of the additional length along the z axis. However, the vertical (y axis) floor length shouldn't be perceptually changed. The camera is not tilted at all. Camera 0 degree tilt. Walls 45 degrees tilt. Floor 45 degrees tilt. My question is What do they mean by quot However, the vertical (y axis) floor length shouldn't be perceptually changed quot . If I tilt the walls and floors by 45 degrees and 45 degrees as said, the sqrt(2) distorted walls (the walls have Z depth and are perpendicular to the ground) line up nicely, but the ground gets distorted (obviously). So I distort the ground tiles by sqrt(2) but this essentially stretches the ground by 40 so every vertical movement now has to be increased by 40 . Can somebody explain what's going on? Any help would be highly appreciated.


Why do asymmetric specular highlights appear in a scene with only ambient lighting in Unity? I have a scene in Unity (2019.3.0f3 Personal) using the High Definition Render Pipeline. There are no lights in the scene, and Baked Global Illumination is disabled. The skybox is a GradientSky. By all means, the lighting in the scene should be absolutely uniform, but instead there is a gradient from one side to the other. This is what the scene looks like Though the effect is faint, you can see that the right side of the plane is slightly lighter than the left. The ground shader is HDRP TesselationLit, and by bringing the Smoothness Remapping to max I can exaggerate this effect, as shown below. This is why I am under the impression the effect is specular in nature. Interestingly, if I switch the camera to the Isometric mode, the effect disappears Finally, the effect appears to occur in world rather than camera space, as shown by the changes in lighting when I rotate my camera in increments of 90 degrees What is causing this effect, and how can I disable it?


How do I draw individual pixels in the distance? Hello everyone I am working with unity3d and I am faced with a task. I have a list of 3D points and I want to draw a pixel for every point on the list that exists after my cameras frustums far plane. After I draw each of the pixels I would like to add a few simple effects to them. Sorry for the terminology I am new to unity! Any help is much appreciated.


How can I efficiently make a solid Texture2D? I am trying to programmatically make an Image to cover the entire screen. I create the Texture2D, then create a Sprite from the Texture2D, then apply the Sprite to my Image. This works, but it is slow. I suspect the issue is that I am setting each pixel individually for my Texture2D private static Texture2D CreateSolidTexture2D(Color color) var texture new Texture2D(Screen.width, Screen.height) for (int y 0 y lt texture.height y ) for (int x 0 x lt texture.width x ) texture.SetPixel(x, y, color) texture.Apply() return texture I have tried creating the Texture2D by resizing a Texture2D of a single pixel, but the color comes out as a translucent white, instead of the color passed private static Texture2D CreateSolidTexture2D(Color color) var texture new Texture2D(1, 1) texture.SetPixel(0, 0, color) texture.Resize(Screen.width, Screen.height) texture.Apply() return texture Why doesn't my second approach work? How can I efficiently create a screen sized Texture2D of a solid color?


How can I iterate over all entities with a particular component? I'm currently designing a game engine and want to implement my own ECS implementation, so I decided to look around for ideas. Unity has recently updated their engine and seems to be pushing towards using ECS, instead of their original components are systems design. I noticed that Unity has a method called "GetEntities", a generic method which can do something like this public struct SomeComponent IEntityComponent public string Message "Hello, World!" public struct Filter SomeComponent someComponent public MovementSystem EntitySystem public override Process() How can I accomplish something like this? foreach(var entity in GetEntities lt Filter gt ()) Console.WriteLine(entity.someComponent.Message) I like this style of iterating over entities, given a filter for a specific component they need to include. But I'm not sure how to accomplish something like this. If someone could shed some light on how something like this is even possible in C that would be great!


Why does WorldToScreenPoint return "strange" results? I would like to show a menu to the right side and at the same y coordinate as a certain gameobject (shown as a green cube in the screenshot). Therefore I'm trying to get the screen coordinates of the object in my scene using WorldToScreenPoint. The code I'm using is this Vector3 nPos new Vector3(GlowCube.position.x GlowCube.localScale.x, GlowCube.position.y, GlowCube.position.z) Vector3 nOff Camera.main.WorldToScreenPoint(nPos) The resulting values however don't look right to me. I have created a red rectangle in order to demonstrate where the coordinates "nOff" would actually be in the screen At first I thought I get these strange results because the GlowCube is parented to the case, but since I use GlowCube's world coordinates (GlowCube.postion...) and not its local coordinates (GlowCube.localPosition...), I thought that this wouldn't matter. What am I forgetting here? Thank you!


UNITY Huge amount of GRAPHICS in RTS Tiled game after year of development and week of unsuccessful optimization I turn for a help from you, guys. So, my game is turn based strategy with hexagon map. One hexagon consists of one texture for hexagon tile type and seven subtiles, which carry spriterenderer with graphics like piece of town. So if soldier steps on the subtile, the graphics of subtile hide. On good machines like mine, if I zoom out maximally (45 orthographic size) on 1920x1080 and have visible around 18x16 tiles I get solid 160 200 FPS at MAX details, but on my laptop I barely get 25FPS on 1280x720 and LOW details. Each tile has resolution of 636x499. I have tried Simple shader on SpriteRenderer supporting transparency, just merging texture with color (This had those best results of 160 250FPS at HIGH END and 25FPS on LOW END) Creating separate material for each subtile and replacing SpriteRenderer with Quad mesh, so those subtiles are statically batched or GPU batched (but I guess they did not batch at all, because frame debugger showed that sometimes more fo the same pieces got rendered and then sometimes just one) So this is just the 50x50 game, when I start large map, like 120x100, it's not really that worse, so I think the problem is just in the graphics and not in the amount of objects. What are your suggestions I should try to get better performance on LOW END devices? Do you think that manual GPU instancing would make it faster? I think, there would be a lot of trouble maintaining which graphic to render and which not.


Pixel Animation is tearing in Unity I am working on a 2D game and I have created a simple sprite sheet. The sprite sheet represents a medkit. The size of the sprite sheet is 128x16 pixels with 8 different frames that animate the medkit bobbing up and down. I have imported the sprite sheet into Unity as a Sprite with Sprite Mode set to multiple, Generate Mip Maps unchecked, Filter Mode set to Point, and Format set to Truecolor. I have sliced the sprite sheet using the Unity Sprite Editor and added the animation to my scene. After doing so, I am able to see my sprite in my game. However I noticed that the animation of the sprite did not correspond to the sprite sheet. Some pixels seem to be distorted and tearing. I have searched online and couldn't find anyone with the issue I had. As you can see from the gif below, the top of the sprite is tearing. Does anyone know what is causing this issue? Gif of the issue here Sprite sheet used


Unity strange performance impact with moving objects I'm trying to find the solution for 46 hours now and I'd be really happy if someone knows it! I'm using a DOTween library for moving the objects. I also use LeanTween, cause I heard it's faster but none of these work for me in this case. I've used tweening libraries alot, but never faced an issue like this. The bug appeared in my project, so to check it I created a blank one. An empty scene, with a camera and one cube with scale 10,2,10 . Now, I've added a simple script Sequence sequence DOTween.Sequence() sequence.Insert(0f, transform.DOMove(transform.position new Vector3(10f,0f,0f),1f)).SetEase(Ease.Linear) sequence.Insert(1f, transform.DOMove(homePosition,1f)).SetEase(Ease.Linear) sequence.SetDelay(1f) sequence.SetLoops( 1) The script moves the cube continously by 10 units to the right, and back (both in 1 second). There's a noticable jitter. This jitter is strange, cause it does not happen contantly. It choses a time and just freezes the cube in place for a really tiny amount of time which is noticable when you see a smoothly moving object and it freezes for a moment. As you can see, there's a linear interpolation, but I've tried with many (it's even better visible with other interplation types). Now. The profiler is not the case, cause I've tested it on the empty project with one object on the scene. Things I've already tried Turning off occlusion culling Turning off everything I could All the combinations of quality settings LeanTween instead of DoTween The one thing I came up with is the profiler's WaitForTargetFramerate. By definition, when WFTF is huge it means that the app is doing well, cause it finished it's work and waits for the next frame. In my opinion in this case it's the reason of the bug. I have a screenshot of the profiler window (with one cube, one directional light and this script attached to a cube) Now, I'm not 100 sure, but I think that this jitter may happen on these V Sync drops on the screen. Everything is tested on the PC. On Android there's the same thing (a noticable jitter), but I didn't run the profiler. If someone has any idea what may be the cause of this I'd be grateful. I'll put a bounty here as soon as I can, cause I'm really tired! ) DMGregory This is before the 'jump' on the GPU chart and that's on the 'jump' There's no RigidBody or Collider, but on my main project there are box colliders on these floors. I've also tried adding RB with the Interpolation checked. No difference. Josh Hamilton Even if this is a normal behavior, that the frame completed faster there are games on Google Play and AppleStore without any glitches like this. In my main project (where I discovered the issue) the biggest problem is that this lag is happening when I move the camera to follow the player smoothly and the freeze it noticable like anywhere else. Like the entire enviroment was freezing for 1 3 frames.


GraphView Dragging a Blackboard causes it to get stuck offscreen I'm playing around with learning GraphView, and running into some strange problems with the Blackboard component. Here's a very simple repro using UnityEditor.Experimental.GraphView using UnityEngine.UIElements public class MyGraphView GraphView public override Blackboard GetBlackboard() var result new Blackboard(this) COMMENTED OUT BLOCK 1 var c result.capabilities result.capabilities c amp Capabilities.Movable COMMENTED OUT BLOCK 2 result.RegisterCallback lt MouseDownEvent gt (OnMouseDown) result.RegisterCallback lt MouseUpEvent gt (OnMouseUp) result.RegisterCallback lt MouseMoveEvent gt (OnMouseMove) return result public override void ReleaseBlackboard(Blackboard toRelease) toRelease.RemoveFromHierarchy() COMMENTED OUT BLOCK 3 toRelease.UnregisterCallback lt MouseDownEvent gt (OnMouseDown) toRelease.UnregisterCallback lt MouseUpEvent gt (OnMouseUp) toRelease.UnregisterCallback lt MouseMoveEvent gt (OnMouseMove) private static void OnMouseDown(MouseDownEvent e) e.StopImmediatePropagation() private static void OnMouseUp(MouseUpEvent e) e.StopImmediatePropagation() private static void OnMouseMove(MouseMoveEvent e) e.StopImmediatePropagation() using System.Collections.Generic using System.Linq using UnityEditor public class MyGraphEditor GraphViewEditorWindow protected MyGraphView view public override IEnumerable lt GraphView gt graphViews get yield return view private void OnEnable() view new MyGraphView() this.rootVisualElement.Add( view) view.style.height new StyleLength(new Length(100, LengthUnit.Percent)) MenuItem( quot Tools Graph Editor Test quot ) public static void ShowWindow() var graphViewWindow CreateInstance lt MyGraphEditor gt () var graphView graphViewWindow.graphViews.FirstOrDefault() if (graphView ! null) var blackboard graphView.GetBlackboard() graphView.AddElement(blackboard) graphViewWindow.Show() Clicking the new menu item causes the window to open, just a blank editor window with a blank Blackboard. Clicking on the title bar of the Blackboard and attempting to drag it, though, causes it to immediately disappear. Checking in the UIElements Debugger shows that this is because it's somehow gotten its World Bound Y set to 79, so it's disappeared off the top of the window. A bit of checking in the reference source suggests that if the Blackboard was not Movable, it couldn't be dragged around. Not ideal, but a temporary workaround at least. But if you uncomment the code that sets this up, (commented out block 1,) it breaks the editor entirely clicking on the Blackboard causes Unity to stop responding to mouse clicks. Attempting to minimize the damage with the other two commented out blocks has no effect. Anyone have any idea what's going wrong here and how to fix it? What do I need to do to have a Blackboard that can be dragged around properly?


How do I hide the camera object in Unity Editor I have 2019 Unity Editor I have a huge camera object that is blocking all the other objects that I need to move in the scene, I want to hide this object, but I cannot find a hide show menu item anywhere or when I right click on the hierarchy


How can I fix problems caused by "ForceMode2D.Force"? I'm making a 2D platformer with Unity. I used transform.position for movement but it caused some problems like vibration, so I decided to use AddForce.ForceMode2D.Force instead. Since this uses mass for moving the player, it makes the player either so heavy and hard to control (even when the mass is 1) or so quick and fast. I tried changing the mass and speed but I haven't found the setting that makes a smooth movement. Also, the jumping has a problem. The player will be suspended in the air for a few seconds after the jumping. I'm just looking for a way to make AddForcesmoother and solve these problems. Here's my code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.InputSystem public class PlayerController MonoBehaviour SerializeField private float jumpSpeed public float maxSpeed 5f public float maxAcceleration 50f public float maxDeceleration 100f SerializeField private LayerMask ground private PlayerActionControls playerActionControls private Rigidbody2D rb private PolygonCollider2D pol private Animator animator private Vector2 movementInput private void Awake() playerActionControls new PlayerActionControls() rb GetComponent lt Rigidbody2D gt () pol GetComponent lt PolygonCollider2D gt () animator GetComponent lt Animator gt () private void OnEnable() playerActionControls.Enable() private void OnDisable() playerActionControls.Disable() void Start() playerActionControls.Land.Jump.performed ctx gt Jump(ctx.ReadValue lt float gt ()) private void Jump(float val) if (val 1 amp amp IsGrounded()) rb.AddForce(new Vector2(0, jumpSpeed), ForceMode2D.Impulse) private bool IsGrounded() Vector2 topLeftPoint transform.position topLeftPoint.x pol.bounds.extents.x topLeftPoint.y pol.bounds.extents.y Vector2 bottomRightPoint transform.position bottomRightPoint.x pol.bounds.extents.x bottomRightPoint.y pol.bounds.extents.y return Physics2D.OverlapArea(topLeftPoint, bottomRightPoint, ground) void FixedUpdate() Vector2 movementInput playerActionControls.Land.Move.ReadValue lt Vector2 gt () movementInput Vector2.ClampMagnitude(movementInput, 1f) Vector2 desiredVelocity movementInput maxSpeed AccelerateTo(desiredVelocity) var scale transform.localScale if(scale.x rb.velocity.x lt 0) scale.x 1 transform.localScale scale void AccelerateTo(Vector2 DesiredVelocity) var deltaV desiredVelocity rb.velocity var acceleration deltaV Time.deltaTime float limit maxAcceleration if (Vector3.Dot(rb.velocity, desiredVelocity) lt 0f) limit maxDeceleration acceleration Vector2.ClampMagnitude(acceleration, limit) Vector2 force rb.mass acceleration rb.AddForce(force)


Angle between two points I have a character who walks to random points in my room in Unity. The problem is he always faces one direction, I want to write in C a piece of code that will get the direction the character is currently facing and the position of the target, then works out the angle between them to turn the character that amount. I have tried the LookAt function but that makes the character walk in an arc shape towards the target which looks very unnatural as it constantly looks at the target.


Moving large group of units 1 by 1 takes too long, how can I improve this? I use use Unity's own NavMesh AI system and I think it works pretty well. The only problem I have is that when I move large groups of units, they will find a path one by one, but it takes a really long time as you can see in the video https gfycat.com blankhalfdartfrog To set destinations I use this public bool SetDestination(Vector3 point) if (SamplePosition(point)) agent.SetDestination(point) return true return false I know I could wait until they all have pathPending false, but that would mean the entire group moves with a huge delay. Is there some way I can improve or fix this issue? Edit It is quite simple to recreate (if you have some basic knowledge on Unity NavMesh) simply create a "click to move" script that moves a List of units to where you clicked using the code above (just fill the list in Start on each unit). Put down a few obstacles and you're done.


My bullets won't bounce in Unity? I wanted bullets to bounce when they hit walls. However when colliding with a wall, they just jitter about on them. I didn't want to create a new physics material as I want to keep the ball moving at a constant speed and to have them destroy themselves after they have bounced once. Thus, I wrote everything in Code. The constraints for the bullet rigidbody's freezing position is the Y axis while the freezing rotation is X, Y, and Z axis. I also wondered if the initial position the instantiated bullet also had something to do with the speed the bullet travels GameObject bulletObject Instantiate(bulletPrefab) bulletObject.transform.position transform.position (transform.forward 1) Here's the minimum reproducible code using System.Collections using System.Collections.Generic using UnityEngine public class bulletMovement MonoBehaviour private Rigidbody bulletRB private Vector3 lastVelocity, initialVelocity public float bulletSpeed 10f private int bounceCount Start is called before the first frame update private void Start() bulletRB GetComponent lt Rigidbody gt () bounceCount 0 bulletRB.AddForce((transform.forward 1) bulletSpeed) void Update() lastVelocity bulletRB.velocity Update is called once per frame private void OnCollisionEnter(Collision col) if (col.collider.tag quot Walls quot ) bounceCount 1 if (bounceCount lt 2) Bounce(col.contacts 0 .normal) else Destroy(gameObject) private void Bounce(Vector3 normal) var speed lastVelocity.magnitude var direction Vector3.Reflect(lastVelocity.normalized, normal) Debug.Log( quot Out Direction quot direction) bulletRB.velocity direction Mathf.Max(speed, bulletSpeed) lastVelocity bulletRB.velocity is required to be in Update or else the bullet won't move at all.


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


SVG textures for 3D game objects in Unity? Is there a way to make textures using vector graphics and use it for 3d models so that textures would be object size independent and won't get blurry?


pause function for x amount of time I've read up on several ways of doing this but can't seem to find one that works for what I need. I have a method that is called and performs some logic, and then I need it to wait for a period of time, then continue with more logic in the same function. I had planned on using a coroutine which is what I did with another part of the game, but I'm running into an issue because the class doesn't directly inherit from Monobehaviour so it can't start a coroutine. I've tried Thread.sleep, but that just makes the game stop, so that isn't what I want. I don't know if there is some way to put a timer in there that will wait and then continue the function or if there is something else that I'm overlooking. Here is the current code public void AssaultRifleShot (GameObject mainBall) if (AmmoRemaining gt 0) if there is ammo remaining, set the main ball to just a normal ball so it can be destroyed on impact and then start coroutine mainBall.GetComponent lt Ball gt ().mainBall false mainBall.GetComponent lt Ball gt ().onBallHitPaddle AssaultRifleShot unsubscribe to event when mainBall is set to false. StartCoroutine(timer, coroutineHost) AmmoRemaining 1 else DestroyPickUp() There are other method calls inside the code for the coroutine, so those would end up going after whatever timer or someting goes in instead of the coroutine.


How does unity size graphics? I'm working on a 2D game. It has tiles. each tile is 50x50 px. I attached script to camera which sets the camera size to screenHeight 2 PixelsPerUnit. Now in the player, as an example i selected 480x320 size. I expected it to show approx 9x6 tiles. However it shows 6tiles horizontally and 4 tiles vertically. Similarly for other sizes, it shows lesser than calculated number of tiles. How does this corelate? Edit i created the tiles in photoshop with 300 dpi. Not sure if that affects anything though.


Footstepper with Vr Unity I have the Footstepper Complete Footstep Solution from the unity store, and i dont get it working with the Vr, I made the footstep material like official documentation said, Then i put the Footstepper Setup in the ovrPlayer object. The problem is that sometimes sound the default fallback, so i think that the colission is not detected as it suppose. Some idea ?


Unity Post process foreground, but leave background as is I am using Unity 2019.3.5f1 and I am using the Universal Render Pipeline (URP). I am trying to use the post processing in URP for the foreground only (in my case, the players), and I want the leave the background (which in my case, is just a quad with a texture), as is. I have tried using the Camera Stack but it wont work for me because the overlay camera can't have post processing effects according to the documentation. The only solution that I could come up with is create the some sort of custom render which Render the background to buffer A. Render the foreground to buffer B, and save the depth. Combine the two using a shader that gets both textures, and the depth texture, and based on the depth, takes buffer A or buffer B. The problem with this I believe is that I cant use it with the post processing for Unity. Any idea what I can do? EDIT I tried another thing in Unity which seem to not be working (might be a bug) I created 3 cameras Foreground Camera, Depth Camera (only render the foreground), and a Background Camera. I set up the Depth camera so it will render to a render texture and, indeed now I have a render texture with the proper depth I need. Now, from here everything went wrong, there seem to be odd things happening when using Unity new Post processing (the built in one) The Foreground Camera is set to Tag MainCamera, and when I enable Post Processing and add an effect, indeed we can see it. (as expected) The Background Camera is essentially a duplicate of the Foreground one, but with Tag Untagged, I use the same options (enabled Post). Now, the expected thing is we see the Background Camera with effects like Foreground, but no When using Volume Mask on my background layer, the Post processing just turns off, no effect at all no matter what (and I have set my background the Background layer). When I disable the Foreground Camera (or remove its tag) and set the Background Camera to MainCamera, still nothing changes, the post still wont work. When I set Volume Mask to Default (or everything), the result is shown ONLY in the scene view, I tried rendering the camera to a RenderTexture but still, you clearly see no effect applied!


Backface culling in Unity I am a Unity noob trying to recreate something I did a long time ago in raw OpenGL. I draw a scene normally glCullFace(GL BACK), and then draw the walls a second time with face culling flipped glCullFace(GL BACK) and a semi transparent alpha to everything. So my question is how to achieve this in Unity? Can I basically set up Unity to draw the scene twice, the second time with the new culling mode, a global alpha and perhaps only drawing meshes that are children of node with a particular tag? Or is there some better or other way to achieve this affect?


How do I create a HUD that appears to occupy 3D space can animate? I'm working with a group to try and make a first person space platformer in Unity, and was wondering if there would be anyway to create a HUD that moves and reacts to player actions, specifically looking around similar to the way the HUD moves in Metroid Prime. I'd also like it appear projected onto the inside of a helmet. I'm not entirely sure what best practice would be in this situation. Should we just attach the GUI elements to transparent objects in 3D space, then parent them to the main camera, essentially building our HUD with actual objects or is there another way that would be more efficient? I'm still very new to game development, but this is something we'd really like to have in our game if at all possible.


Is it possible to use one if statement for each level scene? I'm working on a platform game where you as a player have to collect logs, to keep on all the fires in the level. Each campfire has a timer, which ensures that every x number of seconds the animation of the fire is changed to a numb fire. The timer of a campfire is blocked by the script, when the player has received the fire at 100 . When all fires are 100 you won, if not you lose. Know I use the following if statement to check if the player has won or lose if (Application.loadedLevelName "Level 0") if (campfireAmount allCampfireFull) Do something print ("level 1 complete") Application.LoadLevel (6) if (campfireAmount allCampfireEmpty) Do something print ("level 1 failed") Application.LoadLevel ("GameOver") What I searching for is how I can make this if statement useful for each level, whiteout use for each level scene above if statement. Beside that, what I want is that after each level you get a win scene (if possible a reusable scene) and after clicking in that scene on a button, you should go to the next level scene. Is there a way to load the next level, whiteout set a hard number of the rang list of "Build Settings"?


Is Time.deltaTime framerate dependent? I have a game that calculates your score via Time.deltaTime (the more time the more score). On my PC I get about 1200 points if I just idle the game while on my phone I only get about 400 points. I believe my code must be FPS dependant and that's why my phone is getting a lower score for the same time. Here's the code void Update () time Time.deltaTime score (int)time timerLabel.text score.ToString() Sorry if it's something very obvious. I'm quite new at c . Can't seem to get the solution to work. It just stays at 0 Full Code using UnityEngine using UnityEngine.UI using System.Collections using UnityEngine.SceneManagement public class EndGame MonoBehaviour public Text textWin public Text timerLabel public GameObject retryButton public GameObject points private Vector3 offset private float time private float score void OnTriggerEnter (Collider col) if (col.gameObject.name "Player") setWinText () retryButton.SetActive (true) points.SetActive (false) void setWinText () textWin.text "Final score " score.ToString() void Update () time Time.deltaTime if (time gt 1.0f) score score 1.0f timerLabel.text score.ToString()


Stormy water like Temple Run 2 for Mobile How can I make stormy water like they did in Temple Run 2. I've tried with Unity Water Pro to achieve the same result but when I include it in the project the frame rate crashes to 3 frames per second. Unity Water basic doesn't fulfill the requirements at all. So is there any other way?


Can't rotate object after using transform.forward I'm using above code to rotate object pointing where it moves transform.forward m Rigidbody.velocity It works fine, however the problem is that I can't rotate this object anymore after set direction. transform.forward m Rigidbody.velocity transform.Rotate(0, 0, m RotateSpeed Time.deltaTime 500) Not Working Code is simple, first rotate the object to point where it goes and then rotate z axis. But when I ran the game, it just shaking little bit and didn't rotate at all. Why it doesn't work even rotating code after the transform.forward? Any advice will very appreciate it.


Unity WebPlayer WWW GET Requests fail in webplayer only, not in editor My question is about my game requesting data from my server side cloud based storage (I have the option of free public Dropbox or Amazon S3) via GET and the WWW class, and it not working only in the WebPlayer (works fine in the Editor). By not working, I mean that the request is sent successfully, authorized and responded to by the cloud service, but that WWW shows an error in the logs. In the case of using Amazon S3, the Web Player even crashes, otherwise it just fails gracefully and the user is unable to move forward. The Error log left by the webplayer says the following WWW Error Error when creating request. GET request with custom headers is not supported. for URL https my storage.s3.amazonaws.com myDir myFile.json Here's when I use a similar request to a public directory on Dropbox. There is no crash, but the request also fails. WWW Error Failed downloading dl.dropboxusercontent.com u 7782207 spare change weapons 0.json for URL dl.dropboxusercontent.com u 7782207 spare change weapons 0.json Try it for yourself http webroleplay.appspot.com (currently using Dropbox, so not crashing the player) username test1 password t


Separating part of mesh facing upwards I really hope you can help me fix this code List lt Vector3 gt verticesToExport new List lt Vector3 gt () vertices of the triangles facing upwards. List lt int gt trianglesToExport new List lt int gt () new triangle facing upwards. meshToCut is the original mesh, then I just try to replace it with the new data. int triangles meshToCut.triangles Vector3 vertices meshToCut.vertices for (int i 0 i lt triangles.Length i 3) Vector3 corner vertices triangles i Vector3 a vertices triangles i 1 corner Vector3 b vertices triangles i 2 corner float projection Vector3.Dot(Vector3.Cross(b, a), Vector3.down) if (projection gt 0f) verticesToExport.Add(vertices triangles i ) verticesToExport.Add(vertices triangles i 1 ) verticesToExport.Add(vertices triangles i 2 ) trianglesToExport.Add(triangles i ) trianglesToExport.Add(triangles i 1 ) trianglesToExport.Add(triangles i 2 ) meshToCut.SetVertices(verticesToExport) meshToCut.SetTriangles(trianglesToExport, 0) probably I'm doing wrong here! It works great by retrieving the vertices facing up, and I guess the triangles too but when I put it into a mesh filter I believe the triangles are not in order... 1.The model I'm trying to separate the triangles facing upwards. 2. This is what happens if I just take the vertices and triangulate them again. It proves that vertices are alright! 3. The result I get from the code above


How do I share a downloadable WebGL build in Unity? When I make a WebGL build for my project, I get a folder that lets me click a .html to play my game in a browser. Is there a way I can share a folder like this for playtesters? I tried sending a .zip folder to playtesters, but they only got a Unity loading screen that didn't do anything.


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


Why occlusion culling isn't working? I've bought a 3d model from a 3d marketplace. It is a big interior scene. I've imported the single FBX into Unity, added some collider, changed materials (6 7 materials) etc. There are hundreds of child object mesh Despite what my camera is looking, i noticed Unity is rendering 3 400K tris. Why Occlusion Culling isn't working ? Maybe importing a single huge Fbx isn't the right practice ? Thanks This image is my player looking at a black wall... 360K tris rendered !!!!


Why does 'InvalidCastException Specified cast is not valid.' occur for ARKitFaceSubsystem? Why does 'InvalidCastException Specified cast is not valid.' occur for ARKitFaceSubsystem in the snippet below? var faceManager FindObjectOfType lt ARFaceManager gt () if (faceManager ! null) m ARKitFaceSubsystem (ARKitFaceSubsystem)faceManager.subsystem


Make players Rigibody move in direction its going? I have my snowboard character which I am trying to fix the movement for. At the moment, The player is using transform.forward on the rigidbody to move forward. If my player turns around and faces up the hill, it keeps going no matter what. I need a way that my player goes in the direction that the gravity is pushing it, This will also mean my player can ride switch. Also, My player is a capsule not a sphere so it doesnt roll around. I have tried playing around with rigidbody.velocity but nothing seems to want to work. if(Input.GetButton("Jump")) transform.localPosition transform.forward Time.deltaTime force force is the speed of the character This is also Javascript ( yes I know i should use C I'm learning it currently)


A field initializer cannot reference the non static field, method, or property 'CinemachineFreeLook.Variable' engine unity coding language c I am trying to control CinemachineFreeLook maxSpeed from another script in the struct AxisStat public AxisState(float minValue, float maxValue, bool wrap, bool rangeLocked, float maxSpeed, float accelTime, float decelTime, string name, bool invert) It only accepts to type a number, but not a variable. Whenever I create a public float variable and place it in maxSpeed, it keeps sending the error error CS0236 A field initializer cannot reference the non static field, method, or property 'CinemachineFreeLook.rSpeed' Here is the default unity CinemachineFreeLook script code the added code which I declare a float variable quot rSpeed quot at the beginning and added my variable in the AxisStat maxSpeed public class CinemachineFreeLook CinemachineVirtualCameraBase public float rSpeed 300f lt summary gt Object for the camera children to look at (the aim target) lt summary gt Tooltip( quot Object for the camera children to look at (the aim target). quot ) NoSaveDuringPlay public Transform m LookAt null lt summary gt Object for the camera children wants to move with (the body target) lt summary gt Tooltip( quot Object for the camera children wants to move with (the body target). quot ) NoSaveDuringPlay public Transform m Follow null lt summary gt If enabled, this lens setting will apply to all three child rigs, otherwise the child rig lens settings will be used lt summary gt Tooltip( quot If enabled, this lens setting will apply to all three child rigs, otherwise the child rig lens settings will be used quot ) FormerlySerializedAs( quot m UseCommonLensSetting quot ) public bool m CommonLens true lt summary gt Specifies the lens properties of this Virtual Camera. This generally mirrors the Unity Camera's lens settings, and will be used to drive the Unity camera when the vcam is active lt summary gt FormerlySerializedAs( quot m LensAttributes quot ) Tooltip( quot Specifies the lens properties of this Virtual Camera. This generally mirrors the Unity Camera's lens settings, and will be used to drive the Unity camera when the vcam is active quot ) LensSettingsProperty public LensSettings m Lens LensSettings.Default lt summary gt Collection of parameters that influence how this virtual camera transitions from other virtual cameras lt summary gt public TransitionParams m Transitions lt summary gt Legacy support lt summary gt SerializeField HideInInspector FormerlySerializedAs( quot m BlendHint quot ) FormerlySerializedAs( quot m PositionBlending quot ) private BlendHint m LegacyBlendHint lt summary gt The Vertical axis. Value is 0..1. Chooses how to blend the child rigs lt summary gt Header( quot Axis Control quot ) Tooltip( quot The Vertical axis. Value is 0..1. Chooses how to blend the child rigs quot ) AxisStateProperty public AxisState m YAxis new AxisState(0, 1, false, true, 2f, 0.2f, 0.1f, quot Mouse Y quot , false) lt summary gt Controls how automatic recentering of the Y axis is accomplished lt summary gt Tooltip( quot Controls how automatic recentering of the Y axis is accomplished quot ) public AxisState.Recentering m YAxisRecentering new AxisState.Recentering(false, 1, 2) lt summary gt The Horizontal axis. Value is 180...180. This is passed on to the rigs' OrbitalTransposer component lt summary gt Tooltip( quot The Horizontal axis. Value is 180...180. This is passed on to the rigs' OrbitalTransposer component quot ) AxisStateProperty public AxisState m XAxis new AxisState( 180, 180, true, false, rSpeed, 0.1f, 0.1f, quot Mouse X quot , true)


How to implement 3d maneuver gear physics in unity? I am trying to create a attack on titan styled game for a school project. I am not new to programming, but I am new to game development. I couldn't find any resources for this, hence I am posting it here. How do I go about implementing 3d maneuver gear physics from attack on titan anime? What is it? In case you don't know, here's a brief link about 3d maneuver gear. A brief commentary about 3dMG It's basically a grappling hook based system (similar to what you would find in a spiderman game), but it has different components to it, which makes it quite complex to think about. My Approach so far I have seen tutorials on how to use hooks in unity and stuff, but it would be great if someone could give me a general idea as to how to even start with this kind of thing. I would appreciate your answer, even though it is not unity specific. The idea is to have two points on the character, from where we fire the ropes. These ropes could simply be graphics (or unity's RaycastHit). And then we would also need information about the hook "hit point". Once we know that, we just reel in ourselves towards that. However the problem is that I don't know how to use momentum etc to effect the character's movement. Also since it's not just one rope(like a spiderman's game), but two, it's even difficult to think as to how would the movement be if user uses only left hook, or right hook or both. Also there is this gas aspect, which would propel you further and it should also be taken into account, along with momentum that we would carry. So any general idea would be greatly appreciated.


How to rotate a whole Bezier Curve around a given point I am using the code from the question Adding functionality to make individual anchor points of bezier continuous or non continuous to create bezier curves (I added a line renderer). How can I rotate the whole bezier curve (which may contain multiple cubic B zier segments) around a point? Please note that the rotation point could be any point including the one of the curves anchor points or control points.


What is the most appropriate way to achieve synchronous Addressable asset loading? I am transitioning my project from Resources to Addressables. Some parts of my game just aren't worth doing asynchronously, and would just cause more problems but I still want to use Addressables for its other benefits. Anyway, it doesn't offer any synchronous methods in their API. Unity has an official repository with an example for "synchronous addressables" right here https github.com Unity Technologies Addressables Sample blob master Advanced Sync 20Addressables Assets SyncAddressables SyncAddressables.cs Although the code does appear to work in the few tests I've done The code below won't always work, and it doesn't make sense to me anyway. This is the relevant method public static TObject LoadAsset lt TObject gt (object key) if(!s Initialized) throw new Exception("Whoa there friend! We haven't init'd yet!") var op Addressables.LoadAssetAsync lt TObject gt (key) if(!op.IsDone) throw new Exception("Sync LoadAsset failed to load in a sync way! " key) if (op.Result null) var message "Sync LoadAsset has null result " key if (op.OperationException ! null) message " Exception " op.OperationException throw new Exception(message) return op.Result It will throw an exception if the asset didn't manage to load instantly (the !op.isDone part). Sure, that's technically synchronous, but it seems to ignore the elephant in the room if the asset is large I would expect it to need a bit more time (i.e. freeze the game), which is fine for my current needs but instead, the game will just end up crashing because it couldn't load immediately. What is the most appropriate way to achieve synchronous Addressable asset loading?


Unity3D Efficiently loading chunks in an infinite voxel engine I'm developing a voxel engine in C using Unity and I'm currently trying to implement infinite terrain, so I took a look at other Unity voxel engines that have infinite terrain. I've seen three different ways of doing it Using a dictionary to store the chunks and store the block data in another dictionary Using a dictionary to store the chunks and store the block data on every chunk Using a fixed size array and shifting it every time the player moves The engines using approach 1 and 2 were pretty slow at chunk loading. The engines using approach 3 were faster but produced lag every time the player entered a new chunk. I've already tried to implement it using approach 1, but my chunk loading speed got slower by about 10 times, so it was really unplayable. How is it done in efficient or popular voxel engines like Minecraft or VoxelFarm? Do you have experience with voxel rendering and know a better approach? Thanks in advance!


Lag in Destroy() method I have a script that destroys the player object when a collider with that script touches it. The thing is that, even if there is no time specified in the script, it takes couple seconds before it destroys the player. Why does this happen, and how do I get around it? public class DestroyScript MonoBehaviour public GameObject player void OnTriggerEnter(Collision otherObj) if (otherObj.gameObject.tag "Player") Destroy(player)


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


How do Idle games progress while not active? A hallmark of many idle games is the ability to still progress (or at least regain resources) while the game isn't active. The device can even be off. Initially I figured they just calculated progress off system time next time it was started, but they do not appear fooled by messing with the clock. How do they manage this specific feat?


Is coroutine as good as a delay() function I'm new to Unity and I was learning the usage of coroutines. Is calling a coroutine as good as a delay() function? Does Unity have a delay() function?


Unity Raycasting Error NullReferenceException EDIT I added the if statement if(hitInfo.collider ! null) above the if(hitInfo.collider.CompareTag( quot Player quot )) statement and it seems to work. I'm trying to give my Enemy AI (Red dude) a line of sight via Raycasting. I want it to initiate the Attack() function when it sees the Player (blue dude) whose tag is quot Player quot . I first need to get a quot true quot statement from the RaycastHit2D to write the rest but the game just crashes whenever the Player is out of the ray. When I put the player in range of the enemy model by hand before running the game, it runs okay But when I make something, like jumping, to stay out of the ray, the game crashes and I get the error NullReferenceException Object reference not set to an instance of an object. It shows the line 90 which corresponds to the line if(hitInfo.collider.CompareTag( quot Player quot )) Here is the whole code for my RaycastPlayerDetection() which is called in the Update() function private bool RaycastPlayerDetection() RaycastHit2D hitInfo Physics2D.Raycast(EyeSight.position, transform.right, lineOfSight) Debug.DrawLine(EyeSight.position, hitInfo.point, Color.red) if(hitInfo.collider.CompareTag( quot Player quot )) Debug.Log( quot player has been seen quot ) return true else return false


How can I make it so the baller ball does not keep moving after it bounces? I am pretty new to Unity so how I did it may not be the best way, but when the character jumps it is inconsistent. When I press the up arrow key really quickly and then stop the jump will be further than it is supposed to be and it starts to glide. I want all the jumps to be the same size and the player can't bounce again until it is on the ground. Also if I start playing to quickly within the first second or two the ball jumps really far but if I wait a couple seconds it bounce like normal. Here is my code using UnityEngine using System.Collections public class MovePlayer MonoBehaviour public float distance public float fspeed public float uspeed public float addToDistance bool jumping false PRIVATE private Rigidbody rigidBody void Awake() rigidBody GetComponent lt Rigidbody gt () rigidBody.freezeRotation true void FixedUpdate() if (!jumping) if (Input.GetButtonDown ("up")) rigidBody.AddForce (new Vector3 (0, uspeed, fspeed)) if (Input.GetButtonDown ("down")) rigidBody.AddForce (new Vector3 (0, uspeed, fspeed)) if (Input.GetButtonDown ("right")) rigidBody.AddForce (new Vector3 (fspeed, uspeed, 0)) if (Input.GetButtonDown ("left")) rigidBody.AddForce (new Vector3 ( fspeed, uspeed, 0)) void OnCollisionEnter(Collision other) if (other.gameObject.CompareTag("Ground")) jumping false void OnCollisionExit(Collision other) if (other.gameObject.CompareTag("Ground")) jumping true


How do I properly light characters in a Unity scene? I made a game prototype and want to improve some of rendering the visuals through light baking (which I'm new to). While I was mostly able to do this in my environiments, I'm having issues doing this for my characters in Unity. Previously, they came out with odd ish dark shadows in places as they were affected by light and dull colors. After I begin light baking though and adding Light probes in areas that my characters would be extremely light, especailly on the skin areas. It doesn't look good at all. Alternatively, without using light probes, it looks like this. I'm genuinely confused on how to properly light these characters if I can't get a middle ground of proper lighting. Can anyone help me try to understand this and solve this problem?


Rotate an object on itself, from one random Quaternion to another I have a situation I have a 3D object in the world. let's say a sphere. I have 2 random directionnal vector vector A, and vectorB My question is How to I rotate over time my object, from A to B ? The vector A is important I don't want to simply rotate the forward of the object from current forward to B. I know I can use the function vector3 C Vector3.SmoothDamp(...) in unity to lerp between my 2 vectors A amp B. but then ok, I have vector3 C, how do I apply the rotationof my object to C ? if don't want to do gameObject.transform.forward C I want something like gameObject.transform.rotation SomeQuaternion(C, initial rotation A). or something. Thank you for help ! PS I don't want to parent unparent gameObject or something like that, i want the math answer, using Quaternion.


Unity emission lighting I have created a scene with a blue sphere inside of a white room of planes. The room is being lit by a point light above the roof, and the sphere is emitting a blue light. How do I get the emission from the sphere to contribute to the lighting of the walls without making it static?


Switching between VR and Desktop (VR Controllers are not tracked in Unity Build) I am developing a VR App in Unity3D for HTC Vive Pro (Wireless) everything works well with VR in the usual way. (SteamVR Plugin 2.5.0 (SDK 1.8.19)) Except for some requirement reasons in the same Unity scene, I have to shutdown VR switch to Desktop mode and later at some point enable VR again. The moment, I enable it via script the VR display is ON, the HMD tracking works well but the Vive controllers are not tracked (position amp rotation), I can see the controller model rendered though in the last position when the VR was shut down but I can't get the updated tracking. The issue is only happening in the Unity Build. In the editor, it is working fine now after this change. To fix the issue in the Unity Editor I tried changing the SteamVR ActivateActionSetOnLoad method from Start() to OnEnable() as the error on re enabling was related to controller actions missing, that is now fixed cause of this change. e g private void OnEnable() if (actionSet ! null amp amp activateOnStart) Debug.Log(string.Format(" SteamVR Activating 0 action set.", actionSet.fullPath)) actionSet.Activate(forSources, 0, disableAllOtherActionSets) I am looking for a solution, to fix the issue in the Unity build? Any suggestions are highly appreciated.


Writing a glow shader I'm trying to learn writing shaders. And I've pieced together something that is kinda working. I want to create a transparent glow around a sphere. The problem I have is that I can't seem to alter the transparency of the glow. I tried experimenting with ZWrite off but that doesn't give me the desired results. The red part around the sphere is the glow. But I'm unable to change its alpha. I'd would also like to change the "blurriness" of the glow. How would I do that? EDIT so I did some more tinkering. I've changed the blending to Blend SrcAlpha OneMinusSrcAlpha and enabled ZWrite off. This allows me to change the alpha. The problem with this is that the inside of the object is also colored by the glow. I just want the glow around the circle. not inside. Shader "Custom HoleShader" Properties holeColor ("Color", Color) (1,1,1,1) glowColor ("Glow Color", Color) (1,1,1,1) glowSize ("Glow Size", Range (0.0,5)) 1.0 glowOpacity ("Glow Opacity", Range(0,1)) 1 SubShader Tags "LightMode" "ForwardBase" Pass CGPROGRAM pragma vertex vert pragma fragment frag uniform float4 holeColor uniform float4 glowColor struct appData float4 normal NORMAL float4 vertex POSITION struct v2f float4 pos SV POSITION float4 col COLOR v2f vert (appData v) v2f o o.pos mul(UNITY MATRIX MVP,v.vertex) return o float4 frag(v2f i) COLOR return holeColor ENDCG Tags "LightMode" "ForwardBase" "Queue" "Transparent" "RenderType" "Transparent" Pass ZWrite Off Blend One OneMinusSrcColor Blend SrcAlpha OneMinusSrcAlpha CGPROGRAM pragma vertex vert pragma fragment frag uniform float4 holeColor uniform float4 glowColor uniform float strength uniform float glowSize uniform float glowOpacity struct appData float4 normal NORMAL float4 vertex POSITION struct v2f float4 pos SV POSITION float4 col COLOR float3 viewDirection float3 normalDirection v2f vert (appData v) v2f o float4 pos v.vertex (v.normal glowSize) o.pos mul(UNITY MATRIX MVP,pos) return o float4 frag(v2f i) COLOR return float4( glowColor.rgb, glowOpacity) ENDCG


Add Existing Animation I have several animations that I am using on a GameObject. I switched the folder they were stored in, and they got detached from the gameObject. How can I add the existing animations to my gameObject without having to recreate them? I am not looking to do this programmatically. I just want to undo the damage I have done without having to start over. Ideally, I want a "Load Animation" option from the Animator window in the editor, but that does not appear to exist .


How can I implement UI in Unity using Chromium? I'm looking for an alternative to UI Builder. Ideally I'd like to have basically a Chromium instance atop Unity3D which would have its JS calls somehow land in the C (maybe in the quot Update quot loop it listens to a constant stream of potential calls and the parameters will correspond to function names in my Unity code, I don't know) here's what I found which doesn't quite live up to my expectations Unity WebView doesn't support Windows. 3D WebView for Windows and macOS (Web Browser) requires the UI to be served on an actual live URL and for Unity to access it via that URL and for all interaction to be handled via API, impractical or slow at best. PowerUI HTML CSS is interesting, but was made in 2011. The documentation is all gone. the support for css feature is probably incredibly slim. Embedded Browser looks pretty good, but I'm unsure that it could be bent into a UI system. I want it to frame my game, not to cover it. Coherent Gameface looks probably the best, although the CSS implementation seems a tad lackluster. Also this project was started in 2012, it's probably carrying very old, very slow code. This Unity forum thread may be relevant. Chromium Embedded Framework was a tool used by some assets on the asset store to create chromium UI but it has been removed. If not using these assets, how can I implement my idea of using Chromium as my UI layer?


Make enemy disappear after spawn I have enemies that spawn in different positions but what I want to do is that if you don't kill it after three seconds, the enemy disappears (but the spawning keeps happening of course, the enemy will show up again eventually). I tried using a coroutine but after reading the documentation and watching some tutorials I still don't understand very well how it works so I need some help. Thanks in advance. This is my code so far public class TimedSpawn MonoBehaviour public GameObject spawnee public bool stopSpawning public float spawnTime public float spawnDelay private GameManagerScript GMS void Start () GMS GameObject.Find ("GameManager").GetComponent lt GameManagerScript gt () InvokeRepeating ("SpawnObject", spawnTime, spawnDelay) public void SpawnObject () if (GMS.counterDownDone true) Instantiate (spawnee, transform.position, transform.rotation) if (stopSpawning) CancelInvoke ("SpawnObject")


Ignoring collisions without using physics layers Trying to ignore collisions between certain prefabs, but in this case I don't want to use layers since these are specific object pairs that I want to not collide, and creating a layer for each prefab would complicate the layer matrix more than I want to. What I tried so far public void OnCollisionEnter(Collision collision) if (collision.gameObject.tag "Bullet") Physics.IgnoreCollision(collision.collider, collider) So I tried ignoring the collision in the OnCollisionEnter, but this only worked partially. The objects did go one through the other, but they both slowed down. My guess is that the first frame of the collision, the one that generated the call to OnCollisionEnter, was calculated regardless of the ignore command. Any ideas how I can make all bullets not collide to one another, without putting them in a separate layer?