Resolution problems with global illumination in Unity I am pretty new to Unity and after hours of searching I have finally figured out how to set everything up for (baked) global illumination to work for my model. However the model is an export from a CAD program and so the mesh is rather bad quality (it seems it is optimized by the CAD program for minimum number of triangles). At least I am implicitely assuming that this is a bad quality mesh because it would by standard of finite element meshes, which of course doesn't directly apply here. So what I am observing is three resolution problems (see images) 1) the lighting in the scene is somewhat "cloudy" although the faces are evenly colored and there are no lights that could explain the patterns (see eg. area inside drawn red rectangle) 2) there are slight jumps in brightness visible at the edges of the triangles of the mesh (see red arrows and, for comparison image of mesh) 3) the shadows are pixelated (see red ellipse, yes I have already tried to change shadow quality to high in the project settings, but to no avail) Because there are so many settings that affect lighting, I assume it will take me hours if not days with trial and error to figure that out. Which settings are likely to be responsible for these three problems? I found a display mode of the scene view, called Baked Global Illumination UV Charts that probably explains the first problem, but I don't know how to interpret it, see third image below


HDR mode in windows makes build version of Unity game look washed out I've got a 2D Unity game I've been working on. The development computer is hooked up to a TV that supports HDR. If I turn on the "Play HDR Games and Apps" switch in windows then run the build version of my game the colors all appear overly bright and washed out. It looks fine in the editor though and looks fine when the windows HDR mode is turned off. Is there a setting in Unity that can stop this problem?


How do I find out where a script is attached to in Unity? I'm using Unity 2017.03.0f3 and I have a scripts folder with scripts (C ). Suppose I forget, or am working on someone else's project How do I know exactly which scripts are attached to what GameObjects or PreFabs, without clicking and going through all the Hierarchy objects please, and by first clicking on a script in the Project view? I hope that's specific enough.


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.


Why does adding a value to list makes list not editable in unity inspector I am adding elements from the first list to another similar list, but it makes first not editable in the Unity Inspector. Whenever I try to change values from the inspector it makes them again 0. While If I comment list.Add() I can change values in the inspector. Serializable public class Characterz public string Name public int Age public float Gold public class Actor MonoBehaviour public List lt Characterz gt kings new List lt Characterz gt () public List lt Characterz gt Actors new List lt Characterz gt () void Start() for (int y 0 y lt 30 y ) Actors.Add(new Characterz()) if (y lt 4) I need to comment following line to change Actors list value in editor kings.Add(Actors y )


Ensuring that a randomly generated galaxy wont place stars inside one another? I'm attempting to build a game with a spiral galaxy design. In doing so I followed a short guide on making the rough layout of the galaxy. My code works, but the "stars" (I'm bad with variable names, in this code "star" refers to the central star of a solar system) often clip into one another. Is there a way for me to ensure that no stars will intersect? Code below is what I'm using to generate my galaxies. for(var i 0 i lt starCount i ) var distance float Random.Range(minDistance, maxDistance) distance Mathf.Pow(distance, 2) Choose an angle betweeen 0 and 2 PI var angle float Random.Range(0.0 , 1.0) 2 Mathf.PI var armOffset float Random.Range(0.0,1.0) armOffsetMax armOffset armOffset armOffsetMax 2 armOffset armOffset (1 distance) var squaredArmOffset float Mathf.Pow(armOffset, 2) if(armOffset lt 0) squaredArmOffset squaredArmOffset 1 armOffset squaredArmOffset var rotation float distance rotationFactor angle Mathf.Round(angle armSeparationDistance) armSeparationDistance armOffset rotation Convert polar coordinates to 2D cartesian ones var starX float Mathf.Cos(angle) distance var starY float Mathf.Sin(angle) distance var randomOffsetX float Random.Range(0.0, 1.0) randomOffsetXY var randomOffsetY float Random.Range(0.0, 1.0) randomOffsetXY starX randomOffsetX starY randomOffsetY var newStar Transform Instantiate(star, Vector3(starX, starY), Quaternion.identity) newStar.transform.parent center


Why the main menu is not working on the second time when pressing on escape key to back to the main menu? I have two scenes. Main Menu and the main scene. The game start when only the main menu is loading. When I click on the New Game button it's loading the main scene and removing the main menu scene. If I click now on the Escape key it will remove the main scene and load back the main menu scene but this time I can't click on any of the buttons in the main menu. I'm not sure if this is the right way to switch between the scenes but it's not working good. On the Newgame button I created and attached a new script. And then in the OnClick event of the button I'm calling the method LoadByIndex using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class LoadSceneOnClick MonoBehaviour public void LoadByIndex(int sceneIndex) SceneManager.LoadScene(sceneIndex) On the main scene I added a empty gameobject and attached to it another script using System.Collections using System.Collections.Generic using UnityEngine public class BackToMainMenu MonoBehaviour public int sceneIndex Update is called once per frame void Update () if (Input.GetKeyDown(KeyCode.Escape)) UnityEngine.SceneManagement.SceneManager.LoadScene(sceneIndex) When the game start in the main menu when clicking on New Game button it's loading index 1 the main scene and removing the main menu. When clicking on escape key it's loading index 0 and removing the main scene. But then the main menu is not working.


JSON deserializing 'nested' Array Greetings! I'm working on a class that loads and parses .json files and returns information from the loaded .json, but I have problems reading the nested arrays of my .json files. Turning the serialized object public and looking at the Inspector, the 'Choises' array is not being read at all. It contains four objects, each contain a string and an integer correspondingly. using SimpleJSON using System using System.Collections using System.Collections.Generic using System.IO using UnityEngine public class JsonParser MonoBehaviour private string loadedJson public StoryData storyData Serializable public struct choice public string choiceText public int choicePointer Serializable public struct storyImage public string imagePath Serializable public struct storyText public string text Serializable public struct placeholderStory public string storyText public string storyImage public List lt choice gt choises Serializable public struct StoryData public placeholderStory placeholderStory public void LoadJsonFile(string filename) loadedJson File.ReadAllText(Application.dataPath filename) storyData JsonUtility.FromJson lt StoryData gt (loadedJson) public string GetChoiceText(int storyPosition, int choiceIndex) string choiceString storyData.placeholderStory storyPosition .choises choiceIndex .choiceText Debug.Log(choiceString) return choiceString public string GetStoryText(int storyPosition) string storyString storyData.placeholderStory storyPosition .storyText return storyString public string GetStoryImage(int storyPosition) string imageString storyData.placeholderStory storyPosition .storyImage return imageString


Update the UI Rotation According to camera rotation I have a camera which is showing the userInterface (canvas) object into the front of my camera. I am only updating my userinterface position if the camera raycast is not hitting my userInterface object collider. something like this public class UIPlacerAtCamFront MonoBehaviour public GameObject userInterface public float placementDistance Vector3 uiPlacementPosition RaycastHit objectHit void Update () Vector3 fwd this.transform.TransformDirection(Vector3.forward) Debug.DrawRay(this.transform.position, fwd 50, Color.green) if (Physics.Raycast(this.transform.position, fwd, out objectHit, 50)) raycast hitting the userInterface collider, so do nothing, userinterface is infornt of the camrea already else raycast is not hitting userInterfae collider, so update UserInterface position accoding to the camera uiPlacementPosition this.transform.position this.transform.forward placementDistance userInterface.transform.position uiPlacementPosition Continuously update userInterface rotation according to camera userInterface.transform.rotation this.transform.rotation The above script has attached with my camera, it displaying the object correctly but as i start to rotate my camera my UI object rotation looks very strange as below image suggested As i rotate, this problem occurs I know that the problem is in rotation, so I tired to change my this rotation code userInterface.transform.rotation this.transform.rotation to this userInterface.transform.localEulerAngles new Vector3 (this.transform.localEulerAngles.x, 0, this.transform.localEulerAngles.z) but it bring another strange rotation for me, like given below I want that my userinteface object face my camera correclty, even my camera watching the start or end of my userinteface object. How can i rotate my UI according to camera rotation correctly?


How does Vector3.Angle compute the resulting angle? I don't understand the concept of Vector3.Angle in Unity. Can someone please explain in detail how it computes the angle? From which two points is the angle measured? It would also be really awesome if you could provide some diagrams for me understand it more, visually.


How can I create Portrait game assets to have same with gap for both iPhone 7 Plus and iPhone X? In my Unity game I made changed my Pixel Per Unit value to 243 since the height of a Portrait game for iPhone X is 2436. The game looks great and the asset sizes look just right on the iPhone X simulator. But when I change to iPhone 7 Plus I get considerable space on the sides and it gets worse when I change to the iPad. How can I make my game have the same width gaps for iPhone 7 Plus and iPhone X without making assets look stretched horizontally or vertically? UPDATE The images below give an idea of my game on both 1080x1920 (for iPhone 7 Plus) and 1125x2436 (for iPhone X). It's not a match3 game. All the game objects below are static and have colliders. The gaps between are quite significant for other dynamic objects to move between. Reducing the gaps significantly would alter the movement of the dynamic objects and their sizes too, making the ratio in object sizes look wrong. I haven't started worked on scores or menus yet, so I haven't added a UI canvas yet.


Unity "Update" method with lots of objects with logic In my game I'm working on in Unity, I want to have energy and machines (i.e ore processing machines, smelting (think Minecraft modded)), but I was thinking about performance. The player could have quite a few of these machines in their base, all of them could be doing something and could be off screen, so this could effect performance as each machine will have logic to handle whatever it needs to do, and lots of them could be running at the same time. Machine example Let's say we have a machine that crushes stone. Player puts it into the machine slot, machine then starts crushing it if it has enough energy, and after X seconds, it outputs the crushed stone. Player could keep the machine UI open and watch the progress (i.e progress bar), or be far away from it. Should these machines be running constantly in Update, if not, what would be a better way to do this?


Stop Unity from smoothening out images In Unity, low resolution images are "smoothened out". Is there a way to keep them pixelated? For your information, the images that I'll be using are in PNG format.


