Affect of timeStep on PhysicsBodies in SceneKit In SceneKit, I had a problem on collision of two dynamic spheres, when the one strikes to another with fast speed, it was passing through inside of it. After i have reduced physicsWorld.timeStep value from 1 60 to 1 300, collision of Spheres becomes perfect. However in this moment, if sphere strikes to static wall, it started to slide along the wall (like sticky) instead of being reflected from wall. Ball started to lose so much energy after colliding to wall. When timeStep was 1 60, ball was bouncing on the wall even in so low speeds, instead sticking to wall. What kind of parameters are affected in physicsBody of the wall or ball by the timeStep? Wall Parameters let ballMass CGFloat 0.08 physicsWorld.timeStep 1 300 let wallGeometry SCNPlane(width (maxX minX), height wallHeight) wallGeometry.firstMaterial?.diffuse.contents UIColor.red wallGeometry.firstMaterial?.isDoubleSided true let shapeWallGeometry SCNPhysicsShape(geometry wallGeometry, options nil) su an lik bir ise yaramiyor let wallNode SCNNode(geometry wallGeometry) wallNode.position SCNVector3( x Float(xCenter), y Float(minY cushionHeight 2), z Float(cushionHeight) 2 ) wallNode.physicsBody SCNPhysicsBody(type .static, shape shapeWallGeometry) wallNode.physicsBody?.restitution 0.82 wallNode.physicsBody?.friction 0.91 wallNode.physicsBody?.categoryBitMask PhysicsCategory.WallType.rawValue PhysicsCategory.GravityType.rawValue wallNode.physicsBody?.collisionBitMask PhysicsCategory.BallOneType.rawValue PhysicsCategory.BallTwoType.rawValue PhysicsCategory.BallThreeType.rawValue PhysicsCategory.GravityType.rawValue wallNode.physicsBody?.contactTestBitMask PhysicsCategory.BallOneType.rawValue PhysicsCategory.BallTwoType.rawValue PhysicsCategory.BallThreeType.rawValue self.rootNode.addChildNode(wallNode)


Move a ball horizontally left and right but restricting forwards and backwards motion unity 2d I am trying to develop an endless runner where there is a sphere as the player and it is moving left and right following the position of a finger on a touch screen. However, when I try to do this I cannot get the player to lock on the Y axis. I want a constant force that speeds up overtime which I have using the constant force 2d supplied by unity. I have two versions of code, the first follows the finger but the player is able to move up and down as well using UnityEngine using System.Collections public class Test MonoBehaviour public GameObject character public float speed 500.0f void Start() Input.multiTouchEnabled false void Update() if (Input.touchCount 1 amp amp Input.GetTouch(0).phase TouchPhase.Moved) Vector2 target Camera.main.ScreenToWorldPoint( new Vector2(Input.mousePosition.x, Input.mousePosition.y)) character.transform.Translate(Vector3.MoveTowards(character.transform.position, target, speed Time.deltaTime) character.transform.position) The second code I have allows the player to move left and right by tapping rather than following but is still sloppy using System.Collections using System.Collections.Generic using UnityEngine public class PlayerMovement MonoBehaviour public Rigidbody2D rb public float sidewaysForce 500f Start is called before the first frame update void Start() rb GetComponent lt Rigidbody2D gt () Update is called once per frame void Update() foreach (Touch touch in Input.touches) if (touch.position.x lt Screen.width 2) rb.velocity new Vector2(sidewaysForce 1, rb.velocity.y) if (touch.position.x gt Screen.width 2) rb.velocity new Vector2(sidewaysForce 1, rb.velocity.y) Any help on this would be awesome Thanks!!!


Translating object 2's movement on object 1 I am moving Object 1 with the translation of the object 2. That is, it should not copy the object 2's position, but instead moving in the same direction angle as the object 2 is moving. I am stuck at this point where I must add a certain offset if the object is moving Left Right Up Down, since it may be positive negative floating value. So how do I add an offset to object 1's position? The problem with the below code is that the object2 comes in position of object1 and then translates which is not what I want. public Vector3 offsetPosition public Transform Object2 Update is called once per frame void Update () offsetPosition Object2.transform.position this.transform.position this.transform.position new Vector3 (Object2.transform.position.x, this.transform.position.y, Object2.transform.position.z) new Vector3 (offsetPosition.x 0.02f, 0, offsetPosition.z 0.02f)


Saving score in Unity I have the following script which I use for calculating the score public class Score MonoBehaviour Score sc void Start() GameObject obj GameObject.Find("ScoreSystem") sc obj.GetComponent lt Score gt () void OnTriggerEnter2D(Collider2D coll) if (coll.tag "Ball") sc.score and this is the class where I increase the value public class Score MonoBehaviour public int score void Start() score 0 But the problem I have is that the value always stays 0 when I switch to a different scene. I even used this code to store the value and display in the next scene but it didn't work void Update() PlayerPrefs.SetInt("score", score) PlayerPrefs.Save() and this code for taking the value score PlayerPrefs.GetInt("score") How can I store the latest value inside an Int and display it in the next scene and when I leave that scene it reverts back to 0?


Make the texture array node work with cubemaps? I am working on a procedural interior mapping shader in Unity's Shader Graph. Ideally, I'd like to feed it a set of cubemaps it can pick from semi randomly. However, it seems that by default the texture array asset one can provide to a graph does not support reading cubemaps. Does anyone have a way to use this, or perhaps a clever custom node or alternate texture mapping, so that I can read a number of cubemaps into the shader semi randomly? Preferably an arbitrary number, but even a fixed number would be somewhat of an improvement.


Space to Switch to Hand Tool in Tile Palette? Hi I just download a Utility called Hold Spacebar for Hand (drag) Tool I read the code and I can understand it, but now I wondering how can I modify this to support the same functionality but works in Tile Palette tab, thanks!


Change layout of Unity's Project Assets pane contents to show longer filenames? I'm working on a project with assets that have really long filenames. I know about the slider in the lower right corner of the Project Assets pane, but THAT slider makes the icons absolutely HUGE amp only allows the display of filenames that are slightly longer than the default. Is there a way to either Get Unity to use a view akin to Windows Explorer's "List" view (small icon on the left, long filename on the right) Get Unity to truncate long filenames in the middle? For example... Full name ExtraordinarilyLongFilename 27a.material How it displays now ExtraordinarilyLongF... How I'd like it to truncate ExtraordinarilyL...e 27a (the general assumption of a middle truncated long name being that the last few characters are usually the ones that distinguish between multiple files that all begin with the same prefixes)


How to calculate the stopping distance of a wheel collider? I have an 'AI' bus in my game that needs to pull over occasionally at a bus stop. What I want to do is change the acceleration and brake force based on the stopping distance of the bus. I don't want to simply use the distance between the bus stop and the bus because each time the bus pulls over, it could be traveling at a different speed. Right now it uses the distance between the bus stop and the bus. It doesn't really work well though because if a bus is traveling faster, it will take a longer distance to stop and will likely go past the bus stop. Same thing if it were going slower. How do I calculate the stopping distance my bus will take to come to a complete stop?


How to Fill the Gap Between Camera Clip Plane And Skybox? I'm talking about the brown greyish area i marked with blue. How can i fill it with something that does fit the environment? I'm looking for a solution like this plugin.


How do i put apps on sleep while my game is running in an Android Device How do i put apps on sleep while my game is running in an Android Device. I m a Game Developer (intermediate Level). And i Wanna know the Can i put apps of phone running in background to sleep to free some ram and make my game run on 1 gb of phone smoothly (Android 9).


Unity Ads. Is the Ad.show placementId parameter used anymore? I started a project a long time ago with the Unity ad api v1, now that they have moved onto Advert api v2 i'm wondering if they still use the placementId parameter. I'm only wondering this because they used to support video and image based Ads. As far as I know they only do video now. They used to have examples similar to this Advertisement.Show("rewardedVideo", options) Which specified which of the supported advert types you want, rewardedVideo for video and rewardedImage (or something similar) for images. With the loss of images and the integration guide (behind the login screen) having been changed does the palcementId parameter still matter since I noticed that you can pass in only the callback stuff?


Measure a distance point to point in unity3D? I tried to measure a distance point to point on my phone screen by using following code Vector3 startPoint Vector3 endPoint public Camera cam float distanceX void Update() if (Input.GetMouseButtonDown(0)) Vector3 startPoint cam.ScreenToWorldPoint(Input.mousePosition) if (Input.GetMouseButtonUp(0)) Vector3 endPoint cam.ScreenToWorldPoint(Input.mousePosition) distanceX Mathf.Abs(startPoint.x endPoint.x) Debug.Log(distanceX) but this code does not give me the correct result and I don't know why..


In Unity, can I load a local ( Resources folder) website to safari on an ipad In Unity, can I load a local ( Resources folder) website to safari on an ipad? This works fine on a Mac, opening up a wepage from my Resources folder. string path "file " (Application.dataPath) " Resources testsite.html" void OnGUI() if(GUI.Button(new Rect(20, 20, 100, 100), "site")) Application.OpenURL(path) but when I try to load this on an iPhone or iPad, it doesn't seem to work. Am I accessing the address incorrectly for iOS using "file "? If this is not possible, is there an alternative way I can load a locally stored website on an iOS device?


Unity3D (5.1) NavMesh Agent Error This is my first post in GameDev StackExchange, so please excuse me if I make any mistakes on best practices here (if I do, please refer me so I can learn). I'm making a prototype where I have 2 types of enemy units Uninfected and Infected. The Uninfected are to seek out Infected via AI pathfinding. However, I came across an issue when implementing the NavMesh in the scene. If the Player collides with an Uninfected, they go flying backwards. If they hit the walls, the walls collectively get hit. Here's some screenshots. Example 1 http s7.photobucket.com user Korudo media GameDev RoboInfect 20Scene 20 20WallWeirdness1 zpsg0k2wbyk.png.html Example 2 http s7.photobucket.com user Korudo media GameDev RoboInfect 20Scene 20 20WallWeirdness1 zpsg0k2wbyk.png.html Thanks in advance.


