Using A Pathfinding on terrain created by scripts? I'm looking to use A Path finding as a method of navigating my game terrain. Trouble is, my terrain is built upon play using a script and A grid does not detect this, therefore marking all nodes as "un walkable". I'm wondering if anyone knows a solution for this or an alternative path finding method. I have tried enabling the terrain to spawn on edit more using ExexcuteInEditMode, but this does not seem to work either. The terrain was generated through a fantastic guide called Procedural Terrain Tutorial. Would greatly appreciate any help I'll be able to get. I've attached some screenshots for clarity


How do I draw a tilemap within unity3d? I'm pretty new to Unity and after a bit of googling around I have come up with this code to draw my tilemap (the script is attached to my camera). I am simply trying to use nested for loops to draw a grid of grass tiles, here is my code public class DrawMap MonoBehaviour Use this for initialization void Start () Sprite grass (Sprite)Instantiate(Resources.Load("Grass")) float x, y for (int i 0 i lt 20 i ) for (int j 0 j lt 20 j ) x i 1.28f y j 1.28f Instantiate(grass, new Vector3 (x, y, 0f), Quaternion.identity) Update is called once per frame void Update () I keep getting an error where I initialize "grass" saying the it cannot cast the source type from the destination type. I created "grass" to be a prefab from a slice of a spritesheet that i imported. Any help would be greatly appreciated


