Respawn not working properly upon scene reload. Why is this? So I made a respawn function and what is supposed to happen is the script it supposed to load a saved checkpoint. However I need to reset the scene (and again this worked just fine last night which was odd...). Essentially the checkpoint waits for a player and then when the player enters the current checkpoint is written to a .txt file. Upon reload or death the scene is restarted, the .txt file is read and grabs the checkpoint. Everything works fine without Scene scene SceneManager.GetActiveScene() SceneManager.LoadScene(scene.name) Reload scene. but I need that in order to "refresh" the scene. CheckPoint Code using UnityEngine using System.Collections public class Checkpoint MonoBehaviour public LevelManager levelManager Empty level manager. Use this for initialization void Start() levelManager FindObjectOfType lt LevelManager gt () Unnneeded void OnTriggerEnter(Collider coll) if (coll.tag "Player") levelManager.currentCheckPoint gameObject lt DISABLE WHEN ES2 is fixed!!! Debug.Log("Activated Checkpoint " transform.position) ES2.Save(gameObject.name, "myFile.txt?tag checkpoint") Saves checkpoint to file. LevelManger Code using UnityEngine using System.Collections using UnityEngine.SceneManagement public class LevelManager MonoBehaviour Tooltip("Note this will also serve as the spawnpoint for the player!") public GameObject currentCheckPoint private GameObject player private int PHP public int RespawnHP Amount of health to give player upon respawn. void Awake () Use this for initialization void Start () player GameObject.FindGameObjectWithTag("Player") Update is called once per frame void Update () PHP GameObject.Find("InventoryManager").GetComponent lt InventoryManager gt ().PlayerHealth if (PHP lt 0) Debug.Log("Player HP has been depleted. Respawning.") RespawnPlayer() if (Input.GetKeyDown("r")) Debug.Log("Restarting level!") RespawnPlayer() public void RespawnPlayer() Scene scene SceneManager.GetActiveScene() SceneManager.LoadScene(scene.name) Reload scene. currentCheckPoint GameObject.Find(ES2.Load lt string gt ("myFile.txt?tag checkpoint")) Load saved checkpoint. Debug.Log("Player Respawning...") player.transform.position currentCheckPoint.transform.position GameObject.Find("InventoryManager").GetComponent lt InventoryManager gt ().PlayerHealth RespawnHP void RestartLevel() ToDo Restart level, and reload last check point. public static void SaveLevel() Saves the current level to file. ES2.Save(SceneManager.GetActiveScene().name, "myFile.txt?tag levelName") Saves level to file. ES2.Save("none", "myFile.txt?tag checkpoint") Overwrite checkpoint? Does anyone have a clue what is wrong? Like I said earlier the problem seems to arise on scene reloading. Response to comment(s) What behaviour are you observing at the moment? Jack Currently what happens is the player enters a checkpoint, the checkpoint is saved to a file, and upon respawn the checkpoint is loaded. After this I get spawned to the checkpoint that was saved but then immediately the level reloads itself and the player is not respawnd at the checkpoint. Here is a video to better demonstrate the issue (it will take a minute or two to finish up processing here as I've just pasted the link).


How to get the position of individual characters in TextMeshPro (Unity)? I am making a typing game. There are words falling down what the user have to type, before they can call the OnBecameInvisible() event. When the user types a character I want to apply a force and a torque to it and make it fall down. But to do this I have to instantiate a TextMeshPro GameObject at the position where that letter was located inside that word. But how can I get that position? Just to make things clear


Unity (C ) How can I create dialogue to be used in my game? (also critique my system?) I've created my own system for handling dialogue. There's a class for each 'node' or part of dialogue. It contains the following variables identifier (identifiers are unique for each NPC, but not globally, ie "1", "2"), a text variable, a list of strings (which are the option button values), another list of strings (which contains option identifiers), and a string which is used for passing custom functions through. A collection of these Dialogue classes are made, and then stored in a dictionary, with the key of each being the identifier. public string identifier public string text public List lt string gt options public List lt string gt optionIdentifiers public string onCloseFunction public Dialogue(string identifier, string text, List lt string gt options, List lt string gt optionIdentifiers, string onCloseFunction "") this.identifier identifier this.text text this.options options this.optionIdentifiers optionIdentifiers this.onCloseFunction onCloseFunction At the start, the dialogue with identifier 1 will be chosen, and the text displayed, with each of the buttons. If the first option is chosen, that is index 0 in the options list. The index selected is used to get the correct identifier from the identifier list, which will return "2 1". This is then used to find the next dialogue. The system fortunately works, however I'm wondering if I've overcomplicated this, and if there's a simpler way to do this. Building further on this, it isn't easy to sort out the conversations to appear in. I have made the class 'Dialogue' serializable, so the properties are displayed in the unity window. I've made a public array of dialogue, which then is turned into a dictionary with the corresponding key identifiers. public Dialogue dialogueList public DialogueLibrary dialogueLibrary void Awake() Dictionary lt string, Dialogue gt dict new Dictionary lt string, Dialogue gt () for(int i 0 i lt dialogueList.Length i ) Add all dialogue from inspector into dictionary dict.Add(dialogueList i .identifier, dialogueList i ) dialogueLibrary new DialogueLibrary (dict) This allows me to add dialogue as such The biggest problem I have with this, is the fact that it's just... not very nice to deal with. For example, if there were 30 pieces of dialogue, and I wanted to add another between 2 and 3, I would have to either increase every identifier afterwards, or use something like 2a for an identifier. Furthermore, it would be a lot better if I could read the dialogue list from an XML file. What I'm stuck with is how I can create this XML file. I need some software that can simply create the conversations and export them in XML. Honestly I'm not sure how to go about this. Is there any software which exists already which could do something like this, or should I create my own in Visual Studio? I'm not sure how I'd go about creating something like this in visual studio. Ideally the software would be similar to mind maps, where the node of text is the dialogue text, and the connecting arrows have text on, and are equivalent to the options. Identifiers should ideally handle themselves. Can anyone give me any pointers in what direction I should take, and if the direction is creating my own program, could anyone suggest any resources which would help me? I understand this is a long message and I'm asking a lot, but any help, comments or even constructive criticism on my system would be greatly appreciated. Thanks in advance.


Maya Unity See through models I've recently modeled my character inside Maya here's an image. The first thing I noticed whilst creating my model is that the models could be seen through source 1, after doing a little research people stated that it was a graphical bug in Maya. However, once imported into Unity the same effect occurs. Therefore, my Question is How can I fix this inside Maya or Unity? To prove that my UV map doesn't contain a low opacity texture see the second image below


How to make an event happen only at the first start of the game? I want to know how to make something happen only once like a tutorial in a game which appears only when you first start your game and then when your game got saved to a further point it never appears again even when you close your game and start again. I want to give players some amount of gold when they first got their hands on my game ... but I do not want to give them that again and again whenever they restart the game ... So I want to know how to make something happen only once in a game application.. I hope you get my point ... thanks ..


Problem picking up a value, Delegate I'm having trouble passing values that are inside an int function to an onclick delegate. this script causes the object to move in vector3 ( 1 to the left and 1 to the right), these two values are inside the (int value), but I am trying to pass them to a delegate, but when inserting it it is adding different values than being in the script video of the problem private int index, index2 0 SerializeField private Vector3 Myposic1, Myposic2 SerializeField private Button left, right here I change the positions of Myposic1, Myposic2 SerializeField private float time public int slide 0 index between Myposic1, Myposic2. void Update() call() public void previous() slide call() public void next() slide call() void call() if (slide lt 0) slide 0 if (slide gt 1) slide 1 if (slide 0) left.onClick.AddListener(delegate player( 1) ) right.onClick.AddListener(delegate player(1) ) this.transform.position Vector3.Lerp (this.transform.position, Myposic1 index , Time.deltaTime time) if (index Myposic1.Length 1) right.interactable false else right.interactable true if (index 0) left.interactable false else left.interactable true Debug.Log("1") if (slide 1) left.onClick.AddListener(delegate player2( 1) ) right.onClick.AddListener(delegate player2(1) ) this.transform.position Vector3.Lerp (this.transform.position, Myposic2 index2 , Time.deltaTime time) if (index2 Myposic2.Length 1) right.interactable false else right.interactable true if (index2 0) left.interactable false else left.interactable true Debug.Log("2") public void player(int valor) index index valor public void player2(int valor2) index2 index2 valor2


Unity Isometric Tilemaps Appear Jagged I had issues using the isometric tilemaps feature in Unity. Whenever I try to place tiles, they don't seem to line up and create this jagged effect. I've tried messing with the anchor points and am a complete beginner at this. Edit My grid component looks like this


Unity Creating a Plane from 3 Vectors https docs.unity3d.com ScriptReference Plane ctor.html public Plane(Vector3 a, Vector3 b, Vector3 c) Description Creates a plane. The resulting plane goes through the given three points. The points go around clockwise as you look down on the top surface of the plane. Since there is no Debug.DrawPlane I don't know whether my plane works as expected. Are all 3 Vectors world coordinates? Or are they connected to each other? Can somebody elaborate how this works? Neither can I make any sense of "The points go around clockwise as you look down on the top surface of the plane"


How do I check if animation is of Animation Type "Humanoid"? One can set the Rig Animation type of an animation to quot Generic quot , quot Humanoid quot , etc. How could I check by script if an animation rig has been set to type quot Humanoid quot ?


Unity 3D engine for Ubuntu? Is there any way to get Unity 3D to run on Ubuntu. I am currently running Ubuntu 12.04 64bit edition. I also have Wine installed.


"StrictMode policy violation" warning occurring in my game after upload When I upload my game to my Android device, I get the following warning StrictMode policy violation android.os.strictmode.NonSdkApiUsedViolation Ljava lang invoke MethodHandles Lookup gt lt init gt (Ljava lang Class I)V at android.os.StrictMode.lambda static 1(StrictMode.java 428) at android.os. Lambda StrictMode lu9ekkHJ2HMz0jd3F8K8MnhenxQ.accept(Unknown Source 2) at java.lang.Class.getDeclaredConstructorInternal(Native Method) at java.lang.Class.getConstructor0(Class.java 2325) at java.lang.Class.getDeclaredConstructor(Class.java 2166) at bitter.jnibridge.JNIBridge a. lt init gt (Unknown Source 25) at bitter.jnibridge.JNIBridge.newInterfaceProxy(Unknown Source 8) at com.unity3d.player.UnityPlayer.nativeRender(Native Method) at com.unity3d.player.UnityPlayer.c(Unknown Source 0) at com.unity3d.player.UnityPlayer e 1.handleMessage(Unknown Source 95) at android.os.Handler.dispatchMessage(Handler.java 102) at android.os.Looper.loop(Looper.java 193) at com.unity3d.player.UnityPlayer e.run(Unknown Source 20) What causes this, and how can I resolve it?


Colliders stop working when they move I'm trying to make a game where you play basketball as a catapult. Obviously an idea like this leans heavily on the unity physics engine. The cup of the catapult has a bucket on it to keep the ball from falling out. When you hit space, the arm of the catapult spins, which should throw the ball out of the bucket of the catapult. Instead, the ball passes through the cup of the catapult(when it isn't spinning, it acts normally and rolls around the bucket) and then it doesn't fall whatsoever, eve though has gravity is enabled. Here are my physics settings The ball The cup(and also a cup with flipped normals) The Rim of the bucket Here's my ball throwing code public class BallThrower MonoBehaviour private Vector3 axis Start is called before the first frame update void Start() axis transform.position Update is called once per frame void Update() if (Input.GetKey(KeyCode.Space)) if (transform.rotation.z gt 95.4) transform.Rotate(0f, 0f, 5f, Space.Self) What's missing here? Should I make the cup a rigidbody? Let me know if you need more info, Thanks!