Font Changes in WebGL Build I'm attempting to make a game for WebGL. However, everytime I export a build, the font always changes on everything, just like below. Original WebGL My default font is Arial and I have made a separate Arial font file with which I've replaced all instances of Arial font in my game, but it's still turning out like this. Why?


Why does the keyboard continue to control disabled buttons? Having the whole panel with all its children including buttons disabled by simple gameObject.SetActive(false) doesn't prevent the buttons from interacting (navigation and clicks) with the keyboard. What could be the reason?


ScreenToWorldPoint(Input.mousePosition) always returns 0 for X and Y coordinates I'm trying to convert the mouse position (Input.mousePosition) into world points, but for whatever reason the X and Y coordinates are always, always 0. Here, I printed mousePosition and ScreenToWorldPoint()'s output The 10 in the Z is understandable, but why do I get 0s in X and Y regardless of the actual, varying mouse position? This is inside a custom display I set inside Game View (1440x3040). I tried Free Aspect, but that didn't change anything. I tried parenting the script to an empty game object centered on origin just in case, but that didn't do anything either. The code Vector3 mousePos Camera.main.ScreenToWorldPoint(Input.mousePosition) Debug.Log(mousePos) Debug.Log(Input.mousePosition) Or, more generally private bool hitProjectile() bool hit false Vector3 mousePos Camera.main.ScreenToWorldPoint(Input.mousePosition) Debug.Log(mousePos) Debug.Log(Input.mousePosition) if ((mousePos.x gt (pt.position.x radius) amp amp mousePos.x lt (pt.position.x radius)) amp amp (mousePos.y gt (pt.position.y radius) amp amp mousePos.y lt (pt.position.y radius))) hit true return hit The game is in 2D, the camera is perspective, and I'm using URP. The script is trying to determine if the mouse clicked on a circle ( w a CircleCollider2D). What the hell is going on? I hope this is not a URP thing. I've had nothing but bad experiences with it.


Why isn't OnCollisionEnter2D working? I've made a hole. I have animals tagged as animals. When an animal walks into the hole, they disappear. I tried OnTriggerEnter2D() as well, and set the collider to isTrigger, but it still didn't work. I can get it to work without the tag part, but anything that bumps into each other sets each other to inactive. public class BlackHole MonoBehaviour void OnCollisionEnter2D(Collision2D other) if (other.gameObject.tag "animal") other.gameObject.SetActive(false)


Applying velocity to parent that ignores children's mass not working I am making a VR data visualisation app in Unity and I have a parent with many children (just some primitive cubes) that I can toss around the scene by just setting the parent's rigidbody to the same velocity as my tracked VR controller. Rigidbody rb GetComponent lt Rigidbody gt () Vector3 controllerVelocity Player.instance.rightHand.GetTrackedObjectVelocity() how I ref the controller velocity in SteamVR rb.velocity controllerVelocity 2f the 2f is just to speed up the velocity The above code works fine, but the problem is I think the scale of the children objects, which can be adjusted by the player, is affecting the velocity the parent moves at. Or maybe just when the children are very large...the controller velocity is comparatively too slow? Basically I need this to not be the case I want the parent's rigidbody to move at roughly the same velocity no matter the children's scales masses. So to achieve that I thought to use Rigidbody.AddForce but it doesn't seem to be making any difference i.e. larger children are still moving slower. Here is what I have so far Rigidbody rb GetComponent lt Rigidbody gt () Vector3 controllerVelocity Player.instance.rightHand.GetTrackedObjectVelocity() rb.AddForce(controllerVelocity 2f, ForceMode.VelocityChange) I also tried ForceMode.Acceleration but then nothing moved at all? Am I using AddForce incorrectly? Or do I just need a scaling multiplier based on the size of the children? Any help is welcome.


How to fix flare in unity? I have a simple sun flare that I would like to appear on my directional light (sun). However I cannot see the flare, I have tried setting the ignore layers to everything and checked and double checked that there is a flare layer on my camera. The light is also rotating constantly as I have a day night cycle too if that means anything for the flare... Anyway, could someone show me how to fix this?


How to get crash reports from game Unity3d I am working on a project and I am in need of to gather CrashReports, email crash log, along with allowing the user to describe how the crash happened. I cannot find anything on how to do this, anyone has any ideas? Thanks! Learning Unity User


How to make an authoritative multiplayer game deterministic for all clients? I'm starting to create a multiplayer online game, with an authoritative server. As it is, the clients send inputs to the server which do the simulation and then send back to clients the updated state. The game is a top down shooter, so it's fast paced and input lags are not allowed here, so to avoid this I'm doing the simulation on the client too, and when the server update come back I compare the local simulation with the server response. If they are compatible everything is fine, otherwise, the client version is corrected. I was expecting that the client simulation desync at some point, because of all of the variables on physics, floating points, network etc... But this happens much more than I thought. Just by sending the inputs and simulating on the server, the results are very different, even on simple movements, like forwards and backwards on a clear space. Green is local, red is server response I need help on this step, a way of keeping, at least this kind of simple movement, consistent on the server and the clients.


System.Drawing.dll not found I am creating an asset, in Unity, and I need to use System.Drawing. I have been trying to figure out how to add the DLL in a way that works, but I have had zero luck. I have tried adding the DLL to the assets folder, but it just shows up in Visual Studio as if it couldn't be found. I have also followed the instructions of a similar question, on the Unity Answers page, without any luck. How do I use System.Drawing in Unity?


How can I hide an object for one eye for the unity oculus rift DK2 platform? I am trying to build a game for my son for the Oculus Rift DK2 to help treat his lazy eye using Unity. I need objects that Appear only to his left eye Appear only to his right eye Appear for both eyes. (this helps force the brain to use both eyes together to form the complete scene) How can I pull this off? Thanks!


Unity Extending Game Object best practice What is best practice when wanting to add to GameObject class? I would like all GameObject to be able to change color IF they have a renderer. Ive tried using a helper class that takes a GameObject and lerps the color value but if i want it to have an update method it must inherit MonoBehaviour, and if it does inherit it then i cant instanciate that helper class. Now im thinking about creating a new class that manages a GameObject and inherits from Monobehavoiur. It would have one GameObject as a member that it can manipulate. But then i would have to instanciate it from somewhere. Hmmm unity has its logic but i havent found it yet. Is it clear what i am having problems with? Otherwise please ask.


Why is that when I use Rigidbody the object falls through the floor? It keeps falling through the floor. On the object I added a Rigidbody and it already has a box collider. And the floor I want to make a bouncing ball effect. I'm using the official unity tutorial Tutorial However, my object falls through the floor.


Snooker Pool AI Predicting end location of cue ball Unity I m trying to implement a pool snooker game. I figured the best way to implement the ball movement potting mechanics is to use the physics simulation, apply an impulse to strike the cue ball and let the simulation deal with the rest. This seems straight forward enough but I have no idea where to start with the AI. For the AI to be anywhere near convincing it will need to consider the position of where the white ball will end up when planning what shot to play. Can anyone offer any advice on how I can predict where the white will end up when working with the physics engine? Or does this requirement make using physics a really bad idea?


Unable to instantiate objects Straight in unity I am creating a match card game in unity and I want to place cards in straight direction that is one below another and so on... But with my formula It's showing cards one after another.Please tell me whats wrong with my code. Following is my code void SpawnCards() int cardsinrow 4 int cardsincolumn cardslist.Count cardsinrow if(cardslist.Count cardsinrow gt 0) cardsincolumn 1 float spacebetweencards .2f for(int i 0 i lt cardslist.Count i ) GameObject mc Instantiate(memorycard, new Vector3((i cardsinrow (i cardsinrow spacebetweencards)) (cardsinrow 2f) spacebetweencards, 0, (i cardsinrow (i cardsinrow spacebetweencards)) (cardsincolumn 2f) spacebetweencards), memorycard.transform.rotation) as GameObject mc.GetComponentInChildren lt MemoryCard gt ().SetMemorycard(cardslist i .texture, cardslist i .number)


How to rotate within a fixed interval in Unity? I have very recently started to learn Unity. I'm trying to write code that will make a character swing a flag. I want to use this object and rotate the arm up and down. So I need to make it rotate up and down with within 30 degrees. This is my attempt but it simply keeps on turning. How would I make the hand rotate in motion within the interval 30, 30 degrees. private GameObject myobject public float timeElapsed 0 public float delay 3.0f float OO 0.0f void Start () myobject GameObject.Find ("rightarm").gameObject void Update () timeElapsed Time.deltaTime Debug.Log (timeElapsed) if (timeElapsed gt delay) OO 30.0f timeElapsed 0 if (myobject.renderer.enabled false) myobject.renderer.enabled true myobject.transform.Rotate (OO, 0.0f, 0.0f) else myobject.transform.Rotate ( OO,0.0f, 0.0f )


Tab between input fields I am new to working with Unity3d, I need to navigate between several inputField, for this I have looked at the solution that is in tab between input fields, but always the FindSelectableOnUp() or FindSelectableOnDown() returns null, so my next is always null and always ends in next Selectable.allSelectables 0