Translate position from 3D camera to 2D camera Currently I have 2 cameras, one for viewing the 3D objects (Perspective), and the other camera to view 2D objects (Orthographic). (Also, the view of the camera never intercepts each other.) I am trying to display a 2D object based on the position of a 3D object, like so What I have is the respective 2D and 3D Camera, as well as the Vector3 position of the 3D GameObject. What I have tried public Vector2 Convert3DPositionTo2DPosition(Camera camera3D, Vector3 position3D, Camera camera2D) var tempPos camera3D.WorldToViewportPoint(position3D) return camera2D.ViewportToWorldPoint(tempPos) The only problem is that the returned position is not completely aligned with the 3D position. Which results in this kind of results Also, I have made sure that both the 3D and 2D object have their pivot point are set correctly in the center, but it still does not work as intended. (I am currently using Unity 2019.1.14f1)


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 ?


In Unity (2017) is there a way to set the buttons used by Input.GetAxis() programatically? The buttons used for keyboard axis inputs can be set manually via Negative and Positive Button fields for the axis at Edit Project Settings Input Manager. However I'd like to make this a user configurable option which I think means needing to set the button values from a script. I've been looking for a method along the lines of Input.SetAxis("Vertical").positveButton But so far I'm striking out. Is there a way to do this?


Is it more efficient to add scripts to each GameObject or to a single parent object? Does a C script added to a parent object work more efficiently and effectively (in terms of both memory and performance) on all objects, in my case lighting, or adding script components to each lighting GameObject object? This goes for other GameObjects parented in the hierarchy.


Preload multiple scenes at the same time and activate them on demand in Unity. Unity, async, simultaneous Preload scene in unity this question tells us about how we can pre load a scene in Unity and load it on demand. What it doesn't tell us how do we pre load multiple scenes at the same time and also keep the other scenes in memory waiting to be activated when we load another scene? Use case pre loading multiple scenes at the start of the application, so they are ready when required. Example You have a Scene Intro which takes 20s to complete where you start pre reloading Scene Main Menu that takes 10s to load. When Scene Main Menu has finished pre loading, you still have 10s to spare, those could be used to pre load Scene Main Game. You have a Scene Main Menu. Depending on user choice you load Scene Main Game or Scene Sandbox. You pre load both scenes while user is still in Scene Main Menu. When user makes their choice, chosen pre loaded scene is loaded.


How to not move my character when they collide using Unity and Box Collider? I'm trying to get my characters near to each other so they can attack the other one, but when the player character or otherwise gets near they are pushed to the other direction when they collide. How to prevent that happen so they won't move when touching each other? This is the player objects The Treant objects I what I want is that they collide and can't move through each other and stop moving. But this keep happen gif of my treant getting pushed away Can someone help me with this issue?


Unity PNG sequence animation changing position in animation We are making frame by frame animation and we have a canvas size for animation. Attack animation is changing position in canvas. In Unity after the attack animation is completed it teleports back to the initial position. I tried setting animation event and updating parent position but it does not work. It teleports to nonsense locations like player is looking at x but it teleports to x. Anybody have solution for this? Since it is not rigged, root motion is not working. I tried to put animation event at the last frame and put this script to the character controller which is a child object of empty parent object public void animationFinished() animation finished true void LateUpdate () if(animation finished ) transform.parent.position transform.position transform.localPosition Vector3.zero I have 25 PNG as frames of animations. From idle animation I go to attack animation. Idle is stable as a position, but attack animation is changing position in canvas for example animation canvas is 1920x1080 canvas size and animation starts from the left size to right size. I can't move the character with a script because it has its own timing that I can't set up with script. So I am trying to get the last frame position and pass it to idle animation at that position but instead of that without code it teleports back to the initial position after attack is completed. This is a similar topic, but the solution did not work.


Exporting Fbx from maya to Unity makes the model deformed So I have a female avatar model and I have attached cloth model to it by binding it to skeleton rig. After that copying weights from avatar to the cloth model. Now when i export it as an fbx and open it in unity, it converts the whole model into a deformed shape. I have removed the errors related to scale compensation as well by running the (ScaleCompenstationOff ) mel script in Maya but still no success. Kindly let me know if you guys know of any solution to this problem !!!


How can I manually call fire OnTriggerExit() for colliders a trigger is inside of in Unity? In Unity, the OnTriggerExit() method is not called fired (not sure if it's an event or not) when an object is disabled or destroyed within it's collider. In comparison to it being fired is an active object that was within it's collider no longer being inside the bounds of that collider on the next frame. I want to be able to call OnTriggerExit() on my triggers OnDisable() method as a workaround. How would I go about calling firing OnTriggerExit() manually?


Raycasting center of camera is not working why? In my game i'm using Unity First Person controller. I check every second what I am looking with the following code cam Camera.main RaycastHit hit Vector3 CameraCenter cam.ScreenToWorldPoint(new Vector3(Screen.width 2, Screen.height 2, cam.nearClipPlane)) if (Physics.Raycast(CameraCenter, transform.forward, out hit, 5)) WhatIamLookinTag hit.transform.tag The problem is that isn't working if move Up and down player "view" (so i move up and down mouse..) I need the object that is in screen center (based on what am i looking). Why ?


Jump a gameobject when a key is pressed I am working on a platform game,When I press the space bar the object should jump and when I release the space bar it should come down. The code I have used for jump is void Update () transform.Translate(Vector3.right Time.deltaTime) if(Input.GetKey(KeyCode.Space)) rigidbody2D.AddForce(Vector3.up 3) if(Input.GetKeyUp(KeyCode.Space)) rigidbody2D.AddForce(Vector3.down) But when I release the space bar the object is not coming down


Canvas Element Not Render In Proper Position I don't know what's going wrong. The Text and Slider must be on the red square area. Anyone can help to determine this bug ? Thanks


Add 1 to a PlayerPref float if a day has passed in Unity 2D I'm making a daily rewards system in my Unity 2D game. For each real life day the user logs in (not necessarily consecutive) the player earns a Reward Point. Reward Points do two things Increase the rarity of what the player may obtain from Reward Chests. Increase the frequency that a player may open a Reward Chest. The frequency starts at 24 hours, and for each Reward Point, it is decreased by 24 hours. (The frequency a player earns a Reward Point is not increased, just the frequency that the player can open a chest.) I am asking how to check if a day has passed since the player last opened the game, and, if they have, add 1 to a PlayerPrefs float (this float contains the amount of Reward Points). I am familiar with Time, but I'm not sure how to accomplish my goal with it. .


Why is my button script not working? Okay so i'm new to C and i made this script. The goal i have in mind is that when the player is on the button and presses a button ( W in this case ) the button is switched from on to off ( or vice versa). The problem i have is that when the character stands on the button and presses W it doesn't always switch its state and i have no idea why. Any info would be appreciated. using System.Collections using System.Collections.Generic using UnityEngine public class Button MonoBehaviour public bool Pressed false Animator Anim Use this for initialization void Start () Anim GetComponent lt Animator gt () Update is called once per frame void Update () Anim.SetBool ("Pressed", Pressed) void OnTriggerStay2D(Collider2D other) if (Input.GetKey(KeyCode.W)) if (Pressed) Pressed false else Pressed true


Do meshes marked "shadows only" require light maps to block light? I want to use an .fbx mesh to block light from entering a room (except for holes cut for windows). The mesh itself must stay invisible. I know marking it "shadows only" will hide it from the camera, but light still passes through it unless I mark the mesh as "lightmap static" as well. The problem is that this is a huge mesh that doubles the number lightmaps required, and it won't even be seen. Is there a better way to do this? I am using the Lightweight Render Pipeline in Unity 2019.1.4f1 on Windows 10. Using CPU to render on an Intel Core i5 laptop.


In Unity3D, how do I create an efficient scratch card effect? I want to create a scratch card like effect in new Unity UI's new Image tag. I know it's possible with setPixels, but that's prohibitively expensive on mobile devices. Something like this I'd like the user to be able to drag on any part of the image to "scratch off" the top layer and reveal the content underneath it. How can I do this?


How should a Unity object control it's state? I've been using Unity's component based design, and the biggest problem I've faced is how to control an object's( not component's ) state. The problem is, some components must act differently based on the object's state. However, checking an object's state within a non specific component( imagine we have a "DamageEnemyComponent" ) won't work at all because it makes assumptions about the object it's attached to. The alternative is to make each component perform one, and only one function. The components are then disabled enabled or added removed depending on the object's state( probably managed by a more specific component. ) Imagine we have a "Boomerang" object. Assume it has only two states idle( being held by the player ) and firing. In the idle state, the boomerang would have very few components, because we don't want it to interact with the world while it's simply being held. It may have components to listen for a "throw", though. Once it is thrown, some state manager on the object needs to update the object to have components for moving, damaging enemies, maybe picking up items etc. When the boomerang is back in the hands of the player, it's component list would need to be restored. This would work, but it would basically be building a new game object for each state, which is incredibly tedious and messy without Unity's editor. Not to mention the inheritance and interfaces can't be used well here( since the state specific components will be built into the state manager script. ) I can't see a way to control state using Unity's components. How is this usually done? It feels as if Unity should provide a way to build different states in the editor, much like building an object.


Unity WebGL build throws errors I am working on a multiplayer game for WebGL platform and I am using SocketIo amp node.js server for handling the game. I am facing issues, as shown in the attached image. I have no idea about what these errors mean. I don't think that the issue is from my coding side, as my multiplayer game runs perfectly in standalone builds, with more than 4 instances of the standalone build running. It does not even open in my WebGL build. Does WebGL does not support threading? What are these errors all about? Can these issues be solved, or do I have to change my whole project implementation?


Is there any way to bring animation into unity without a rig bones? I am developing for mobile and to make the game run on lower spec mobiles, I was only going to import bones rig for the main character. There are other humanoid characters in the scene which do move about and are rigged already in my 3d app but since they wont be controlled in anyway by the player in the game, I just wanted to bake and import their animations alone without the bones. I know unity can handle blendshapes but I am more comfortable with rigs and also cos these characters are already rigged properly.


Unity C Raycasts, How to Ignore Triggers? Let's say I have a Raycast, but I don't want it to collide with any triggers. I don't want to change the Project settings since that's a little inflexible. How can I have a Raycast ignore any triggers?