Why when using Linerenderer it's drawing a line also in scene view? I want to draw lines using the Linerenderer only in the game view window. I'm using Debug.DrawLine but only drawing Red lines but for some reason when the Linerenderer draw a line s one of the Linerender lines is yellow it seems the green linerenderer is getting on the red one in the scene view window. Debug.DrawLine(Input.mousePosition, hit.transform.position, Color.red) Is there a way to avoid it ? So Debug.DrawLine will draw only in sceneview and the Linerenderer will draw only in the game view window ? using System.Collections using System.Collections.Generic using UnityEngine public class RotateObjects MonoBehaviour public GameObject objectsToRotate public float speed 0.1f public Vector3 spinDirection public bool useMouse false public bool automaticSpin false public LineRenderer linerendererPrefab List lt LineRenderer gt lrs new List lt LineRenderer gt () Use this for initialization void Start() for(int i 0 i lt objectsToRotate.Length i ) var lr Instantiate(linerendererPrefab) lrs.Add(lr) Update is called once per frame void Update() if (objectsToRotate.Length gt 0) for (int i 0 i lt objectsToRotate.Length i ) var hits Physics.RaycastAll(Camera.main.ScreenPointToRay(Input.mousePosition), 100.0f) for (int x 0 x lt hits.Length x ) RaycastHit hit hits x if (hit.collider.name objectsToRotate i .name) objectsToRotate i .transform.Rotate(1, 1, 1) Debug.DrawLine(Input.mousePosition, hit.transform.position, Color.red) SpawnLineGenerator(Input.mousePosition, hit.transform.position, false) if(hits.Length 0) SpawnLineGenerator(new Vector3(0,0,0), new Vector3(0,0,0), true) if (useMouse true) if (Input.GetMouseButton(0)) Rotate(i) else Rotate(i) private void Rotate(int i) if (automaticSpin true) objectsToRotate i .transform.Rotate(1, 1, 1) void SpawnLineGenerator(Vector3 start, Vector3 end, bool reset) for(int i 0 i lt lrs.Count i ) if (reset) lrs i .SetPosition(0, start) lrs i .SetPosition(1, end) else lrs i .SetPosition(0, start) lrs i .SetPosition(1, end)


I try to recreate a plasma gun from halo into my fps game this is my code public class WeaponTest MonoBehaviour public float weaponHeat public float weaponOverHeat 100f public bool weaponIsOverHeat Start is called before the first frame update void Start() weaponHeat at the start was 0 weaponHeat 0 Update is called once per frame void Update() if (Input.GetButton( quot Fire1 quot ) amp amp !weaponIsOverHeat) if (weaponHeat lt weaponOverHeat) Weapon Shoot() weaponHeat IsHeating() float IsHeating() weaponHeat Random.Range(5f, 10f) return weaponHeat void Weapon Shoot() RaycastHit hit if (Physics.Raycast(playerCam.transform.position, playerCam.transform.forward, out hit, range)) code for damaging the enemy the shoot method was function exactly like what is want but I need the cooldown method I already try a few them but it not work exactly like I want. the I idea was went the left mouse was click the weapon heat will increase and when the left mouse was not been click the weapon heat will decrease until it reach 0. I hope you can help me solve this problem


Unity blur on one camera effects the other as well I'm trying to fake a DOF effect for Sprites by using 2 cameras, one for the sharp objects, one for the blurred ones. I have set up the layers like Blur and Sharp accordingly. So I have these 2 cameras, and I use Unity's Blur (optimized) script to blur things, and I have this script on only one camera, the one that is responsible for the blurred render. I have the cameras like Cam 1 Clear flags Don't clear (this is the main, sharp cam) Culling mask sharp layer has no blur effect (or any other post proc effect). Cam 2 Clear flags don't clear (this is the blur cam) culling mask blur Has Blur (optimized). Now, if this blur cam is on the back, meaning its depth is LESS than the main cam's depth, I have a sharp player ground and a blurry background. However, I need a blurry foreground too that should be on top of the player ground. The issue starts when I set the blur camera's depth higher than the main cam's. In this case, everything gets blurred, no matter that the main cam has no blur effect on it. Question is, how to set this up so only the desired layers get the blur?


Dot product not working as expected Recently I am learning dot product, While below code works from Unity's documentation, http docs.unity3d.com ScriptReference Vector3.Dot.html public Transform other void Update() if (other) Vector3 forward transform.TransformDirection(Vector3.forward) Vector3 toOther other.position transform.position var dot (Vector3.Dot(forward, toOther) Debug.Log(dot) But it doesn't work when I change direction of "other".It keeps giving same value no matter how much I rotate other unlike when I rotate transform,it does change values. For example, transform is at 0 0 0 and other is at 0 0 10 both has 0 rotation so facing straight in Z axis. The desiire out put I get is negative. Now suppose I change rotation of transform to 180 then the output gets positive as expected. I undo the rotation of trasnform and rotate other to 180 i.e., facing transform, then the output doesn't get change and show negative value only.Which is not correct as other is facing player.. Why is that the case? I am not able to get around it.


How to set a directory to download assetbundles from? Hi I'm using unity and I've created an AssetBundle file containing two different sprites. I set it's path to my desktop and I can load my assets. But how to download the AssetBundle from a directory on the web. How can I set a directory for everyone to be able to download the AssetBundle?


Unity Editor Scene View does not match built executable I'm trying to make my game resolution independent. I'm using Unity's 4.6 UI, and I've got custom resolutions defined at 1280 x 720, 1600 x 900, and 1920 x 1080. In editor, if I swap between any of these resolutions, the observed scene doesn't change. It looks like this I then build an executable (set to only allow 16x9 resolutions), and run this scene. On 1280 x 720 (as selected from the resolution dialog), I get this While on 1920 x 1080 (as selected from the resolution dialog), I get this Which matches the editor view. (Ignore the character sprites those are in worldspace on a separate camera and aren't relevant to this question). What is it about the executable that causes lower resolutions to be "zoomed in" like this, even if that lower resolution is the Reference Resolution for the Canvas Scaler?


How to synchronize damage with attack animation in a RTS game? I have been working on a RTS game in unity and did damage deal through code and a timer but it does not fit with the animations quet well. The damage is dealt in the beginning of the animation and about 4 attacks it fits perfectly and after more 4 attacks the damage is dealt delayed after the animation. My big question is if hitboxes would be a good answer to solve this problem or is it to preformance heavy?


How to load an AudioClip at runtime without the WWW class? I am currently pulling a .wav file from an API. I would like to play it at run time. Currently I need to save the .wav file to the persistentDataPath and then use the WWW class to load an audio clip using the file prefix. It works fine but the docs do mention that the WWW class is obsolete. What other options do I have if I want to avoid the obsolete method group? I don't need to save the file to disk, I am simply doing that at the moment because its fairly safe to save it and then read it back out.


How to share image in persistentDataPath to facebook feed? I'm trying to share an image taking from CaptureScreenshot() using FB.ShareLink(...) to Facebook. My code is the following (After calling FB.Init(), etc..) string tmpScreenshotPathname "file " currentScreenshotPathname System.Uri contentUri new System.UriBuilder(tmpScreenshotPathname).Uri System.Uri imageUri new System.UriBuilder(tmpScreenshotPathname).Uri FB.ShareLink(contentUri, "Test", "Test desc", imageUri) However, when open the FB share, the page opens for a split second before returning me back to the game. I tried using a normal Uri such as http ........jpg and it works fine, but when I try to use a local Uri, it fails. Is there any way to share the image to the feed without uploading it to the user's Facebook gallery using FB.API? Because there's the case where the user might decide not to share the image to the feed.. but it would have already been uploaded to his gallery from FB.API.


When would a mesh collider be better than primitive colliders I have been reading through the Unity Manual and have come across some interesting information about mesh colliders and primitive colliders. It got me wondering if using many primitive colliders would be better than using a mesh collider for say a character object? I was also wondering if there was any information on exactly how inefficient a mesh collider is to say having 20 box or cylinder colliders on a character mesh. I am guessing that the number of polygons on the mesh would be a factor but it would be interesting to see some raw comparisons between how this efficiency scales per polygon (or per 100 polys or some unit of measurement)


How to animate a bezier curve over a given duration I have created a bezier curve by adding the following script to an empty game object in the inspector. This draws to complete curve at once when I run the code. How can I animate it over a given period of time, say 2 or 3 seconds? public class BCurve MonoBehaviour LineRenderer lineRenderer public Vector3 point0, point1, point2 int numPoints 50 Vector3 positions new Vector3 50 Use this for initialization void Start () lineRenderer gameObject.AddComponent lt LineRenderer gt () lineRenderer.material new Material (Shader.Find ("Sprites Default")) lineRenderer.startColor lineRenderer.endColor Color.white lineRenderer.startWidth lineRenderer.endWidth 0.1f lineRenderer.positionCount numPoints DrawQuadraticCurve () void DrawQuadraticCurve () for (int i 1 i lt numPoints 1 i ) float t i (float)numPoints positions i 1 CalculateLinearBeziearPoint (t, point0, point1, point2) lineRenderer.SetPositions(positions) Vector3 CalculateLinearBeziearPoint (float t, Vector3 p0, Vector3 p1, Vector3 p2) float u 1 t float tt t t float uu u u Vector3 p uu p0 2 u t p1 tt p2 return p