What's the most efficient way to find the position of a point in relation to corners of a rectangle despite rectangle's scale I am struggling to achieve the following with C (in Unity). I need to find the position of the points that lay at a given distance (let's say 1m) from the corners of a rectangle, in a way that the segment between these points and the given rectangle corners form 135 degrees with the corresponding sides the of rectangle no matter where the rectangle goes, what is its rotation or what is its size. Like the following So, using the picture above as reference, it means that the red dotted line has always the same length and divides the angle ABC in the middle. So, the angle of the line with AB is 135 and with BC is also 135. One of the ways to achieve that is the following code Vector3 dotpos rectangle.transform.TransformPoint(rectangle.transform.localPosition.x 1.5F,0,rectangle.transform.localPosition.z 1.5F) bluedot.transform.position dotpos The problem is that in such solution the distance between the blue dot and the corner of the rectangle is not independent of the scale of the rectangle. It means, the greater the rectangle, the blue dot goes more distant from the corner. Can anybody tell what is the most efficient way to achieve what I want, i.e. so the position of the blue dot is always at the same distance from the corner no matter the scale, position or rotation of the rectangle? PS blue dot is not an object that can be made child of the rectangle.


Sending position updates from server to clients (Unity gRPC) So clients connect to the server and the server spawns an entity for each of them. What I'm confused about is how to send position updates from the server to the connected clients. I read about bidirectional streaming but I'm confused because that would mean clients would have to specifically request the positions every update, which is not what I want. I want the server to send positions to every connected client. Is it possible to do it with gRPC? If so, how would I go about it?


How can I cast light onto a sprite in 3D environment? I'm making a 2.5D game, where 2D sprites are in a 3D environment. I'm using URP and I have a problem with lighting the sprites. The sprites are lighting up from behind, and not front. I tried with directional, spot and point lights but the result is the same no matter what official shader I use they only light up when they receive light from behind. Front light has no effect whatsoever on the sprites. I spent the entire day looking for a solution but I've got almost nothing. Only solution I saw someone else mention is making the game object with the quot sprite renderer quot on, a child of another gameobject and rotate it 180 degrees on Y. But that is not an option for me cause I'm using custom scripts to rotate that game object already. So can there be a custom shader? Can one be created using shadergraph maybe? I know some others have faced the same problem but did anyone really solve it? Thanks.


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


How to make counter unity? How do I count how many diamonds my player has collected in my 3d world What I need to do is to make a script which will update my text ui when the player collides with a diamond but I do not know how as I auto generate the diamonds How could I go about writing a script that will update the text score What I tried so far, but I'm not sure where to place it. (taken from comment) void OnTriggerEnter(Collider other) if (other.CompareTag( quot Diamind quot )) Debug.Log( quot Picking up... quot ) GetComponent lt Counter gt ().ScoreAmount 1


Unity3d webplayer failed to download data file When testing my game web builds on localhost, I get the error "Failed to download data file". The game data file is correctly placed, and the page loads fine, it just wont download the plugin, or prompt me to do so. I tried the following things Add MIME Types to IIS 7.5 Open IIS Manager Double click "MIME Types" in the IIS section. Click Add on the right side "Actions" menu. File name extension .unity3d MIME type application unity3d click ok Restart the server (right side "Actions" menu) That didn't work for me specifically because it turned out I was using IIS Express, so I did the following If Windows 7, browse to 'C Users Documents IISExpress config ' and open the file ApplicationHost.config. Search for 'staticContent' and add the following before the closing tag However, again, it didn't work..


Update function only running once For some reason, the update function is only running once. Why does this happen? using System.Collections using System.Collections.Generic using UnityEngine public class LightFlicker MonoBehaviour float timer float timetowait Use this for initialization void Start() timer 0 timetowait Random.Range(0.01f, 0.8f) Update is called once per frame void Update() Debug.Log("Updating") timer Time.deltaTime if(timer gt timetowait) if (gameObject.activeInHierarchy true) gameObject.SetActive(false) else gameObject.SetActive(true) timetowait Random.Range(0.01f, 0.8f) timer 0 The debug.log statement only fires 9 times. The timetowait changes, but the timer stays the same.


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


Push Notification to start a scene I was wondering whether I can use APNs in iOS to trigger an event in my game, like start a scene without user clicking the notification. Is it possible to use remote push notifications for events like this?


Pausing and resuming in Unity I've been writing this code quite late so please bear with me. I'm trying to pause the game and show a menu when I'm inside a collider and then when i press a key it should unpause the game and continue but it wont and i cant figure out why. Here's the very simple (in my eyes) code var savedTimeScale float var playerStatus Player Status var inTheZone boolean false private var startTime float 0.1 var start GameObject enum Upgrade None,Main private var currentPage Upgrade function Start() currentPage Upgrade.None function for ontriggerenter and pressing button to show menu function OnTriggerEnter(collider Collider) playerStatus collider.GetComponent(Player Status) if(playerStatus null) return inTheZone true function OnTriggerExit(collider Collider) playerStatus collider.GetComponent(Player Status) if(playerStatus null) return inTheZone false function Pause() savedTimeScale Time.timeScale Time.timeScale 0 AudioListener.pause true currentPage Upgrade.Main function UnPause() Time.timeScale savedTimeScale AudioListener.pause false currentPage Upgrade.None if(IsBeginning() amp amp start ! null) start.SetActive(true) function IsGamePaused() return Time.timeScale 0 function OnGUI() if(inTheZone true amp amp Input.GetKeyDown(KeyCode.E)) Pause() if(Input.GetKeyDown(KeyCode.N)) UnPause() if(IsGamePaused() amp amp !IsBeginning()) UpgradeMenu() function UpgradeMenu() BeginPage(200,200) GUILayout.Button("Hello") EndPage() function BeginPage(width, height) GUI.DrawTexture GUILayout.BeginArea(Rect((Screen.width width) 2,(Screen.height height) 2,width,height)) function EndPage() GUILayout.EndArea() ShowBackButton() function ShowBackButton() if(GUI.Button(Rect(20, Screen.height 50,50,20), "Resume")) UnPause() function IsBeginning() return Time.time lt startTime I think it's just a case of a new set of eyes. But by my logic this should work.


How can I draw a line of the raycast hit in game view while the game is running? using System.Collections using System.Collections.Generic using UnityEngine public class CameraRaycast MonoBehaviour public Camera cam public LineRenderer laserLineRenderer public float laserWidth 0.1f public float laserMaxLength 5f void Start() Vector3 initLaserPositions new Vector3 2 Vector3.zero, Vector3.zero laserLineRenderer.SetPositions(initLaserPositions) laserLineRenderer.startWidth laserWidth laserLineRenderer.endWidth laserWidth void Update() Ray ray cam.ViewportPointToRay(cam.ScreenToViewportPoint(Input.mousePosition)) RaycastHit hit if (Physics.Raycast(ray, out hit, 100)) if (hit.transform.tag "Interactable") print("I'm looking at " hit.transform.name) laserLineRenderer.enabled true laserLineRenderer.SetPosition(0, ray.direction) laserLineRenderer.SetPosition(1, hit.transform.position) else print("I'm looking at nothing!") laserLineRenderer.enabled false When it detect a "Interactable" object i want it to draw green line from the mouse cursor to the point where the raycast is hitting. Now it's not drawing anything.


Ordering a List doesn t work. InvalidOperationException Operation is not valid due to the current state of the object I have this method. It s for ordering actors and only displaying the ones which are in direct line of sight with the player. public Actor OrderActorListByDistance(List lt Actor gt list, Vector2 pos) return list.FindAll(d gt Physics2D.Linecast(d.transform.position, pos, LayerMask.GetMask("Default")).collider null).OrderBy(i gt Vector2.Distance(pos, i.transform.position)).First() But that Method throws that error InvalidOperationException Operation is not valid due to the current state of the object I already made a lot of google research but I couldn t find any solution. I would appreciate any suggestion or help. Thanks in advance


stepOffset wont work I made a model of a staircase in blender and loaded it into unity. Now my player cant go up the stairs while it can walk up a slope just fine. I have tried puting the stepOffset at different levels,


Does anyone have a example of Dual Contouring in C ? I'm trying to develop a method of creating terrain using Perlin. I've followed plenty of the Minecraft tutorials, and got them to function. I've done some playing around with MarchingSquares, but I'm not digging it. Now, I've been trying to create a method of dual contouring, and I'm also trying to get the concept of Octrees down at the same time. I used to segment my array of data in small chunkes, but the whole Collapsing and making a larger "chunk" function like a smaller chunker is just not regiserting. I was hoping someone can share some C code, preferably for Unity but really just something for me to try to pick apart to understand would help. When it really comes down to it, I'm not trying to make a game where different "voxels" aren't different types of blocks, just represent where dirt is and where dirt isn't. In game, I want dirt to be taken away due to explosions, but not have a method of placing dirt. I'd like this effect for large enclosed game levels. Any comments or advice are appreciated.


How to achieve this sprite mesh tile splitting like in Peggle? Everyone knows Peggle. Here's a simple screenshot from one of their 'shapes' On the first look, it looks so simple. It's a circle made of identical tiles It's easy to make a circle like this, even programatically. But then I realised that I can't make bigger smaller circles with this single tile. For instance, the shape above has 17 tiles. If I want to make a circle with 9 tiles, I need to make a tile more curved, so it can close the entire shape with 9 elements. Here's a sample of a shape which cannot be constructed using the above tile As you can see, it's probably made dynamically. Each tile has different size and it's warped differently and I don't think so that they've used 30000 types of tiles with multiple angles. They did actually, in the first version of the game coded in Lua, but there were 3 5 types of tiles. In their latest game, they've created more exotic shapes, and that would be so inefficient, especially for mobiles. Are there any algorithms for filling an oval or circle with irregular tiles like this? I assume I'd need to split some meshes dynamically for that, or at least sprites. I'll be thankful for pointing me a right direction!


Something is preventing my NavMeshAgent from moving I apologize for the vague title. I really wish I could ask something more specific, but I can't. I had my click to move script working fine with the NavMesh. I showed it to my colleague earlier today, and must have accidenntally made a change and saved. Now the guy's not walking. There are no errors and my debugging leads me to believe all code paths are working as expected. When I click on a location, it checks that it is valid on the NavMesh, then updates the NavMeshAgent's destination I am not going to post the code because I don't think the problem resides there, but rather it was something I did in the editor. The character also turns in the correct direction, and starts the walk animation correctly, but it looks like something is blocking its movement, and I can't figure out what that is. The following screenshots will help clarify my situation. Note that the camera is shaking because its position is set to match the character's in Update. The character appears to be colliding with something, which makes it look like the camera is colliding too (note this is not a physics based game in any way). edit here's some more screenshots, showing the person slightly above the ground and their collider (it's the box near their feet). I disabled the collider on the floor so there are no colliders other than the player's.