How do I get the InputManager to recognize a certain axis Vector2D with a Vive motion controller? Right. So basically I want to map the Vive motion controller touchpads (certain locations) to the certain inputs in Unity's InputManager. How do I do this? Like I want a certain area on the touchpad to equate to forwards backwards in the InputManager. How would I do this? I am not seeing a way to do it natively. Long story short I'm wondering if I can use the Vive with the InputManager or not.


HDR bloom techniques using post processing in Unity3D I've seen many posts on how to accomplish HDR bloom effects in Unity3D using its (now legacy) Bloom component as part of the standard assets package. I'm trying to replicate it using the new post processing package, but I can't seem to get it to work. I have an an emissive material that's emitting at a value far 1 sitting at 10 Bloom is set in a Post Processing Profile, and the threshold is 1 Finally, HDR is enabled on my camera, along with a deferred rendering path. Yet this doesn't work. I only see the bloom effect if I set my bloom threshold lt 1, after which all my materials bloom. It's as if HDR is not actually enabled. Anyone know why?


Downloading 10 images and storing their data with WWW I would like to download 10 images, and store their texture data into my list. I don't really know how to do that I heard that for this you use the WWW class, so I went List lt byte gt StartDownload() List lt byte gt result new List lt byte gt () for (int i 0 i lt 10 i) WWW request new WWW("http www.example.com " i ".png") result.Add(request.texture) return result Which of course doesn't work, but I'm not sure why.


Unity3D in WebGL the Player doesn't have animations I using Unity 2019.2.14f1 to create a simple 3D game. I want to build the project for WebGL, but, even though the player has animations on Unity, in the web the Player doesn't have animations even though it jumps and moves around as you can see here . For the Player, I am using the ThridPersonController from on Standard Assets but I have hidden Ethan and added my own character avatar. And this is the inspector of the avatar What am I missing here?


Hide back button bar of android mobile while playing game I just want to hide back button bar of android mobile while playing the game. I tried to make it close by pressing back button,it getting close but its always visible. please help..


EventSystem.current is null private void OnEnable() Debug.Log(EventSystem.current) EventSystem.current.SetSelectedGameObject(gameObject) Very simple script for selecting a UI element on enable. However, EventSystem.current prints null to the console. Unity 2019.3.15f1 I have an Rewired event system in the scene. Also tried putting this in an IEnumerator and waiting a frame before logging to the console no change.


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


How to rotate and move an object in precise time frame My task is to rotate and move an object into a new position and rotation in a given time. Say I have to move a cube from (0,0,0) (0,0,0) to (1,1,1) (0,90,0) in 5 seconds. Could anyone explain to me please how to achieve that? My experiment is private IEnumerator DoMove( float time, Vector3 targetPosition ) foreach(WayPoints wp in tposes) float counter 0 float duration wp.timeStamp while (counter lt duration) counter Time.deltaTime Vector3 curpos cube.transform.position Quaternion crot cube.transform.rotation float time Vector3.Distance(curpos, wp.position.position) (duration counter) Time.deltaTime cube.transform.position Vector3.MoveTowards(curpos, wp.position.position, time) cube.transform.rotation Quaternion.Lerp(crot, wp.position.rotation, time) yield return null Debug.Log( quot Reached position quot wp.position.position quot in time quot Time.time) The cube gets to its position in time, but rotation is late. The end position of the cube should be (2,2,2) (0,120,0), but it stops moving at (2,2,2) (0, 110,0). There are two positions I want the cube to be in (1,1,1) (0,90,0) in 5 seconds (2,2,2) (0,120,0) in next 4 seconds