Animation with pivot modification in Mecanim Assume I have two animation cycles Walking Crouching Both assume that the model's pivot is on the same level as the model's feet. Now I also have two animated transitions Get on all fours while walking Climb onto a (table) The first is not too complex. The model walks upright, then gets down on all fours (animation 1) and crouches. Pivot remains on the same level, all fine. What I want However, I can't get my head around the second transition. I want the model to walk up to the table (pivot on ground level) climb onto the table (animation 2) (pivot..?) crouch on the table (pivot on table level, 1 m above ground) What I have The climbing animation (2) assumes pivot to remain on ground level and simply animates the model's climbing up. I built a StateMachineBehaviour which raises the model to the table level as soon as the climbing animation is complete. From then on the pivot is on table level and the crouching can continue. This seems to work fine in a standalone application, however, in multiplayer, where the models' transform and animator state are not necessarily synchronized in the same frame, this prooves problematic. One can clearly see the model jump when the change in the model's position arrives one frame earlier than the switch from climbing to crouching animation. What I tried I thought it might be a better idea to have the pivot move gradually from ground level to table level over the duration of the climbing animation (2), instead of having one instant jump at the end. This way network synchronization would be much more robust because of the relatively small change per frame. Also this approach would much closer resemble the actual thing that's happening in the real world, which is generally a good thing. I tried offsetting the root transformation of the animation clip, and accomodate the modification by adding the negative offset to the root bones. This however did not work, as there seems to be no animatable translations in Mecanim animation clips. So im stuck at this approach. Question Is there a better way? A simpler way? How are you guys tackling this?


Isometric ball moving in unity 3d. Ball moving in opposite direction I am making a game in unity 3d. It is a 2.5d game which mean it is in isometric. The game is quite simple. Player drags mouse and a trajectory will be shown just like in angry bird and when player release the mouse the ball will move to the direction. However I am having issue here that once mouse is released the ball moves in exact opposite direction. I am not able to understand what the real issue is. My code is as follows For Ball public class BallScript MonoBehaviour public Rigidbody2D rbg public CircleCollider2D col public Vector3 BallPos get return transform.position void Awake() rbg GetComponent lt Rigidbody2D gt () col GetComponent lt CircleCollider2D gt () public void PushBall(Vector2 force) rbg.AddForce(force,ForceMode2D.Impulse) to enable rigidbody so we can use projectile again public void ActivateRb() rbg.isKinematic false public void DeActivateRb() rbg.velocity Vector3.zero rbg.angularVelocity 0f rbg.isKinematic true The code for my game manager is as follows public class Trajectory MonoBehaviour SerializeField int dotsNumbers SerializeField GameObject dotsParent SerializeField GameObject DotsPrefab SerializeField float dotSpacing Vector2 pos float timeStamp Transform dotsList void Start() hide trajectory in the start Hide() PrepareDots() void PrepareDots() dotsList new Transform dotsNumbers for(int i 0 i lt dotsNumbers i ) dotsList i Instantiate(DotsPrefab,null).transform dotsList i .parent dotsParent.transform public void UpdateDots(Vector3 ballPos,Vector2 forceApplied) timeStamp dotSpacing for(int i 0 i lt dotsNumbers i ) pos.x (ballPos.x forceApplied.x timeStamp) pos.y (ballPos.y forceApplied.y timeStamp) (Physics2D.gravity.magnitude timeStamp timeStamp) 2f dotsList i .position pos timeStamp dotSpacing public void Show() dotsParent.SetActive(true) public void Hide() dotsParent.SetActive(false) Here is the code for gamemanager using singleton pattern Camera cam public BallScript ball public Trajectory trajectory public static GameManagerScript Instance void Awake() if(Instance null) Instance this SerializeField float pushForce 4f bool isDragging false Vector2 startPoint Vector2 endPoint Vector2 direction Vector2 force float distance void Start() cam Camera.main ball.DeActivateRb() void Update() if(Input.GetMouseButtonDown(0)) isDragging true OnDragStart() if(Input.GetMouseButtonUp(0)) isDragging false OnDragEnd() if(isDragging) OnDrag() void OnDragStart() ball.DeActivateRb() startPoint cam.ScreenToWorldPoint(Input.mousePosition) trajectory.Show() void OnDrag() endPoint cam.ScreenToWorldPoint(Input.mousePosition) distance Vector2.Distance(startPoint,endPoint) direction (endPoint startPoint).normalized force direction distance pushForce trajectory.UpdateDots(ball.BallPos,force) void OnDragEnd() ball.ActivateRb() ball.PushBall(force) trajectory.Hide() The ball moves in exact opposite direction where I wish to send it by dragging. Is it because of the isometric issue or I am missing something?P.S have applied negative force as well as in case and have also made change in direction formula rbg.AddForce( force,ForceMode2D.Impulse) direction (startPoint endPoint).normalized


Removing FMOD from a Unity WebGL project causes an error about not being able to copy fmod register static plugins.cpp When I imported the FMOD plugin into a Unity WebGL project, then removed it afterwards, I wasn't able to build it due to errors about trying to copy an FMOD file fmod register static plugins.cpp Restarting the editor, reimporting everything, deleting Library Temp folders did not help. Neither did deleting the FMod folder.


How to connect a skeleton to an animator at the parent I have two different meshes with similar armatures. And the parent contains the Animator Component with a universal avatar and animation controller. The animations doesn't apply when the bones are not the imminent child of the Animator. Is there a way to get this working?


Is it better to create a scene in blender or in unity? First of all, I am really new to all of this. This is my first time so its really confusing me if it's better to create a scene and then import it into Unity or is it better to just create objects like chracters, chairs in blender and scenes in Unity? I just want to recreate a scene of my school and include it in my final project as a Unity game where it will have no function other than walking around and some jumping and fighting? Because my project is not based on the game, it will just help it.


Delay for seconds when key is held down? Hello I am very new to Unity and am trying to make a shooting game in which when the space key is pressed down the gun charges then shoots. I want it to wait for 0.3 seconds before the gun fires off because I want an effect to happen with a particle system(I confused animation with effect in the first post). Also the problem the script has is that the bullet would not fire at all when the space is pressed. Here is the scripts I wrote void Start() StartCoroutine("Shoot",0.3f) IEnumerator Shoot() yield return new WaitForSeconds (0.3f) Bam () void Bam() transform.Translate (0, 0, 12) void Update () if (Input.GetKey (KeyCode.Space)) Shoot()


Keep track of VoxelData NPC in parallel Level Background I'm tring to make a First Person Shooter Game in a Voxel World (Finit Size) with Unity3d. The Player has some kind of a Base that he has to protect against Enemy units. There are also one or more enemy Bases that the Player has to destroy, but in a different Level Map. The Game has multiple Levels that are connected through predefined Ports. So the Player and other Units can travel from Level to Level. There are a couple of Levels to explore. (Maybe there could be infinit Levels in the future.) At game start I create a LevelManager and all Levels as Children of them. They can spawn an manage the Units and Voxel Blocks independently. One ChunkManager renders always the current Level where the Player is in. He creates multiple Chunks which itself generate the Mesh from the current Voxel Data of the Level. This works all very well and I'm also able to travel between the Levels. (This runs all in one Scene.) At the moment I try to implement some kind of a Worm unit. They spawn from time to time anywhere in each level and can move randomly around and modify the Voxel World by eating the Blocks away... type of random enviroment event. Problem The problem I can't solve is how to simulate all the Worms in parallel Levels? And the Blocks they have eaten? Same problem would occur for the enemy bases if they grow and build new defences and so on. Because when the Player enter a Level there should be some differences since his last visit. My attempt All my Units and Buildings have already separated logic and rendering components. So they can work properly even when not rendered by the ChunkManager. Its working for maybe 3 Levels and a handfull of worms but if I increase the amount of Levels it gets starting to go laggy (4 10FPS). So this would not be the right way to go or is it and my code is crap? Has someone any suggestions for me how I can solve this? Edit I disable now all none active Levels and reactivate always the current Level where the Player is in. So I can better manage the objects that realy need computation time. The problem I get now is how can I simulate the progress in a Level since start? Example for the worm unit. He would have moved across the Level and left a path of removed voxels. Should I made a seperate method to calculate the path that would be made or the last X minutes or should I just call the Update method multipletimes to match the missed calls since last X minutes? This should then be made by all Objects that can modify the Level or produce something.


How to detect speed on collision The problem with OnCollisionEnter2d is that it only gets called when there is a collision but what I wanted is to get the current speed of object at the moment of impact until the object stops moving. So that I if the object stops moving after impact I will call another function. void OnCollisionEnter2d(Collision2D collision) Debug.Log(speed) problem this will only give the speed at the moment of impact if(speed lt 0) blah blah I also tried putting speed variable on the Update() void Update() var currentVelocity player rb.velocity speed currentVelocity.magnitude


Capsule getting stuck on edge of block I'm making a first person game and when I jump and my character gets close to the top of the wall, the vertical movement stops, jitters, or suddenly snaps to the top of the wall. Video Here is my character controller code, based on this tutorial using UnityEngine RequireComponent(typeof(CharacterController)) public class PlayerController MonoBehaviour private InputManager inputManager private CharacterController controller private Vector3 playerVelocity private bool groundedPlayer SerializeField private float playerSpeed 2.0f SerializeField private float jumpHeight 1.0f SerializeField private float gravityValue 9.81f private Transform cameraTransform private void Start() controller GetComponent lt CharacterController gt () inputManager InputManager.Instance cameraTransform Camera.main.transform void Update() groundedPlayer controller.isGrounded if (groundedPlayer amp amp playerVelocity.y lt 0) playerVelocity.y 0f Vector2 movement inputManager.GetPlayerMovement() Vector3 move new Vector3(movement.x, 0f, movement.y) move cameraTransform.forward move.z cameraTransform.right move.x move.y 0f controller.Move(move Time.deltaTime playerSpeed) Changes the height position of the player.. if (inputManager.PlayerJumpsThisFrame() amp amp groundedPlayer) playerVelocity.y Mathf.Sqrt(jumpHeight 3.0f gravityValue) playerVelocity.y gravityValue Time.deltaTime controller.Move(playerVelocity Time.deltaTime) I also tried using other solutions by changing the physics material of the level and player, neither worked.