Character keeps falling through the terrain and jittering I honestly don't know what the problem could be anymore. I have a humanoid character with animations, and a charactercontroller. I also have a ragdoll (seperately) that only follows the animations through script (doesn't do anything else). the ragdoll has a script on both feet, with colliders and rigidbody's, and sets a bool to true when either of them hits something. It also has an update function that casts a ray, and sets that same bool when it hits something. this way i know if it is grounded or not. the charactercontroller is also used to see if it is grounded or not. In my control script I translate the character downward when it is not grounded, and set that gravity vector to 0 if it is. the collisions work, the raycasts work, and the charactercontroller work, but still the character falls through. i've also tried increasing the solver settings, turning off auto simulation and PCM, increasing the contact offset to the point where it floats above the ground, and still falls through. All the scripts use update functions, but the behaviour is the same in FixedUpdate. I tried with and without rigidbody's in the charactercontroller, and with and without charactercontroller itself. this part of code is for movement bool walking skaterParams.walking if (walking amp amp !Onboard amp amp !Helper.bailing) moveDirection.y 0 moveDirection new Vector3(Input.GetAxisRaw("Horizontal"), 0.0F, Input.GetAxisRaw("Vertical")) moveDirection transform.TransformDirection(moveDirection) moveDirection speed if (Input.GetKeyUp ("joystick button 1")) moveDirection.y jumpSpeed if (!walking amp amp !Onboard) moveDirection.y gravity Time.deltaTime if (!Onboard amp amp !Helper.bailing) Char.transform.Translate (moveDirection Time.deltaTime 10) i could also share the code for seeing if he is grounded, but i'm trying to limit the post here, to not have too much text. I just know it works, but it's just not consistent. When setting auto simulation to true, the ragdoll is also extremely jittery... the ragdoll and character are on seperate layers and cannot collide. The raycasts have a layermask set to the terrain layer.


Speedup Dev process for bug fixing and debugging in Unity? We're using Unity 2017 for a big Indie game. at the moment We have some issues with our development speed In order to fix issues and bugs, We used the visual studio and attach the process to Unity and go through the code step by step. every time we change something (even just a line of code) we back to unity and wait for all scripts to recompile which takes up to 1 minutes sometimes. after that, we run the game and go to the place that bug happened which takes us about two minutes. I was wondering if there was a Best practice for fixing issues and debugging in Unity which brings us speedup on script compiles and also helps us to get to bug location faster.


Why isn't my BoxCollider2D doing anything? I'm trying to make a speech bubble appear when you approach the tutorial board. The bubble is there and it has its animation states "Appear" and "Disappear" Appear is called OnTriggerEnter2D Disappear is called OnTriggerExit2D The collider is on the parent, tutorial board The animator and script are on the bubble itself. This is the script I have attached to the bubble, the conditions script. using System.Collections using System.Collections.Generic using UnityEngine public class Conditions MonoBehaviour private Animator bubblecondition private BoxCollider2D boxCollider Start is called before the first frame update private void Awake() bubblecondition this.GetComponent lt Animator gt () bubblecondition.Play("Disappear", 0, 1f) void Start() bubblecondition.SetBool("Here", false) boxCollider this.GetComponentInParent lt BoxCollider2D gt () Update is called once per frame void Update() public void OnTriggerEnter2D(Collider2D other) if (other.tag "Player") bubblecondition.Play("Appear", 0, 0f) else return public void OnTriggerExit2D(Collider2D other) if (other.tag "Player") bubblecondition.Play("Disappear", 0, 0f) else return What am I doing wrong? I spent an hour trying to know why. I even tried to have the console write a message on collision but it's just dead. Not only that, but I also tried to make it public and referenced it, still nothing. Help me see my mistake )


Change button sprites in scrollview Unity3D 5.2 I have a scroll view with lots of buttons on it. when i press one button, that button needs to change the sprite and stay like that. if any other button (or same one) is pressed previous button needs to revert back to original sprite.. here is some example button 2 was pressed and changed sprite, it stays like that untill it is pressed again or any other (in this case button 3) is pressed


Unity Render Texture Artifacting I'm having weird black artifacts appear on my render textures when they are transformed while the game is running. I am using a ScrollRect as a scrolling container for buttons (the buttons are just textured quads with the same render texture applied to them). When I translate the quads while the game is running, strange black artifacts will appear on the quads themselves. Is there a way to fix this? Edit Interesting to note, setting every quad inactive except for one fixed the artifacting on the only visible quad http i.imgur.com OInBBWs.png The intensity of the artifacting seems to be related to the number of objects on screen that use the same render texture. 5 quads active with the same render texture has a really pronounced artifacting, 3 is more subtle, 1 is visibly non existent.


How to create in game menu attached to unit I'm creating a game similar to Banner Saga, except my game will be in 3D, with a camera that can move around and zoom in and out. What I want is for a menu to appear after the user clicks on a unit. This menu must always be visible and facing the camera. The menu that has the foot and sword symbols is what I want. How can I get a similar result in 3D? The new Unity UI canvas isn't really suitable, since the camera will move around, and the menu must stay next to the unit. The menu elements can't be covered up by things in front of it, like other units. Thanks


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


Is Time.deltaTime different on various devices? Can someone say what is wrong with my code. I have custom timer implemented like this float timeRemain 10f void Update() timeRemain Time.deltaTime if(timeRemain lt 0) ...code here. On PC it runs like expected but on Android device timeRemain variable becomes 0 in less then 10 secs. Who can suggest me what happens when i run it on Android device?


Adjust Line Renderer start position to follow bone rotation I'm trying to make my first game in Unity and I want a line renderer to draw from the end of a turret's gun barrel. The problem is I'm rotating 2 bones in the turret to make it look at the enemy. I've used the bounding box of the turret to calculate the offset from the turret's origin to the end of the gun barrel. But when the turret rotates this position is obviously wrong. How can I calculate the correct starting point for the line renderer after performing a rotation? Here is the code for the rotation and the line renderer void Start () enemyManager GameObject.Find("EnemyManager").GetComponent lt EnemyManager gt () lazerLine GetComponent lt LineRenderer gt () platform transform.root.Find("Armature BaseBone PlatformBone") Get the root transform of this turret (I.e. the turret itself, not the gun barrel) gunBox transform.root.FindChild("Armature BaseBone PlatformBone LowerArmBone UpperArmBone GunBoxBone") gunBounds transform.parent.GetComponent lt SkinnedMeshRenderer gt ().bounds.size Get the bounding box of the turret void LateUpdate() Vector3 lookAt Quaternion platformRotation Vector3 gunLookAt Quaternion rotation if (enemiesInRange.Count gt 0) Rotate Platform (The silver platform at the base of the turret) lookAt enemyManager.activeEnemies enemiesInRange 0 .transform.position platform.position lookAt.y 0 0 the Y axis to stop the turret tilting up or down platformRotation Quaternion.LookRotation(lookAt) float rotateSpeed 10.0f Time.deltaTime platform.rotation Quaternion.Lerp(platform.rotation, platformRotation, rotateSpeed) Rotate GunBox gunLookAt enemyManager.activeEnemies enemiesInRange 0 .transform.position gunBox.position rotation Quaternion.LookRotation(gunLookAt) gunBox.rotation Quaternion.Lerp(gunBox.rotation, rotation, rotateSpeed) if (timer lt effectsDisplayTime) Vector3 lazerStart transform.position Adjust the lazer to draw from the default position of the top gun barrel (using the bounding box of the turret to calculate the position) lazerStart.y (gunBounds.y 0.85f) lazerStart.z (gunBounds.z 2) 0.05f Adjust the lazer to follow the current rotation of the gun This is the part I need to add Draw the lazer lazerLine.enabled true lazerLine.SetPosition(0, lazerStart) lazerLine.SetPosition(1, enemyManager.activeEnemies enemiesInRange 0 .transform.position) Of the enemies in range, shoot the first enemy that entered the turrets range effectsEnabled true Here are 2 picture to give you a better idea of what's happening. This is with the rotation code commented out. This is with the rotation code running.


Events vs direct reference in Unity3D? I'm developing a simple NPC controller that the player can talk with. At the moment a NPCController script on the NPC gameobject manages several "high level" feature of the NPC such as intelligence. Every time the player talks with the NPC, the latter will respond with "Bzz", "Hello" or "Heya" depending on his intelligence level. The talking part is implemented in a TalkController script. I did this way in order to have multiple behaviours depending on the player npc interaction without creating a giant NPCController class. Plus some NPC may not speak at all (in this case I'd simply remove the TalkController). I have a small dilemma on how to change the NPC response in TalkController based on the intelligence level in NPCController. I could use Events NPCController.cs public delegate void OnIntelligenceLevelHandler(int level) public static event OnIntelligenceLevelHandler OnIntelligenceLevelChanged When intelligence increases OnIntelligenceLevelChanged(2) and TalkController.cs Store intelligence 1 Subscribe to OnIntelligenceLevelChanged Upgrade intelligence when the event fires Switch word on intelligence when talking I could use a direct reference TalkController.cs Store npccontroller GetComponent lt NPCController gt () Switch word on npccontroller.Intelligence when talking What would be the best approach?


Unity 2D Diablo style movement I've made a totally new scene for a 2D mobile game. I placed a sprite on the center of the screen and attached the following script onto it (this is basically a diablo style click to move control script, the sprite follows the pointer when it is clicked) using UnityEngine public class Movement MonoBehaviour private float moveSpeed 5 private Vector3 targetPosition private float targetDistance void Update() targetDistance Vector3.Distance( targetPosition, transform.position) if ( targetDistance lt 1) moveSpeed 0 else if ( targetDistance gt 1) moveSpeed 5 if (Input.GetMouseButton(0)) Plane playerPlane new Plane(Vector3.up, transform.position) Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) float hitdist 0.0f if (playerPlane.Raycast(ray, out hitdist)) targetPosition ray.GetPoint(hitdist) if ( targetDistance gt 1) transform.position ( targetPosition transform.position).normalized moveSpeed Time.deltaTime Normally this script doesn't work unless I rotate the main camera by 90 degrees (axis X) and rotate the sprite also by 90 degrees (axis X). How should I modify the script to make it work without rotating the camera and all the sprites I place on the scene? Thank you in advance!