Problem with Animating on local position Unity Currently, I am having a Cube that needs to be animated to roll on its edge. Using unity built in animation feature, I created 4 animations (RotateUp, RotateDown, RotateLeft, RotateRight). At the end of each animation I would put an Event to call a method on my script. To be able to move the object every time the animation is played, I put the cube with animator attached inside a parent object. Below is the script attached to my cube. using System.Collections using System.Collections.Generic using UnityEngine public class RedCubeBehavior MonoBehaviour Animator anim bool isMoveTriggered false void Start() anim gameObject.GetComponent lt Animator gt () void Update() if (Input.GetKeyDown(KeyCode.UpArrow)) MoveUp() else if (Input.GetKeyDown(KeyCode.DownArrow)) MoveDown() else if (Input.GetKeyDown(KeyCode.LeftArrow)) MoveLeft() else if (Input.GetKeyDown(KeyCode.RightArrow)) MoveRight() if (isMoveTriggered) if (IsBackToIdle()) transform.parent.position transform.position transform.localPosition Vector3.zero isMoveTriggered false void AnimationFinished() anim.Play("IdleState") public void MoveUp() if (isMoveTriggered) return else Debug.Log("MoveUp") isMoveTriggered true anim.Play("RotateUp") public void MoveDown() if (isMoveTriggered) return else Debug.Log("MoveDown") isMoveTriggered true anim.Play("RotateDown") public void MoveLeft() if (isMoveTriggered) return else Debug.Log("MoveLeft") isMoveTriggered true anim.Play("RotateLeft") public void MoveRight() if (isMoveTriggered) return else Debug.Log("MoveRight") isMoveTriggered true anim.Play("RotateRight") bool IsBackToIdle() return anim.GetCurrentAnimatorStateInfo(0).IsName("IdleState") Every time the arrow key is pressed the object would rotate but in the end when AnimationFinished() is called, the cube would just roll back to its starting position (because of playing IdleState). It will only work (the object didn't return to its starting position) if I pressed the arrow twice quickly. I've tried to not call the IdleState (which is only an empty state), but what happens next is it just won't play another animation again when triggered. What should I do in order to get it work without having to press the key twice?


How to unpack game data files encrypted with AES key? In game development pak files are secured by some encryption and one of these are AES key. I want to know that for security purpose is the AES key is stored in the game files itself? I know that computer cannot store the AES key in his mind so it need some clues or files to extract these Ppak files, so where does these AES keys gets stored in a game file itself?


How to store references to scene objects in prefabs? i am instantiating a few game objects in my scene using prefabs and i would like to attach a script to some of them to do something at a certain time but for that i need to reference to scene objects and its not allowing me. anyone know why? and whats the workaround? i can pull those prefabs into my scene and use them as game objects but that would destroy the idea of prefabs isn't?


how to put elements around circle with equal distance? I know circle formula and know how to draw it. but I want put 4 points on it with equal distance from each other. how can I do that? I work with unity.


How can I avoid false positives with "blow" input? I m working on a game which uses blow functionality to move an object in the game screen. This screen also has background music in it. The problem is that the microphone is detecting the BGM as blow input and the object is being moved without any actual user input. How can I avoid this kind of false positive?


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


Rotating with a preferred direction I do a RayCast to the terrain and then use the RaycastHit.normal to plant flags. I would like to have the flags to point up with the normal, but have them all face the same direction. As seen in the image flag 1 points to left of the screen and flag 5 to the right. I understand why, but do not know how to rotate it. I saw LookRotation (Unity) has an override that takes a forward direction too. I thought it would work with say Vector3.Forward, but if a flag is placed on a wall it points into the wall. The direction or angle they face can be set by the player. I have a hard time understanding quaternions, every time I think I do, I get stuck. Any tips ?


Could not establish connection with local server process when opening or making Unity project Whenever i try to either create or open a Unity project, I get faced with this error. Does Unity need a proxy server, because I dont have one. (If so, how do I get one?) And apparently I need to add some environment variables, (HTTP PROXY, HTTPS PROXY and UNITY NOPROXY localhost,127.0.0.1) what values do i add to these? Unity Package Manager Diagnostics (v0.1.5) Ran 7 checks 1 succeeded 6 failed UPM registry reachable (FAIL) Make an HTTP request to the UPM package registry Connection error. This could be because a proxy is misconfigured. Ping UPM registry (FAIL) Measure the latency of the UPM package registry API No successful pings could be made in 0.062 seconds (30 failed) Ping UPM download (FAIL) Measure the latency of the UPM package download endpoint No successful pings could be made in 0.039 seconds (30 failed) UPM registry download speed (FAIL) Test the Internet connection using the UPM package registry Connection error. This could be because a proxy is misconfigured. Speedtest.net (FAIL) Test the Internet connection using Speedtest.net Connection error. This could be because a proxy is misconfigured. HTTP proxy environment variables (PASS) Detect whether proxy related environment variables are set (HTTP PROXY, HTTPS PROXY, ALL PROXY, NO PROXY, UNITY PROXYSERVER, UNITY NOPROXY) Proxy support has been configured through the following environment variables HTTPS PROXY C Program Files Unity Hub Unity Hub.exe HTTP PROXY C Program Files Unity Hub Unity Hub.exe UNITY NOPROXY C Program Files Unity Hub Unity Hub.exe UPM health check (FAIL) Start the UPM process and call its health endpoint Server started but did not respond to health requests Error Invalid protocol c How do I fix this?


In Unity, rotating character spine keep going back to original rotation this is the code for rotating spine in my character model Transform spine float horzMovement void Awake() spine transform.Find("Character Healthmale Root pelvis spine 01") void Update() horzMovement Input.GetAxis("Mouse Y") void LateUpdate() spine.localRotation Quaternion.Euler( spine.localEulerAngles.x horzMovement, spine.localEulerAngles.y, spine.localEulerAngles.z ) print(horzMovement " " spine.localRotation.eulerAngles.x " " Time.time) Code is quite simple, I'm just rotating "X" axis from y mouse movement. The problem is when running this code, it seems work but it keeps rotating back to the original rotation. This is the log that I printed into the console. Note that spine's original x rotation is about 27.62928. 0 27.69298 4.510662 0 27.69298 4.527147 0.1 16.33139 4.543715 minus movement detected 0.1 16.3314 4.560284 0.1 16.33139 4.57685 0.1 16.33139 4.593714 0.1 16.3314 4.609998 0.1 16.33139 4.626548 0.1 16.33139 4.643115 but it seems not much changed, why? 0.15 10.51222 4.659858 0.15 10.51222 4.676248 0.15 10.51222 4.692952 0 27.69298 4.759083 this is when I stopped the mouse. It's reset. 0 27.69298 4.775648 As you see the above log, first time, it prints 27.692.. and it's original x rotation of spine. Next, I moved my mouse so the "horzMovement" value was updated to minus, and it updates x localRotation also. But when I stopped move mouse, it just return to initial x rotation 27.69298! There is no code or functionality to "rotating back" to original rotation of spine. I don't know why this is happening. Wham am I missing? Any advice will very appreciate it!!


OnMouseUpAsButton not always called I'm working on a 2D implementation of Free Cell in Unity 4.6.1, and I'm having trouble getting my click detection code working consistently. The code below should be called every time a card is clicked (they all have BoxCollider2D components) but it doesn't always happen. Handle Clicks on Card void OnMouseUpAsButton() print ("test") int cardLayerMask LayerMask.GetMask("Cards") RaycastHit2D hit Physics2D.RaycastAll(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, Mathf.Infinity, cardLayerMask) print ("Hit length " hit.Length.ToString()) if (hit.Length gt 0) print ("Hit") Even the "Test" print statement doesn't get called consistently, so it's not a problem with the raycast. If it manages to print the test, the raycast always works. Each time the game runs, the cards get dealt onto the playing field randomly into stacks. On each run, some subset of the cards don't call the above code. The number of cards that work correctly varies, as does their position on the field. It's not consistent with any particular card. I'm wondering if maybe there's an issue with the BoxCollider2D instances overlapping. The other colliders in the scene, like the one on the "table", always trigger OnMouseUpAsButton() successfully. I need to be able to register clicks on every card, so I need to find a way to make this work. Have any of you run into a similar issue before? If not, is there a way for me to work around this? Maybe a different way to detect the clicks on the cards? Here's a screenshot of an example card from the inspector. Aside from transform position amp script property values, all of them are identical (from a prefab) Update w Solution from Accepted Answer Using Byte56's solution, I was able to take care of this pretty easily. I've included sample code below. Note that to get the sample to work, the "top" object has to have the highest transform.position.z out of all the objects the raycast hits. I also put all the possible hit objects into their own layers so I can trigger different behavior based on what type of object is clicked. Handle clicks if (Input.GetMouseButtonDown(0)) Cast a ray, get everything it hits RaycastHit2D hit Physics2D.RaycastAll(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, Mathf.Infinity) if (hit.Length gt 0) Grab the top hit GameObject GameObject lastHitObject hit hit.Length 1 .collider.gameObject Determine layer of last hit object, take next steps as appropriate switch (LayerMask.LayerToName(lastHitObject.layer)) case "Cards" print ("Hit card!") break case "Table" print ("Hit Table!") break case "Cells" print ("Hit cell!") break


Coroutine different behaviour when called from another script I am quite new with game dev, specially with unity. In order to understand how it works, I decided to start small with a pong game. I have a Ball script, which in the Update() method move the ball depending to the speed, and if a player score, it increment a score field and reset the ball to the center (and stop the ball for 2 seconds) trough a coroutine function. Ball script public class Ball MonoBehaviour SerializeField float speed int isMoving 1 float radius Vector2 direction Vector2 startPosition Start is called before the first frame update void Start() direction Vector2.one.normalized radius transform.localScale.x 2 half the width startPosition new Vector2(transform.position.x, transform.position.y) Update is called once per frame void Update() transform.Translate(direction speed isMoving Time.deltaTime) if (transform.position.y lt GameManager.bottomLeft.y radius amp amp direction.y lt 0) direction.y direction.y if (transform.position.y gt GameManager.topRight.y radius amp amp direction.y gt 0) direction.y direction.y Ball go in any goal if (transform.position.x lt GameManager.bottomLeft.x radius amp amp direction.x lt 0) GameManager.instance.addScorePlayer("p2") StartCoroutine( Reset() ) if (transform.position.x gt GameManager.topRight.x radius amp amp direction.x gt 0) GameManager.instance.addScorePlayer("p1") StartCoroutine( Reset() ) IEnumerator Reset() isMoving 0 transform.position startPosition yield return new WaitForSeconds(2) isMoving 1 This works as expected! The score is incremented, the ball go back to the center, wait for 2 seconds and start to move again. However, now I want to call the Ball Reset() method trough my GameManager (because I want to code some logics inside the GameManager). So here are my modifications Ball script (remove Reset() calls and update Reset() method to public) public class Ball MonoBehaviour ... Update is called once per frame void Update() ... Ball go in any goal if (transform.position.x lt GameManager.bottomLeft.x radius amp amp direction.x lt 0) GameManager.instance.addScorePlayer("p2") if (transform.position.x gt GameManager.topRight.x radius amp amp direction.x gt 0) GameManager.instance.addScorePlayer("p1") public IEnumerator Reset() isMoving 0 transform.position startPosition yield return new WaitForSeconds(2) isMoving 1 GameManager script public class GameManager MonoBehaviour public Ball ball ... void Start() ... Create ball Instantiate (ball) public void addScorePlayer(string player) if (player "p1") score1 1 score1Text.text score1.ToString() else if (player "p2") score2 1 score2Text.text score2.ToString() StartCoroutine( ball.Reset() ) This doesn't work for some reason. The ball don't come back to the center, and the score increment infinitely. I have tried many things and I have figured out that the behaviour is the same as running the Reset() method trough the Ball script without the StartCoroutine. So it seems that the Coroutine don't work properly if called trough the GameManager ? I have also printed some logs into my console in the Ball.Reset() method, and the method is being called, so I don't understand why the ball don't go back to the center. (Link to my public github repository https github.com Sewake Unity2D Pong)


Checkerboard like rendering does not save performance I have a simple scene in Unity with a camera and a quad facing the camera filling the whole viewrect. The quad has a material with the following shader Shader quot Skip quot SubShader Pass CGPROGRAM pragma vertex vert pragma fragment frag include quot UnityCG.cginc quot struct appdata float4 vertex POSITION struct v2f float4 vertex SV POSITION float4 screenPos TEXCOORD0 v2f vert (appdata v) v2f o o.vertex UnityObjectToClipPos(v.vertex) o.screenPos ComputeScreenPos(o.vertex) return o fixed4 frag(v2f i) SV Target int2 screenUV (i.screenPos.xy i.screenPos.w) ScreenParams bool skip (screenUV.x screenUV.y) 2 0 if (skip) return fixed4(1,0,0,1) else fixed4 clr fixed4(0,0,1,1) for (int i 0 i lt 10000 i ) clr i 2 0.5 return clr ENDCG The shader returns simple color for an even pixel and runs an expensive computation for an odd pixel. There is no performance difference between running the expensive operation on all the pixels and running it on just half the pixels. bool skip (screenUV.x screenUV.y) 2 0 13fps bool skip true 2300fps bool skip false 13fps Why is there no improvement in performance?


Stop Mesh render on intersect I am generating camera frustum mesh through code, it is working fine. Now I am searching a solution (shader based or else) to restrict the camera frustum mesh if it intersect with any object. Like you can see in the image my frustum is passing through the plane which is not correct. How can I control it, I search and apply different kind of shader but nothing worked.


Unity resizing particles dont mantain collisions properly I am trying to make particles for blood on death. This is what I got so far Which looks fine and all. But now I also wanted to make the blood particles turn smaller over their lifetime, so I checked "Size over lifetime" and this is what happens now See the problem? As they shrink, they seem to float a little, giving some space between the floor they are laying on. This behaviour is not really desired. How could I solve this?


A python script controlling a Unity game I wish to build a simple game in Unity such that the objects in the game can be controlled via a Python script (or a code in any other programming language). Is this possible? If yes then how? If no then are there any other alternatives to achieve similar results? To make it more clear, say that I have 10 objects in my current scene. What I wish to do is to address each object individually via Python. One way of doing this is setting up keyboard bindings to select a particular object and then using keyboard and mouse events to control this object. But, is there a more cleaner (a native) way of doing the same?


Unity3D mesh showing only black triangles My mesh in the unity editor won't show the correct texture. Instead I get to see loads of black triangles. Anyone know what's wrong? thanks )


Unity, choosing a mobile shader I have multiple 3d objects in my scenes. These are without any graphics and have different colors and some lights. I was building all of the scenes with a standard shader and now, when running on an Android device, FPS drops to 30 50. I've already fixed the particles with Mobile shaders, these work well now but I have some problems with normal cubes, spheres etc. As I read, Standard shader death on mobiles and here comes my question. I read that I should use one of these from Mobiles tab or Legacy ones. Which one is better in my case? Which one should I use when I only want to adjust the color of the object ( support a lightmap ) ?


Is a final yield return 0 required in corutines? I have the following code run in a coroutine. I would like to know if the last yield return 0 is necessary and why. Thank you! private IEnumerator pChangeFoV() float duration 0.7f float zValue 5f for (float t 0f t lt duration t Time.deltaTime) float fNew Mathf.Lerp( camera.fieldOfView, zValue, t duration) camera.fieldOfView fNew yield return 0 camera.fieldOfView zValue make sure we're really where we want to be now do everything that should be done after we're done with this coroutine pEnableSomeScripts() yield return 0 is this final yield return 0 required???