How to change pre splash image for iOS? When I launched my game on my iPad, the screen first displayed a faulty splash image with a black lower half momentarily, before displaying the normal splash image. No matter what I tried, I couldn't get rid of this faulty 'pre splash image'. I have tried the following Entered my Plus package serial number and updated my seat in Unity. Deleted and left all splash images blank in Unity. Checked all the LaunchScreen XXX.png images in Xcode. Checked the files referenced by Images.xcassets in Xcode. Changed all the above images to a completely black image. Still, the old faulty picture would appear. Cleared all the data and installation files on my iPad. Deleted General Launch Images Source. I wonder where Xcode kept the faulty image. I am using Unity 5.5.1 and Xcode 9.2. Could someone please help?


How can I flip a coin? I am working in unity and have flattened out a cylinder object to make a coin for a 3d coin flipping game, but I am not sure how to get the coin to flip when the player swipes across it and allow for a double flip if the player swipes over it a second time while in mid air. here is what I have tried using System.Collections using System.Collections.Generic using UnityEngine public class CoinFlip MonoBehaviour private Vector3 start private void Start() start gameObject.transform.position void Update() transform.position transform.right Mathf.Sin(Time.time 0.45f) 0.025f void OnEnable() gameObject.transform.position start


Force change prefab source I have a prefab A and i use it in scene A (as gameobject A). Then i to save that scene A as scene B and also renamed the gameobject A to gameobject B. Then inside unity (in project window ) , i duplicated the prefab asset A to prefab B. Fyi, i'm using .blend (blender file) as the prefabs. in scene B, i want the gameobject B which refers to prefab A , to switch its prefab's source to prefab B. This way , i have 2 different scenes which has independent gameobjects which refer to unique prefab. So i can modify prefab A and will affect scene A but not scene B. Ussually, i can drag the gameobject to project window and choose create 'new original prefab' option, but this method can't be used, since i want both prefab as .blend file (so i can modify them directly using blender). What i did so far, is to drag prefab B to scene B, which then i have to manually redo all the setting which has been done in scene A . I want to avoid this tedious process. Does anyone have any idea ?


Prefab disables its script when a clone is instantiated A clone of a cube is spawned when it is destroyed, however the clones disable the script in the editor (example http gfycat.com SnarlingScornfulEgg). Used the exact same script for a different kind of 'enemy' and it worked as intended. Relevant part of script function Start () health 100 function Update () if(health lt 0) Dead() function OnCollisionEnter (col Collision) if(col.gameObject.tag "Bullet") health 25 function Dead () Destroy(gameObject) var posx Random.Range( 50, 50) var posz Random.Range( 50, 50) Instantiate(enemyl, Vector3(posx, 0.5, posz), transform.rotation) Is there something I'm missing? EDIT The clone takes damage but doesn't die like the original when its health is lt 0.


Instantiated object not tracking collision I have an issue, and I'm not sure why it's happening. I have a prefab that I've built in a colour changing game. It has the following Four 2D objects that if they collide with the player (2D collider attached to all), they cause the player to die. One 2D object that if the player strikes, it generates a duplicate of itself with the Instantiate function. All 2D objects are created The four objects that cause the player to die are being created as normal and continue to cause the player to die. However, the object that instantiates the prefab and increments the score can no longer be collided with. The player appears to pass behind it. I'm pasting my code below. I would really appreciate if anyone can offer advice on this void Update () if (Input.GetButtonDown("Jump") Input.GetMouseButtonDown(0)) thing.velocity Vector2.up bounciness scoreText.text score.ToString() private void OnTriggerEnter2D(Collider2D collision) if (collision.tag "plusScore") score Destroy(collision.gameObject) Instantiate(barrier, new Vector2(transform.position.x, transform.position.y 7f), transform.rotation) return if(collision.tag ! currentColour) Debug.Log("You DIED!") SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex) score 0


How to scale our multiplayer support, similar to Among Us We are a small team with the goal of creating our first multiplayer game, and we want to support multiplayer that can rapidly scale up as Among Us has successfully done. We don't have a huge budget and we are struggling to find an appropriate way to implement multiplayer, including peer to peer (although it would be exhausting to combat cheating and make a smooth experience). Our game has no more, no less than 50 players in a very tight space. As an example, we're looking at the indie game Among Us. They went from such a small game with barely any players, to maintaining well over 3 million CCU (concurrent users). How can we achieve similar scalability?


How to avoid enemies overlapping each other when chasing player in Unity? I am trying to get enemies to chase player but without them overlapping each other when they get closer to the player. So far what I have is that I check for the distance between current enemy and the another enemy in a list and if their distance is less than 2 then update their position away from each other. But when I do that, the enemies instantly move away rather than smoothly moving away from each other. What can I do to improve this? Here is my script for chasing player public void ChasePlayer() foreach (GameObject enemy in enemies) if (enemy ! null) float currentDistance Vector3.Distance(transform.position, enemy.transform.position) if (currentDistance lt 2.0f) Vector3 dist transform.position enemy.transform.position transform.position dist if (lantern.transform.GetChild(0).gameObject.GetComponent lt Light gt ().enabled) gameObject.GetComponent lt MeshRenderer gt ().enabled true gameObject.GetComponent lt Collider gt ().enabled true transform.LookAt(player.transform) transform.position transform.forward speed Time.deltaTime else gameObject.GetComponent lt MeshRenderer gt ().enabled false gameObject.GetComponent lt Collider gt ().enabled false


Unity3d Find out if current animator animation is playing? I need to call a function immediately after animator animation finished playing, I know I could solve this by adding an event to my animation, but I try it without. How can I find out if the current animator animation is playing? On normal legacy animations I solved it by writing a coroutine public static IEnumerator playAndWaitForAnim(Animation anim, string clipName, Action callback) anim.Play(clipName) Wait until Animation is done Playing while (anim.IsPlaying(clipName)) yield return null Done playing. Do something below! callback() Which I use like this StartCoroutine(AnimationHelper.playAndWaitForAnim( myAnimation, "ToSettings", () gt Debug.Log ("Finished playing") )) But how does this work with mecanim animator animations?


How can I insert random numbers in specific place in text of UI Text? I have a Canvas with Text and a Panel. I want that it will show random numbers between 3 and 10 between the almost and hours Hello my friend, It's about time to wakeup. You were sleeping for almost...hours. My name is NAVI and i'm your navigation helper in the game. Sometimes when running the game I was sleeping for almost 5 hours and sometimes when running the game I was sleeping for almost 3 hours. For example Hello my friend, It's about time to wakeup. You were sleeping for almost 5 hours. My name is NAVI and i'm your navigation helper in the game. Instead the 3 dots to add a random number.


Limiting interaction between certain RigidBodies I'm developing a 2D game in Unity and have been tasked with building a particular feature I'm not sure how to accomplish with Unity's physics engine. To simplify, a bunch of objects of type X and O are filled into a pit XXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXX XXoXXXoXXXoX Both objects have Rigidbody2Ds and colliders. Objects of type X have normal gravity and should settle into place. Objects of type O have inverse gravity and should float. However, O should not be able to push X, and X should not be able to push O. Another way of looking at it is that O should only be able to move upward, and X should only be able to move downward. If we remove some of the Xs directly above an O, the O should float upwards as the Xs fall downwards until the Xs settle on top of the O and everything stops moving XXXXXXXXXXXX XX XXXXXXXXX XX XXXXXXXXX gt XXXXXXXXXXXX XX XXXXXXXXX gt XXoXXXXXXXXX XXoXXXoXXXoX XX XXXoXXXoX (In the actual game Xs and Os can be different sizes their movement is continuous and they are not constrained into rows or columns). The Os should be able to support the weight of any arbitrary number of Xs without sinking. XXXXXXXXXXXX XXXXXXXXXXXX XooooooooooX X X Lastly, the Os should be able to float diagonally if there is a space available XXXX XXXXXXX XXX XX XXXXX XX gt XXXXX XXXX XXXX XXXX gt XXXXoXXXXXXX XXXo XXXXXXX XXXX XXXXXXX I can't solve this problem simply by adjusting the mass of the Xs or Os since the number of Xs on top of an O may vary. I can't use the built in RigidBody constraints since they don't allow you to disable only one direction along an axis (e.g. saying an object can move upward but not downward). What's the proper way to handle this? I could do something like this void FixedUpdate() if (movementDirection Direction.UP) if (transform.position.y lt lastYCoordinate) Vector3 position transform.position position.y lastYCoordinate transform.position position lastYCoordinate transform.position.y but that feels hacky to me and I suspect it will keep the objects from sleeping. Are there better solutions here?


unity input event consumed by image raycast target that is "under" a sprite with a 2D collider I am having a hard time getting my UI to work. Basically I have a canvas with a UI image A that is the size of the screen. This image has raycast enabled and if effectively receiving inputs. Not in the canvas I have a sprite B that have a 2D collider attached to it. No matter what I try, the UI image is always consuming the input event when I click on the sprite. When I disable the image A , the sprite B gets the events, so the setup looks right (camera with Physic2D raycaster for the sprite B, layerMask set to the layer of the sprite B, canvas with Graphic raycaster for the image A, no blocking object, no mask). What do I need to do so that the sprite B gets the input event BEFORE the image A and consume it? EDIT Those two elements are part of the UI and must be interactable at all time. I use a sprite for the second element as it is dragged from the UI inside the game and I don't want to make it an image. The image A is a big cancel button with opacity 0 on the whole screen that must be active at all time. I just want to know if the Collider of sprite B can intercept the input before the image A. If it isn't possible, I'll create an Image B instead of the sprite B and destroy it to create a Sprite with the same texture when the is interacted with.