Issuing one to one inter player challenges I have a small game I have written in Unity (at present only for Android). It is a very simple game where you get more points the longer you last. Nothing complicated. In order to help "spread the word," I want to enable players to challenge others to see who can score higher. I am not talking about their all time high scores (these I save in the Google Game Play leaderboards). How can I easily manage a one to one challenge? I can't seem to find a straight forward way to do it using the Google SDK. It has the turn based play option but in my case each one plays separately. When both have played, the results get compared. Short of setting up my own backend, how can I go about this? Note I am happy to use the FB SDK if necessary since that is how the challenges will be generally sent.


How can I plug a Unity application into native Android and native iOS? There are a lot of questions about running native Android and iOS code in Unity. I am trying to run Unity inside of native Android and native iOS apps. My problem is that I have two native apps, and I don't want to write code twice when I add a feature. I currently have two native apps one in Android and one in iOS. I am trying to write code once, and add it to both. Can I write a Unity program, and put that into my native apps? I am thinking something along the lines of writing a Unity Android app, building it as an Activity instead of an APK, and launching that Activity from the native android app. Then also the equivalent in iOS, whatever that may be. Does anyone know a solution to this problem?


Unity Change Sceneview to camera view On selecting camera, I get the camera preview. In Unity, while editing the scene, I wish to switch in such a perspective view that is exactly visible by the main camera. Is there a short cut to change the view?


Unity5 UI How to trigger button click event while preventing menu item deselect event? So I've got a load menu using Unity's new UI system, basically just a list of save games you can select with a mouse click along with a couple of buttons at the bottom to delete or load the selected game file. I've been disabling the Load Game and Delete Game buttons using the interactable attribute whenever a saved game item in the list is deselected deleteButton LoadPanel.GetComponent lt Button gt ().interactable false loadButton LoadPanel.GetComponent lt Button gt ().interactable false This disables the buttons fine, but when I click on a saved game and then click a button, the deselect event for each save file is triggered BEFORE the onclick event for each button. This is no good. If I have no deselection event for each individual save file I can click on each save file and then click the load or delete buttons and every thing works fine, but the buttons never get disabled which is not ideal. My question is How can I disable the buttons when an item is deselected, but still trigger the onclick event when they are selected? Are there any workarounds to this?


What are the legal issues when using free Unity Assets on a commercial game? In the unity asset store one can find tons of thousands of assets, a lot of them being distributed for free. When using a free Unity Asset is it implied that you can do anything with it(commercial or not)? Is there any legal agreement concerning free Unity Assets?


How can i put a skybox on a new layer with a new camera and then move the skybox? I want to create a moving start effect. For example the space station is moving around the star or moving to the star. But instead moving the space station i think it will be better to make effect of the skybox moving. I have in the Hierarchy a RigiBbodyFPSController and a child MainCamera. Now i added a new Camera to the Hierarchy. Now how do i make the rest ? Moving the new camera and the skybox to new layer and move the skybox ? Or it's more logic to say to move the new camera that the skybox is with in it in the new layer. Not sure if my idea is logic or if there are a better ways to do it. The general idea is to make movement effect like the space station is moving around the star or to the star. Star i mean the skybox. The skybox is on the right. I can't see the skybox in the scene view i see it only when running the game in the game view. This is a screenshot when the game is running then i can see the skybox in scene view and game view


Unity point light baking into lightmap I'm developing a puzzle with a ball with cracks on it. Inside the ball there's a point light. Its light rays come out of the cracks and hit some platforms (walls ceiling floor). To solve the puzzle the player must rotate the ball to match the light coming out of the cracks with some pre lit pattern on the platforms. I don't know how to do the pre lit pattern. I don't want it to be manually done using a texture editing tool like Photoshop or GIMP. I remembered this could probably be done using light baking. I think what I need is to bake the light from only that point light into a lightmap and use it only on those platforms, but don't know how to do that. Can someone help me with a solution?


How to prevent unwanted scaling of textures in world space I allow players to select buildings of different sizes in my game, in the image below is a building that is 30x30 units and one that is 10x10 units. To indicate that the building is selected, I added a child called Selection indicator, this child is simply a texture dragged into the scene, which creates a plane. I activate deactivate this on select deselect. So far so good, but as you can see in the image, in order to match the different sizes, I need to scale the Selection indicator, which distorts its edges. Simply using sprite editor here does not seem to change anything since it's in world space. How could I approach this in a way that the frame for my Selection indicator does not stretch like in the image?


Is it possible to detect a collision between a sprite and a UI image in Unity? I have a stationary sprite with the tag "Player" with a Rigidbody2D (dynamic body type and discrete collision detection) and circle collider 2D. I also have a moving UI image also with a Rigidbody2D (dynamic body type and discrete collision detection) and circle collider 2D. I want to detect when the moving UI Image collides with the sprite, however I'm not getting the print statement inside of the OnCollisionEnter2D() function below whenever I see them collide on the screen. public class MeteorController MonoBehaviour float xCoor float yCoor float newXCoor float newYCoor Vector3 newPos float speed 1.25f Start is called before the first frame update void Start() xCoor transform.localPosition.x yCoor transform.localPosition.y newXCoor xCoor 1 newYCoor yCoor 1 newPos new Vector3(newXCoor, newYCoor, 0) Update is called once per frame void Update() transform.Translate(newPos Time.deltaTime speed) void OnCollisionEnter2D(Collision2D coll) if (coll.gameObject.tag "Player") SceneManager.LoadScene("PlanetSpawningTest") print("PLAYER") else if (coll.gameObject.tag "Planet") print("PLANET")


How can I get the Launch dynamic link in Unity? I have integrated firebase dynamic link sdk in my app and it is working perfectly fine, I can generate dynamic links, and when clicked on them if the app is not installed it redirects me to the playstore and if installed open up the link in app. My question is how can I get that generated link when I open the app through it, I just could not able to find anything in docs the code I am using to listen for link clicks is as follows void Start() DynamicLinks.DynamicLinkReceived OnDynamicLink Display the dynamic link received by the application. private void OnDynamicLink(object sender, EventArgs args) var dynamicLinkEventArgs args as ReceivedDynamicLinkEventArgs Debug.LogFormat("Received dynamic link 0 ", dynamicLinkEventArgs.ReceivedDynamicLink.Url.OriginalString) Above line gets me the original base link, But I want the link which I clicked


Unity3D and Texture2D. GetPixel returns wrong values I'm trying to use Texture2D set and get colors, but I encountered a strange behavior. Here's the code to reproduce it Texture2D tex new Texture2D(2,2, TextureFormat.RGBA32 ,false) Color col new Color(1.0f,0.5f,1.0f,0.5f) col values 1.00, 0.500, 1.00, 0.500 tex.setPixel(0,0,col) Color colDebug tex.getPixel(0,0) col values 1.00, 0.502, 1.00, 0.502 The Color retrieved with getPixel is different from the Color set before. I initially thought about float approximation, but when inspectin col the value stored are correct, so can't be that reason. It sounds weird even a sampling error because the getValue returns a value really similar that not seems to be interpolated with anything else. Anyway I tried even to add these lines after building the texture but nothing change this.tex.filterMode FilterMode.Point this.tex.wrapMode TextureWrapMode.Clamp this.tex.anisoLevel 1 What's my mistake? What am I missing? In addition to that. I'm using tex to store Rect coordinates returned from atlas generation, in order to be able of retriving the correct uv coordinate of an atlas inside a shader. Is this a right way to go?


ScriptableObject not working after build in Unity? I have a GameObject with a ScriptableObject on it, stats. It works fine in editor but when I try to build I get a message, A script behaviour (script unknown or not yet loaded) has a different serialization layout when loading. What is wrong here?


Unity3D, How do I press one key and then cant press another key while the one is pressed? I am making a horror game, and I want to press a key to look up while I am idle, that i've done but if I press the W key it stands in idle but floating forward. How can I disable the W key while I press the F key to look up ? Everything works fine I can press F and the LookUp Animation is being played and if KeyUp on F the Animation goes back to Idle. My problem is if I am in LookUp Animation when I press F, I can also press W to go forward but its floating not walking. I want to deactivate this function so I can just press F when I am Idle. Thanks for help. my Script public float speed 10f public Rigidbody rgb public Animator anim bool walk false Use this for initialization void Start () rgb.GetComponent lt Rigidbody gt () anim GetComponent lt Animator gt () Update is called once per frame void Update () float move Input.GetAxis ("Vertical") anim.SetFloat ("Speed", move) if (Input.GetKey (KeyCode.W) walk true) rgb.transform.position new Vector3(0, 0, 1) speed Time.deltaTime Debug.Log("Walking") else walk false Debug.Log("Idle") if (Input.GetKey (KeyCode.F)) anim.SetBool("LookUpIdle", true) rgb.transform.position transform.position else anim.SetBool("LookUpIdle", false)


How can I record and replay axis input accurately for testing? I want to do integration testing for an old C Unity project. The project uses its own input system, so I can't use inputEventTrace or any other convenient Unity class. So I subscribed a new game object to the custom input system so that it records any input detected in each frame. But when I replay, because of the difference in frame times, the replays are not quite equal to the original playthrough (especially because of the axis input). My understanding is that input in Unity is not event based, so I can't think of any way to perfectly mimic the input given different frame times. Does anyone know of a way to do this?


transform.Rotate needs to change axis of rotation So I'm making a game in Unity. After many failed attemps from either being bored of the idea, or something going wrong and me giving up I think (hope) that will be the good one. I have made a simple racing game with a track and a car. I am using transform.Translate to move it, but when I use transform.Rotate to turn it goes around the x axis. How do I change the axis it goes around? I cant find anything online. if (Input.GetAxisRaw("Horizontal") gt 0.5f) transform.Rotate(Vector3.right Time.deltaTime handling) if (Input.GetAxisRaw("Horizontal") lt 0.5f) transform.Rotate(Vector3.left Time.deltaTime handling) if (Input.GetAxisRaw("Vertical") gt 0.5f Input.GetAxisRaw("Vertical") lt 0.5f) transform.Translate(new Vector3(0f, Input.GetAxisRaw("Vertical") moveSpeed Time.deltaTime, 0f)) Thanks for any help you can give me.


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