Problems with gravity and box colliders in Unity 3D I have a game character that can jump or roll in order to avoid obstacles. He is able to roll while on the ground and he can also roll while he is in the air after jumping. Everything was working fine when I made him roll. I want to make it so that when he rolls while he's in the air after jumping, he would fall at a faster pace than if he was just falling normally. So I did this in my c script IEnumerator IncGravAcc() Physics.gravity new Vector3(0, 50f, 0) yield return new WaitForSeconds(2f) Physics.gravity new Vector3(0, 9.8f, 0) I call this coroutine in the function that runs when the down arrow is clicked. Everything is working fine. When he rolls while in the air, he falls at a faster than normal rate. However he doesn't land properly and he just falls right through the platform like it's not even there. Here's a video to show what I mean https youtu.be sirc4L3MnqM I have a box collider, not set to isTrigger, on the player (you can see it, the green box, right underneath him in the video) and the player's also a rigidbody. The platforms don't have rigidbodies on them but they do have box colliders set to trigger. You can see the platform's box collider in the relation to player's box collider in the picture provided (the platform's box collider is the larger one of course) How do I get it so that the character doesn't fall through? Please let me know if there's anything else you need to know about the project. Thank you for helping me!


Make an arrow to point at a direction from UI I want to have a guiding arrow on the left side of UI. The arrow is child of the player's camera and it's rendered from another camera into render texture. The render texture is displayed on the screen. The arrow is rotated via transform.LookAt(targetPosition) The problem I'm having is that although it does point in the right direction, form player's point of view it looks like the arrow is pointing somewhere else. I want that arrow to point from the point where it's placed on the UI. It should look something like this I tried to do this Vector3 direction targetPosition arrowRawImage.rectTransform.position transform.LookAt(direction) but it didn't work.


Unity Remote screen resolution I just made a game using Unity. However, when I tested the game on unity remote, the resolution or graphic of the game was really low compared to the actual game. Would this change when I deploy the game or do I have to tweak the settings? If I have to tweak the setting, can you guys tell me what to tweak.


Want event to occur when button is held but not when clicked I'm wondering if there is a way to have an event occur when the left mouse button is held down, but not to occur when it is initially clicked. I think you can do something like... if (Input.GetMouseButtonDown(0)) do stuff else if (Input.GetMouseButton(0)) do other stuff It looks at first like this would work because when left click is clicked it would execute the first if statement and not test for the second. And if left click is held it would fail the first if condition. But, does this in fact work? Do you actually enter the second if statement when attempting to click because you actually hold it down for slightly longer than a true click since this is happening in Update? Now, I want to do this in one condition. Something like... if (!Input.GetMouseButtonDown(0) amp amp Input.GetMouseButton(0)) do the stuff that should happen when mouse is held but not clicked but I don't think this works either. Any pointers? For Context, I want to have something happen in every case when mouse button is held down, and only happen in some cases when mouse button is clicked. if (Input.GetMouseButtonDown(0) amp amp !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject() !Input.GetMouseButton(0) amp amp Input.GetMouseButton(0)) This doesn't work though


GetCurrentAnimatorStateInfo(0) returns animation hash which is not found in list of animations I trigger the animation quot hg reload g2f quot from quot Any State quot using a trigger. Here is a screenshot of my animator I would now like to detect if the animation is still being played. To do that, I have tried the following approaches. None of them returned True while the animation is being played void LateUpdate() Debug.Log( animator.GetCurrentAnimatorStateInfo(0).IsName( quot hg reload g2f quot ) quot n quot ) Debug.Log( animator.GetCurrentAnimatorStateInfo(0).IsName( quot 6 Reload Pistol quot ) quot n quot ) Debug.Log( animator.GetCurrentAnimatorStateInfo(0).IsName( quot Base.hg reload g2f quot ) quot n quot ) Debug.Log( animator.GetCurrentAnimatorStateInfo(0).IsName( quot Base.6 Reload Pistol quot ) quot n quot ) I have then tried a different approach which gives me deeper insights of what is currently being played At void Start(), I build a dictionary of the animations in the animator like that private void pBuildAnimationNameTable() NamesTable new Dictionary lt int, string gt () foreach (AnimationClip nClip in animator.runtimeAnimatorController.animationClips) NamesTable Animator.StringToHash(nClip.name) nClip.name And then at LateUpdate, I call the following public string GetCurrentAnimatorStateName() if ( animator null) Debug.Break() return quot nothing assigned yet quot AnimatorStateInfo stateInfo animator.GetCurrentAnimatorStateInfo(0) string sStateName if ( NamesTable.TryGetValue(stateInfo.shortNameHash, out sStateName)) return sStateName else return quot Unknown animator state name. quot However, it doesn't find the current animation's hash in the list What might be the reason why it's not found in the list of animations?


Unity GameObject.Find() not working in batchmode? I am trying to make GameObject.Find() work in batchmode but for some reason it returns a null object. my code public class test Monobehaviour public static GameObject go static void doing() go GameObject.Find ("testing") testing is the name of the gameobject in the editor I call it from the console on mac using Applications Unity Unity.app Contents MacOS Unity quit batchmode projectPath "" executeMethod test.doing


How to create a high score in Unity from a Time.deltatime float? When I play my game, it sets my score to 0 and does not change, no matter how high my float gets. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class highscore MonoBehaviour public Text Highscore void Start () Highscore.text PlayerPrefs.GetFloat ("Highscore", 0).ToString() This is where the next page starts using UnityEngine using UnityEngine.UI public class Score MonoBehaviour public Text ScoreText public float playerScore 0 void Update () playerScore Time.deltaTime 10 ScoreText.text playerScore.ToString("0") private void OnCollisionEnter (Collision collisionInfo) if (collisionInfo.collider.tag "Obstacle") PlayerPrefs.SetFloat ("Highscore", playerScore)


How to speed up script compilation? Is there a way to speed up script compile time when I change something in VS then click on Unity? It takes 15 seconds. Is this normal?


Unity movie texture behaviour when hidden I have a UI with a button and a panel. Clicking the button toggles the panel on and off GameObject.SetActive() Now the panel element has a child which is a plane. This plane has the following components mesh renderer videoPlay, a script I've written an audio source The videoPlay script basically applies the MovieTexture to the plane's material, sets the plane's audioSource to the movie's audio clip, and starts audio and video. public MovieTexture movie void Start() GetComponent lt Renderer gt ().material.mainTexture movie as MovieTexture GetComponent lt AudioSource gt ().clip movie.audioClip movie.Play() GetComponent lt AudioSource gt ().Play() Now when at runtime I click the button (which hides the panel which is the plane's parent element), the audio and video stop as the plane disappears which is expected behaviour. When I reopen the panel though, the sound restarts right away but as if it were catching up for the time it was hidden (so it starts really fast and then comes back to regular speed) and the video is just frozen for empirically and approximately the same time the panel was hidden. I've tried in the script in Update() messing with if (!transform.parent.gameObject.activeSelf amp amp movie.isPlaying) movie.Pause() GetComponent lt AudioSource gt ().Pause() for example, (and the same with Play() when it shows back up) but it doesn't seem to change anything.


Why Post Processing v1 not works in WebGL build? In my WebGL browser app, i've tried to add Post Processing (first version) stack. I'm using Unity 2018.4.6f1 (i started 1 years ago to develop this app). I've added Post Processing Behaviour to my Camera, and this is what i've enabled When i run my scene on Chrome or Firefox, Camera appears all black but UI is correctly rendered. Are there any incompatibility issue using Post Processing and WebGL ? Thanks


Saving total play time could be fine? I'm making a game that needs to save total played time into file (using JSON) for comparing amp resolving data conflicts between local and cloud. I will override outdated one. Currently, I'm just adding Time.realtimeSinceStartup, but is that okay? What if the time is really, really big and couldn't be handled in Unity anymore? Could that eventually happen? If so, what are some alternatives?


Executing Components in an Entity Component System Ok so I am just starting to grasp the whole ECS paradigm right now and I need clarification on a few things. For the record, I am trying to develop a game using C and OpenGL and I'm relatively new to game programming. First of all, lets say I have an Entity class which may have several components such as a MeshRenderer,Collider etc. From what I have read, I understand that each "system" carries out a specific task such as calculating physics and rendering and may use more that one component if needed. So for example, I would have a MeshRendererSystem act on all entities with a MeshRenderer component. Looking at Unity, I see that each Gameobject has, by default, got components such as a renderer, camera, collider and rigidbody etc. From what I understand, an entity should start out as an empty "container" and should be filled with components to create a certain type of game object. So what I dont understand is how the "system" works in an entity component system. http docs.unity3d.com ScriptReference GameObject.html So I have a GameObject(The Entity) class like class GameObject public GameObject(std string objectName) GameObject(void) Component AddComponent(std string name) Component AddComponent(Component componentType) So if I had a GameObject to model a warship and I wanted to add a MeshRenderer component, I would do the following warship gt AddComponent(new MeshRenderer()) In the MeshRenderers constructor, should I call on the MeshRendererSystem and "subscribe" the warship object to this system? In that case, the MeshRendererSystem should probably be a Singleton("shudder"). From looking at unity's GameObject, if each object potentially has a renderer or any of the components in the default GameObject class, then Unity would iterate over all objects available. To me, this seems kind of unnecessary since some objects might not need to be rendered for example. How, in practice, should these systems be implemented?


Is there a way to exclude original sprites in spritepacker that's in asset bundle? I use spritepacker with assetbundle. It's working great. Its memory assumption is about just 8 MB. However, when I looked at the disk space that asset took on android phone, it took about 25MB. Which is 4 times from 8 MB. If I sum up all original sprites that have been used to create the atlas in spritepacker, they will be about 25MB as they are. Is there a way to exclude original sprites out of the bundle? It waste too much space in the device. I think only output atlas that generate from sprite would be enough to pack within the bundle. I'm sure of it. I tested with 18 sprites and use the packer to generate 1024x2048 atlas. If I choose 2 sprites to make asset bundle, it used 5.76 MB disk space. If I choose 3 sprites to make asset bundle, it used 6.62MB. Its different is about 0.9MB which is the size of each sprite.


Quality deterioration on a device I am using Unity. When I try the game out in the IDE everything looks pretty good But when I am trying to play the same game on a device the quality becomes a great deal worse and you can see it for yourself I am using Xiame Redmi 4X and I do not think that it is because of device. So, how can I fix it? How can I preserve the quality? I would like to try out this solution, but there is no Android settings in my Inspector for quality I would like to preserve at least colors. And here are setting for my player sprites


vuforia how do I force objects into a 2D plane I'm working on a game in which cards are placed on a table and then rendered in augmented reality. These objects have 3D physics attached to them which doesn't work as well if they are either rotated or if the system mistakes them for being higher or lower then they really are. Is there a good method to force Vuforia Unity to place all items in the same 2D plane and keep all of them upright compared to that plane? I currently have the following code using UnityEngine using System.Collections public class projectioncode MonoBehaviour Vector3 p1 Vector3 p2 Vector3 p3 Vector3 v1 Vector3 v2 Vector3 normal use a plane with the following 3 coordinates public void setPlaneByPoints(Vector3 point1,Vector3 point2, Vector3 point3) p1 point1 p2 point2 p3 point3 v1 p2 p1 v2 p3 p1 normal getNormal(v1,v2) public Transform projectTransform(Transform input) input.position projectPoint (input.position) return input projects a 3d point into space Vector3 projectPoint(Vector3 point) Vector3 vOToPoint point p1 vector between origin and point float dist Vector3.Dot (vOToPoint, normal) distance plane to point return point dist normal caclulates the normal of 2 vectors Vector3 getNormal(Vector3 v1,Vector3 v2) Vector3 res (Vector3.Cross (v1, v2)) res.Normalize() return res This seems to project objects onto a plane but the results tend to be inaccurate and result in weird movements, particularly when moving the camera around. This is what it looks like


Where do I store project data in Unity? In Unity the PhysicsManager has project data. It exists across scenes but its data is unique to each project. If it make my own CustomManager, where how to I store its data so that it's associated with the project, not a particular scene. Most of the examples show storing data in properties in components on GameObjects but the PhysicsManager is not a component of a GameObject as far as I can tell. I want my custom manager to do whatever PhysicsManager is doing to store its data. Any examples, pointers, links to articles?


How to write properly shader with gradient based on vertex color? I took 4 squares with the outer corners painted in black, and the other ones in white. For some reason, they have a different gradient. fixed4 frag (v2f i) SV Target fixed4 mainTex tex2D( MainTex, i.uv) fixed4 overTex tex2D( OverTex, i.uv3) fixed4 final fixed4(lerp(mainTex.rgb, overTex.rgb, overTex.a) i.color, 1.0) final lerp(float4(0, 0, 0, 1.0), final, i.color.a) shadows return final How can i make the same gradients as bottom left and top right? In game this is faces of blocks (like minecraft) and gradients is smooth shadow light. So I cannot change tris


Not able to upload to Oculus Store I am building for Quest and signing the package with V2. I am also creating store based Android Manifest file. Unfortunately the upload stops at 2nd step where I receive the error quot The APK was signed with the V1 signature system, previously marked with V2 and signed again with V1. Such APKs are considered corrupted and cannot be installed. quot Here is my Android Manifest file lt manifest xmlns android quot http schemas.android.com apk res android quot package quot com.VR.VRCube quot android versionCode quot 1 quot android versionName quot 1.0 quot android installLocation quot auto quot gt lt application gt lt meta data android name quot com.samsung.android.vr.application.mode quot android value quot vr only quot gt lt meta data android name quot com.oculus.supportedDevices quot android value quot quest quest2 quot gt lt activity android screenOrientation quot landscape quot android theme quot android style Theme.Black.NoTitleBar.Fullscreen quot android configChanges quot density keyboard keyboardHidden navigation orientation screenLayout screenSize uiMode quot android launchMode quot singleTask quot android resizeableActivity quot false quot gt lt activity gt lt application gt lt uses sdk android minSdkVersion quot 21 quot gt lt uses feature android glEsVersion quot 0x00030001 quot gt lt uses feature android name quot android.hardware.vr.headtracking quot android required quot true quot android version quot 1 quot gt lt manifest gt


What is the bare minimum I need to set up the Android SDK for Unity development? I want to import my Unity project to Android, and I need to download the Android SDK, but I do not want to download any unnecessary components. Do I need to download all platforms, or just the latest one? I am worried about the size of Android 7.1.1 (API Level 25) the SDK Manager reports this as the latest version, but I am not sure. I only want to import my project for Android smartphones, with no plan of publishing it. I do not want to build to Android TV or Android Wear, for example. Do I need to download all of the contents under the specific platform? I ask because there are Android TV and Android Wear system images, and the files can get quite large.


Getting error when I Send a message to the RaycastHit object I have created a shooting game, here when I am shooting I have a c script for damage for enemies.I have Used Raycast to Shoot enemies.if the RaycastHit becomes an enemy, it will be deducted it's health.It works properly.But the thing is, If I shoot objects except enemies it causes an error. I have provided some details about that.this is the script, public class DamageSMG MonoBehaviour public int DamageAmount 5 public float TargetDistance public float AllowedRange 50 public RaycastHit Shot public int Firing void Update() if(Input.GetButton("Fire1")) if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward),out Shot)) TargetDistance Shot.distance if (TargetDistance lt AllowedRange) if (Firing 0) Deduct() public void Deduct() Firing 1 Shot.transform.SendMessage("DeductPoints", DamageAmount) StartCoroutine(Wait()) IEnumerator Wait() yield return new WaitForSeconds(0.1f) Firing 0 I am using an machine gun.therefore I have created Script to fire coutinously with 0.1sec break.When I press Fire1 button, The RayCastHit Object is received a message where the method called DeductPoints with the DamageAmount.As this Script my enemies are deduct point 5 by 5 every hit.Then Destroy the object.The Enemy script is this. using System.Collections using System.Collections.Generic using UnityEngine public class EnemyScript MonoBehaviour public int EnemyHealth 20 void DeductPoints(int DamageAmount) EnemyHealth DamageAmount Update is called once per frame void Update() if (EnemyHealth lt 0) Destroy(gameObject) GlobalScore.GlobalScorecount 1 But my problem is when I shoot objects except Enemies(Ex walls),The console gives an error.The error is like this SendMessage DeductPoints has no receiver How can I solve this error or is there any other way of Deducting enemy health with raycast? I can play the game with this error in UnityEngine.but it is not possible to Build the game.Please help me to Solve this..


How do I get access to the PS4 platform tools for Unity? I know that you can go to the "Xbox ID" program to get all the resources you need for the Xbox platform (developer forums, Unity SDK, etc.). but there is not really information about how to get the PlayStation tools. ...Well other than the contact sales button in Unity which links to Unity and not Sony (oddly enough). So where does someone who hopes to put their games onto one of the Sony platforms (PS4, Vita, PS3, etc) go to get the build tools (and other things) they need? Do Sony contact you about it if they're interested or is it really only for developers who are considered above Indy?


Using keyword NonSerialized causes Property to disappear from Inspector I have the following class to represent items in an inventory System.Serializable public class InventoryItemInfo MonoBehaviour public int Row 0 public int Col 0 public int Rotation 0 public InventoryItemType ItemType public int Amount public int EffectiveWidth 0 public int EffectiveHeight 0 public int Width 0 public int Height 0 public bool Selected false public Vector3 TilePosAccordingToCurrentRotation public Vector3 TileScaleAccordingToCurrentRotation NonSerialized public Transform TheNicelyPositionedMesh HideInInspector private int iCurRow 0 private int iCurCol 0 private int iRotationToCheckForDirtyness 1 public Vector3 DefaultRotation public bool Initited false public bool Dirty true private bool bInitialRotationGotten false (...) With the keyword NonSerialized , the property "TheNicelyPositionedMesh" disappears from the Unity Inspector. I don't see why. Why is that keyword coupled with the visibility in the Inspector? Thank you!


How can I create a stretchy, breakable pizza cheese material? I want to create realistic pizza and allow user interact with it. What I want What I created I created model of the pizza (8 pieces) in Blender, then imported it into Unity. The piece of pizza looks very artificial, mostly because it is "rigid triangle". How can I make the cheese stretch and break when the user moves a piece?


Unity3D Making heavy calculation on separate thread So, I've created a program with Kinect as its input. As you know, Kinect will send the data 30 frame per second. I have a model that will mimic Kinect's input motion, so on Update() I read the motion from Kinect. The problem is, on Update(), I've done a heavy computational algorithm. It makes the system lag and freezing. I've tried to do the calculation every 60 frames instead of each frame, but the system still got lag. void Update() ... GET DATA FROM KINECT frame new SkeletonRecorded() frame.root.rotation skeletons kinect2SensorID, playerID .root.rotation ... frame.rightShoulder.position skeletons kinect2SensorID, playerID .rightShoulder.position frames.Add(frame) if (frames.Count gt 60) CALLING THE CALCULATION METHOD (Here is the heavy part begin) comparatorClass.GetSkeletonData(frames) frames.Clear() The above code is just small parts of the Update() method (I cut it short for convenience). So, how should I call the GetSkeletonData() method without making the interface lag?


game button animation lag with Photon Friends, I am making games using photon. But I could not do the delay animation as described in this link. The action appears to be late on the player according to the ping. Can you give an ideas about this?


Basic Moving Anim Script Unity CSharp So, I got this to do the anims for my sprite in Unity 2d... using UnityEngine using System.Collections public class Move MonoBehaviour public float Speed 2 Animator anim Use this for initialization void Start () anim GetComponent lt Animator gt () void FixedUpdate () rigidbody2D.velocity new Vector2(Input.GetAxis("Horizontal") Speed, 0) anim.SetFloat("HorizontalSpeed", Mathf.Abs(rigidbody2D.velocity.x)) if(transform.localScale.x gt 0 amp amp rigidbody2D.velocity.x lt 0) transform.localScale new Vector3( 1, 1, 1) if(transform.localScale.x lt 0 amp amp rigidbody2D.velocity.x gt 0) transform.localScale new Vector3(1, 1, 1) That works fine... then I add the script so he can move up and down. (the previous was moving left right) using UnityEngine using System.Collections public class UpMove MonoBehaviour public float VerticalSpeed 2 Animator anim Use this for initialization void Start () anim GetComponent lt Animator gt () void FixedUpdate () rigidbody2D.velocity new Vector2(Input.GetAxis("Vertical") VerticalSpeed, 0) anim.SetFloat("VerticalSpeed", Mathf.Abs(rigidbody2D.velocity.y)) Welll.. The second script doesn't do anything. I've been working at this (rookie noobness) for around an hour now.. so pls pls pls.


Fire an event while the mouse is down within my box 2d collider in Unity The method OnMouseDown() is called once when the mouse presses my box 2d collider. Is there a method that keeps firing while the mouse is still holding the button down inside the collider? Something like WhileMouseDown(). I could use Input.GetMouseButton(0) in the Update() method. However, this does not check if the mouse is pressing the collider.


Unity 2D Pixel perfect movement using physics I'm trying to make a game in the style of many NES games and I'd like object movement to do two things I want to move an exact number of pixels per update. I want, for lack of a better term, absolute movement. The object should move or not move, I don't want a ramp up or down in speed. I'm trying to do this with physics because I would like to use Unity's hitbox collision detection. Moving objects using the translation property does not allow for this, at least that is my understanding. Any help is appreciated and if my thought process is off, I'd like any suggestions or pointers in the right direction, thanks. Here is my move method that gets called on Update. I expect to movement to be in whole pixels, however, when I test the x and y are always fractional. private void Move() VerticalMovement 0 HorizontalMovement 0 if (Input.GetKey(KeyCode.W)) VerticalMovement 1 if (Input.GetKey(KeyCode.S)) VerticalMovement 1 if (Input.GetKey(KeyCode.A)) HorizontalMovement 1 if (Input.GetKey(KeyCode.D)) HorizontalMovement 1 this.GetComponent lt Rigidbody2D gt ().velocity new Vector2(HorizontalMovement Speed, VerticalMovement Speed)


How to achieve dotted trail behind moving object with use of Trail Renderer? How can I achieve effect shown on picture below with use of Trail Renderer in 2D game? Is it even possible? I need dotted (dashed) trail behind my object and i can't figure it out. don't know why stack can't load my images LINK HERE Why trail renderer? Because I feel this is the right way to do this. Earlier, (Unity ver 5.3) I achieved this using Mesh Particle Emitter Particle Animator (Fade) Particle Renderer, but sometimes it behaves strangely in multiplayer. Particles not always came out from object, sometimes they were offset. Anyway, Unity in ver. 5.5 released new component (TrailRenderer), which I would like to use (if it is possible to accomplish effect I need). I am looking for efficient ways, so answers like "you can instantiate"dot" every X sec. at position of your moving object" ... Please no. What I have tried. I added to my gameobject a child (gameobject) with Trail Renderer. Then I put material into Materials array field. Material shader currently is set to Mobile Particles Additive (I am targeting Mobile devices). Material Texture is don't know why stack can't load my images LINK HERE I've tried different settings to accomplish my needs but with no success. Trail Renderer Texture Mode Tile (my gameobject is followed by one dot and line) Texture Import Wrap mode Repeat (my gameobject pulls dots without gaps behind instead leaving dots in place it was) Also i tried different shaders, different Trail Renderer parameters with no success. Most of time, my gameobject is followed by stretched dot, line or dots without gaps which are pulled instead of left in place where object was.


How can I increase the speed and frequency of a spawn? I'm using the official Unity tutorial for the Space Shooter game, and I'm at the part where the ability to spawn a set amount of hazards in a wave at a certain delay is introduced. I want to make it so that at the end of a certain level, the speed of the hazards, and the amount of hazards both increase. I'm pretty sure that can be handled in the game controller, but I don't know the commands I would be needing to use to make that happen. This is the existing code public class GameController MonoBehaviour public GameObject hazard public Vector3 spawnValues public int hazardCount public float spawnWait public float startWait public float waveWait void Start () StartCoroutine (SpawnWaves()) IEnumerator SpawnWaves () yield return new WaitForSeconds (startWait) while (true) for (int i 0 i lt hazardCount i ) Vector3 spawnPosition new Vector3 (Random.Range ( spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z) Quaternion spawnRotation Quaternion.identity Instantiate (hazard, spawnPosition, spawnRotation) yield return new WaitForSeconds (spawnWait) yield return new WaitForSeconds(waveWait) What commands would I need to use to increase the amount of hazards that spawn at the end of each round? And likewise, how could I change the Hazard's script so that it will increase in speed by a certain factor at the end of each round? Is there a way I can reference the hazard's script in this script, by any chance?


How to avoid many import iterations while generating sub assets? I have a ScriptedImporter that generates other assets in the same directory. Whenever it happens, import progress bar pops in again, this time like Importing (iteration N). I've tried to use AssetDatabase.DisallowAutoRefresh to circumvent this behavior but that failed. Question How to prevent subsequent import iterations and rather group them to happen all at once ?


Distance Cost for 3D A Algorithm I'm currently implementing an A Algorithm for my Unity project. I found this entry on stackoverflow, but its not telling me how to solve my problem. https stackoverflow.com questions 32205891 a star algorithm in a 3d configuration space I'm not sure about the math required to calculate the distance cost correctly. How to properly implement this in 3 dimensional space? In 2D space it is clear how to implement public static int CalculateDistanceCost(int3 a, int3 b) int xDistance math.abs(a.x b.x) int yDistance math.abs(a.y b.y) int remaining math.abs(xDistance yDistance) return 14 math.min(xDistance, yDistance) 10 remaining However in 3d space it is unclear to me how to calculate it public struct AStarMath public static int CalculateDistanceCost(int3 a, int3 b) int xDistance math.abs(a.x b.x) int yDistance math.abs(a.y b.y) int zDistance math.abs(a.z b.z) int remaining math.abs(xDistance yDistance zDistance) return 14 math.min(math.min(xDistance, yDistance), zDistance) 10 remaining My neighbour cells are set up as follows int3 neighbours new int3 X(width),y(height),z(depth) new int3( 1, 1, 1), Left, Bottom, Front new int3(0, 1, 1), Middle, Bottom, Front new int3( 1, 1, 1), Right, Bottom, Front new int3( 1, 0, 1), Left, Middle, Front new int3(0, 0, 1), Middle, Middle, Front new int3( 1, 0, 1), Right, Middle, Front new int3( 1, 1, 1), Left, Top, Front new int3(0, 1, 1), Middle, Top, Front new int3( 1, 1, 1), Right, Top, Front new int3( 1, 1, 0), Left, Bottom, Middle new int3(0, 1, 0), Middle, Bottom, Middle new int3( 1, 1, 0), Right, Bottom, Middle new int3( 1, 0, 0), Left, Middle, Middle Middle, Middle, Middle (0,0,0) gt dont add, were already here new int3( 1, 0, 0), Right, Middle, Middle new int3( 1, 1, 0), Left, Top, Middle new int3(0, 1, 0), Middle, Top, Middle new int3( 1, 1, 0), Right, Top, Middle new int3( 1, 1, 1), Left, Bottom, Back new int3(0, 1, 1), Middle, Bottom, Back new int3( 1, 1, 1), Right, Bottom, Back new int3( 1, 0, 1), Left, Middle, Back new int3(0, 0, 1), Middle, Middle, Back new int3( 1, 0, 1), Right, Middle, Back new int3( 1, 1, 1), Left, Top, Back new int3(0, 1, 1), Middle, Top, Back new int3( 1, 1, 1), Right, Top, Back As you can see in this image, my enemy (magenta) now takes a weird path, but will always find a path towards target (blue).


How can I apply the changes in runtime? using System.Collections using System.Collections.Generic using UnityEngine public class AnimFlyertransportationController MonoBehaviour public GameObject JetFlame public bool turnOffOn false Start is called before the first frame update void Start() TurnAllAnimtorsOff(transform, turnOffOn) if (turnOffOn) JetFlame.SetActive(false) else JetFlame.SetActive(true) Update is called once per frame void Update() private void TurnAllAnimtorsOff(Transform root, bool onOff) Animator animators root.GetComponentsInChildren lt Animator gt () foreach (Animator a in animators) if (onOff) a.enabled false else a.enabled true I want that if in runtime I change the turnOffOn flag state apply the changes in real time in the Update for all Animators and also for the JetFlame. Now it's only aply the changes in the editor before running the game.


Making isKinematic false when OnCollisionEnter()? I have an issue with my script, I want to make rb.isKinematic go from true to false when collision is detected. With this script, nothing happens when a supposed collision is happening which means that rb.Kinematic false does not work... The problem is that collision CANNOT be detected in the first place because rb.isKinematic is initially true (in my other script)! I checked this using Debug.Log to detect collisions. How can I fix this problem? string lastTagCollided "" public Rigidbody rb void OnCollisionEnter(Collision col) if(col.gameObject.tag "Pentagon" amp amp lastTagCollided "Pyramid") rb GetComponent lt Rigidbody gt () rb.isKinematic false transform.DetachChildren() Destroy (GameObject.FindWithTag("Sphere")) if(col.gameObject.tag "Pyramid" amp amp lastTagCollided "Pentagon") rb GetComponent lt Rigidbody gt () rb.isKinematic false transform.DetachChildren() Destroy (GameObject.FindWithTag("Sphere")) lastTagCollided col.gameObject.tag My other script if you are curious void OnCollisionEnter(Collision col) if (col.gameObject.tag "Pyramid" col.gameObject.tag "Pentagon") rb GetComponent lt Rigidbody gt () rb.isKinematic true gameObject.transform.SetParent (col.gameObject.transform)


Player shooting himself when moving Unity UNET Setting Creating my first multiplayer game and running into an odd issue. it's a tank game where players can shoot bullets and kill each other Problem When the client shoots while moving, the bullet seems to spawn with a little delay which causes the the player to collide with the bullet. The issue seems to be that the player itself is local and the bullet is being spawned on the network ( which is causing the delay) Note The host player does not have this problem, therefore it's somehow related to networking. How can I sync the bullet with the client player? private void Fire() Set the fired flag so only Fire is only called once. m Fired true CmdCreateBullets () Change the clip to the firing clip and play it. m ShootingAudio.clip m FireClip m ShootingAudio.Play () Reset the launch force. This is a precaution in case of missing button events. m CurrentLaunchForce m MinLaunchForce Command private void CmdCreateBullets() GameObject shellInstance (GameObject) Instantiate (m Shell, m FireTransform.position, m FireTransform.rotation) Set the shell's velocity to the launch force in the fire position's forward direction. shellInstance.GetComponent lt Rigidbody gt ().velocity m CurrentLaunchForce m FireTransform.forward NetworkServer.Spawn (shellInstance)


Mesh getting offset on combine because of worldmatrix When I try to combine my mesh, it get offset to an other position, but the collider is still at the same place (because i dont delete and add it again). I saw a fix on internet that is to do Matrix4x4 myTransform transform.worldToLocalMatrix combine i .transform myTransform meshFilters i .transform.localToWorldMatrix which worked in one of my script, but I just cant get it to work in this one. How can it be fixed ? Vector3 cb Vector3.zero Vector3 n hit.normal Vector3 p hit.point if(n new Vector3(1.0f,0.0f,0.0f) n new Vector3( 1.0f,0.0f,0.0f)) cb new Vector3((n.x 0.5f) p.x,Mathf.Round(p.y),Mathf.Round(p.z)) if(n new Vector3(0.0f,1.0f,0.0f) n new Vector3(0.0f, 1.0f,0.0f)) cb new Vector3(Mathf.Round(p.x),(n.y 0.5f) p.y,Mathf.Round(p.z)) if(n new Vector3(0.0f,0.0f,1.0f) n new Vector3(0.0f,0.0f, 1.0f)) cb new Vector3(Mathf.Round(p.x),Mathf.Round(p.y),(n.z 0.5f) p.z) GameObject cub Instantiate(cube,cb,Quaternion.identity) GameObject dupli Instantiate(hit.collider.gameObject,hit.collider.gameObject.transform.position,Quaternion.identity) MeshFilter meshFilters new MeshFilter cub.GetComponent lt MeshFilter gt (),hit.collider.gameObject.GetComponent lt MeshFilter gt (),dupli.GetComponent lt MeshFilter gt () CombineInstance combine new CombineInstance meshFilters.Length Matrix4x4 myTransform meshFilters 2 .transform.localToWorldMatrix combine 0 .mesh meshFilters 0 .sharedMesh combine 1 .mesh meshFilters 1 .sharedMesh combine 2 .mesh meshFilters 2 .sharedMesh combine 0 .transform meshFilters 0 .transform.localToWorldMatrix combine 1 .transform meshFilters 1 .transform.localToWorldMatrix combine 2 .transform meshFilters 2 .transform.localToWorldMatrix meshFilters 2 .mesh new Mesh() Vector3 sP meshFilters 2 .gameObject.transform.position meshFilters 2 .gameObject.transform.position Vector3.zero meshFilters 2 .mesh.CombineMeshes(combine) meshFilters 2 .gameObject.transform.position sP Destroy(meshFilters 0 .gameObject) Destroy(meshFilters 1 .gameObject)


How can I provide an instance of a certain script to all scripts that need it? Problem Whenever a player is added to the game (in the form of the server instantiating a player Game Object with a Player component), I want to provide it to every script that needs a reference in other words, dependency injection. Potential Solutions I thought I'd create an IPlayerRequester interface and have the Player script look up all implementing scripts on the client when it's created, but Unity has no interface searching equivalent of FindObjectsOfType lt gt (). More Info The game is multiplayer, where 1 player is the host a client and the server that is joined by other clients. I'm using Mirror. When a new client is added, the Player script's (that was just spawned) callback OnStartLocalPlayer() is invoked, and so far, that's the only way I've found to access the local environment. But because this is the same Player that I'm trying to inject into requesting scripts, I can't just raise an event in that method, so that's out. What would be a good solution here?


How can I make trailing ghost effect (3d game)? I'm trying to draw previous frame of animation on screen you can see this effect here https youtu.be WNL KJNl6pU Mortal Combat X (left) , Street Fighter Alpha 2 (right) This effect also found in animation software and called onion skinning I've implemented this by spawning object every second but I think It is possible with shader. Update I could make this effect by using RenderTexture for capturing previous frame , but I can't remove background color ( I tried with Blending and grab pass but don't work(it was rendered normally)!! sources https github.com smkplus TrailingFX https unitylist.com r 4tp unity fluid 2d blur image effect


Unity Animation Change the "Transition Speed" between 2 animations during runtime I need to change the Transition Duration per Runtime. I just didnt find a way to do access it. I found questions with similar problems though (links below) those didnt work for me because they accessed it to change it via editor script. But I need it in runtime. Is that even possible? https stackoverflow.com questions 29315507 unity 5 access modify animatorcontroller from c sharp script in editor


How to get interior uniform lightning? I'm trying to reach uniform lighting as in this image. This scene i've bought is rendered with 3ds and v ray (i suppose). This is the same scene i've imported in Unity. I've put a "big" point light on top of my room, i've added also directional light and a Reflection Probe. This is my (unsatisfactory) result This is my baking settings Do you have some advice to improove my Unity lightining as the first scene ? Thanks


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


Rotate an object smoothly by using Accelerometer Input in Unity There is a simple script where the object orientation is equal to the mobile devices orientation. it works but the object doesn't rotate smoothly. void FixedUpdate() float accelx Input.acceleration.x float angle Mathf.Asin(accelx) Mathf.Rad2Deg transform.eulerAngles new Vector3(angle , 0, 0) How to rotate an object smoothly by using Accelerometer Input ?


Bizarre Physics FixedUpdate Lag spikes So I have this large forest of around 2M tris Same chunk selected with view on the whole level It's been generated within Blender and exported as fbx into Unity. Exporting each tree as an individual object is very performance expensive so the whole forest is split into 2 Objects Treetrunks and leaves. The Treetrunks all have meshcolliders on them, the leaves obviously don't. (However I do split the forest into chunks as seen above, each chunk roughly 400k tris) When the Player gets outside visible range of the forest it is disabled, and enabled when the Player gets within a certain range. When it is enabled sometimes it causes a massive lag. When looking into the Profiler it shows this Physics? FixedUpdate? The leaves have absolutely no colliders on them, why does it take up Physics.Processing? So I wanted to search further what part of Physics.Processing takes up so much processing time but the top process already shows nothing I have an 8 year old GTX760 but it still manages to render the entire forest at 200fps so no, the 2 million Tris are definitely not overkill for my computer. I've tried this and that and 3 things managed to stop the issue (as seen in the profile screenshots above, the Physics processing time significantly reduced a few frames later) Pausing amp Unpausing the game or simply Alt Tabbing outside the Unity Player and back (not always effective) Disabling the Player amp Reenabling it (almost always effective) Starting the Scene with the Player (including Rigidbody, Camera and raycasting scripts) disabled and enabling him a few seconds later via script. (almost always effective) However this only worked if ALL of the forest was set active (roughly 2M tris). If half the forest was disabled on start, and activated after the Player was enabled LAG. The Player is the only thing in the game (at this moment) that has a Rigidbody, Raycasting Scripts and a camera. Things that didn't work Waiting a few minutes Disabling amp Reenabling the Players Character Controller at any time Disabling amp Reenabling the camera on the Player at any time. Disabling amp Reenabling the fucking trees Anyone got an idea? I'm dumbfounded over here.


Unity find position within range of object Say you have a gameobject that is at a certain position(this could be your player). Now say that you have a melee NPC that has to be within a certain range to hit the Player. Now you would do something like this to find out where the player is var targetPosition target.transform.position Say that the range of the NPC is 4 meaning he can be 4 units away from the player before he can start attacking him. My question is how would you subtract that to get a position that is within range? And am i doing this type of thing correctly? or is there a better way of doing it? ) Any help would be appriciated a lot!


Why when rotating object 360 degrees on the x, it rotates once then stops? using System using System.Collections using System.Collections.Generic using System.Linq using UnityEngine public class MeshGenerator MonoBehaviour public GameObject meshPrefab public Vector3 newVertices public Vector2 newUV public int newTriangles private List lt Vector3 gt verticesList new List lt Vector3 gt () private List lt Vector2 gt uvsList new List lt Vector2 gt () private List lt int gt trianglesList new List lt int gt () private GameObject go private void Start() Mesh meshprefab meshPrefab.GetComponent lt MeshFilter gt ().sharedMesh newVertices meshprefab.vertices newTriangles meshprefab.triangles for (int i 0 i lt newVertices.Length 2 i ) DrawLine(newVertices i , newVertices i 1 , Color.red) DrawLine(newVertices i 1 , newVertices i 2 , Color.red) DrawLine(newVertices i 2 , newVertices i , Color.red) void DrawLine(Vector3 start, Vector3 end, Color color, float duration 0.2f) go GameObject.Find("Lines") GameObject myLine new GameObject() myLine.transform.parent go.transform myLine.transform.position start myLine.AddComponent lt LineRenderer gt () LineRenderer lr myLine.GetComponent lt LineRenderer gt () lr.material new Material(Shader.Find("Particles Alpha Blended Premultiply")) lr.startColor color lr.endColor color lr.startWidth 0.05f lr.endWidth 0.05f lr.useWorldSpace false lr.SetPosition(0, start) lr.SetPosition(1, end) private void Update() var p go.transform.eulerAngles p.x 1 go.transform.eulerAngles p This is the rotation part private void Update() var p go.transform.eulerAngles p.x 1 go.transform.eulerAngles p It's rotating 360 degrees once, then it stops rotating but keeps shaking like it's trying to keep rotating but something keeps it from continue.


Applying a getButtonDown getButtonUp on a GUI button for touch input I have a GUI interface with a button for the character's attack, however I want to implement a defense button where the user can hold the button down to block incoming attacks, when the user stops touching the button then the player goes back to idle. Right now I have the attack button working correctly, whenever the button gets pressed, it triggers a method where the animator gets called and performs the action. I want to implement the getButtonDown("") and getButtonUp("") used commonly with the keyboard input. How can i implement such fucntions to a GUI button?


How to convert depth values into Unity's distance I am new in Unity and now only studying for my work project. I need help with computing real distances from depth values. Can't figure it out. My shader is Shader quot Custom MyDepthShader quot Properties MainTex ( quot Texture quot , 2D) quot white quot SubShader No culling or depth Cull Off ZWrite Off ZTest Always Pass CGPROGRAM pragma vertex vert compile function vert as vertex shader pragma fragment frag compile function frag as fragment shader include quot UnityCG.cginc quot struct appdata float4 vertex POSITION float2 uv TEXCOORD0 struct v2f float2 uv TEXCOORD0 float4 vertex SV POSITION v2f vert (appdata v) v2f o o.vertex UnityObjectToClipPos(v.vertex) o.uv v.uv return o sampler2D MainTex sampler2D CameraDepthTexture fixed4 frag (v2f i) SV Target float depth tex2D( CameraDepthTexture, i.uv).r depth Linear01Depth(depth) depth depth ProjectionParams.z return depth ENDCG I Blit then these values from renderTexture to texture2D and use function GetPixel(i,j). Knowing, that a cube is at 1.5 units distance from camera I can't get this value from depth texture. Thank you for your help. Now I suspect that I have got distance values, but they are biased by 0.5 for some reason... Can anyone explain this as well? I found how to get distances from depth texture, so basically I can answer this question, but there is still unexplained bias in measurements.


Trying to make pitch black night some meshes still dimly lit I have a directional light as a "sun". At night, I need a pitch black scene, but a mesh I'm using as terrain somehow stays faintly lit when the light intensity is 0. At night The direction light "sun" is rotated so it's beneath my world. The sun light is set to black, intensity to 0 I tried setting fog and ambient light color in RenderSettings to black I tried setting ambient intensity to 0 Notice how the background is lighter than the character. Something is causing that light to remain. However, if I enter playmode with the light object inactive, the coloring works fine.


Show Camera field of view in minimap but without y axis rotation Here is the function to draw a triangle that represents the camera field of view in a minimap. The problem with this code snippet is that when I rotate up and down (Change the pitch of camera) the viewport triangle also rotates up down. void makeViewPortCube() if (player.GetComponent lt Camera gt () null) Debug.LogError( quot Please assing a Main Camera to Follow quot ) return if (viewPortMesh null) viewPortGameobject new GameObject() viewPortGameobject.AddComponent lt MeshFilter gt ().mesh makeStartingMeshForViewPort(2.0f, 2.0f) viewPortGameobject.AddComponent lt MeshRenderer gt ().material materiaForViewPortGameobject() viewPortGameobject.name quot View Port Object quot viewPortMesh viewPortGameobject.GetComponent lt MeshFilter gt ().mesh viewPortGameobject.layer LayerMask.NameToLayer( quot MiniMap quot ) viewPortGameobject.transform.position new Vector3(viewPortGameobject.transform.position.x, transform.position.y 100, viewPortGameobject.transform.position.z) change vertices of the viewport Vector3 aVertexList viewPortMesh.vertices if (stopRotation false) Orignial aVertexList 1 player.GetComponent lt Camera gt ().ScreenToWorldPoint(new Vector3(Screen.width, 0, 10f)) aVertexList 2 player.GetComponent lt Camera gt ().ScreenToWorldPoint(new Vector3(Screen.width, 0, player.GetComponent lt Camera gt ().nearClipPlane)) aVertexList 3 player.GetComponent lt Camera gt ().ScreenToWorldPoint(new Vector3(0, Screen.height 4, player.GetComponent lt Camera gt ().nearClipPlane)) aVertexList 0 player.GetComponent lt Camera gt ().ScreenToWorldPoint(new Vector3(0, Screen.height 4, 10f)) for (int i 0 i lt 4 i ) aVertexList i .y 3 viewPortMesh.vertices aVertexList viewPortMesh.RecalculateBounds()


How can I get my player's character to slide along a rail? I am creating a snowboarding game and would like my player to be able to jump on a rail and move along it if it lands on it. I have no idea how to approach this. I have already tried using ray casts and waypoints but nothing works. I need to make sure the player moves along the rail, from any point that the player jumps onto it e.g. if they land in the middle of the rail they keep following its curve from that point. The rails are not straight and have curves on them. How can I get my player to be able to jump on a curved rail like this, and start sliding from the point they jumped onto it?


Conversion of a C library to DLL I'm developing an augmented reality application and I'm supposed to use the ALVAR library for AR marker detection. I use Unity as the game engine and unfortunately it doesn't support C . Is there any possible way to use the C library as a DLL?


Unity Default Shader Greyed Out I created a pland in Unity 3D and then tried to alter the material. I looked at it's material component, but all the options are greyed out! how do I fix this problem?


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.


Unity 3d Forge Networking Transfer object ownership I have a simple chess game setup to play around with the Forge Networking asset. I am having an issue where only the server is able to click and drag pieces around the board. If a client attempts to move a piece, it gets snapped back to its original position. I assume this issue is because the server is the actual owner of the NetworkedMonoBehaviour components on my chess pieces. Is it possible to transfer ownership of a NetworkedMonoBehaviour in code? It seems that all of the owner properties have protected set methods so I am unable to access any of them.


Finding the last GO in a set of generated objects? I currently generate the maptiles using Tags purely, which works great but doesnt satisfy my needs. I want to delete tiles that i dont need(since my player will only be going to the right) but I have a problem with checking when to delete old tiles so that i can generate new ones. My idea would be checking how close the player is to the last tile given and then delete the first, but i cant do that with tags since tags are given in the order that unity finds the GOs with that tag and not from left to right AFAIK. What would be the best way to get the last ground tile? (the one that got generated last). using UnityEngine using System.Collections.Generic public class MapGenerator MonoBehaviour private GameObject groundTiles lt summary gt Represents the minimum amount of active tiles needed lt summary gt public int ActiveTiles void Start() void Update() groundTiles GameObject.FindGameObjectsWithTag("ground") if (groundTiles.Length lt ActiveTiles) SpawnTile() public void SpawnTile() GameObject tile (GameObject)Instantiate(groundTiles groundTiles.Length 1 ) Vector3 tmpVec tile.transform.position tmpVec tile.transform.position tmpVec.x 1 tile.transform.position tmpVec public void DespawnTile(int tileIndex) List lt GameObject gt tmp new List lt GameObject gt (groundTiles) tmp.RemoveAt(tileIndex) groundTiles tmp.ToArray()


Unity Save load in a sandbox game, how to instantiate saved objects I have a game where a player can place GameObjects. I can save load this GameObjects data with using JSON, for example its position, but I cannot think of a good way to tell my save file (and my load) what Prefab it needs to instantiate at position X. How I could this be done in a clever way?


is there a way to alternate between two state machines? I'm programming an enemy on Unity that has two state machines, one controlling the quot normal quot behaviour of the enemy (that consists in three states idle, patrol and chase) and another one controlling the battle behaviour of the enemy (that consists in three more states attack, dodge and run away). I'm doing these state machines by using enums, like the following code public enum StateMachines NORMAL, BATTLE public enum NormalStates IDLE, PATROL, CHASE public enum BattleStates ATTACK, DODGE, RUNAWAY I want to loop between the Normal and Battle state machines but I have one problem that is they always get executed at the same time. Is there a way I can alternate between state machines through code in a single script (by conditions)? Thank you!


Why the transform never rotate between the range angle of 70 and 70? When running the game the rotationRange is always 0. using System.Collections using System.Collections.Generic using UnityEngine public class Rotateturret MonoBehaviour public enum RotateOnAxis rotateOnX, rotateOnY, rotateOnZ public bool randomRotation false Range(0, 360) public int rotationRange 70 private void Start() private void Update() if (randomRotation true) rotationRange Random.Range(rotationRange, rotationRange) transform.Rotate(Vector3.right, rotationRange) I want it to rotate on the x axis between 70 and 70


Unity Make sprite visible only to shaders I have made a shader for my UI buttons, the sprites should be black and white, so they can be used as a mask when blending. They should allow for the image behind them to pass through the whiter pixels and be blocked by the darker ones. I want to use this effect for my menu, have a black background and a colored one (like a gradient or a pattern), let the colored one pass only through the buttons and the black one everywhere else. My shader does just that, but with one problem. I can't hide the colored background from the camera. If I change it's layer it is useless (I guess because it is the child of a canvas), and if I use a regular sprite (non UI) it is just ignored by the camera and the buttons don't pick up the color. How can I achieve this effect, having the sprite be invisible to the camera but visible to the shaders of the buttons.


Bouncing ball loses its forward momentum after the first bounce I've created a bouncing ball in Unity, and I want to bounce the ball across the field, but the results I get seem very unrealistic. The ball should bounce in the direction it was launched 2 or 3 more times, but after the first launch the next bounce is bouncing at the same place, going straight into the air. I also didn't see any spin effect on the ball. How can solve this problem? And here's my physics settings


How can I apply the changes in runtime? using System.Collections using System.Collections.Generic using UnityEngine public class AnimFlyertransportationController MonoBehaviour public GameObject JetFlame public bool turnOffOn false Start is called before the first frame update void Start() TurnAllAnimtorsOff(transform, turnOffOn) if (turnOffOn) JetFlame.SetActive(false) else JetFlame.SetActive(true) Update is called once per frame void Update() private void TurnAllAnimtorsOff(Transform root, bool onOff) Animator animators root.GetComponentsInChildren lt Animator gt () foreach (Animator a in animators) if (onOff) a.enabled false else a.enabled true I want that if in runtime I change the turnOffOn flag state apply the changes in real time in the Update for all Animators and also for the JetFlame. Now it's only aply the changes in the editor before running the game.


Component based programming with child objects I am presently working on a game in Unity3d and have come to a cross road regarding scripting for repetitive child objects. Should these child objects handle its own scripting for best practice? For example, I have a parent game object, Game Board, that spawns repetitive child objects, Tiles, on the board. Right now, I let these child objects handle its own position on the board and its own animation when the tiles move. However, I can just as easily do this with the parent object's scripting class. The reason I chose to let the child object do so is because I believe that child objects should be as independent to the parent object as much as possible. But since these are repetitive child objects, I start to wonder if it is just as easy to do all the scripting in the parent object. This way I decrease the number of class instances in the child objects. According the component based programming, which method is recommended?


2D Unity How to make a enemy jump from a navmesh platform to another? I'm currently working on a 2d platformer, however I came across an issue where the enemy moves within a certain range of the platform. In this case I use a navmesh to limit the enemy's movement however I want the enemies to be able to jump within platforms. I'm not sure how to achieve this effect, where the enemy moves in the platform a couple of times and the jumps into the next one until the player gets in range for it to attack the player. How can I acheive this effect? Should i keep on using navmeshes or try another way around?


Photon2 Unity2D How to send float with RPC I have big problem in my code .. I want to spawn obstacle exactly on the same position as on the server is spawned so I made rpc Method and tried to pass random variable of float , but when i run the game obstacles are spawned on the diffrent position. I am loosing a lot of time to get it done but I still can not find solution. Here is the code PunRPC void RPC SpawnColumn(Vector3 position) Instantiate(prefab, position, Quaternion.identity) Debug.Log("THIS IS SPAWNYPOSITION" spawnYPosition) Instantiate(prefab, new Vector2(9, spawnYPosition), Quaternion.identity) private void OnTriggerEnter2D(Collider2D collision) print("Are we here") if (collision.GetComponent lt ColumnsMultiplayer gt () ! null) print("Or are we here") if (SpawnOnce) spawnYPosition Random.Range( 3.36f, 2.98f) photonView.RPC("RPC SpawnColumn", RpcTarget.Others,new Vector3(9, spawnYPosition)) this is SpawnColumn() SpawnOnce false Thank you so much for reading post. Edit I need to send spawnYPosition from method two to method one and spawn it with same position of spawnYPosition in the second method.


Unity CSharp Placing Instantiated Object in the Direction of Player So, I am making a Minecraft ripoff. I have a raycast that hits a block. It then places a block inside of that block. I am trying to make it place next to the block in the direction the user is facing. I got some of that figured out. I use Math.Round() to round up the floats. My problem is figuring out what axis to round on. I need it to depend on the direction the player is facing to figure it out. I tried doing a complicated algorithm to figure out which face of the collider the player is facing, but that didn't work out that well.... How do I solve this? I can't figure it out.


How can I completely hide and protect strings from the player in Unity? I have been using Unity to create a 2D game which will be completely offline (which is the problem), the game play needs you to enter certain strings at certain levels and Unity compiles to DLLs, which can be easily reverse engineered, so is there a way to protect those strings (the game is offline so I can't retrieve from other source)? The game relies heavily on those strings, and yes I'm aware of Obfuscation but I want something more robust. And I know that the easy way out would be doing everything online from a data source but I was wondering if it's possible. It can be decompiled like this


Touch input not working well for mobile game made with Unity 2D I made a simple game in unity where the user taps their phone screen and the player jumps up. When I test it on my phone (not sure if this matters but it's a Samsung s9 ), I tap the screen and usually the tap causes the player to jump up and fall back to the platform properly, but sometimes when I tap the screen nothing happens at all it just stays in place. The game on my phones is also very slightly laggy (although, on my computer it runs smoothly) and I'm not sure how to fix that either or if they're related. This is the code attached to the player void FixedUpdate() Jump() Dead() void Jump() if (Input.touchCount gt 0 amp amp isGrounded) gameObject.GetComponent lt Rigidbody2D gt ().AddForce(new Vector2(0f, jumpForce Time.fixedDeltaTime), ForceMode2D.Impulse) Also, I know that it's the touch input that's the problem, because when I make it so that pressing the up arrow key on the keyboard makes the player jump, it works perfectly fine. If there's some other information about the game you'd need to know to answer my question, let me know. Thanks for your help.


PS3 controller with Unity on Mac I am trying to use my PS3 Controller with Unity but it has been unsuccessful. I followed this video to do so https www.youtube.com watch?v LcettC1QHu4 I have done the same thing as the video but for some reason unity is not getting ANY input from the controller. I have tested the controller with another commercial game on my Mac and it works perfectly, so my controller is well connect to my computer. here is a screenshot of the input manager joystick button 0 is the X button


Text Based Tutorials for Unity3d I hope this is the right place to ask this. I'm very new to Unity but not to programming. I also have some basic game programming experience. I'm searching for text based versions of the videos from unity3d.com learn tutorials. These tutorials are very good, but I end up forwarding videos a lot to get key screenshots and code snippets. Is there any text pdf html .doc .rtf (i'm very open) version or similar resource to learn unity? Again, those tutorials are amazing and I'd hope to find something of similar quality, but I know that if I have to skim through tens of hours of video I'll end up frustrated. I get that the long hard way is probably the most robust one for deeper understanding, but I was hoping to hack a quick project. EDIT If this can make it a relevant question, then I am currently looking at the "Roll a Ball Tutorial". Really, any other text tutorial would be very welcome


CharacterController should I work with FixedUpdate or with Update? I know that updates related to the physics engine should be made in FixedUpdate, but I am not sure about updates related to CharacterController should they be done in Update or FixedUpdate? I tried both options and putting them in FixedUpdate appears smoother, but this may be due to other factors, so I would be happy to know what the recommended practice is.


Vuforia jewellery try out without marker I need to create a virtual jewellery try out in unity 3d vuforia. I have done it with marker as a target but now i need to do it without marker. Is there any way we can track live objects using userdefined targets i mean face , neck ,arm, finger using vuforia. I have done a lot of research but didnt got anything useful.


Unity How to receive input events on a RectTransform that does not contain any image text ...? In Unity 2018.3 Imagine a GameObject with only a RectTransform component and a custom script attached to it otherwise completely empty. Is there a way to receive input events (like IPointerClickHandler.OnPointerClick) without adding any graphical GUI components like text image rawimage etc. ? In other words Is there a component or superclass available to receive input events without adding an unused graphical component? Any clarifications are welcome, Thank you.


Putting a material on a fractured model I have a square model that has been fractured using blender's cell fracture. I also have a material that I want to apply onto the broken pieces. The only problem is that the material needs to be organized in a certain way so it looks right when I replace it with the broken model. Scripting wise i'm using Brackey's tutorial for destruction How can I make the material look the same on both the fractured and the unfractured model? I also left a picture if it helps. The one on the left, is the unbroken model with the material. The one on the right is the broken model with all the cells having the same material.


My orbit code produces the wrong results I have a GameObject called "Sun" in the sky. A game object called "GameManager" keeps track of time in the game, it is responsible for updating the hours and days. For my sun I do something like this to get a percentage to use for the position of the sun on the orbit circle float percentage (((float)theGameManager.GetHourOfDay() (float)GameManager.numberOfHoursInADay) 360.0f) I have a piece of code that can return the point in a circle if given a radius, an angle and an origin point. public static Vector3 GetPointInCircle(float radius, float angleInDegrees, Vector3 origin) Vector3 resultingPoint new Vector3(0.0f, 0.0f) resultingPoint.x origin.x radius Mathf.Cos(angleInDegrees) resultingPoint.y origin.y radius Mathf.Sin(angleInDegrees) return resultingPoint I use this function to determine the suns position each frame, as the angle i am passing is just the percentage of the circle, i expect the percentage variable to give increasingly bigger angles that make up 360 degrees. It does. However when I set the suns new position using Vector3 newPos new Vector3(MathsHelper.GetPointInCircle(sunOrbitRadius, percentage, new Vector3(50.0f, 0.0f, 50.0f)).x, MathsHelper.GetPointInCircle(sunOrbitRadius, percentage, new Vector3(0.0f, 0.0f, 0.0f)).y, transform.position.z) transform.position newPos and the resulting behavior is the sun jumping to totally random positions around the circle, often picking ones that are near the start and end of the circle (by hour 4 the y value is already negative, which shouldn't be the case). I notice if I swap out the percentage variable for Time.time it works perfectly, however this does not give me control over the sun in accordance to GameManagers day tracking and I feel like I am missing something obvious as to me it looks as though the math should work. Additionally, I am using C in Unity.


Vector3 Array serialization ReorderableList I've been working on a ReorderableList, but it's given me quite the headache. I've come to the point where I want to define a "drawElementCallback" callback, which looks like this list.drawElementCallback (rect, index, active, focused) gt EditorGUI.PropertyField(rect, list.serializedProperty.GetArrayElementAtIndex(index), GUIContent.none) What it's supposed to draw is one Vector3 object from an array of Vector3 objects. I get this property like this ("property" is a SerializedProperty that contains the property that I need) SerializedProperty locationsProperty property.FindPropertyRelative("locations") The array is declared as follows public Vector3 locations Inside a container class that is marked as "Serializable". The problem I kept getting with different code is that the ReorderableList shows all the Vectors correctly but it doesn't allow me to reorder any of the items, nor delete them (I can add new Vector3 objects and change them as expected). With this code, I wanted to fix that issue. However, now I keep getting the following error "InvalidOperationException The operation is not possible when moved past all properties (Next returned false)" I wanted to make a reorderable list because it seemed easy, but I can't figure out the problem and I honestly wish I hadn't started working on it. It's taken up most of the past 3 days. If anyone knows how to fix this, I would be very grateful. To clarify, this code shows the array properly list.drawElementCallback (rect, index, active, focused) gt SerializedProperty item locationsProperty.GetArrayElementAtIndex(index) EditorGUI.BeginChangeCheck() item.vector3Value EditorGUI.Vector3Field(rect, string.Empty, item.vector3Value) But doesn't allow me to remove or reorder items. I thought I should show the code to demonstrate that there are indeed array items.


Not sure how to deal with overlapping UI As shown above, that is the issue I am faced with, tbh I am unsure how to fix it, I have tried and its coming to a point where I am drawing blank. I am quite newbie when it comes to this. So what I have now is multiple canvas each one displaying the name of the part that it is linked to and when the part moves so does the UI with it, the problem I have is that some parts dont move and therefore creating the issue of UI clustering together, so I need to move the UI rather than the parts. What I have tried is OnTriggerEnter and adding a box collider rigidbody to the canvas and tried to move the UI when they collided but I couldnt get that to work, probably down to me. if (gameObject.tag "car") get the gameObjects name that canvas is attached to canvasName.text gameObject.name newPos mainCam.ScreenToWorldPoint(this.transform.position) set the position of the UI newPos.x transform.position.x newPos.y transform.position.y 7f newPos.z transform.position.z canvas position if ( canvas ! null) canvas.transform.position newPos That is the code that I am using to attach the UI to the part. I was hoping to try something along the lines, but then again I am clueless. if collision is detected, newPos.y newPos 2f etc... So any help would be appreciated. Apologies if that was explained bad.


Accessing a char array from another class I'm working on a crossword puzzle game. In order to set the letters in my tiles, I have a script attached to text components that accessing a char array that stores my letters. It looks like this First class public class GenerateBoard MonoBehaviour public static char , gameBoard new char 15,15 void Start() gameBoard 0, 0 'W' Second class public class SetLetter MonoBehaviour Text letter public int x public int y Start is called before the first frame update void Start() letter GetComponent lt Text gt () letter.text GenerateBoard.gameBoard x,y "" Update is called once per frame void Update() Debug.Log("glitch " GenerateBoard.gameBoard 0, 0 ) I would expect Debug.Log to print 'W' but it appears to be empty. Why isn't it accessing the letter 'W' from the first class? When I use Debug.Log in my first class it properly prints 'W'.


Using keyword NonSerialized causes Property to disappear from Inspector I have the following class to represent items in an inventory System.Serializable public class InventoryItemInfo MonoBehaviour public int Row 0 public int Col 0 public int Rotation 0 public InventoryItemType ItemType public int Amount public int EffectiveWidth 0 public int EffectiveHeight 0 public int Width 0 public int Height 0 public bool Selected false public Vector3 TilePosAccordingToCurrentRotation public Vector3 TileScaleAccordingToCurrentRotation NonSerialized public Transform TheNicelyPositionedMesh HideInInspector private int iCurRow 0 private int iCurCol 0 private int iRotationToCheckForDirtyness 1 public Vector3 DefaultRotation public bool Initited false public bool Dirty true private bool bInitialRotationGotten false (...) With the keyword NonSerialized , the property "TheNicelyPositionedMesh" disappears from the Unity Inspector. I don't see why. Why is that keyword coupled with the visibility in the Inspector? Thank you!


Artifacts at seams between meshes in Unity in isometric camera only I'm trying to piece together some very simple placeholder models that I intend to use as tiles in Unity and I'm seeing odd pixel artifacts along the seams of the tiles that only show up when using an isometric camera. You can see them in this image. And the same geometry but just from a perspective camera shows no artifacts. I verified that the two models are exactly aligned right along the seam by checking the actual vertex data. The artifacts are dependent on the camera itself and shift along the seam as the camera is panned and zoomed. I've disabled shadows, set the texture filter mode to point, disabled mipmap generation The geometry is quite simple and is imported from the OBJ file below. normals vn 1 0 0 vn 1 0 0 vn 0 0 1 vn 0 0 1 vn 0 1 0 vn 0 1 0 texcoords vt 0.970703 0.5 vt 0.974609 0.5 verts v 0 2 0 v 0 2 4 v 0 2.3 0 v 0 2.3 4 v 0 2.5 0 v 0 2.5 4 v 4 2 0 v 4 2 4 v 4 2.3 0 v 4 2.3 4 v 4 2.5 0 v 4 2.5 4 faces f 3 2 1 2 2 1 1 2 1 f 4 2 1 2 2 1 3 2 1 f 5 1 1 4 1 1 3 1 1 f 6 1 1 4 1 1 5 1 1 f 7 2 2 8 2 2 9 2 2 f 9 2 2 8 2 2 10 2 2 f 9 1 2 10 1 2 11 1 2 f 11 1 2 10 1 2 12 1 2 f 7 2 3 3 2 3 1 2 3 f 9 1 3 5 1 3 3 1 3 f 9 2 3 3 2 3 7 2 3 f 11 1 3 5 1 3 9 1 3 f 2 2 4 4 2 4 8 2 4 f 4 1 4 6 1 4 10 1 4 f 8 2 4 4 2 4 10 2 4 f 10 1 4 6 1 4 12 1 4 f 2 2 5 7 2 5 1 2 5 f 8 2 5 7 2 5 2 2 5 f 5 1 6 11 1 6 6 1 6 f 6 1 6 11 1 6 12 1 6 With the following texture applied as Albedo on a default Unity material (a bit odd since it was originally generated in MagicaVoxel) I'm really at a loss for what could be causing these to show up. Only spotted them because I was testing an outline shader and it was outlining all the artifacts as the normals on those pixels were odd. With a pixel shader set to display CameraNormalsTexture instead of the color the artifacts are still visible as variances in the normals as you can see in the image below.


Unity Is it possible to copy a rig from one model to another Lets say I have a model with a ready humanoid rig and a humanoid model with no rig. Can I somehow copy the bones from the rig to the model with no rig in unity?


ScreenToWorldPoint problems in otherwise awesome Unity demo I am using this neat Unity demo I found on Stack Overflow, which demonstrates texture masking via RenderTexture Can you erase a texture in real time in Unity But the mapping from mouse position to world space is wrong. This is the script that does the mapping using UnityEngine using System.Collections public class MaskCamera MonoBehaviour public Material EraserMaterial private bool firstFrame private Vector2? newHolePosition private void CutHole(Vector2 imageSize, Vector2 imageLocalPosition) Rect textureRect new Rect(0.0f, 0.0f, 1.0f, 1.0f) Rect positionRect new Rect( (imageLocalPosition.x 0.5f EraserMaterial.mainTexture.width) imageSize.x, (imageLocalPosition.y 0.5f EraserMaterial.mainTexture.height) imageSize.y, EraserMaterial.mainTexture.width imageSize.x, EraserMaterial.mainTexture.height imageSize.y ) GL.PushMatrix() GL.LoadOrtho() for (int i 0 i lt EraserMaterial.passCount i ) EraserMaterial.SetPass(i) GL.Begin(GL.QUADS) GL.Color(Color.white) GL.TexCoord2(textureRect.xMin, textureRect.yMax) GL.Vertex3(positionRect.xMin, positionRect.yMax, 0.0f) GL.TexCoord2(textureRect.xMax, textureRect.yMax) GL.Vertex3(positionRect.xMax, positionRect.yMax, 0.0f) GL.TexCoord2(textureRect.xMax, textureRect.yMin) GL.Vertex3(positionRect.xMax, positionRect.yMin, 0.0f) GL.TexCoord2(textureRect.xMin, textureRect.yMin) GL.Vertex3(positionRect.xMin, positionRect.yMin, 0.0f) GL.End() GL.PopMatrix() public void Start() firstFrame true public void Update() newHolePosition null if (Input.GetMouseButton(0)) Vector2 v camera.ScreenToWorldPoint(Input.mousePosition) Rect worldRect new Rect( 8.0f, 6.0f, 16.0f, 12.0f) if (worldRect.Contains(v)) newHolePosition new Vector2(1600 (v.x worldRect.xMin) worldRect.width, 1200 (v.y worldRect.yMin) worldRect.height) public void OnPostRender() if (firstFrame) firstFrame false GL.Clear(false, true, new Color(0.0f, 0.0f, 0.0f, 0.0f)) if (newHolePosition ! null) CutHole(new Vector2(1600.0f, 1200.0f), newHolePosition.Value) I fixed line 49 and 50 like so Vector2 v GetComponent lt Camera gt ().ScreenToWorldPoint(Input.mousePosition) Rect worldRect new Rect(0.0f, 0.0f, 16.0f, 12.0f) So the script compiles and the worldRect is in the right place now. Through debugging I found that the world coordinates returned on line 49 are off. I also tried setting the z value of mousePosition to 10, even though the cameras are orthographic, like so Vector3 mousePos Input.mousePosition mousePos.z 10 Vector2 v GetComponent lt Camera gt ().ScreenToWorldPoint(mousePos) The mapping from the mouse to worldspace is still wrong though. Mouse coordinates within a small rectangle near the center are mapping to the full width and height of the image in world space.


Confused by scaling, units, and more Ok, so I've already waded through a bunch of questions around this, and it's just making me even more confused. Let's say I am trying to model a card table in a 2d game. Behind (beneath) the table is a quad with a floor texture. The "table" is a sprite that is just an oval (using basic shapes at this stage until I have real artwork). I've read plenty of questions on how to scale to different device resolutions. And, that is certainly one way to do it (bit seems like a lot of work). I've also read posts about changing the size of the orthographic camera to match the device (this seems easier). But i'm left not quite understanding what the frame of reference is. Let's say I design the game to work in 16 9 at HD resolution (1920x1080). I size the "floor" to fill the entire space (and maybe extend a little beyond). I size the "table" to fit within a smaller portion of that space. If you have a fixed scene (ie, not a scroller), and you want the contents to fill the entire viewport, what is the best way to go about this? Scaling the objects, scaling the camera? As far as units, what's the best choice? 1 PPU? What rule of thumb do you use when choosing PPU? What are the reasons to choose different PPU's? I think i'm missing the forest for the trees. I understand so many of the basic concepts from reading so many questions, I just don't know how to put them together and when to choose which method.


VertexColor shader is not working correctly in built application I want to change the vertex colors of my mesh. The light sources must not affect the objects with this shader, its lighting must be determined only by its vertices colors, so I turned the Lighting Off. I use this simple shader Shader "VertexColored Simple" Properties MainTex ("Base (RGB)", 2D) "white" SubShader Pass ColorMaterial AmbientAndDiffuse Lighting Off SetTexture MainTex Combine texture primary Fallback "VertexLit" And this script using UnityEngine using System.Collections public class BehaviourScript MonoBehaviour void Start() Color exclrs new Color 11 new Color32(25, 25, 25, 255), new Color32(50, 50, 50, 255), new Color32(75, 75, 75, 255), new Color32(150, 150, 150, 255), new Color32(200, 200, 200, 255), new Color32(255, 255, 255, 255), new Color32(200, 200, 200, 255), new Color32(150, 150, 150, 255), new Color32(75, 75, 75, 75), new Color32(50, 50, 50, 255), new Color32(25, 25, 25, 255), Mesh mesh GetComponent lt MeshFilter gt ().mesh Vector3 vertices mesh.vertices Vector3 normals mesh.normals Color colors mesh.colors for(int i 0 i lt vertices.Length i ) for(int j 0 j lt 11 j , i ) colors i exclrs j i mesh.colors colors When the game is launched, in editor I can see this This is EXACTLY what I wanted to achieve! But in built for PC(x86) version I see this Why the results from the editor and from the built .exe differs? What should I do to see my effect in built version? Maybe I need to use an another shader?


Unity3d Detect a collision between an image and a sphere So, I just realized, an image with BoxCollider2D wont detect any collision with Sphere with SphereCollider. I tried adding a BoxCollider to my image, but it behaves in a weird manner (The Canvas position keeps shifting) So, I can see the only way for it to work is adding a 2D Collider to the sphere? Is there any other better way to solve it? Adding a 2D Collider to the sphere wont cover the whole area


In Unity shaders, how is IN.worldRefl calculated? I want to know how the world reflection vector in shaders is calculated so that I can manipulate it, but there is no documentation on what it does or how Unity calculates it. How is the reflection vector calculated and exactly what does it do?


UniRX, how much of it should I use? for good optimization I come from the Front End dev world and I'm taking my baby steps in Unity. I'm already very familiar with RXJS and glad to see it being re coded into almost every other big language (there's starting to be quite a few) Java RxJava JavaScript RxJS C Rx.NET C (Unity) UniRx Scala RxScala Clojure RxClojure C RxCpp Lua RxLua Ruby Rx.rb Python RxPY Go RxGo Groovy RxGroovy JRuby RxJRuby Kotlin RxKotlin Swift RxSwift PHP RxPHP Elixir reaxive Dart RxDart And as I discovered and as you can see, it is available in Unity flavor. here's a quick intro https youtu.be kFoBvjwzbNA But not every framework or environment or every variable and event is necessarily improved by RX, or is it? Since I don't quite understand how Unity operates internally (nor do I plan to do that fully, I have a game to make), I'd like to know is it a performance gain or a performance loss, to use UniRX to (for example) store every input my game might need into observables, and then susbcribe to those observable versions of user Inputs wherever applicable in my C scripts?, or does the repeated use of the Update() method to listen to inputs in multiple scripts get interpreted somehow by Unity at compile to automatically optimize the built code and adding my extra RX step would just be a net loss? What about game state, and, say I'm coding an RTS, unit states? What about RayCast Hits, should I make those observable? What UniRX usages are poor practice, and which result in performance gain optimized code? (especially with my given examples in mind) The obvious use case is game UI, obviously, but disregarding that, what could I extend UniRx usages to? PS Since UniRX is a relatively new topic here could someone with 3000 points create the unirx tag and add it to my question please?


"Following" Object is acting Strangely? So I recently designed an enemy that will follow the player when he comes within a certain distance of the object. However, there are times when the player comes in range, only for the "follower" enemy to seemingly reverse before following, or almost kind of circle the player on the way towards him. I can't quite put my finger on why this is happening, so I have attached my code. I hope someone can give me some advice on how to improve this public class Follower MonoBehaviour spawn position and other info of Follower private Vector3 pos1 new Vector3( 7f, 0.5f, 7f) public float speed 1.0f public int Range public GameObject target private Vector3 targetTran private Vector3 diffVec private float diffMag void Awake() transform.position pos1 sourceCollFol GetComponent lt AudioSource gt () void Start () target GameObject.FindWithTag("Player") targetTran target.transform.position void Update () pos1 transform.position targetTran target.transform.position diffVec (targetTran pos1) diffMag diffVec.sqrMagnitude check for range between Player and Follower Enemy if ( diffMag lt Range) transform.LookAt(targetTran) diffVec.Normalize() transform.Translate(diffVec.x speed Time.deltaTime, 0f, diffVec.z speed Time.deltaTime)


How to stop switching between paths to a moving target? I've noticed after implementing A pathfinding into my game, that there is exploitable unrealistic behavior that goes on when the player moves between two nodes that alter the path of the AI trying to reach them. I have made a few images to demonstrate this problem. This image above shows how the pathfinding in my game would behave if the player stood on the opposite side of a wall than my AI. If the player doesn't move it will take this single path to reach them. Assume that the red icon is the AI (enemy) and the blue icon is the target (player). Now, if the player in this image above moves along the white arrows up and down, and the AI is constantly finding the optimal path to the player (ignore the performance costs of doing that), then the AI will also get stuck moving up and down because the optimal path will constantly shift between going above the wall and going under the wall. Is there a way to modify a standard A implementation to remedy this? I will include my pathfinding code for clarity, but it's pretty much a standard top down implementation. The "Node" object is a node on my grid, and the grid is an object that holds a list of nodes, with a few functions to find a node from a world point. public class Pathfinding MonoBehaviour public Transform seeker, target AstarGrid grid void Awake() grid GetComponent lt AstarGrid gt () public List lt Node gt FindPath(Vector3 startPos, Vector3 targetPos) Node startNode grid.NodeFromWorldPoint(startPos) Node targetNode grid.NodeFromWorldPoint(targetPos) List lt Node gt openSet new List lt Node gt () HashSet lt Node gt closedSet new HashSet lt Node gt () openSet.Add(startNode) while (openSet.Count gt 0) Node node openSet 0 for (int i 1 i lt openSet.Count i ) if (openSet i .fCost lt node.fCost openSet i .fCost node.fCost) if (openSet i .hCost lt node.hCost) node openSet i openSet.Remove(node) closedSet.Add(node) if (node targetNode) return RetracePath(startNode, targetNode) foreach (Node neighbour in grid.GetNeighbours(node)) if (!neighbour.walkable closedSet.Contains(neighbour)) continue int newCostToNeighbour node.gCost GetDistance(node, neighbour) if (newCostToNeighbour lt neighbour.gCost !openSet.Contains(neighbour)) neighbour.gCost newCostToNeighbour neighbour.hCost GetDistance(neighbour, targetNode) neighbour.parent node if (!openSet.Contains(neighbour)) openSet.Add(neighbour) return null


Wrong Second position of LineRenderer I'm drawing some kind of bullet trace effect with LineRenderer in my 2D Game Project with Unity. At some position, setting position of LineRender result weird In the above screenshot, you can see two types of lines are exists. Pure red lines are result of Debug.DrawRay which is only renders in Scene view, not actual game play, and another lines which has yellow to red gradient are actual line renders I want to draw. I used exactly same code for rendering both two, Debug.DrawRay() and LineRenderer.SetPosition(), but as you can see only DrawRay works as I expected and LineRenderers are cutted and pointing wrong direction. Here's the code I'm trying void Fire() Vector3 shootDirection m ShootPoint.right RaycastHit2D hit Physics2D.Raycast(m ShootPoint.position, shootDirection, m Range) Debug.DrawRay(m ShootPoint.position, shootDirection.normalized m Range, Color.red, 20) On Hit, set end position where it hits if (hit) CreateBulletTrace(m ShootPoint.position, hit.point) Otherwise, render straight until it's range else CreateBulletTrace(m ShootPoint.position, shootDirection.normalized m Range) void CreateBulletTrace(Vector3 startPos, Vector3 endPos) GameObject bulletTraceObj Instantiate(m BulletTraceLineRendererPrefab) LineRenderer bulletTraceLineRenderer bulletTraceObj.GetComponent lt LineRenderer gt () bulletTraceLineRenderer.useWorldSpace true bulletTraceLineRenderer.SetPosition(0, startPos) bulletTraceLineRenderer.SetPosition(1, endPos) Destroy(bulletTraceObj, 0.1f) Note that LineRenderer checked use world space to true. What am I missing? Using Unity 2019.1.0f2.


Object reference not set to an instance of the object using System.Collections using System.Collections.Generic using UnityEngine public class PlayerMovement MonoBehaviour public CharacterController2D controller public float runSpeed 40f private float horizontalMove 0f Update is called once per frame void Update () horizontalMove Input.GetAxisRaw("Horizontal") runSpeed void FixedUpdate() controller.Move(horizontalMove Time.fixedDeltaTime,false,false) error is somewhere here Though all the classes are defines it throws the error please help!!!!!


Why aren't the Physics2D.Raycasts reliably colliding with the 2D Box Collider walls? I've got this NPC walking around and I'm trying to create a cone to represent their line of sight, including how it would be blocked by buildings, similar to how Nicky Case has implemented it as described here https ncase.me sight and light My main problem with this, right now, is that it seems like I'm not detecting collisions between my 2D box colliders and Physics2D.Raycast when I would expect to much of the time. The green rays in the image below are NOT colliding (this is fine on the corners, I don't really care, but when the rays are going straight through walls, that's a big problem for me). Red rays are colliding. Why aren't the Physics2D.Raycasts reliably colliding with the 2D Box Collider walls? I believe everything is in the same z plane and has the correct collision matrix in place. ! image of my NPC and raycasts from them at various points along their path List lt UnityEngine.Vector2 gt endPoints new List lt UnityEngine.Vector2 gt () GameObject corners GameObject.FindGameObjectsWithTag("verticies") corners MUST BE WORLD ORIENTED! for(int i 0 i lt corners.Length i ) UnityEngine.Vector2 corner new UnityEngine.Vector2(corners i .transform.position.x, corners i .transform.position.y) RaycastHit2D endPoint Physics2D.Raycast(this.transform.position, corner) if(endPoint.collider ! null) endPoints.Add(endPoint.point) Debug.DrawLine (this.transform.position, endPoint.point, Color.red) else Debug.DrawLine (this.transform.position, corner, Color.green)


Unity Build looks different then gameview runtime reflection probes not working correctly Im having a really hard time figuring out how to configure my reflection probes to update in runtime once I build. The game port view looks totally different than the build view. Ive tried turning off baked GI in the lighting scene panel, and unchecking "auto" under "other settings" but keep getting an error message "baking lighting data asset failed" when I try to build the light maps. Maybe this is not the right way to solve the problem? Has anyone else encountered this and figured it out?


How can I render from a buffer that exists and was created on on the GPU? I'm looking for a unity API or function call to allow me to do the following ... I wrote some really complex functions that are compute shaders. These compute shaders manage a huge compute buffer containing voxel information. I then take portions of (or the entire) voxel buffer in another compute shader and produce a vertex buffer. All of this is done on the GPU with only compute shader calls from the CPU. Now I want to render that vertex buffer but I must be looking in the wrong place because I can't find any information on how this is done within unity despite there being other examples on how to do this using raw DX or openGL approaches. Can anyone point me in the right direction to determine how I can render using a specified shader a buffer already in graphics RAM (and ideally give it some textures too)?


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


unity 5 how to get a shadowmap I'm writing a custom shader in unity 5 that requires a shadowmap (not just for drawing shadows but also for different computations involving scattering particles through fog). Does anybody know how to actually get the shadow map in unity rather than just using the fallback option? That is including the actual Z buffer not just the resulting 1's and 0's. I could also use the depth buffer from the camera but that only appears to apply to camera used by the player rather than the second one I can add to replace the light (inside the light).


Display hide image with zoom in out After spending a while looking through the forums, I haven't been able to find a thread that deals with transforms on an image. Essentially, what I'm trying to do is display and hide an image at the start of a level in a game I'm working on. The image should start out large and with 100 transparency, then shrink to a certain size within the camera bounds with no transparency, idle for a second, then fade back out the way it came. How would this be done programmatically? Thanks in advance!


Unity sprites and layouts I am trying to learn Unity for a simple board game. The question is, is it possible to use grid layout group (or any layout component) with sprites? The goal is to fit a board into my view regardless of the aspect ratio of the device. The following grid should contain 7 by 7 sprites and it should scale up and down (no more then lets say 100 px) and have an aspect ratio of 1. I've tried adding a canvas and a panel that has a grid layout group component but it seems like sprites are not affected when added to the panel. Also it seems like when I try to work with a panel or a canvas they have a fixed sizes in units. Having fix sizes feels a little bit off. Is there a way to use layout components so sprites can have relative distances between them. So far I am stuck and lost in tutorials and feeling like the answer should not be this complicated. Any push to the right direction is welcome.