In Unity, how do I add a MeshFilter to an empty GameObject to generate a procedural model? My code below is modeled after Unity's documentation. When I put the script into an empty GameObject, the error I get is MissingComponentException There is no 'MeshFilter' attached to the "myMesh" game object, but a script is trying to access it. How do I add a MeshFilter (and the other necessary Components) to the empty GameObject in order to generate the model procedurally? using System.Collections using System.Collections.Generic using UnityEngine public class myMesh MonoBehaviour public Mesh mesh void Start() mesh new Mesh() GetComponent lt MeshFilter gt ().mesh mesh


Unity3D post process unwanted on UI I have scene rendered with a single camera using target texture (a). Second camera is used to render UI and using same target texture (a) as the first one. Third camera takes target texture (a), depth texture and apply post proces. Result is rendered to the screen. How can I apply postprocess only to the output elements that are not UI?


Fixed distance between character and ground whatever slope value I am working on character moving on any ground meaning whatever slope degree ,the result i got is the character does not moving on just shake in his place the following the code i wrote public float speed 1 bool isMoving Transform childPosition Rigidbody rb private void Start ( ) rb GetComponent lt Rigidbody gt () Update is called once per frame void FixedUpdate () if (Input.GetAxis("Horizontal") gt 0) rb.velocity new Vector3(1f, rb.velocity.y, rb.velocity.z) else if (Input.GetAxis("Horizontal") lt 0) rb.velocity new Vector3( 1f, rb.velocity.y, rb.velocity.z) else transform.position transform.forward Time.deltaTime speed detectRoad() private void detectRoad() Ray ray new Ray(transform.position, transform.up) RaycastHit hit if (Physics.Raycast(ray, out hit)) transform.rotation Quaternion.FromToRotation(transform.up, hit.normal) transform.rotation if (hit.distance lt 0.6f) transform.position transform.up Time.deltaTime else if (hit.distance gt 2f) transform.position transform.up Time.deltaTime This animated gif is about what I want


How to apply Image effect only on specific part of objects? I need a way to censore part of characters' bodies like Cyberpunk 2077.this is mean I want to apply Image effect only to specific parts of bodies that you can see in the below Image


Find alternate shortest paths in Unity I'm developing a game in Unity. It's a simple game where the rocket has to reach the point where the player touches on the screen. The movement of the rocket is physics based. When the rocket goes off screen on right side, it appears on left side and when it goes off on left side, it appears on right side. Similar for vertical axis. In the picture above, the user touches on the bottom right corner. The rocket could either rotate and go there (Path 1) or it would directly go up left off the screen and appear on bottom right corner and reach there(Path 2). I want to implement the Path 2. How would it calculate the distances and determine the shorter path and then proceed in that direction?


After baking my lights again in Unity, my character is black? I had to re bake my scene several times before getting the look that I wanted. This last time, the scene looks great, but my characters are now very dark and the playable character is completely black. He lights up only when the directional light hits him. Saying this makes me realize the problem (sort of) All the spotlights from the room's interior were probably baked while the characters were turned off, making their solution require the only real time light in the scene in order to be seen. Still, I didn't think the characters would be involved in the lightmap data? How do I redo the lights just for characters and moving objects? How can I fix this and keep the scene lighting?


Draco encoder lossless, is it possible? I'm trying to use the draco library in a Unity project. I've a lot of obj files with models of a person in different positions. When I encode these models with the draco encoder command I obtain a lossy conversion, and a lot of parts of my original models get lost. I tried to play around the parameters qp and cl in order to change the quantization and the compression level, but also with qp at its maximum and cl to its minimum some parts get lost. In this image the left model is the original one. The right model is the one converted with draco encoder by using cl 0 and qp 21. As you can see some parts are missing. Do you have any suggestion on how can I obtain a lossless (as lossless as possible) conversion?


How can I reduce the performance impact of rendering trees? I'm making a low poly stylized kind of game. I have a terrain with some water, and I want lots and lots of trees I have 10,000 trees mass placed, at the moment. Each tree consists no more than 200 triangles, so they aren't too taxing. The main problem is, there are lakes, and the lakes are quite large. You can't actually see any trees on the other side of the lake, and that looks really bad, especially when you walk there and trees suddenly appear. To fix this, I have to increase the tree distance so that you can see a decent amount of trees on the other side of the lake, but that reduces performance to 40 50fps, and there is hardly anything else in the game yet. I'm using a GTX 1080, if that helps. What can I do to make my game run faster with more trees?


Updating object's property on Start is visible for a second when game loads I have a world selection scene in which I have GameObjects representing worlds. The GameObjects have default properties when the scene is loaded. For example the world name text is red and each world has a "locked" status. This initial state can be seen in the following screenshot On the Start() method I'm dynamically updating the properties on each GameObject based on values I'm reading from a save file. If a world is unlocked the name text is set to white. If a world is currently selected the name text is set to green. Here's what that looks like at run time The problem is that when the scene is loaded from another scene(e.g. by clicking a navigation button) the initial state of the GameObjects can be seen for a second and then they change to the proper values as dictated by the save file. How can I prevent this from happening? I was under the impression that anything that happens in the Start() method takes place before GameObjects are rendered. Here's some slimmed down code of what my code looks like var worldIcons FindObjectsOfType lt WorldIcon gt ().OrderBy(x gt x.WorldNumber).ToList() var saveFile GameSaveManager.GetSaveFile() if (saveFile null) Debug.LogError("Could not find save file while loading worlds") return foreach (var worldIcon in worldIcons) var savedWorld saveFile.Worlds.SingleOrDefault(x gt x.Number worldIcon.WorldNumber) if (savedWorld null) add world to save file GameSaveManager.CreateWorld(worldIcon.Controller) unlock first world by default if (saveFile.Worlds.Count 0 amp amp worldIcon.WorldNumber 1) worldIcon.Unlocked LevelMapController.LockedStatus.Unlocked.ToString() else worldIcon.DisplayName savedWorld.Name worldIcon.WorldNumber savedWorld.Number var button worldIcon.GetComponent lt Button gt () if (savedWorld.Unlocked) button.interactable true button.targetGraphic.color Color.white worldIcon.Unlocked LevelMapController.LockedStatus.Unlocked.ToString() else worldIcon.Unlocked LevelMapController.LockedStatus.Locked.ToString()


Help with OnTriggerEntered Canvas UI This seems like it should be incredibly easy and I know there are other posts out there with a similar title, but I promise you I have looked at all of them. All I want is for my canvas that simply says "you win" to appear when I enter an invisible box collider that I have . My canvas is by default set to disabled. public class YouWin MonoBehaviour public Canvas myCanvas private void Start() myCanvas GetComponent lt Canvas gt () void OnTriggerEnter (Collision Collider) myCanvas.gameObject.SetActive(true) This script seems incredibly simple and straightforward, but for whatever reason, when I enter my box, nothing at all happens. Why might this be? What am I missing? As per an answer I also tried public class YouWin MonoBehaviour public GameObject canvas void OnTriggerEnter (Collider Collider) canvas.gameObject.SetActive(true) But had no luck with this either. I've been tinkering to no avail, can you please give me some suggestions?


Prevent showing movie files after packaging unreal game I developed a game which has some videos inside it. I added videos into my project folder so that I can access them. After packaging, on the folder all videos will be shown as its original format which everyone can play it. How is it possible on release version no one can go to game folder and play it? Maybe some kind of encryption or change format of file which only its game can play it would help it. For example when you have a game on your computer, the only way to see the video is that you play the game and you will see relevant videos in the right time. However, after packaging, all videos will be on a folder any everyone can go to the folder and play it and see videos even without playing game. In Unity after releasing the game, you can't access assets, it will be shown in a file with .resource extension so no one can access it. However, in Unreal Engine, it will show the real file.


How to select multiple frames from a sprite sheet in unity I have a sprite sheet and cannot figure out how to select multiple frames in unity 5.5 I am watching a tutorial and it doesn't say how to do it. Is there a button I have to press while clicking or is it having to change some settings?


How can I hide the touch screen joysticks in the main menu? I am a Unity beginner trying to make an app game. How do I hide the touch screen joysticks from showing on screen in the main menu before the game app actually starts?


Detect Collision on Child Object I've created an obstacle prefab. The Prefab has following hierarchy. The player must die if he collides with Enemy. But It detects collision with parent object. I am also uploading the screen shot of property of enemy(Child Object) and Parent Object. What should I change to let player collide with Child Object (Enemy).


How can I get the vector3's names to gameobject name? void DrawBox() SpawnLineGenerator(v3FrontTopLeft, v3FrontTopRight, color) SpawnLineGenerator(v3FrontTopRight, v3FrontBottomRight, color) SpawnLineGenerator(v3FrontBottomRight, v3FrontBottomLeft, color) SpawnLineGenerator(v3FrontBottomLeft, v3FrontTopLeft, color) SpawnLineGenerator(v3BackTopLeft, v3BackTopRight, color) SpawnLineGenerator(v3BackTopRight, v3BackBottomRight, color) SpawnLineGenerator(v3BackBottomRight, v3BackBottomLeft, color) SpawnLineGenerator(v3BackBottomLeft, v3BackTopLeft, color) SpawnLineGenerator(v3FrontTopLeft, v3BackTopLeft, color) SpawnLineGenerator(v3FrontTopRight, v3BackTopRight, color) SpawnLineGenerator(v3FrontBottomRight, v3BackBottomRight, color) SpawnLineGenerator(v3FrontBottomLeft, v3BackBottomLeft, color) And the gameobjects name void SpawnLineGenerator(Vector3 start, Vector3 end, Color color) GameObject myLine new GameObject() myLine.name start.ToString() 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.03f lr.endWidth 0.03f lr.SetPosition(0, start) lr.SetPosition(1, end) The method SpawnLineGenerator get two vector3 and a color SpawnLineGenerator(v3FrontTopLeft, v3FrontTopRight, color) In the SpawnLineGenerator i'm setting a name for each gameobject myLine.name start.ToString() This give me the name for example ( 2.1, 3.4, 4.9) Nut I want it be the name like this format v3FrontTopLeft ( 2.1, 3.4, 4.9) v3FrontTopRight ( 1.1, 3.4, 4.9) The problem is if there is a easy way to get the names v3FrontTopLeft and v3FrontTopRight and the rest from the method DrawBox instead typing each one. I want to know that ( 2.1, 3.4, 4.9) are the coordinates for v3FrontTopLeft