Write Data From List To CSV File I am trying to write to a CSV file the values that I put in lists from a key press in the keyboard. It does work somehow but in my csv file I get the values 2 times. Also, when I put values to only one of the lists, I don't get any data to CSV file. How can I save the values from the lists to my csv file but to be independent from each other? This is my code using UnityEngine using System.Collections using System.Collections.Generic using System.Text using System.IO using System public class record MonoBehaviour public List lt string gt inventory new List lt string gt () public List lt string gt OnlyX new List lt string gt () void Update() if (Input.GetKeyDown(KeyCode.F)) inventory.Add("F") if (Input.GetKeyDown(KeyCode.J)) inventory.Add("J") if (Input.GetKeyDown(KeyCode.X)) OnlyX.Add("X") string filePath getPath() StreamWriter writer new StreamWriter(filePath) writer.WriteLine("Inventory,OnlyX") for (int i 0 i lt inventory.Count i) for (int j 0 j lt OnlyX.Count j) writer.WriteLine(inventory i "," OnlyX j ) writer.Flush() writer.Close() private string getPath() if UNITY EDITOR return Application.dataPath " Data " "Saved Inventory.csv" elif UNITY ANDROID return Application.persistentDataPath "Saved Inventory.csv" elif UNITY IPHONE return Application.persistentDataPath " " "Saved Inventory.csv" else return Application.dataPath " " "Saved Inventory.csv" endif


Panning value of 2nd GameObject's AudioSource is not initializing I'm making a prototype and stuck in a problem where two GameObjects swap but there values of panStereo of AudioSource is not initializing from a float array which contains all the default values of panStereo of all the GameObjects in a scene panningArray new float Inventory.bowlsManager.BowlPanningValues.Length for (int i 0 i lt Inventory.bowlsManager.BowlPanningValues.Length i ) panningArray i Inventory.bowlsManager.BowlPanningValues i Selectable false SelectedBowl.GetComponent lt AudioSource gt ().spatialBlend SelectedBowl2.GetComponent lt AudioSource gt ().spatialBlend 1 iTween.MoveTo(SelectedBowl, iTween.Hash( quot position quot , temp2, quot time quot , transitionspeed)) iTween.MoveTo(SelectedBowl2, iTween.Hash( quot position quot , temp, quot time quot , transitionspeed)) SelectedBowl.GetComponent lt Renderer gt ().material SubsituteMaterial SelectedBowl2.GetComponent lt Renderer gt ().material SubsituteMaterial int SelectedBowlIndex Array.FindIndex(Inventory.allBowls.ToArray(), x gt x SelectedBowl.GetComponent lt Bowl gt ()) int SelectedBowlIndex2 Array.FindIndex(Inventory.allBowls.ToArray(), x gt x SelectedBowl2.GetComponent lt Bowl gt ()) print(Inventory.bowlsManager.BowlPanningValues SelectedBowlIndex2 ) print(Inventory.bowlsManager.BowlPanningValues SelectedBowlIndex ) val1 BowlPanning(SelectedBowl2 , panningArray SelectedBowlIndex ) val2 BowlPanning(SelectedBowl , panningArray SelectedBowlIndex2 ) Here is my bowl panning function public float BowlPanning(GameObject BowlRequire,float value) BowlRequire.GetComponent lt AudioSource gt ().panStereo value return BowlRequire.GetComponent lt AudioSource gt ().panStereo


Smooth Flat shaded meshes cause shadow artifacts (understanding the source of the problem) I'm using blender to create assets to use in Unity3D, and I'm having some trouble understanding how the smooth flat shading interacts with shadows, I'm sorry if it has been asked before, but all the "related" answers refer only to the shading of the object itself, not the shadow it casts. I'm a 3D artist, I do not understand Unity and the mechanics behind it the same way I understand 3D stuff, I'm also trying to understand if the problem lies in the 3D object or some configuration in Unity. I'm using a real time directional light. 1 and 2 are flat shaded. 2 has open geometry while 1 has closed geometry, both have such artifact but it's clearly seen on 2. 3 and 4 both have closed geometry. 3 is fully smooth shaded while 4 is flat shaded. Solution A Mess around with Bias and Normal Bias. With Normal Bias at 0, the shadow artifacts are gone but the mesh itselt gets some other artifacts. Solution B Use Two sided shadows, this method completely fixes the problem, in any situation, but it adds another draw call and makes it more expensive (I'm not 100 sure it does) is this an optimal solution? This same issue was discussed in a closed group but no one could give me a conclusive answer. However, someone who works with 3DS Max said that exporting a mesh with proper smoothing groups does not result in these artifacts, I tested that in 3DS Max and it did not work I think I did it the right way, but I'm not 100 certain. For all the proposed methods, I tested several times, with diferent mesh modifier and exporting options. I'm using mostly .fbx but I also tested in .obj format (which includes a specific option for smoothing groups in blender). Smooth shaded objects work perfectly, flat or smooth flat shaded objects result in this drama. Please help me to bring light to this issue, I might be blind to some obvious aspect, I'm confused because in the other discussion I was presented with contradicting arguments without conclusive proof of anything. Now I don't know if the problem lies with Blender export or Unity configuration. Let me know if I can provide more information.


How can I make an instantiation random? I'm trying to do it so when I have an instantiated an item upon the game starting, it is random as to whether it actually instantiates or not. Here's the code I have so far public GameObject anyItem void Start() Instantiate(anyItem, new Vector3(0, 0, 0), Quaternion.identity) Instantiate(anyItem, new Vector3(11, 0, 0), Quaternion.identity) How can I do it so these items (individually, not both together) are decided randomly as to whether they will actually be instantiated or not?


How do I resolve the error "Trying to send command for object without authority."? I don't know what I did wrong I tried couple different ways from not using commands to using SpawnWithClientAuthority. But It either gives build and compile errors or just the Error in the title Here the Start function of my player object void Start () player isLocalPlayer race Data.races (int)selectRace .getInstance() clss Data.classes (int)selectClass .getInstance() health race.Health clss.HealthMultiplyer speed race.Speed clss.SpeedMultiplyer armor race.Armor clss.ArmorhMultiplayer energy race.Energy clss.EnergyMultiplayer skills.AddRange(race.RaceSkills) skills.AddRange(clss.ClassSkills) Data.entities.Add(this) Debug.Log(isLocalPlayer) if (!isLocalPlayer) return int enID Data.entities.IndexOf(this) foreach (Skill s in skills) s.CmdSpawn(enID) And here is the spawn functions from skills I try to spawn Command public override void CmdSpawn(int enID) setEntity(Data.entities enID ) Debug.Log("Spawned") dir getEntity().lookingAt gameObject.transform.position getEntity().transform.position dir 0.65f transform.up dir NetworkServer.Spawn(gameObject) and Command public override void CmdSpawn(int enID) setEntity(Data.entities enID ) dir getEntity().lookingAt transform.up dir dir new Vector3(dir.z, dir.y, dir.x) gameObject.transform.position getEntity().transform.position dir 0.65f NetworkServer.Spawn(gameObject) If you can help, thank you .


Authoritative Server for single player but with leaderboard I made a Fps single player, timed survival with a leaderboard ( a bit like devil daggers and others). I know would like to create a server that will prevent cheats such as avoiding collision or altering the timer. My issue is I don't know the theory on how should my server behave. Should it run an instance of the game per player which will handle the collision and other stuff for that player ? is this viable Any advice ?


What exactly is the "blend factor" t in Color.Lerp? I had a bit of a look around and couldn't see anywhere this was addressed, my apologies if it has been. In Color.Lerp, I understand that the 3rd parameter t is not in fact the time that it takes to change between the colors but is rather the "blend factor". If the first color is at 0 and the second is at 1, then a blend factor of e.g. 0.2 would indicate it is closer to the first than the second. My confusion is this how exactly is it determined how long it takes the lerp to occur? I assume it's something to do with the frames per second? e.g. if the blend factor is 0.001 and frames per second are 50, with lerp in the update function then it should take 0.001 50 0.05 of a second for the change to occur?


Is it really more efficient to have a local variable for transform here or is Rider being over zealous? I'm just going through a quick C Unity crash course (coming from Java) and I recieved a warning about "Repeated property access of a built in component is inefficient" while working in Jetbrains Rider for the following code snippet. if (Mathf.Abs(horizontalMovement) gt Mathf.Epsilon) horizontalMovement horizontalMovement Time.deltaTime var position transform.position horizontalMovement position.x position new Vector2(horizontalMovement, position.y) warning is for this line transform.position position It was already complaining about using transform.position.x and transform.position.y which seemed fair enough so I created the position var but would declaring var cachedTransform transform ... cachedTransform.position position really be more performant here or is the overhead of creating the local variable just going to negate it? I'm not asking if this is a valid warning in general, it seems to be. I'm asking if it's valid when you're literally just reassigning in the same statement as I am in the last line of my code above For reference here's what I would end up with if I followed the warning if (Mathf.Abs(horizontalMovement) gt Mathf.Epsilon) horizontalMovement horizontalMovement Time.deltaTime var cachedTransform transform var position cachedTransform.position horizontalMovement position.x position new Vector2(horizontalMovement, position.y) cachedTransform.position position


Strange problem with rotation missile unity3d c I have a vertical missile with launcher that should find closest target and fire it's rocket to hitting target! I use complete code of this 12min tutorial for launching my rocket, and the different between mine and its about the direction of rocket, mine is vertical and its horizontal! homingMissile.velocity transform.forward missileVelocity Quaternion targetRotation Quaternion.LookRotation(target.position transform.position) homingMissile.MoveRotation(Quaternion.RotateTowards(transform.rotation, targetRotation, turn)) After running the code, the rotation of my rocket change from (0,0,0) to ( 8 .3, 4.7,0)!!!! and just change a little while hit target and explosion do. In fact my rocket move to target in right path, but in wrong rotation!, in STRANGE! Standby Rocket Moving to Target Anyone can help me for this problem?