Unity wall jump issue I've got a very annoying problem that I have been stuck on for a few days and I can't figure it out. It is for a wall jump. I basically want my wall jump to have a bit of force away from to wall to make it look and feel better than just jumping up straight. The problem is, when i add a force on the x axis, it does not register when i am also holding the arrow towards the wall. If I am not holding down the walking button, then press jump...then the x force works. I have a feeling that the horizontal axis force is competing with the opposite force that i want to add to the player when he hits the jump button... Walking code private void ApplyMovement() if (isGrounded) myRigidbody.velocity new Vector2(movementSpeed movementInputDirection, myRigidbody.velocity.y) else if (!isGrounded amp amp !isWallSliding amp amp movementInputDirection ! 0) Vector2 forceToAdd new Vector2(movementForceInAir movementInputDirection, 0) myRigidbody.AddForce(forceToAdd) if (Mathf.Abs(myRigidbody.velocity.x) gt movementSpeed) myRigidbody.velocity new Vector2(movementSpeed movementInputDirection, myRigidbody.velocity.y) else if (!isGrounded amp amp !isWallSliding amp amp movementInputDirection 0) myRigidbody.velocity new Vector2(myRigidbody.velocity.x airDragMultiplier, myRigidbody.velocity.y) if (isWallSliding) if (myRigidbody.velocity.y lt wallSlideSpeed) myRigidbody.velocity new Vector2(myRigidbody.velocity.x, wallSlideSpeed) Jump code private void Jump() if (canJump amp amp !isWallSliding) myRigidbody.velocity new Vector2(myRigidbody.velocity.x, jumpForce) numberOfJumpsLeft else if ((isWallSliding isTouchingWall) amp amp !isGrounded amp amp canJump) isWallSliding false numberOfJumpsLeft Vector2 forceToAdd new Vector2(wallPushForce facingDirection, wallJumpForce wallJumpDirection.y) myRigidbody.AddForce(forceToAdd, ForceMode2D.Impulse) Where I call The code void Update() CheckInput() private void FixedUpdate() ApplyMovement() private void CheckInput() movementInputDirection CrossPlatformInputManager.GetAxisRaw("Horizontal") if (Input.GetButtonDown("Jump")) Jump() if (Input.GetButtonUp("Jump")) myRigidbody.velocity new Vector2(myRigidbody.velocity.x, myRigidbody.velocity.y variableJumpHeightMultiplier) Any help would be much appreciated. Thanks in advance


how to use unity3d webgl content in a asp.net mvc view? I asked this question in stackoverflow but no answers so I think it would fit here better. I have a unity webgl project and an asp.net mvc project. I need to show the webgl content in a view. The first thing that came to my mind was to simply copy the content of the index.html that unity gave me and paste it in a .cshtml file and change the addresses. But when I do this the incorrect header error pops up. Am I doing some thing wrong or everything wrong. should I change my method entirely? I also added these file extensions to the web.config lt staticContent gt lt ! Unity 5.x gt lt remove fileExtension ".mem" gt lt mimeMap fileExtension ".mem" mimeType "application octet stream" gt lt remove fileExtension ".data" gt lt mimeMap fileExtension ".data" mimeType "application octet stream" gt lt remove fileExtension ".memgz" gt lt mimeMap fileExtension ".memgz" mimeType "application octet stream" gt lt remove fileExtension ".datagz" gt lt mimeMap fileExtension ".datagz" mimeType "application octet stream" gt lt remove fileExtension ".unity3dgz" gt lt mimeMap fileExtension ".unity3dgz" mimeType "application octet stream" gt lt remove fileExtension ".jsgz" gt lt mimeMap fileExtension ".jsgz" mimeType "application x javascript charset UTF 8" gt lt staticContent gt


Parent Child position mathematics What is the math theory when a child object moves with the parent transform? I am doing an angle indicator which shows a field of view, which works fantastic when the angle is static. But I cannot get the field of view indicators to play nice with the angle changing. Everytime I change the angle, the indicators are reset to default positions and then the direction indicator and FoV indicators are out of sync. There is of course a ghetto way of resetting the whole thing when changing the angle, but I'd prefer not to do it that way. The red circles are the points which are used to draw the FoV lines and they are childed to the white sphere. If the angle is not modified after start they follow the white sphere nicely and show the FoV correctly. Here is how it looks after trying the dynamic angle changing. The FoV lines should be pointing to the right and the white sphere should be in the middle. Currently I am changing the red circles' position based on the angle given(transform is the green square in the middle.) leftAngle.transform.position transform.position new Vector3(Mathf.Cos(firstLineRendererAngle Mathf.Deg2Rad), 0, Mathf.Sin(firstLineRendererAngle Mathf.Deg2Rad)) 10 rightAngle.transform.position transform.position new Vector3(Mathf.Cos(secondLineRendererAngle Mathf.Deg2Rad), 0, Mathf.Sin(secondLineRendererAngle Mathf.Deg2Rad)) 10 How do I add the position of the FoV direction sphere to emulate parent child relationship with the objects?


Unity, Replace or modify camera with own script I am making an RTS game which has a slowdown when many units are on screen at once. I have a plan to write my own camera script to speed this up. Since I have an efficient way to find where units are without the raycast, I want to write scripts to replace the camera and check raycasts against only the few objects that my scripts will identify as in the correct area for that raycast? Alternatively is is possible to have the camera ignore certain entities on one part of the screen, and then a different set on another part of the screen? Edit I am very grateful for people helping in anyway, but I wanted to know if this Could be done even if in my case it shouldn't be.


Making an object orbit using c script for Unity Vuforia I have written a simple c script for Unity Vuforia. I want to create a simple sample project where an object like a sphere is revolving (orbiting) origin (0,0,0) above image target. The code I have written is here using System.Collections using System.Collections.Generic using UnityEngine using Vuforia public class Orbit MonoBehaviour float angles float radiuss float angleSpeed Start is called before the first frame update void Start() angles 0 radiuss 0.2f angleSpeed 1 Update is called once per frame void Update() angles Time.deltaTime angleSpeed float x radiuss Mathf.Cos(Mathf.Deg2Rad angles) float z radiuss Mathf.Sin(Mathf.Deg2Rad angles) float y 0 transform.position new Vector3(x, y, z) It works perfectly fine if I am not using it with Vuforia, but when I attach this script as component to an object in Vuforia, it does not work and acts weird. These are the configurations and hierarchy Please help me out, I tried a lot of things.


How to reset the world in an infinite runner game to prevent an overflowing float? Im following Mike Geig's 2D infinite runner tutorial. However, I'm seeing a potential problem of overflowing the float How can I reset all objects and camera back again to the origin? The approach I'm seeking is similar to the advice made by David Debnar on this question http answers.unity3d.com questions 491411 best practices for endless runner type games.html Definitely player. It's a lot easier, but to prevent float overflow, you should pop everything back a few thousand units every few thousand units


Touch sides of tablet, moves that direction I am making a game where the player flies a balloon through a cavelike structure. I am having trouble making him fly correctly when I try it out on my android tablet, seeing as it requires different input to move. How can I make the player move towards the touched side? By creating a ray? through touched objects? )


How can I use shaders in Unity to write a scientific computing program? I want to write a GPU shallow water code on Unity3D. For sure, performance matters a lot. I've done this before using DirectX and C . But for a couple of reasons I want to redo it in Unity3D. I have some hands on experiences with Unity3D, but I have no idea how I can write GPGPU codes, like what I did in DirectX. In DirectX I am using textures as my data structure for the properties of water cells (height, x velocity, y velocity, etc.) and HLSL shaders as my parallel computational functions (kernels). Furthermore, I prefer my code to be near cross platform. Is it possible to do something similar in Unity3D using OpenGL? I am an engineer, and not a game developer, so please keep it simple ...


C JSONs not formatting array of objects stored inside another object. I know the title is a bit confusing because I don't really know how to phrase this. This is what I have System.Serializable public class Sector public string name public Vector3 sectorPosition public float sectorRadius public buildingComponent components System.Serializable public class buildingComponent ScriptableObject public string componentType public Vector3 componentPosition public Vector3 compenentRotation When I try converting this into a json string like this Sector ssector new Sector() ssector.name "sTom" ssector.sectorPosition Vector3.up ssector.sectorRadius 2 ssector.components new buildingComponent 3 print("component length " ssector.components.Length) ssector.components 1 new buildingComponent() ssector.components 1 .componentPosition new Vector3 (1, 2, 3) string sdata JsonUtility.ToJson(ssector) I end up with the following "name" "sTom","sectorPosition" "x" 0.0,"y" 1.0,"z" 0.0 ,"sectorRadius" 2.0,"components" "instanceID" 0 , "instanceID" 341752 , "instanceID" 0 The components array is not actually being formatted, it's only saved with an instanceId or whatever this does. Is there any solution to this or will I have to go with an alternative formatting. I just want to save this data on a server but I only get one string to do so, so I have to format everything into one string. Thanks in advance!


Smooth Scene transitions with SceneManager and additive scene in Unity I'm trying to work with the new SceneManager class with Unity, I'd like to have smooth transitions between scenes. Currently I suppose that the only way to do those transitions is to manually implement them on the scene objects leveraging on the fact that scenes can be loaded additively. In pseudo code I image something like for gameObject in previousSceneGameObjects gameObject.animateSceneExit() endFor for gameObject in nextSceneGameObjects gameObject.animateSceneEnter() endFor I feel that there is something I'm missing P which is the best approach that you'd suggest? Is it my approach valid?


add random force and direction to rigidbodies every x seconds i need to add a windForce to multiple rigidbodies, with random direction and random force every x lapse of time. I'm using InvokeRepeating to update the windDirection so that the rigidbodies can be pushed in a different direction every x seconds. Here's the code void windRotate() windDirection.y Random.Range(0, 360) transform.Rotate(windDirection smooth) if (objectsInWind.Count gt 0) foreach (Rigidbody rigid in objectsInWind) rigid.AddForce(windDirection 10) This way the rigidbodies don't receive any force. I guess the system does not recognize the Vector3 Update of windDirection, so I need to recalculate it, bit I was not able. On the other hand if I use this rigid.AddForce(Vector3.Up 10) the rigidbodies moves but in one direction only, and it's not updated on the next windDirection change. I tried playing with the various Vector3 values (up, right etc..) and different force methods (AddRelativeForce) but nothing changed. By using Debug.Log(windDirection) i know that windDirection is updating correctly ever 3 seconds, so it should also be updated in my methods when i apply the force, but id does not work. Any suggestion? Thanks


Unity applying forces using animation I'm trying to make a croquet mallet swing to hit the ball using an animation that rotates the mallet mesh. The mesh appears correctly positioned to hit the ball in the center but the ball doesn't go straight. Using a script with rigidBody.AddForce works fine. I do have Animate Physics selected on the animator and have explored many other options. Is there a way to debug the physics in this situation? Am I going about it the wrong way to use an animation to apply a force? This is what it looks like now