Trouble with assigning a model's own mesh to a mesh collider in Unity I'm trying to use a mesh collider on the player's avatar, rather than the box collider. I've added the mesh collider to the game object (which also has a rigid body) and selected the "convex" checkbox. However, the player still falls through all geometry, including Unity primitives, terrain, and other models. In the mesh collider's property box, there's a value for "Mesh", which I have set to "None (Mesh)". I was led to believe this defaults to the model's own mesh, but now I'm not certain. If I change the value to something else from the "select mesh" list, like the cube, the collisions work. When I click over to Select Mesh Scene, the list is empty. I'm assuming I need to add the model's mesh to the list, but I can't find any documentation about that.


Tile draws pixels from adjacent tiles Whenever I try to draw from the tile palette, this is the result. why does this happen? I have tried messing around with the palette, how the sprite editor has sliced the tiles and played around with the anchors and cell sizes, but to no avail. I found a few threads about offset tiles in the tile map, but it doesn't help at all. Any leads as to why this happens?


How to create a grid of 3d objects without making them actual GameObjects Very simple question If I'm going to be generating and placing a lot of 3d objects (in this case cubes), that are not going to be interactive, like no collision, no raycasting intersections etc. Should they be GameObjects or is there a lighter solution that doesn't inherit the GameObject blob? Cheers,


Billboard rendering without distortion? I use the standard approach to billboarding within Unity that is OK, but not ideal transform.LookAt(camera) The problem is that this introduces distortion toward the edges of the viewport, especially as the field of view angle grows larger. This is unlike the perfect billboarding you'd see in eg. Doom when seeing an enemy from any angle and irrespective of where they are located in screen space. Obviously, there are ways to blit an image directly to the viewport, centred around a single vertex, but I'm not hot on shaders. Does anyone have any samples of this approach (GLSL if possible), or any suggestions as to why it isn't typically done this way (vs. the aforementioned quad transformation method)? EDIT I was confused, thanks Nathan for the heads up. Of course, Causing the quads to look at the camera does not cause them to be parallel to the view plane which is what I need.


ECS Stats, damage types damage calculation Prologue Im quite new to data oriented programming and my goal is to implement a runescape stats damage mechanic. This is quite a pretty complex topic Runescape Mechanics 1 and i havent found any ECS related sources on that topic yet. In the following example we see a bunch of items which modify the weares stats based on a few conditions. This happens in two different variants, either for the damage calculation only, or as a buff. Brine sabre and Brackish blade increase damage against crabs. or Silverlight and Darklight increase ability damage by a scaling of 25 124 against most demons. The exact damage bonus is based on your base Attack and Strength, and the monster's base Defence. The problem Such a RPG system is very complex. There different damage types, different resistences and other stats. Having a strong OOP background and no real experience in DOP, i cant find a suitable architecture to fill those needs. In my current approach every stat is a component. Items and Buffs are structs. A item quot buffs quot its owner and the buff modifies his stats. This works so far, but i have no idea how i could realise the damage calculation, while still keeping it that flexible as it is in runescape. This little example would just be able to buff the stats... not deal, receive or modify the damage itself. The stats public struct Health float max float value public struct MeeleDamage float base float value public struct MeeleResistence float base float value Item amp Buffs public struct Item string name int amount bool equipable List lt Buff gt buffs public struct Buff string name float duration Condition applyable ToBuff stat float value Its also important that an entity can also deal damage to multiple other entities in one frame. How would you implement such an complex mechanic ? Any examples are appreciated !


Generating mesh along path I'm currently trying to generate a path along an array of points (Vector3) This is the result I'm currently getting The dark gray points are the given path The red points are the generated vertices And the triangles are obviously the mesh I failed to generate correctly And from the bottom it looks like this, which is odd, because I'd expect all the missing triangles to be at the bottom. But some of them just don't exist here's the code i wrote that generates the path mesh Removed code since there's no need in showing something that doesn't work And here's a quick example of what it looks like when I drag a path SOLUTION FOUND As the accepted answer states, I was skipping triangles in my triangle for loop. Here is my new working code public static Mesh extrudeAlongPath(Vector3 points, float width) if (points.Length lt 2) return null Mesh m new Mesh() List lt Vector3 gt verts new List lt Vector3 gt () List lt Vector3 gt norms new List lt Vector3 gt () for (int i 0 i lt points.Length i ) if(i ! points.Length 1) Vector3 perpendicularDirection new Vector3( ( points i 1 .z points i .z ), points i .y, points i 1 .x points i .x).normalized verts.Add (points i perpendicularDirection width) norms.Add (Vector3.up) verts.Add (points i perpendicularDirection width) norms.Add (Vector3.up) else Vector3 perpendicularDirection new Vector3( ( points i .z points i 1 .z ), points i .y, points i .x points i 1 .x).normalized verts.Add (points i perpendicularDirection width) norms.Add (Vector3.up) verts.Add (points i perpendicularDirection width) norms.Add (Vector3.up) m.vertices verts.ToArray () m.normals norms.ToArray () List lt int gt tris new List lt int gt () Changed i 3 to i for(int i 0 i lt m.vertices.Length 3 i ) if(i 2 0) tris.Add(i 2) tris.Add(i 1) tris.Add(i) else tris.Add(i) tris.Add(i 1) tris.Add(i 2) m.triangles tris.ToArray () m.name "pathMesh" m.RecalculateNormals () m.RecalculateBounds () m.Optimize () return m


How to get LineRenderer coordinates? I am trying to get the coordinates or positions that are generated at the time I draw with linerenderer, but it gives me an error. This may be a rookie mistake and I am not using the Linerenderer's methods well. I would be very grateful for your help. LineRenderer.GetPosition index out of bounds! UnityEngine.LineRenderer GetPosition(Int32) sendData Figura Trazo(Int32) (at Assets sendData Figura.cs 115) sendData Figura Update() (at Assets sendData Figura.cs 93) public LineRenderer line public static int contadorTrazo 0 void Update() Trazo() void Trazo() line line.GetComponent lt LineRenderer gt () Debug.Log("Trazo " line.GetPosition(contadorTrazo)) contadorTrazo


Issues loading in AudioSource at runtime using WWW class I am having an issue with loading in an OGG audio file to my project. Basically I want to set my game up so that players can drop audio files into a folder called Playlist in the game directory then they can listen to this music while they play. For some reason my audio clip never becomes instantiated. I have an Audio Source in my scene with this script attached to it. As you can see I have commented out some code for the time being as I am trying to get a simple case of only 1 audio file playing at this stage. So my question is what exactly am I doing wrong here? I have printed out the file path and it comes out as file B Users Matt Development Unity Projects Space Game Playlist 19 Tumbling Dice.ogg which is the location to my audio. However when I print out the audioLoader.audioClip.name it comes out as blank... RequireComponent(typeof(AudioSource)) public class MP3AudioImporter MonoBehaviour private List lt string gt playlist private string musicDir "B Users Matt Development Unity Projects Space Game Playlist " private int currIndex 0 void Start() string songs Directory.GetFiles( musicDir, " .ogg", SearchOption.TopDirectoryOnly) playlist new List lt string gt (songs) StartAudio() void StartAudio() WWW audioLoader new WWW("file " playlist currIndex ) Debug.Log(audioLoader.audioClip.name) audio.clip audioLoader.audioClip audio.Play() currIndex if (currIndex gt playlist.Count) currIndex 0 Invoke("StartAudio", audio.clip.length 0.5f)


Why are setcolor and color not reset When I do a color exchange directly on the material in playmode, but then I go back to editmode, why do the settings still remain? For example mymaterial.SetColor( quot Color quot , blue) or mymaterial.color blue


Unity Built In Shader Transformation Explanation Resource I'm working on some of my first shaders and taking a look at the variables included by cginc I see this list of transformation matrices I've watched some beginner talks and I understand what the first one does but pretty much every other one I'm not sure what it does or how to apply it. Does anyone know of a good resource for explaining these transformations?


Unity3d 2017 trail renderer behaving weird Please see the screenshot I attached, I am trying to make skid marks using trail renderer, but one side of trail is going upwards just after it renders, it was working fine Unity 5.4, but when I upgraded it to 2017, it is behaving like this.


What would be the best way to find a Game Object that is closest to another Game Object in unity? I made a 2d space shooter game awhile ago and I want to go back into it and overhaul some things. I'll provide a link to the game so anyone can play and get a better understanding of what I'm trying to do. https your pal drewdle.itch.io starspeed With how the game is currently set up, all the enemies are constantly setting their rotation to be facing the position of the player. I want to go back in and add a co op mode where there are 2 players, however, if I just added a second player without changing any code, the enemies would always be facing Player 1, never directly facing Player 2. I was thinking that I could get around this by giving each enemy an invisible circle with the center at the enemies position that would constantly expand until it hit one of the two players, I could then set the enemies rotation to face the point where the circle collides with one of the players. In theory, this would make it so that each enemy is facing towards whichever player is closest to it. So my question is How could I go about implementing this in unity? Or, is there a better or more efficient way to do this that would yield the same result? I've spent a decent amount of time researching this and I haven't had much luck. All help is appreciated, if you need more explanation just let me know and I will do my best to explain in more detail.


How can I set up potentially dozens of cameras rendering to targets without killing performance? I'm thinking through how I'd do a particular trick for playing cards with animated 3D faces. Setting up a single card is pretty trivial. I would create another camera somewhere, maybe restrict some layers so it'll only show what I want it to show so I don't have to worry what's behind it, put an object in front of it that is the basis of the card, have the camera render to a texture, and put that texture on a quad (the card) with the same aspect ratio. Now whenever the main camera views the card, regardless of angle, the card displays what the other camera sees. I don't believe this approach would scale well as I'd have to duplicate everything for every card. The way I imagine it, there could be dozens of cards visible at once so every frame would require rending all of them. Even at low qualities that sounds bad for performance. Also the main reason I want to animate cards is to have them respond to input and actions happening to the cards so two instances of the same card won't show exactly the same thing. Another thing is where would I place all these cameras and their models in the 3D space so that they won't see each other? I could put them on top of each other and use layers to only capture what I want but something doesn't feel right about having dozens of layers. How would I begin to pull this off on a scale of dozens of cards?