Do I need a server if I only want to upload data to a DB? I'm currently creating a game where people get some kind of reports for their game performance on a website. Let's say, you log in, play the game, the system gathers your performance data and this is being sent to a database so that it can be read and interpreted by an external website later. For this, I'm using a firebase real time database and it's working fine by now. I'm pretty noob with unity and I have read and watch tutorials on the internet where people actually create a server to achieve this but do I really need a server when the only thing I need to do is to post data to a database based on users? This isn't really a multiplayer game, but there is some kind of information which is shared for example sometimes I need to get those data in order to get high scores and that kind of small information, but that's it. I'm using unity webgl and firebase for the moment, and everything is working fine, but then why people always create a server for this? PS sorry for my bad english


Why does unlocking cursor with keyup behave the same as unlocking it with keydown? To understand the difference, let me review a bit about the behavior of GetKeyUp and GetKeyDown with the following code snippet. void Update() if (Input.GetKeyDown(KeyCode.Escape)) Debug.Log("Escape Key Down") if (Input.GetKeyUp(KeyCode.Escape)) Debug.Log("Escape Key Up") Right after pressing the Esc key (and holding it), a message "Escape Key Down" is produced. Later right after releasing the key, a message "Escape Key Up" will show. The behavior does make sense. Now I apply this for toggling (locking unlocking) the mouse cursor. Here is my code snippet. void Update() if (Input.GetMouseButtonDown(0)) Cursor.lockState CursorLockMode.Locked Cursor.visible false if (Input.GetKeyUp(KeyCode.Escape)) Cursor.lockState CursorLockMode.None Cursor.visible true Right after clicking the left mouse button, the cursor becomes invisible. However, right after pressing down the Esc key, the cursor becomes visible again. The expected behavior is that the cursor will be visible right after releasing the Esc key rather than right after pressing the key. Question How to fix this abnormal behavior?


How can shader code duplication be reduced in Unity? In our current Unity project we have a few shaders that are basically just supersets of another shader. For example, we have a shader that performs lighting calculates with diffuse, normal, specular, and gloss maps, and a shader that performs lighting calculations with a diffuse, normal, specular, gloss, and glow map. The first is a subset of the second, but for performance reasons we've decided to separate them. This leaves us with heaps of duplicated code. On top of this, I need to add stencil buffer operations to some of these materials, which is about 3 lines, but from what I can see, requires the entire shader file to be copied again. How can we reduce this code duplication? In an object orientated language we'd used inheritence and polymorphism. What can we do here?


Share content FROM Facebook, not to it Regarding Unity 2018.x The Facebook SDK provides a way to get log in information from a user's FB account, and allows information or an image from an app to be shared TO Facebook. Is it possible to link access reference or in any other way make use of a specific image on Facebook within my Unity app? Ideally, I would like to be able to access the image upon target recognition and, even better, store the image for subsequent display within the app. Finally, even more ideally ideally, this would not be the FB profile picture. All suggestions and links welcome.


The rightmost part of the game screen is truncated in HTML I created a game that, when I play it in Unity, looks like this But when I build it in WebGL, the rightmost part of the screen (with the red player character in it) is truncated Play it in browser on itch.io to confirm. It looks the same when I open the HTML file locally, so the problem is with the WebGL version and not with itch. Only when I click the "full screen" button, the rightmost part is shown. What am I doing wrong?


Blender mesh mirroring screws up normals when importing in Unity My issue is as follows I've modeled a robot in Blender 2.6. It's a mech like biped or if you prefer, it kindda looks like a chicken. Since it's symmetrical on the XZ plane, I've decided to mirror some of its parts instead of re modeling them. Problem is, those mirrored meshes look fine in Blender (faces all show up properly and light falls on them as it should) but in Unity faces and lighting on those very same mirrored meshes is wrong. What also stumps me is the fact that even if I flip normals in Blender, I still get bad results in Unity for those meshes (though now I get different bad results than before). Here's the details Here's a Blender screen shot of the robot. I've took 2 pictures and slightly rotated the camera around so the geometry in question can be clearly seen Now, the selected cog wheel like piece is the mirrored mesh obtained from mirroring the other cog wheel on the other (far) side of the robot torso. The back face culling is turned of here, so it's actually showing the faces as dictated by their normals. As you can see it looks ok, faces are orientated correctly and light falls on it ok (as it does on the original cog wheel from which it was mirrored). Now if I export this as fbx using the following settings and then import it into Unity, it looks all screwy It looks like the normals are in the wrong direction. This is already very strange, because, while in Blender, the original cog wheel and its mirrored counter part both had normals facing one way, when importing this in Unity, the original cog wheel still looks ok (like in Blender) but the mirrored one now has normals inverted. First thing I've tried is to go "ok, so I'll flip normals in Blender for the mirrored cog wheel and then it'll display ok in Unity and that's that". So I went back to Blender, flipped the normals on that mesh, so now it looks bad in Blender and then re exported as fbx with the same settings as before, and re imported into Unity. Sure enough the cog wheel now looks ok in Unity, in the sense where the faces show up properly, but if you look closely you'll notice that light and shadows are now wrong Now in Unity, even though the light comes from the back of the robot, the cog wheel in question acts as if light was coming from some where else, its faces which should be in shadow are lit up, and those that should be lit up are dark. Here's some things I've tried and which didn't do anything in Blender I tried mirroring the mesh in 2 ways first by using the scale to 1 trick, then by using the mirroring tool (select mesh, hit crtl m, select mirror axis), both ways yield the exact same result in Unity I've tried playing around with the prefab import settings like "normals import calculate", "tangents import calculate" I've also tired not exporting as fbx manually from Blender, but just dropping the .blend file in the assets folder inside the Unity project So, my question is is there a way to actually mirror a mesh in Blender and then have it imported in Unity so that it displays properly (as it does in Blender)? If yes, how? Thank you, and please excuse the TL DR style.


Rendering lightmaps at runtime I'm creating a procedural terrain system for Unity. And I'm looking for ways to efficiently cast self shadows on it. If it wasn't procedural, I could simply bake a lightmap using Beast. But, I can't because the terrain mesh is created at runtime. What kind of methods can be done for this, I'm sure it has been done before. If possible, I'm looking for a solution that works for non pro. I was thinking that maybe some kind of onetime ray tracing method might be a solution.


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


Mathematical equation for CHOMP AI? Players take turns in taking a rectangular bite out of the bottom right corner of the bar, by shading a square, tighter with all the squares below and or to the right it. The top left hand square is poisoned, and the player forced to eat the square loses. How do I determine who is currently winning while the game is being played? (Creating the game in Unity using c )


How to split a group of tiles in a grid into separate groups if a break occurs between tiles? I have a grid where objects can be placed down by the player. Each object that gets placed down is added to a dictionary where the key is the grid position. Each object that gets placed down either gets added to a new zone, or added to an existing zone if any of the neighbors are in an existing zone. If there are multiple zones, then it just picks the first one it finds and adds it. The issue I am struggling with is how to handle splitting up zones if an object is removed from the grid. In the first image I have 2 zones. In the second image, I add a new object to the grid, because that tile contains 2 neighbor tiles that are in a zone, it merges the 2 zones into one. In the third image, I remove an object from the grid, which removes it from the zone, and in this case it creates 2 new zones (but could be more depending on neighbors). This is where I am struggling to work out the best way to efficiently do this. I have a grid array that holds all objects placed on the grid. A zone contains a list of tiles that are in that zone. Each tile in a zone also gets a zone id. What would be a fast efficient way of splitting up a zone into multiple zones? I thought about checking all the tiles in the zone by checking its neighbors, but thought that it could be quite slow, as a zone can grow to be very big over time (zones can auto merge as well). Also wouldn't there be a chance of an endless loop?


Managing draw calls for customized materials when targeting mobile I want to know how to minimize draw calls when rendering multiple customized characters onscreen, presumably with 3 4 materials apiece. Is there a better way to achieve custom color configurations than instancing duplicating materials? Am I overthinking the problem? Our game is a frenetic, goofy arena fighter, made in Unity. We plan to publish on mobile, first. I am tasked with creating an art pipeline which allows for customizable additions and color changes to the player's avatar. I'm trying to look ahead to when this character creator will be a part of the game and consider the performance implications of this kind of system. A character creator could potentially serve us in the generation of random NPCs at launch, and will feature heavily when we move to multiplayer. My concern is with the number of draw calls on mobile. Currently, we have a bunch of identical characters, all creating instances of the main material on spawn to differentiate by random color. Since draw calls are directly linked to the number of materials onscreen, this process concerns me. Before complicating the issue with variations in mesh and texture on a per object basis, having 1 material per character already limits us to a certain number of NPCs onscreen. I delivered a material solution which allows changing one color to differentiate from other characters. Now the director is asking about the feasibility of breaking each character into multiple materials to allow for player customization. With 4 materials per character (1 shared), draw calls would increase geometrically per spawn. I've heard mobile platforms tend to be limited to about 20 120 draw calls between low and high end devices. That would make for 5 35 characters allowed onscreen at once, assuming we could get the environment down to around 5 draw calls. I would be especially interested in any material masking techniques people are aware of. Having a need for around 4 customizable aspects would seem to point towards using some sort of RGBA texturing and masking solution, but I have no idea how to make Unity do that.


400 bad request UnityWebRequest hey everyone any ideas why im getting a 400 error? im trying to post a json to a subscription list. doing that through postman works just fine! using System using System.Collections using System.Collections.Generic using System.IO using System.Text using UnityEngine using UnityEngine.Networking using UnityEngine.UI public class testing MonoBehaviour public InputField field SerializeField private Email email new Email() private string URL quot https a.klaviyo.com api v2 list YeXzKp members?api key pk ec448e1bdab7504c143466ca5eeabc5e95 amp profiles quot IEnumerator SaveIntoJson() string data JsonUtility.ToJson( email) System.IO.File.WriteAllText(Application.persistentDataPath quot Data.json quot , data) UnityWebRequest www UnityWebRequest.Post( quot URL quot , data) www.SetRequestHeader( quot Content type quot , quot application json quot ) UnityWebRequest request UnityWebRequest.Put(URL, data) request.SetRequestHeader( quot Content Type quot , quot application json quot ) yield return request.SendWebRequest() yield return www.SendWebRequest() if (request.isNetworkError request.isHttpError) Debug.Log(request.error) else Debug.Log( quot Form upload complete! quot ) Debug.Log(data) public void SaveData() StartCoroutine(SaveIntoJson()) System.Serializable public class Email public List lt Profiles gt profiles new List lt Profiles gt () System.Serializable public class Profiles public string email