Unity CaptureScreenshot captures and editor as well I'm trying to create some screenshots but ScreenCapture.CaptureScreenshot actually captures the entire editor and not just the Game view. I'm using this few lines of code here public class ScreenShotTaker MonoBehaviour public KeyCode takeScreenshotKey KeyCode.S public int screenshotCount 0 private void Update() if (Input.GetKeyDown(takeScreenshotKey)) ScreenCapture.CaptureScreenshot("Screenshots " " " screenshotCount " " Screen.width "X" Screen.height "" ".png") Debug.Log("Screenshot taken.") What could be the issue?


Programmatically placing objects along Polygon Collider 2D In my game, I have Tiled "rooms" that were imported with Tiled2Unity. All of these rooms have walls that are defined by Polygon Collider 2D objects. In the event of a cave or dungeon, I'd like to implement torches. Currently, I literally randomly place torches in each room, which is pretty good for lighting, but looks ridiculous. After the room is added, rather than randomly place torches anywhere, I'd like to have them placed along the inside of the collider. Is there a good way to make this happen? Edit One of my first attempts was to get a list of all of the points in all colliders in a given room after it's instantiation. I was starting with something like this. GameObject roomGO (GameObject)Instantiate( room.gameObject, new Vector3 ( 6.5f, 6.5f, 0f), Quaternion.identity) List lt PolygonCollider2D gt polyList roomGO.GetComponentsInChildren lt PolygonCollider2D gt ().ToList() However, this only gets the points from the first collider, whereas I need the points for all colliders in the room GameObject. Additionally, I'm not sure how those points are stored in such a way that I could create a List or Array of lines, then evaluate those lines to determine which are inside the room (as opposed to along the outside, so nothing in the set (x,0),(x, 13),(0,y),(13,y) . Once I had a list of lines that weren't part of that set, I could choose a point on the line and drop in a torch. Edit2 images Edit 3 Thank to SP., I've used some of his code as shown here if ( torches) Transform roomGOLayer roomGO.transform int numTorch rndObjects.Next(2,4) List lt PolygonCollider2D gt polyList roomGO.GetComponentsInChildren lt PolygonCollider2D gt ().ToList() foreach (PolygonCollider2D polCol in polyList) foreach (Vector2 point in polCol.GetPath(0)) Debug.Log(point.x " " point.y) you will be using these values GameObject to Instantiate( torch, new Vector2(point.x, point.y), Quaternion.identity) as GameObject to.transform.parent roomGOLayer to.transform.position to.transform.parent.transform.position new Vector3 (point.x, point.y, 0f) The biggest problem I'm having up front is that polyList is only getting the first collider definition. I think if I could solve that, I'd be in good shape.


How Do I Play An AnimationClip I want to play an animation but it seems that in The new version of unity it is harder. I have an AnimationClip but I don't know how to play it. I have been looking at this for 2 hrs now and i cant get it to work. using UnityEngine using System.Collections public class FPSCamera MonoBehaviour public float lookSensitivity 5 private float xRotation private float yRotation private float currentRotationX private Animation walking void Start() DONT KNOW HOW TO FIND AND START WALKING ANIMATION void Update() yRotation Input.GetAxis("Mouse X") lookSensitivity xRotation Input.GetAxis("Mouse Y") lookSensitivity xRotation Mathf.Clamp(xRotation, 90, 90) transform.rotation Quaternion.Euler(xRotation, yRotation, 0)


Unity 3D Rotate towards object with random offsets Title is a little confusing, but let me explain I want to make the enemies look at the player, and shoot at him, with random precision, meaning that one time the enemy will shoot a little bit to the left of the player, next time a little bit to the right of him, and sometimes exactly at him. Currently I have this scene The turret rotates, and when the green direction spots the player, it shoots a bullet facing the player (the green arrow). Now I need where the rotation is passed for the Instantiate, to have some random precision, and I don't know how to do it. Here's what I have so far Vector3 pos new Vector3(firingPoint.transform.position.x, firingPoint.transform.position.y, firingPoint.transform.position.z) float playerX playerObject.transform.position.x float playerY playerObject.transform.position.y float playerZ playerObject.transform.position.z float randomX Random.Range(playerX 1f, playerX 1f) float randomY Random.Range(playerY 1f, playerY 1f) float randomZ Random.Range(playerZ 1f, playerZ 1f) Quaternion aimPrecision Quaternion.LookRotation(new Vector3(randomX, randomY , randomZ)) Instantiate(bulletPrefab, pos, aimPrecision) How can I do this? EDIT Right now, the enemy shoots like this but never towards me, or backwards


How can I get the parents and childs from the hierarchy in the same order it is in the hierarchy the structure of the hierarchy? The line var gameObjects GameObject.FindObjectsOfType lt GameObject gt () Is getting all the parents and children but not in the order it is in the hierarchy. I tried to use the gos List and to add first the childs then the parents to create a List with all parents and it's childs but it's getting messed. I want to get the structure of the Hierarchy. var gos new List lt GameObject gt () var gameObjects GameObject.FindObjectsOfType lt GameObject gt () for (int i 0 i lt gameObjects.Length i ) if (gameObjects i .transform.childCount gt 0) get children GameObject children new GameObject gameObjects i .transform.childCount for (int z 0 z lt children.Length z) children z gameObjects i .transform.GetChild(i).gameObject gos.Add(children z .gameObject) else gos.Add(gameObjects i )


View Matrix from Camera in Unity Script I am looking to get a Camera component's "view" matrix in a script. I see that I can get the projection matrix using Camera.projectionMatrix, but I don't see a Camera.viewMatrix property... I want these matrices in a script for a 3D graphics refresher tutorial that will visualize a camera's view and projection transforms in the form of game objects (representing vertices) that can be moved around the scene.


My trigger does not detect my player My trigger does not detect my player. My Trigger.cs file using UnityEngine public class Trigger MonoBehaviour public Camera camera1 public Camera camera2 public GameObject panel void OnTriggerEnter(Collider other) camera1.enabled false camera2.enabled true panel.SetActive(true) Debug.Log ( quot Entered quot ) void OnTriggerExit(Collider other) camera2.enabled false camera1.enabled true panel.SetActive(false) private void Update() if(Input.GetKeyDown(KeyCode.DownArrow) Input.GetKeyDown(KeyCode.S)) panel.SetActive(false) Where I can start troubleshooting te issue? Object on which the trigger script is sitting on. The solution I created two colliders, and assigned one as a collider, the other (bigger) is a trigger. I also had problems with the small triggers in the scene. The triggers were to small to be detected by my main player, althought they detected my quot sphere quot player object


New Input System Differs Between Editor and Runtime? I'm sure the problem is me. Here is a simple look script (from a tutorial, actually). I'm getting inconsistent results between editor and runtime. I'm guessing its a framerate thing. Code using UnityEngine using Mirror using Cinemachine public class PlayerCameraController NetworkBehaviour Header( quot Camera quot ) SerializeField private Vector2 maxFollowOffset new Vector2( 1f, 6f) SerializeField private Vector2 cameraVelocity new Vector2(4f, 0.25f) SerializeField private Transform playerTransform null SerializeField private CinemachineVirtualCamera virtualCamera null private Controls controls private Controls Controls get if (controls ! null) return controls return controls new Controls() private CinemachineTransposer transposer public override void OnStartAuthority() transposer virtualCamera.GetCinemachineComponent lt CinemachineTransposer gt () virtualCamera.gameObject.SetActive(true) Controls.Player.Look.performed ctx gt Look(ctx.ReadValue lt Vector2 gt ()) enabled true ClientCallback private void OnEnable() gt Controls.Enable() ClientCallback private void OnDisable() gt Controls.Disable() private void Look(Vector2 lookAxis) float deltaTime Time.deltaTime float followOffset Mathf.Clamp( transposer.m FollowOffset.y (lookAxis.y cameraVelocity.y deltaTime), maxFollowOffset.x, maxFollowOffset.y) transposer.m FollowOffset.y followOffset playerTransform.Rotate(0f, lookAxis.x cameraVelocity.x deltaTime, 0f) The code seems right. Watching the values of Vector2 lookAxis reveals that the numbers are slightly different coming into the function based on environment. Is there something wrong with this code that would give different results between editor and runtime?


How do I correctly unload an additive Scene in WebGL? I am creating an app in WebGL. I have a loading scene that I am loading additively SceneManager.LoadScene("Loading Scene", LoadSceneMode.Additive) It loads correctly. Then after I finish loading everything, I remove the additive loading scene SceneManager.UnloadScene(SceneNames.Loading) In the Editor, it unloads perfectly. However, in browser, via WebGL, it gets called, but does not unload. If I throw it in a coroutine and wait for 3 seconds, it does unload. I have a two part question Why does waiting for 3 seconds before unloading fix the problem? What is the correct way to unload this scene so that there is not an arbitrary "Wait for seconds" in there?


How can I attract repel the mouse cursor from particular UI controls? This question came from some of my students. I wanted to share it here so others can find amp improve on the solutions we've found so far. In particular, my answer below doesn't behave as well as I'd like in windowed editor mode UI buttons no longer respond to hovering the cursor. I welcome alternative answers that solve this more completely. We're making a visual novel game using the Fungus asset for Unity. We want to add a twist where some dialogue options are easier or harder to press, because they attract or repulse your mouse cursor. Unfortunately, we haven't been able to identify a cross platform way to manipulate the mouse's position, nor a way to create a "Fake" mouse cursor image that can still interact with Fungus's UI buttons. How can we pull this off?


Card flip animation in a prefab. How to flip with local position? I'm making a simple card game, with some cards laying on the table. I want to flip the card when it's clicked, so I thought I'd use an animation to do it (lift card up in the air, rotate it and lower it back down). It works as I want with one card, but when I save it as a prefab and instantiate another one next to it, the card (obviously) moves to the same position as the prefab (as the animation stores global position I guess). Is there any way to make animations in local space, or is there any other way I should do the flip?


Why is the Position Handle placed at certain distance away from vector3 unit in Unity? I have a vector3 value that I am setting in inspector and I am drawing a ray using OnDrawGizoms to draw that vector line. However, the position handle I made using Handles API to set the vector3 value is placed certain distance away from the vector unit. It's not placed exactly at the end point of the vector line that is drawn and I am not sure why. My goal is to just make a handle to position a vector3 value. EDIT For some reason, the handle is positioned correctly for y position alone but not for x and z positions. Here is my code In this script, it is the localTargetPosition vector3 value that I want to make my handle for. public class MovePlatform MonoBehaviour public Vector3 localTargetPosition new Vector3(5, 0, 0) public Vector3 m initialPosition get return initialPosition set initialPosition value private Vector3 initialPosition, targetPosition, targetPosDebug public float speed 3 public bool loop void Start() initialPosition transform.position SetTargetPosition(localTargetPosition) void Update() transform.position Vector3.MoveTowards(transform.position, targetPosition, speed Time.deltaTime) if (transform.position targetPosition) if (loop) SwitchDirection() public void SwitchDirection() if (transform.position initialPosition) SetTargetPosition(localTargetPosition) else targetPosition initialPosition private void SetTargetPosition(Vector3 localPosition) targetPosition initialPosition transform.TransformDirection(localPosition) targetPosDebug targetPosition void OnDrawGizmos() if (Application.isPlaying) Debug.DrawLine(initialPosition, targetPosDebug, Color.red) else Debug.DrawRay(transform.position, transform.TransformDirection(localTargetPosition), Color.red) This is the script used for making handle CustomEditor(typeof(MovePlatform)), CanEditMultipleObjects public class MovePlatformEditor Editor protected virtual void OnSceneGUI() MovePlatform movePlatform (MovePlatform)target Vector3 initialPosition movePlatform.transform.TransformPoint(movePlatform.m initialPosition) Vector3 targetPosition movePlatform.transform.TransformPoint(movePlatform.localTargetPosition) EditorGUI.BeginChangeCheck() Handles.Label(targetPosition, "Target", "button") targetPosition Handles.PositionHandle(targetPosition, movePlatform.transform.rotation) if (EditorGUI.EndChangeCheck()) Undo.RecordObject(movePlatform, "Move Handles") movePlatform.localTargetPosition movePlatform.transform.InverseTransformPoint(targetPosition) Handles.color Color.yellow Handles.DrawLine(initialPosition, targetPosition)


I already have a GameManager script, but need to have a 2nd one I'm making a Unity game, and I want to use the Unity Distribution Portal. My problem is that you have to make a script named GameManager for this, but I already have another script called GameManager, so every time I try to rename the first GameManager script, the game stops working. I don't want to rewrite every script I've used GameManager variables in. So the way I've been trying to rename this is by right clicking on the GameManager.cs file in the Unity project window and renaming it there, then typing a 2 in the name inside Visual Studio. If I call the script for UDP for example something like GameManager2, UDP doesn't seem to understand that this is the script it needs for Sandbox Testing. Can anyone help me with this? Here is the UDP script I want to add (which is currently called GameManager2, but needs to be called GameManager) using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UDP public class InitListener MonoBehaviour, IInitListener public IInitListener listener public void Start() StoreService.Initialize(listener) public void OnInitialized(UserInfo userInfo) Debug.Log( quot Initialization succeeded quot ) public void OnInitializeFailed(string message) Debug.Log( quot Initialization failed quot message)


Unity3D Tag as a public variable in editor How do you incorporate Tag strings into a scripts editor found in the inspector? What it is I'm babbling about When you create a public GameObject fooObject in a script, it shows up as a box that can have Game Objects dragged onto in its editor. It also has a small clickable dot that shows every Game Object that could be selected. Now, say I have a public string fooString that would specifically be used for referencing the Tag strings of Game Objects (such as if (fooObject.tag fooTag) or another use). Is there a way to define that string so that in the script's editor it strictly allows tag names to be used with it? I'm assuming with a similar clickable dot or a drop down menu of every selectable tag. Although I could just manually type my string, a solution like the one above would have big object orientated advantages. For example, if I was to change the name of this tag, it would change the string variable accordingly, as if the variable was a reference to such tag. Note to the moderators I looked for an answer to this question for nearly 2 hours now to no avail. I understand that I may be missing some specific wrong word choice, in which case this question easily could have already been answered here. If this is closed as a duplicate, then, a quick comment explaining my mistake would be greatly appreciated.


How to implement the seek steering behavior in Unity3d? Following this tutorial Understanding Steering Behaviors Seek, I tried to add seek and steering behavior to my Unity prototype but it's not working this is my script. The cube does not steer it just follows the target. public GameObject target float maxForce 15 float maxSpeed 30 float maxVelocity 200 float mass 15 Vector3 velocity void Start() velocity Vector3.zero void Update() transform.LookAt(target.transform) var desiredVelocity target.transform.position transform.position desiredVelocity desiredVelocity.normalized maxVelocity Time.deltaTime var steering desiredVelocity velocity steering Vector3.ClampMagnitude(steering, maxForce) steering steering mass velocity Vector3.ClampMagnitude(velocity steering, maxSpeed) transform.position velocity Time.deltaTime What could be the problem??


Unity solution not compatible with Visual Studio Since updating to the most recent version of Unity 5.4.0f3 Personal Edition, whenever I double click on a script, it launches Visual Studio, but I get an error saying that this version of Visual Studio (Community Studio 2015) is unable to open my project. Please see the screenshots attached for the actual error message. Monodevelop also launches with it's own error message. I am still able to open the individual script manually using the menu in VS but it's a little frustrating that it doesn't open automatically, and more annoying is that the intellisense code completion features no longer work. Anyone know how to fix this? I have Visual Studio Tools for Unity installed and have tried running the installer to repair this tool also.


Multiple updates for Unity animation per one method call I'm trying to do some simulation where I move objects procedurally in a loop within one method call. So instead of using Update(), method I do for example void Simulate(float deltaTime) real logic look a lot different, this is just an example for(int i 0 i lt 1000 i) transform.position direction speed deltaTime ..... The reason I'm doing this is because I want consistent 'framerate' by passing that deltaTime parameter Which is for example 0.01f And each step of that loop I'm taking snapshots on multiple cameras with calling Render() method on them before taking a picture. The movement works fine and I see it on snapshots, but some objects has an animation which should also be updated procedurally. I've tried to do animator.speed 0 and then in the same loop, to test it for (int i 1 i lt 1000 i) ... animator.Play("WalkFWD", 0, i 1000f) for example But animation does not change over that loop. It only works with that Play method when I either make this Simulation() method a coroutine and pass one frame (yield return null), or if I use in Update(). So, my question is it possible to procedurally update redraw animation after normalized time of that animation is set. (without waiting for another frame)


Unity3D GameObject as a static function Newbie Unity3D C developer here. I've tried learning Unity3D during my May June college vacation and came across a problem Code 1 CameraObj returnVoid void Start () returnVoid GameObject.Find ("Main Camera").GetComponent lt CameraObj gt () returnVoid.ComponentType () Code 2 GameObject returnDirectLight void Start () returnDirectLight GameObject.Find ("Directional Light") Debug.Log (returnDirectLight.GetComponent lt DRLight gt ().directionString) CameraObj is my custom component. As far as I know, GetComponent is actually a public method. I understand the logic behind Code 2. What I fail to understand is Code 1. How does GetComponent become a static function here? Does it become abstract in my CameraObj class?


Initializing Consumable product to an amount on first use I am using Unity's In App Purchase plugin to implement an in game store. In my game every player has fuel. I'd like to use the plugin in order to keep track of the amount of fuel the player has so that just erasing the cache on the phone or something wouldn't effect the regeneration time of fuel (like it would if I use PlayerPrefs). Right now i have it setup so the fuel amount is saved in PlayerPrefs and when fuel is used, a timestamp is saved in PlayerPrefs. Then it checks every once in a while if enough time has passed since they used it in order to regenerate it. Instead of doingoing it this way I want to initialize the fuel amount in Unity's in app purchase plugin so that Googles servers will have the amount and then I can use the same idea for regeneration that I already have but nowe the amount will be more safe. Is there a way to initialize the amount of a consumable product a player has on their first launch of a game?


Adding some recoil to the Camera so that the crosshair is pushing to the sky (FPS game) I just want to add some recoil to the camera, but I can't find a working script. It's an fps, so I take my mouse axis to rotate the camera. And now I want a pushback to the top, so that the camera looks into the sky after shooting a whole clip. It should be pretty easy, just add some amount to the axis, but it isn't working for me. I've got something like this from another post, but it just does nothing for me... I got a feeling that my axis is locked in some way, I'm using the "MouseLook" from the standart assets. transform.Rotate( recoil Time.deltaTime, 0, 0 ) Update This Script is working partially, but I think I reactivate the MouseLook too fast after the Rotate, so that the Mouse just jumps back to the starting position. mouseLook.enabled false transform.Rotate ( 5, 0, 0) mouseLook.enabled true


Unity orthographic camera and shadow When using an Orthographic Camera, the shadows appear to be of poor quality. How can I display smooth shadows?


How do you freeze your cursor in Unity? In a typical MMORPG, when I hold down the right click button and drag, the cursor disappears and stays in the same position. How does one do that?


Unity change sprites to something that uses less memory I have a game that uses only silhuette textures, but they take up waay too much memory (360 MB overall and this is a mobile game) so I plan to avoid using sprites with alpha punchouts (1 bit alphas). From what I gathered, I could use an asset from Unity store like SVG importer, but I have no financial means to do so. So I plan to make low poly 3D (in fact 2D) planes that somewhat cover my textures. Now, I have a lot of sprites already. I saw that Unity can create a 2D mesh collider around my sprites. Can I use that to create my meshes and then apply a single colour unlit material to them? How would it roughly effect memory usage as opposed to my generally 500x600 sprites? If I'm going in the wrong direction, is there a way to create Shapes, just like in Photoshop or GIMP?


How to apply force towards direction using mouse drag and or touch input direction and input speed? I've to object. I can move object 1 (my Player) using mouse (or Touch for smartphone version). I want apply a force to object 2 when object 1 hit it. Force direction must be mouse vector direction or touch vector direction. For Mouse input i'm using event OnMouseDown and OnMouseDrag to determine mouse original position. But I think this is not the best approach. Behaviour is not what i am expecting void OnMouseDown() mouseDragStartPosition Input.mousePosition translate the cubes position from the world to Screen Point screenSpace Camera.main.WorldToScreenPoint(transform.position) calculate any difference between the cubes world position and the mouses Screen position converted to a world point offset transform.position Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z)) void OnMouseDrag() keep track of the mouse position var curScreenSpace new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z) convert the screen mouse position to world point and adjust with offset var curPosition Camera.main.ScreenToWorldPoint(curScreenSpace) offset transform.position new Vector3(curPosition.x, ClampY, curPosition.z) void OnCollisionEnter(Collision collision) Debug.Log("OnCollisionEnter") if (collision.collider.tag "Disc") ApplyForce() void ApplyForce() Vector3 direction mouseDragStartPosition Input.mousePosition direction new Vector3(direction.x, ClampY, direction.z) ClampY used to not allow Y DiscRb.AddForce(direction 1, ForceMode.Impulse)