Calculate a random position inside a 2D area excluding a subset Given this area X X X X I have a GameObject size 4x4 and inside another GameObject size 2x2. I know how to calculate a random position inside the 4x4 zone (using GameObject position and collider size), but I do not know calculate a random position evading the 2x2 zone. What I am using right now is Calculate position inside 4x4. If that position is inside 2x2 go back to step 1. But it is not a good way to do this. Do you know can I calculate a random position inside 4x4 area evading a 2x2 area? I though generating small GameObjects, 1x1 instead if 4x4. So first select a random of the 4x4 tagged, for examble, as "IsWalkable", and then calculate a random position insided the selected small square.


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


Is there any way to get PVRTexTool's version from the command line? I am to make an automated task which involves requiring the version of the PVRTexTool that comes with the Unity installed in a machine. Is it possible to get the version of PVRTexTool on the command shell?


character and camera not moving in the same speed the two scripts below do the similar things, get the key press and calculation the direction after the direction calculated, they multiple with the same speed, say 0.05f, while the character and the camera, do not move at the same speed, and the character move faster than the camera. if i rotate the camera a bit and move the character, the character move even faster than camera. i believe there are something wrong in the variable direction, i would like to like how can i fix it so that both of them can move at the same speed in every direction. Thank you. character movement script animation.CrossFade("moving") direction Vector3.zero myposition transform.position if(Input.GetKey("i")) animation.CrossFade("moving") direction Vector3.forward currentkeydown true if(Input.GetKey("k")) animation.CrossFade("moving") direction Vector3.back currentkeydown true if(Input.GetKey("j")) animation.CrossFade("moving") direction Vector3.left currentkeydown true if(Input.GetKey("l")) animation.CrossFade("moving") direction Vector3.right currentkeydown true if two key press if(Mathf.Abs(direction.x) Mathf.Abs(direction.y) Mathf.Abs(direction.z) gt 1) direction.x 2 direction.y 2 direction.z 2 if direction change if (direction ! Vector3.zero) direction Quaternion.Euler(0.0f, Camera.main.transform.localEulerAngles.y, 0.0f) direction transform.rotation Quaternion.LookRotation(direction) if(currentkeydown) transform.position direction speed and camera script if(Input.GetKey("i")) direction Vector3.forward currentkeydown true if(Input.GetKey("k")) direction Vector3.back currentkeydown true if(Input.GetKey("j")) direction Vector3.left currentkeydown true if(Input.GetKey("l")) direction Vector3.right currentkeydown true if(Input.GetKey("u")) transform.RotateAround(player.transform.position,Vector3.up, 2f) if(Input.GetKey("o")) transform.RotateAround(player.transform.position,Vector3.up,2f) direction transform.TransformDirection(direction) direction.y 0 if(currentkeydown) if(Mathf.Abs(direction.x) Mathf.Abs(direction.y) Mathf.Abs(direction.z) gt 1) direction.x 2 direction.y 2 direction.z 2 transform.position direction speed


Best way to connect multiplayer users with each other (matchmaking) on a low powered server? OK so I am using unity to make a multiplayer game, but I'm not sure how to connect players with each other over the internet. Unlike other questions, this isn't a general problem of working out how to do UPnp or using unity's matchmaking server. My issue is that my server that I would use is a simple low powered pc (running normal windows 10, no idea how to use windows server). I think it is powerful enough to match players with each other, but not to host more than one or two actual games. The other issue is that I have a residential internet connection with a dynamic ip that changes every few months. However the speed should be ok (150Mb s download, 20Mb s download). Also, I'm not planning to spend money on a monthly basis for a server (like unity's matchmaking service) as I plan to spend as little as possible (So far I've paid 12 to Microsoft for a dev account and I've received a 200 voucher from them so my current spending is 189!) So my question is should I use my server (would it work), are there any online services that are very cheap to use, or is there another way to make this work? Only other thing is I could use the free 20 users at once on unity's matchmaking, but would this limit be too small? EDIT just for information, my game is a simple tank shooter. I was thinking about limiting the amount of tanks in a game somewhere around 8 20. The bullets in my game are physical objects with rigidbodys and they move at a slower speed (if you've ever played tank trouble, it looks like that). The world is in 3D. There is a potential for there to be up to a hundred bullets in a scene at once at the worst. After hosting a LAN world with 7 players connected for about 20 30 minutes, windows reports the data usage being around 3 4MB.


Apply new default transform values for gameobject I'm not sure if the title is correct. But how does one go about the following I imported a mesh created in blender.When i import the object it is at the desired rotation and scale, however, when i look at the properties of the transform the scale is 100 and the rotation is 89.9123xxxxxxx. Is there any way i can rotate it to the desired rotation, scale it to the desired scale then tell unity that it should update the prefab and set this new rotation as 0,0,0 and the scale as 1,1,1. Reason behind this, is i am tiling a few prefabs, and the rotations are being used.... after a couple of hundred tiles, there are floating point errors.


How can I customize scrollbar sensitivity in editor property drawers in Unity3D? A custom property drawer, in my Unity 2017.3 project, has code like this in its OnGUI implementation public void OnGUI(Rect position, SerializedProperty property, GUIContent label) ... EditorGUI.BeginDisabledGroup(maxX 0) scrollX (uint)GUI.HorizontalScrollbar(new Rect(xyPos new Vector2(slHeight, normalizedSize), new Vector2(normalizedSize, slHeight)), scrollX, 1, 0, maxX 1, GUI.skin.horizontalScrollbar) EditorGUI.EndDisabledGroup() EditorGUI.BeginDisabledGroup(maxY 0) scrollY (uint)GUI.VerticalScrollbar(new Rect(xyPos, new Vector2(slHeight, normalizedSize)), scrollY, 1, maxY 1, 0, GUI.skin.verticalScrollbar) EditorGUI.EndDisabledGroup() ... But these scrollbars have a sensitivity of 10 (pressing the up down, or left right, buttons will change the current value by 10 in the respective direction). I need them to have a sensitivity of 1. How can I do it?


How to Change position rotation of a parent while keeping X and Z Rotation Sooo this question is a problem , a evolution by another solution of this problem here How can I change the parents rotation so the childs rotation is looking at a specific direction Basically We have a "Eye" (HTC Vive). We have a "Parent" which is the Parent of "Eye". We can not change the position or rotation of the Eye in code. We can only change the position and rotation of the Parent. 1.We want to modify the Parent Position so that Eye to goes to a certain "Target 1" position. 2.We want to modify the Parent Y Rotation so that the Eye looks at a certain "Target 2" position. 3.While doing this we dont want to modify the Parent X or Z , because this would lead to a Rotated game experience. The Parent Position changes so the Eye gets to "Target 1" position. The Parent Position changes so Y Rotation should look at Target 2 position The Parent X Z Rotation should not modify the Eye X Z


Switching from software Engineer to Game developer I don't know if this is the right place to ask this. I've been working as a software engineer for 3.5 years so far, mostly web apps, mobile apps, web pages in banking systems, educational, etc but I always wanted to work as a game developer. Currently I have a university degree in CS, and I'm attending a masters degree in Apps design. I've very little experience in game dev (only for hobby), some space shooters and some steps in unity, also I took some courses of blender, and did some simple sprites (those 8 bit characters but animate them is a big problem for me atm.) but I've never gone too far. I know I cannot focus on all aspects of game development, because it is a huge world integrated with different disciplines, but I need to make a portfolio with some of my games at least. (I only have partial prototypes, some of them work, some don't...) I need some advise of people who are in the game business. Which platform framework do you recommend for me ? I already know a bit of Unity and I feel pretty comfortable with it. I can get some assets to work with (models audio, etc), there are some free material in the store, and I have budget to spend on that too if necessary. How do game companies hire people? What am I suppose to aim for a job? I mean this is a world full of disciplines and I need to focus in something particular I guess, I'm a senior frontend developer too, so I guess I should focus on coding. I think portfolio is the best way of showing your work. Any suggestions are welcome! thanks!


Knowing when an ad was clicked Is there a way in Unity to know when an ad was clicked? Some plugins for different advertising networks have events that fire when the ad was clicked, but if there is no such event how do I know when an ad was clicked?


Random Range Without Duplicates I have an array of gameobjects (some questions) if player hit some triggers a question from the array is displayed randomly, I want to avoid duplication of displaying questions. public GameObject Q public static int ColliderCounter 0 int WrongAnswerCounter 0 public int i,old private void OnTriggerEnter2D(Collider2D collision) if (collision.gameObject.tag "Obstcle") i Random.Range(0, Q.Length) old i ColliderCounter Q i .SetActive(true) GetComponent lt PlayerMovement gt ().enabled false IEnumerator waitWrongAnswer() WrongAnswerCounter yield return new WaitForSeconds(3f) Q old .SetActive(false) i Q i .SetActive(true) old i And I want to know how to check if all questions are displayed do something. Thanks in advance


Run a Script at Game Startup in Unity I have a script that is made to run when the game is loading. That script set the resolutions, fullscreen, and loads other screen and important settings and it applies them. I have the script attached to a gameObject in the main screen that have some game and scene scripts. The problem is that everytime that you return to the main scene, that script runs again and cause several bugs. So, there is a way to run a script only at game startup?


Unity Tilemaps Best practices I'm pretty new to Unity and I just finished some courses and tutorial found in the official documentation. I'm now in the process to apply what I learned so far using different assets from the ones provided with the tutorial, to see if I understood all the material. I'm trying to build a simple top down game with some free asset I found online. My tile palette is composed, among others, of tiles like these Now, in order to create something like this sorry for the quality, I recreated it in gimp since I'm not on the computer where I have Unity now I had to create three Tilemaps under the same Grid. The botton tilemap contains the grass (sort order 2), the middle one contains the fence (sort order 1) and the top one contains the house (sort order 0). My first question is given the tileset I have, is this the most efficient way to obtain what I needed? After having solved this problem I wanted to add a collider to the fence and to the house, but since they are on two different tilemaps I cannot use a composite collider to optimize the collider's layout. Is there another way to do this in a more efficient way? Instead of using tiles for quot interactable objects quot , should I use quot proper quot game objects instead?


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


How to write a unit test in Unity? is there a tutorial and patterns to write unit tests in Unity ? Should we use the classical c way and test the code or should we test the interactions in UI ? If so how?


How can I prioritize the call order of decoupled scripts? I have a player with many individual components that each handle a behavior such as jump, block, attack, duck, etc.. None of the scripts know about one another. Each listens for a specific input to fire. Some behaviors share the same input depending on the characters state such as ok the ground, in the air. I'm running into issue where the wrong behavior will fire that has shared input (down attack instead of down attack being held down for x seconds). I'm looking for advice on how to manage these behaviors and have more control over what can happen when. I've tried resolving this issue by creating a method that will disable other behaviors temporarily while completing the action and I've changed the script execution order. I thought about adding a discrete player state and restricting what behaviors are able to be performed at any given time but this increases the complexity quiet a bit.


Unity Augmenter Reality on Android with Video playing Hey sisters and brothers, So, I created an augmented reality marker, which works perfectly, I was able to display 3 shape on the screen with my Nexus 5. I would like to replace my shapes with a Video. So, when the user track on the marker, I would like to start to play a video above the marker as a part of the augmented reality (No full screen playing). I tried to use this video tutorial (https www.youtube.com watch?v YBc3ubr18ks) , but on Android you can't use MovieTexture (they say). My question(s) how can I display a shape above the marker, with a video on it and what it the video format ? When I trying to build the project with mp4, it failing, but when I do with AVI it's okay, but the app crashing. Thank you,


Unity third person controller and hills So I've been building a game and using the out of the box unity third person controller demo stuff. I found that even the tiniest of slopes seems to stop the "dude" dead in his tracks. Is there an easy way to adjust the sensitivity on the scripts somewhere? I tried messing with the sensitivity options in the input options setup thinking that it might help but it didn't and I don't really want to go messing about in the scripts unless I really have to because i end up complicating my life when I do that.


Problem with grid generation in Unity 5.1 Using Unity 5.1 and was following a tutorial for generating a grid for a Minesweeper style game. Link to the tutorial for reference http gamedevelopment.tutsplus.com tutorials build a grid based puzzle game like minesweeper in unity setup cms 21361 Tutorial is Unity 4, but I don't think it should matter. Here's my code public GameObject tilePrefab public int numOfTiles 10 public float distanceBetweenTiles 1f void Start () CreateTiles() void CreateTiles () float xOffset 0f for (int tilesCreated 0 tilesCreated lt numOfTiles tilesCreated ) Vector3 positionVar new Vector3(transform.position.x xOffset, transform.position.y, transform.position.z) xOffset distanceBetweenTiles Instantiate(tilePrefab, positionVar, transform.rotation) Essentially, the problem is that when I coded the spacing algorithm, Unity decided to ignore the spacing of 1f, but instead do 10,000. No matter the number I substitute for "distanceBetweenTiles", Unity spaces the cubes by 10,000 points. I'm assuming it has to do with how Unity is handling the float numbers, but I'm not quite sure, considering the number I substitute doesn't seem to matter. I've included a screenshot of Unity running the script and the inspector view of the giant X position. Thanks so much in advance 1


Unity Editor Get Mouse coordinates on left click on Scene Editor I need a simple script which does the following When I left click somewhere in the Editor Scene (doesnt matter if there is an object under the cursor or not) Do NOT deselect the current selection in the Inspector. Do not select the object under the cursor. and Just print the mouse X and Z interception with the Y Plane in the Debug.Log() i stumbled on many solutions but somehow i couldnt get this to work. i tried HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive)) and Tools.current Tool.None both seem to do nothing ..... X.x EDIT Happens that "HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive)) " needs to be inside public void OnSceneGUI() and called every frame to "block" the mouse clicks on the editor. i thought it toggles it off. still the problem of the mouse coordinates persists.