Need to generate seamless gradient noise texture for water Shader I need to generate something like this for my water Shader, because on fly calculations are to expensive for mobile (https docs.unity3d.com Packages com.unity.shadergraph 6.9 manual Gradient Noise Node.html). The texture needs to be seamless. I currently clueless where and how to make this happen (especially about the seamless thing). Any help appreciated!


Unity Dimensions of color surface does not match dimensions of depth surface I am receiving the error, "Dimensions of color surface does not match dimensions of depth surface" whenever I attempt to use my screenshot code, without any callstack or anything further insight of what I am doing wrong. I have a separate camera from my main camera, whose purpose is to take screenshots at different angles. Hierarchy as such The main camera captures the 3D scene just like a normal main camera would, including post processing components. No HDR or MSAA. The GUI camera captures just the UI layer. Nothing enabled except MSAA. The canvas and image are simply a watermark, rendered by the GUI camera. I point both the main camera and GUI camera to the same target render texture. When ready to take a screenshot, I enable the camera components, thus Unity takes over and tells them to render the frame. In the OnRenderImage callback, I disable the camera so it can be used again, I remove the render texture I previously assigned, extract the pixels, and save it as a PNG. In a separate test, this all seems to work as intended. No error messages. However, when playing the full game, suddenly I receive the dimensions errors upon each screenshot. I have read that RenderTexture.IsCreated will test if the render texture is still available. Supposed, it will be set to false due to a large variety of events, such as window changes. I have made it impossible to even get the reference to the render texture without it checking if the IsCreated bool is true. I have also tested if the render texture matches its Descriptor property, out of paranoia. All of these checks succeed. I don't know what to look at next. What is SUPER strange is I have a GIF generator, using quite similar code, that's much more complicated, and it does not suffer from this problem. Has anyone dealt with this error before? Any hints at all?


Converting Unity .fbx model to .stl using the exporter? We bought this script asset from the Unity store. We need to run it to convert some .fbx files to .stl. Is there any simple guide on how to run a script from the asset store?


Specular reflections shine at the wrong angle when using a normal map I'm using Unity with URP and I'm trying to include a normal map in my shader graph. Here is a basic graph that just display a normal map, with properties to control tiling and smoothness. When I render the scene, the sun reflection highlights the wrong parts of the surface. In this example, we can see the shadow direction of the cube, and the light itself. The sun reflection is clearly at the wrong place. I tried with several normal maps from the web, all maps behave exactly like this one, so I think I'm missing something. Ah, and strangely, when I rotate the object, the light reflection origin seems to change! Of course, without the normal map, the light reflects gracefully. What am I missing?


How can I rig an object to animate from two different orientations? As an example Say you're animating a skateboard. The board has a nose and a tail. Normally, the nose points forward and the tail points backward. Now say you have two animations idle and trick. The idle is animated with the nose pointing forward. The trick, however involves the board rotating 180 , ending with the nose pointing backward, functionally swapping the nose and tail. Now, if you were to blend the trick animation back into idle, the blend would rotate the board back around so the nose points forward, which would not be the intended behavior. The intended behavior would be for the animator to somehow know that the tail is now the forward facing orientation and animate as if the tail were the nose. I'm competent but no expert with rigging animation and I've been racking my brain trying to come up with either a way to cleverly rig the object to somehow work as intended or to be able to modify the animations procedurally in code or something, but I haven't been able to figure it out. This seems like a problem that must come up somewhat frequently with game animation, but I haven't been able to find any specific resources. I'm using Blender and Unity. Edit To be clear, I'm not talking about root motion or the animating object's position rotation in the world, just the orientation of the bones being animated.


How to find a non active gameobject in unity? I am trying to find a gameobject, which is not active in the current scene.It throws Null Reference error. GameObject gameObject void start() a non active gameobject tagged with InactiveTag gameObject GameObject.FindGameObjectWithTag("InactiveTag") void update() if(someCondition) gameObject.setActive(true) this line throws Null Reference error


Problem finding correct value for Yaw I use an Arduino and a 9dof sensor ( gyroscope, accelerometer and magnetometer ) and i'm trying to use the pitch, roll and yaw that the sensor gives me to rotate an object in unity. I managed to correctly compute pitch and roll ( the z and x axis in unity ) from the accelerometer but it seems that I can't get the Yaw right. By that I mean that when I rotate my sensor pitch or roll it rotates my Yaw too in a weird way. Code in the arduino to get the heading void getHeading(void) heading 180 atan2(Mxyz 0 ,Mxyz 1 ) PI if(heading lt 0) heading 360 void getTiltHeading(void) float pitch asin( Axyz 0 ) float roll asin(Axyz 1 cos(pitch)) float pitch atan( Axyz 0 sqrt( Axyz 1 Axyz 1 Axyz 2 Axyz 2 ) ) float roll atan( Axyz 1 sqrt(Axyz 0 Axyz 0 Axyz 2 Axyz 2 )) float xh Mxyz 0 cos(pitch) Mxyz 2 sin(pitch) float yh Mxyz 0 sin(roll) sin(pitch) Mxyz 1 cos(roll) Mxyz 2 sin(roll) cos(pitch) float zh Mxyz 0 cos(roll) sin(pitch) Mxyz 1 sin(roll) Mxyz 2 cos(roll) cos(pitch) tiltheading 180 atan2(yh, xh) PI if(yh lt 0) tiltheading 360 Pitch and roll float Pitch (float)(180 Math.PI Math.Atan( m ResultX Math.Sqrt( m ResultY m ResultY m ResultZ m ResultZ ) ) ) float Roll (float)(180 Math.PI Math.Atan(m ResultY Math.Sqrt(m ResultX m ResultX m ResultZ m ResultZ))) float Yaw (float)(m TiltHeadingResult) Don't hesitate to ask for details.


How do I connect Unity to a server backend developed in .net core? I'm currently running to a wall in my game development and I need now some discussion to clear my mind... In my mind I have a plan for some little online game (focused around clicking and idling), which I imagined could be served both on website and winapp, and in future even in mobile platforms. I have chosen C for it, build some server backend (join server, game server), but 'cause I want this server components be runned on linux, I have chosen .net core. Which is now my problem, because I'm building the game client in Unity, which only works in .net standard. My main problem now is that I have build some quot base network library quot for communication, written in .netcore with plenty of NuGet packages, which I now have implement to Unity to get it work, but there are now conflicts (the main one is that unity is using another version of System.Threading). Now I am wondering what steps should I choose nexts... There are some work behind now (but not so much, there are only some basic proceses for login and creating game worlds), so probably make that base network package compatible with .netstandard and .netcore. Or I am thinking if it isn't more suitable to choose some another technology like c and some 2D engine in it (which to choose?). What are you opinions? And what would you do in this situation?


Unity GL.Lines going over 3D models I'm drawing lines using GL.lines but they disregard the zbuffer and always appear over my model. I found this thread http answers.unity3d.com questions 434827 gllines over game objects.html and decided to give the answers a try, but it didn't seem to fix things. For now I'm using the shader found in that thread, here is the rest of the code void OnPostRender() GL.PushMatrix() testMaterial.SetPass(0) GL.Begin(GL.LINES) for (int i 0 i lt basicMesh.linePoints.Length i ) GL.Color(new Color(1,1,1,1)) GL.Vertex(basicMesh.linePoints i .point1) GL.Vertex(basicMesh.linePoints i .point2) GL.End() GL.PopMatrix() Any advise on how to make the lines not go over my 3D models?


How do I correctly use GetComponent to get the rigidbodies of each element in an array of colliders? I was trying to implement an AddExplosionForce script that was shown in a Unity live training session a few years back. It has out of date calls to rigidbodies because it uses the old gameobject.rigidbody way of accessing them. I tried doing the standard process of declare a rigidbody, link it to a GetComponent lt gt , and act on the rigidbody through the resulting variable. However, as shown below, the rigidbodies I need to interact with are used in a foreach loop that goes through an array of colliders. How do I access the rigidbody of each collider in the array as it is used? (and if that is the wrong approach, please let me know). Will using GetComponent in that way harm performance? Here is the original script from the video, w minor comments. I have left out my botched attempt at fixing it for the sake of brevity. public class MassExplosionScriptOriginal MonoBehaviour public float force public float radius void Update() if(Input.GetMouseButtonDown(0)) Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit, 100)) Collider colliders Physics.OverlapSphere(hit.point, radius) overlap sphere collects all the colliders that it overlaps with touches. From the point you click (hit.point), create a sphere of the given radius (radius),collect all the colliders from the objects overlapped, and then return them with the array colliders. foreach (Collider c in colliders) declare a variable to hold a collider if (c.rigidbody null) continue the if statement clause says that, if the collider touched has no rigidbody, then skip it and continue on. c.rigidbody.AddExplosionForce(force, hit.point, radius, 1, ForceMode.Impulse) Whenever you click, this script will collect all the colliders and then apply the explosive force to them. It works on everything


Using Lerp to zoom in on an object inside an if statement I'm trying to zoom in on an object once the raycast hits it in the Update method, I am using the Lerp method to make the camera movement smoother but it's not working properly. The object only lerps for a single frame. I also tried using a coroutine but the result is still the same. I can't simply just place it outside the if statement because I only need to change the field of view once the raycast hits an object. Here's a sample of my code if (Input.GetMouseButtonDown(0)) ray mainCam.ScreenPointToRay(Input.mousePosition) if (Physics.Raycast(ray, out hit)) if (hit.collider.tag.Equals("Building")) SetTarget(hit) mainCam.fieldOfView Mathf.Lerp(mainCam.fieldOfView, newFOV, Time.deltaTime smooth)