How do I find the face of an object? I'm working on a build mode but the thing of it is the player is able to deform meshes. Part of my build system includes having "snap" points thus I need to be able to find the face and recenter the snap point on deformed meshes. So, how do I find the face of an object and the center of said face? Also how would I find the center? To clarify The end goal is to keep the snap point positioned properly with the face that has been deformed manipulated.


Camera position and angle different when running inside Unity and when running on Android On Windows, running Unity 4.6.1p5, my simple game with only a cube, camera and light looks like this but under Android (Gingerbread on a 5 inch Galaxy Player) the cube appears lower down, slightly different angle and smaller (relative to the screen size). Sorry couldn't get a screenshot with my screenshot app... Any ideas why please?


Unity control time interval when using getAxis() in bolt visual scripting i use bolt visual scripting. I add input.getAxis in Bolt and set the axis name to Vertical so to get response when i press w and s . When running the game and press the w key, the output data (acceleration) will increase from 0 to 1. The problem is the increasing time is too fast or too short. How to make it slower longer? Let say i want it to take 3 seconds to reach 1. Edit This is what i want to achieve (at time 6 10 to 6 25) https youtu.be m8rGyoStfgQ?t 370 And the code is at the same video at time 6 00 . That codes works perfectly fine. And this is all i want to achieve but i want to do it in Bolt (visual scripting) rather than manual scripting. So that line of code at 6 00 on that video Velocity time.Deltatime acceleration That code is controlling how fast or slow the acceleration can go from 0 to 1 when pressing w key. But in Bolt, i use getAxis and by using default sensitivity setting, if i press w it will take less than half a second for the acceleration to go from 0 to 1. I want to make it slower so i can go from 0 to 1 in 3 seconds or 5 seconds. In fact , this the same as setting up the sensitivity in input manager to low value, but i want to keep this setting as default and want to control it inside bolt. Pls check my video here getAxis