The A,I can't seems to move strafe on the left continously? void Update() ChasingPlayer() void ChasingPlayer() if (chasing true) transform.LookAt(player.transform) facing player transform.position transform.forward approaching Time.deltaTime going towards player float distance Vector3.Distance(transform.position, player.position) Debug.Log(distance) calculating the distance between player and enemy if(distance lt 10) chasing false transform.position Vector3.left 2f Time.deltaTime Debug.Log( quot STOP! quot ) I want my A.I to approach to the player but when it reaches within 10 feet(?), I want it to stop moving towards the player and strafe move to the left or right from there but instead it just moving in a curve movement that leads towards the player. How should i stop the AI within 10 feet(?) and move to the left right?


unity and maya how to export import fbx animation with rootmotion and non rootmotion clips? I've started learning about and playing around with animations in Unity and I've installed the Basic Motions Pack by Kevin Iglesias. I wanted to know how they work and to see if I can modify them so I've looked at the animation files which are .fbx. The animation hierarchy in Unity looks like this where BasicMotions Walk01 is the in place animation and RootMotion is the root motion variant which has velocity. I've looked into what root motions are and I think I've grasped what they are, but here's where things have gotten interesting. I've imported the BasicMotions Walk01.fbx into Maya and it looks like this it has a root joint for root motion and the animation moves the rig in each keyframe. So far so good! I've modified the animation so that it plays in reverse, basically made a sketchy reverse walk animation. Exported it to .fbx with the following parameters And then opened that in Unity, however when I import the animation and rig it it only has one clip and it's the Root motion clip, and I can't get the non rootmotion clip. The Root Transform Position (XZ) Loop match is always red and if I don't bake it into pose the animation functions like the Kevin's RootMotion animations, but I don't know how to get the non RootMotion clip. What am I doing wrong here?


IsolatedStorageException Could not find file I'm trying to save load player data from a file using the persistenceDataPath using the following code private void Save() if (File.Exists (Application.persistentDataPath " playerInfo.dat")) FileStream file File.Open (Application.persistentDataPath " playerInfo.dat", FileMode.Open) data.userExperience userExperience bf.Serialize (file, data) file.Close () private void Load() if (File.Exists (Application.persistentDataPath " playerInfo.dat")) FileStream file File.Open (Application.persistentDataPath " playerInfo.dat ", FileMode.Open) PlayerData data (PlayerData)bf.Deserialize (file) userExperience data.userExperience file.Close () Serializable class PlayerData public int userExperience It works fine if I play the game with Unity Editor. However, on Android, when I try to execute this line of code in Load() FileStream file File.Open (Application.persistentDataPath " playerInfo.dat ", FileMode.Open) I get this error The file does exist since the code pass through the if(File.Exist...) and it works when I try to access the file from the Save() method. I really don't know what it could be since the code that open the file in Save() and Load() is the same.


Throwing a grabbed object I'm trying to throw the carried object in the direction of the first person controller, but unable to make it. I could make the carried object drop, but the same time i need to instantiate velocity to the carried object, so that i could forward. I'm building up a bowling game and trying to make the ball behave like the same when the player throws the ball. It should hit the alley and move forward to hit the pins. Below is what so far I've tried. using System using System.Collections using System.Collections.Generic using UnityEngine public class pickupobject MonoBehaviour GameObject mainCamera public GameObject empty bool carrying public GameObject carriedObject Camera cam public float distances public float smooth float speed 1000f Use this for initialization void Start() cam GameObject.Find("MainCamera").GetComponent lt Camera gt () mainCamera GameObject.FindWithTag("MainCamera") Update is called once per frame void Update () if (carrying) carry(carriedObject) CheckDrop() else pickup() private void pickup() if(Input.GetKeyDown(KeyCode.E)) int x Screen.width 2 int y Screen.height 2 Ray ray mainCamera.GetComponent lt Camera gt ().ScreenPointToRay(new Vector3(x, y)) RaycastHit hit if(Physics.Raycast(ray, out hit)) pickupable p hit.collider.GetComponent lt pickupable gt () if(p! null) carrying true carriedObject p.gameObject void carry(GameObject o) o.GetComponent lt Rigidbody gt ().isKinematic true o.transform.position mainCamera.transform.position mainCamera.transform.forward distances void ThrowBall() GameObject go (GameObject)Instantiate(carriedObject,transform.forward, Quaternion.identity) pickupable to go.GetComponent lt pickupable gt () to.Throw(carriedObject.transform.forward speed) void CheckDrop() if(Input.GetKeyDown(KeyCode.U)) Drop() void Drop() carrying false carriedObject Instantiate(carriedObject, new Vector3(transform.position.x, transform.position.y, transform.position.z), transform.rotation) carriedObject.GetComponent lt Rigidbody gt ().isKinematic false gameObject.GetComponent lt Rigidbody gt ().AddForce(carriedObject.transform.forward 100) carriedObject.GetComponent lt Rigidbody gt ().AddForce(0,0,1f) carriedObject.gameObject.GetComponent lt Rigidbody gt ().isKinematic false carriedObject null Thanks in advance!


Unity job system long running task I have a long running task (250ms )that I want to pick up a resultant array from. This job is a path finding service that should run periodically in the background. It's all prototyped in another language using a background Thread. According to the Unity docs, I should call Complete() when I'm ready for the results of this job. However, I don't know when this task will complete I don't want my main thread to wait on this job completing. I want this job to run async and to collect the result from a Nativearray the resultant search array null (if it's a first run and still in process. with concurrent array access protected by a lock. If the job is writing to the array, it should be locked. What's confusing is that most of the Unity job examples seem to use short jobs that last a few frames, then pick up a result in a LateUpdate() or next Update(). My job is much longer running. Since my job uses no Unity API directly, am I correct that standard c Threads seem more applicable for my kind of problem?


Manual response when 2 shapes made of rectangular volumes collide I have 2 compound objects made of rectangular blocks. One of them (the one that is moving) has a script that listens to OnTrigger callbacks. What I need is to position the moving compound object on the first compound object to make then not collide but stay in contact. As an example you can thing of two "spheres" made of blocks. Both spheres are on the floor. Then I move one of the spheres (still on the floor) and I detect that it collides the other sphere, so, I need to push the moving sphere up to make it not collide with the first one but stay in contact. I have a manual algorithm that make tests on the different blocks of the two groups to push it up enough to make them not collide but it is a bit intensive. Do anybody know if unity physic engine can help here? The main problem is that after I receive the collision I can not move the moving sphere up and recheck manually first of all because there's no Check for rectangles and on the other hand if I want to be notified by the physical engine after I move the moving sphere up (to see if it still collides)I need to wait a new frame which is not feasible in my case. P.S. I'm using unity engine.