Tetris block kinematic rigidbodies pass through one another with Transform.Translate I am trying to build a Tetris 3D game in Unity but I am stuck at getting the different blocks to interact (to detect each other, to sit one on top of the other rather than going through each other). I have set the ground with a box collider and the spwaned blocks come in with rigidbodies and trigger colliders. This works for them to nicely settle on the ground but when I try to sit a block on top of another block they both have kinematic rigidbodies and the collision detection doesn't work and they end up overlapping. The problem is if I remove the rigidbody of the already settled block then it will go through the ground. Any idea how to get 2 spawned objects to detect each other? using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UIElements public class moveBlock MonoBehaviour public static float speed 2 public GameObject blocks public static List lt GameObject gt blocksSpawned new List lt GameObject gt () public static List lt Rigidbody gt blocksRBSpawned new List lt Rigidbody gt () public static bool triggerPlatform true Rigidbody rb void Update() Vector3 input new Vector3(Input.GetAxisRaw( quot Horizontal quot ), 0, Input.GetAxisRaw( quot Vertical quot )) Vector3 direction input.normalized Vector3 velocity direction speed Vector3 moveAmount velocity Time.deltaTime if (triggerPlatform) blocksSpawned.Add((GameObject)Instantiate(blocks Random.Range(0, 7) , new Vector3(0, 6, 0), Quaternion.Euler(Vector3.right))) rb blocksSpawned blocksSpawned.Count 1 .GetComponent lt Rigidbody gt () blocksRBSpawned.Add(rb) triggerPlatform false if (!triggerPlatform) Destroy(blocksRBSpawned blocksRBSpawned.Count 1 ) if (blocksSpawned blocksSpawned.Count 1 ! null) blocksSpawned blocksSpawned.Count 1 .transform.Translate(Vector3.down Time.deltaTime speed, Space.World) blocksSpawned blocksSpawned.Count 1 .transform.Translate(moveAmount) using System.Collections using System.Collections.Generic using UnityEngine public class trigger MonoBehaviour private void OnTriggerEnter(Collider other) moveBlock.triggerPlatform true


LineRenderer not working using Vuforia in Unity So I'm trying to render a line that shows up when camera sees an image target and moves around with it. Very typical AR application. But my line renderer doesn't seem to show at all. Here's the code using UnityEngine using System.Collections public class myLine MonoBehaviour Creates a line renderer that follows a Sin() function and animates it. public Color c1 Color.yellow public Color c2 Color.red public int lengthOfLineRenderer 20 void Start() LineRenderer lineRenderer gameObject.AddComponent lt LineRenderer gt () lineRenderer.material new Material(Shader.Find("Particles Additive")) lineRenderer.widthMultiplier 0.2f lineRenderer.positionCount lengthOfLineRenderer A simple 2 color gradient with a fixed alpha of 1.0f. float alpha 1.0f Gradient gradient new Gradient() gradient.SetKeys( new GradientColorKey new GradientColorKey(c1, 0.0f), new GradientColorKey(c2, 1.0f) , new GradientAlphaKey new GradientAlphaKey(alpha, 0.0f), new GradientAlphaKey(alpha, 1.0f) ) lineRenderer.colorGradient gradient void Update() LineRenderer lineRenderer GetComponent lt LineRenderer gt () var t Time.time for (int i 0 i lt lengthOfLineRenderer i ) lineRenderer.SetPosition(i, new Vector3(i 0.5f, Mathf.Sin(i t), 0.0f)) and here's my set up I also tried attaching the script directly to the ImageTarget and nothing happened.


System.Runtime.Serialization.SerializationException while trying to deserialize List I'm trying to serialize deserialize a class that holds inventory items. The code is attached below. First I call AddOne() void a few times, then I call SaveFile(), then I call LoadFile(). In LoadFile() the following error occurs ex "System.Runtime.Serialization.SerializationException End of Stream encountered before parsing was completed. r n at System.Runtime.Serialization.Formatters.Binary. BinaryParser.Run () 0x00288 in lt 1f0c1ef1ad524c38bbc5536809c46b48 0 r n at System.Runt... Does anybody see my mistake? Thank you for the help! using System using System.Collections using System.Collections.Generic using System.IO using System.Runtime.Serialization.Formatters.Binary using UnityEngine public enum Type undefined 0, Pistol 1, Magnum 2, Grenade 3, BlendGrenade 4, FireGrenade 5, PistolAmmo 6, MagnumAmmo 7, Rifle, RifleAmmo, System.Serializable public class Inventory MonoBehaviour public class InventoryItem public int Amount 0 public int Row 0 public int Col 0 public int Rotation 0 public Type ItemType Type.undefined public List lt InventoryItem gt Items public void Start() Items new List lt InventoryItem gt () public void AddOne() InventoryItem n new InventoryItem() this.Items.Add(n) public void SaveFile() string destination Application.persistentDataPath " save3.dat" if (File.Exists(destination)) File.Delete(destination) using (Stream stream File.Open(destination, FileMode.Create)) BinaryFormatter bin new BinaryFormatter() bin.Serialize(stream, this.Items) public void LoadFile() string destination Application.persistentDataPath " save3.dat" using (Stream stream File.Open(destination, FileMode.Open)) BinaryFormatter bin new BinaryFormatter() try this.Items (List lt InventoryItem gt )bin.Deserialize(stream) catch (Exception ex) Debug.Log(ex.ToString())


Rigidbody2D moves on x axis without adding force I'm currently trying to learn some Physics2D in Unity. Now, I've created a Ball (sprite) and added a RigidBody2D and a CircleCollider2D on it. The RigidBody2D has the following settings Bodytype Dynamic Simulated true Use Auto Mass false Mass 1 Linear Drag 0 Angular Drag 0 Gravity Scale 25 Collision Detection Continous Sleeping Mode Start Awake Interpolate None Now, when I start the scene, the ball drops as expected. However, it's also moving on the x axis by 83 pixels, which I don't want. The movement on the x axis stops once it reached that 83 pixels point. If I freeze the x position in the Rigidbody2D Settings I get the intended behaviour (ball just dropping on y axis), but I feel like that would be a hack instead of fixing the actual problem. What could cause this? I expected the ball to just drop, if I have no drag, a certain mass and gravity enabled.


How can I send different contoller input to the different player avatars? My apologies in advance for the vague question, since I don't understand the problem well enough to ask in finer detail. I want to create a multi player Unity application using the Oculus SDK. Let's say there are two players in the scene, A and B. The problem is this When player A presses a button using his index finger, the hand avatar for player B also displays a moving index finger. In short, hand movements for one player are also observed for the other. Controller inputs are also read without any ability to distinguish whether they originate from player A or B. What are the possible approaches for eliminating this problem, if it is mandatory that I continue using Oculus SDK?


Adding an extra Pass to the Unity Standard Shader I'm experimenting with adding some procedural textures to the unity standard shader. I'd like to add an extra pass (with vert and frag functions), but am unsure about where in the sequence this should go, and how to properly integrate it with the other passes (I want to keep all the standard shader lighting features etc.). To keep things simple, I'd like to start with adding an extra pass which simply paints the mesh one color. Where should this go (in Standard.shader)? Note I've tried adding a pass between passes 1 ("FORWARD"), and 2 ("FORWARD DELTA"). This works, and casts shadows, but does not recieve shadows. Thank you!


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