_id
int64
0
49
text
stringlengths
71
4.19k
0
Unity Cloud Build Corrupted reffernces. Reimport All Assets possible? When references in scenes or prefabs are missing, usually a reimport all fixes all issues. But when those problems occur in a cloud build that get's its data from a git repository the solution seems much harder. The AssetDatabase API allows for a reimport in a prebuild script using UnityEditor using UnityEditor.Build using UnityEditor.Build.Reporting class Reimporter IPreprocessBuildWithReport public int callbackOrder get return 0 public void OnPreprocessBuild(BuildReport report) AssetDatabase.ImportAsset( quot Assets quot , ImportAssetOptions.ImportRecursive) But the UnityEditor libary isn't accessible in a cloud build. Is there a way to fix missing references in a cloud build or trigger a reimport via a pre build script or something similar? PS Local builds after a fresh checkout of the github project do not have this issue, and only Cloud builds suffer from these missing references. Maybe someone knows the root of the issue and how to overcome it, so that none of these hacky solutions would be required.
0
Why aren't the Physics2D.Raycasts reliably colliding with the 2D Box Collider walls? I've got this NPC walking around and I'm trying to create a cone to represent their line of sight, including how it would be blocked by buildings, similar to how Nicky Case has implemented it as described here https ncase.me sight and light My main problem with this, right now, is that it seems like I'm not detecting collisions between my 2D box colliders and Physics2D.Raycast when I would expect to much of the time. The green rays in the image below are NOT colliding (this is fine on the corners, I don't really care, but when the rays are going straight through walls, that's a big problem for me). Red rays are colliding. Why aren't the Physics2D.Raycasts reliably colliding with the 2D Box Collider walls? I believe everything is in the same z plane and has the correct collision matrix in place. ! image of my NPC and raycasts from them at various points along their path List lt UnityEngine.Vector2 gt endPoints new List lt UnityEngine.Vector2 gt () GameObject corners GameObject.FindGameObjectsWithTag("verticies") corners MUST BE WORLD ORIENTED! for(int i 0 i lt corners.Length i ) UnityEngine.Vector2 corner new UnityEngine.Vector2(corners i .transform.position.x, corners i .transform.position.y) RaycastHit2D endPoint Physics2D.Raycast(this.transform.position, corner) if(endPoint.collider ! null) endPoints.Add(endPoint.point) Debug.DrawLine (this.transform.position, endPoint.point, Color.red) else Debug.DrawLine (this.transform.position, corner, Color.green)
0
Player Flying after colliding Unity I have a Player with a capsule collider on him and i have various objects in the scene. Most of the objects have either mesh collider or box collider enabled. When i move my player and the player collides with any object, my player just starts flying into space, literally. Any way to fix this? Thanks in Advance. The code i have on my player is this using UnityEngine using System.Collections public class Controller MonoBehaviour Animator anim Rigidbody rbody float inputH float inputV int Life 20 bool Dead false public float sensitivity 10f void Start () anim GetComponent lt Animator gt () rbody GetComponent lt Rigidbody gt () void Update () if (Dead false) inputH Input.GetAxis ("Horizontal") 50f inputV Input.GetAxis ("Vertical") 20f anim.SetFloat ("inputH", inputH) anim.SetFloat ("inputV", inputV) float moveX inputV Time.deltaTime float moveZ inputH 0.5f Time.deltaTime this.transform.position this.transform.forward moveX this.transform.position this.transform.right moveZ transform.Rotate(0, Input.GetAxis("Mouse X") sensitivity, 0) if (Input.GetKey (KeyCode.Z)) Life if (Life 0) Dead true anim.SetBool("Dead",Dead)
0
Should the level design be in Unity scenes (GameObjects) or in 3D programs (mesh) I am wondering what is the most common and best way to design a game in Unity from the point of view of best practice and performance and the most easily maintainable? Is it really performant to design the level in Unity editor using a GameObject for each part of the level? or should the whole world of the level be designed in any 3D software and then exported to Unity as a on GameObject?
0
XInputDotNet not working when building for UWP in Unity I am working on a game where a controller has to vibrate. I have found the XInputDotNet plugin which worked very well in the editor and a normal windows build, but if I build for UWP (both Xaml and D3D) the controller doesn't vibrate. When building in unity for UWP it also gave me an error saying this Plugin 'XInputInterface.dll' is used from several locations Assets Plugins x86 XInputInterface.dll would be copied to lt PluginPath gt XInputInterface.dll Assets Plugins XInputInterface.dll would be copied to lt PluginPath gt XInputInterface.dll Plugin 'XInputDotNetPure.dll' is used from several locations Assets Plugins x86 XInputDotNetPure.dll would be copied to lt PluginPath gt XInputDotNetPure.dll Assets Plugins x86 64 XInputDotNetPure.dll would be copied to lt PluginPath gt XInputDotNetPure.dll Please fix plugin settings and try again. UnityEditor.Modules.DefaultPluginImporterExtension CheckFileCollisions(String) UnityEditorInternal.PluginsHelper CheckFileCollisions(BuildTarget) (at C buildslave unity build Editor Mono Plugins PluginsHelper.cs 25) UnityEditor.HostView OnGUI() The only way I found to remedy this is by deleting one of the plugin folders. I tried manually copying the ddl's to the build folder, but this didn't help. I tried using the 32 bit dll's and the 64 bit dll's, I tried building for x86 and x64 and I tried all three modes in visual studio(Debug,Master,Release). I found some links to the Windows.Gaming.Input namespace, but I dont't know if it is possible to add this namespace to unity and if so how. Does anybody have an idea how to fix my problem?
0
Setting a texture's "Max Size" while ensuring that its dimensions are still multiples of 4 A version of my game has several large textures with dimensions that are multiples of 4 so that Crunch compression can kick in. A ported version of my game, for platforms that have very limited RAM restrictions, will need us to limit the quot Max Size quot of our textures to 512 or 256, etc. There are some cases in which a Crunch friendly texture, when resized by Unity's quot Max Size quot parameter, will actually end up with dimensions that aren't multiples of 4. 944x800 would end up as 512x434, if we select quot 512 quot , which isn't good for Crunch. The naive solution in my mind is to write a simple script tool that resizes pads all my textures by a couple of pixels in such a way that Unity's resize will end up in a Crunch friendly way. However, I'd rather do that as a last recourse if possible. Is there a more standard way to approach this situation of mine?
0
How to properly copy paste object between folder? I'm new to unity and found some simple task can't be done here. For example in projects tab, i want to copy paste a script from script folder to other folder. I should be able to simply select the script, press ctrl C , go to target folder , press ctrl V to paste but nothing happen. So for now , i have to duplicate it then move it to new folder then rename it. But why can't i do simply copy and paste ?
0
Moving a character according to the animation, rather than code I'm using 3ds Max to export character animations in which my character is moving. I expected this to mean that the character will move in Unity, but it doesn't... For example, if my animation (in 3ds Max) moves my character forward for a second, from 0,0,0 to 1,0,0, in Unity, the character snaps back to 0,0,0 once the animation ends. Is there a way to change the position of the character according to the animation, without something like CharacterController.Move?
0
Display canvas in front of player I have stuck in this simple problem but unable to understand that why i am unable to control it. I have these line of code which is displaying my canvas object in front of my player(camRotationToWatch object name in code) at certain rotation of the player. if (camRotationToWatch.transform.localEulerAngles.x gt navigationCanvasXMinmumLimit amp amp camRotationToWatch.transform.localEulerAngles.x lt navigationCanvasXMaximumLimit) if (!navCanvasHasDisplay) navigationCanvas.SetActive(true) Debug.Log(camRotationToWatch.transform.forward) Vector3 navCanvas camRotationToWatch.transform.position camRotationToWatch.transform.forward navCanvasDisplayDistanceFromCam navCanvas new Vector3(navCanvas.x, 2f, navCanvas.z) navigationCanvas.transform.position new Vector3(navCanvas.x, navCanvas.y, navCanvas.z) navigationCanvas.transform.rotation camRotationToWatch.transform.rotation navCanvasHasDisplay true else navigationCanvas.SetActive(false) if (locationPanel.activeSelf false amp amp infoPanel.activeSelf false) navigationCanvas.SetActive(false) navCanvasHasDisplay false This code is actually work fine when camRotationToWatch object rotate from down to up and Canvas show at correct position but as I try to to rotate camRotationToWatch from up to down it display(active) Canvas at very top position. How can I restrict canvas to show at same position (No matter player rotate from up to down or down to up) but display on front of the player object?
0
Creating custom types that extend certain objects Really new to C scripting. I'm trying to extend a TileBase type object to be able to hold custom methods and variables. I want to create a pathfinding script and I need to store certain information for each tile. Something like this TileBase startPoint tilemap.GetTile (tilemap.WorldToCell (transform.position)) startPoint.customVariable 5 Is there a way to extend TileBase into a new type and create custom methods inside it? How can I achieve this in Unity?
0
Are prefabs the only way to dynamically build a world in Unity? I'm trying to understand how to setup my Unity prefabs and scripts to dynamically spawn a series of "encounters", with each encounter containing several GameObjects. For example, imagine spawning the next several portions of an infinite runner level. One encounter is a ramp, the other encounter is a pit with some coins. This is what I am currently doing A global SceneManager script has a handle to an EncounterFactory prefab. When needed, the SceneManager will begin constructing the game world. The EncounterFactory prefab contains a script that has a method SpawnRandomEncounter. The EncounterFactory also contains handles to several other prefabs for the objects that can be found in an encounter. The SpawnRandomEncounter method uses the prefabs linked to EncounterFactory and builds the expected GameObjects. So when building out a new "encounter", the SceneManager clones the EncounterFactory (which serves as the parent object for the full encounter), and then calls SpawnRandomEncounter to build out the child objects. This seems suboptimal. First, I need to have myriad prefabs for each thing that could be spawned. It also requires a meta prefab to EncounterFactory. That is, a prefab who just allows me to spawn other prefabs. Is there a better way to dynamically build out a game world or level in Unity? Or is it prefabs upon prefabs upon prefabs? For example, I'm aware that I can find an existing object by name. (e.g. find EncounterTemplate5 and clone that.) However, that requires that EncounterTemplate5 exist in the game world. (So it can be cloned.)
0
Help in 2d platform script Now I finished my 2d game but when I set up it in my mobile it becomes like this so I change some scripts in Maincamera but it's still the same How can I change the screen to become horizontal in my mobile like this? what I need that how can I make it fit my mobile screen.
0
Android build has white image over game In unity when I am playing my game it displays fine, but when I build and run it to my nexus 5 there is this white something I don't even know over my game. Any suggestions for fixes?
0
Unity Gyroscope orientation (attitude) "wrong" I am using the Unity reference and example implementation here https docs.unity3d.com ScriptReference Gyroscope.html I struggle to fix an orientation problem. When my phone lies flat on the ground, screen facing upwards, unity thinks I am looking as if I'd take a photo of a landscape. When I actually hold the phone as if I'd take a landscape photo, the screen shows me the sky. Rotating then shows me an arc from sky to my left or right side. What I want is Holding the phone as if I'd take a landscape picture should do the same in Unity. Here is a short video where the phone lies flat and then I pick it up and look left and right on a chair. and this is the codesnipped responsible protected void Update() GyroModifyCamera() void GyroModifyCamera() transform.rotation GyroToUnity(Input.gyro.attitude) The Gyroscope is right handed. Unity is left handed. Make the necessary change to the camera. private static Quaternion GyroToUnity(Quaternion q) return new Quaternion(q.x, q.y, q.z, q.w)
0
Is it possible to make an obj with single triangle I am not good in using blender so i wanted to ask if it is possible to make an object with just one triangle and how would it look like, will the no of triangle increase if you scale it up.
0
Why do we get artifacts on objects rendered using depth node depth render camera on Android? I've encountered and error I can't seem to find online. I get it on all the water shaders I test, and any thing else that I have a depth node depth render script on the camera for. I'll share a bit more information about what we're doing in the game. This artifact changes as we pinch zoom on Android. So I wonder if the Render Depth script doesn't like that we are changing the zoom depth for some reason? Maybe it has something to do with how we are handling out cameras movement in Unity? It is adding more depth information somehow, because the shader is reacting to the artifact. Depending on where the line cuts, the other details will warp to meet it. This problem doesn't show on all phones. Mostly Android, newer versions, but wasn't showing up on an older S5. Some other things I've tried within the shader are different shader models 2.5 amp 3.0. Any suggestions on tests I can do, or ideas on what might be the issue? Here are the nodes I use for the opacity depth Currently we've got the controls on one camera, and the depth script on another. Update, I've found someone talking about a similar sounding problem, but I'm not sure how to do this myself. Thread here https forum.unity.com threads depth texture not working on some devices.319568 "If I set my RenderTexture Depth format to 16 bits instead of 24 bits it's working!" How do I do this? Can I edit my Camera script to do this? The Camera script seems simple, but I'm not sure how to make it render 16bits instead of 24 bits to test this out. Toony Colors Pro Mobile 2 (c) 2014 2018 Jean Moreno using UnityEngine using System.Collections using System.Collections.Generic Makes the Camera render a depth texture. This is needed for some water shaders that use depth based effects such as edge intersection. ExecuteInEditMode, RequireComponent(typeof(Camera)) public class TCP2 CameraDepth MonoBehaviour public bool RenderDepth true void OnEnable() SetCameraDepth() void OnValidate() SetCameraDepth() void SetCameraDepth() var cam this.GetComponent lt Camera gt () if (RenderDepth) cam.depthTextureMode DepthTextureMode.Depth else cam.depthTextureMode amp DepthTextureMode.Depth Thanks!
0
Is there a way to hardcode a JSON file into a Unity build? I'm currently creating an external tool to generate dialogues that are exported as JSON files. The idea is that after you create a dialogue (as a JSON), my main Unity project reads that file and generates a dialogue. Right now it works just fine, but the JSON is an external file that you can modify even after compiling the game (of course). Is there a way to actually "hardcode" that JSON file so that the game doesn't need to find and read the file every single time it plays?
0
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
0
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?
0
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.
0
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.
0
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 )
0
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
0
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.
0
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
0
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?
0
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.
0
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.
0
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?
0
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.
0
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)
0
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 ?
0
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?
0
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?
0
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.
0
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.
0
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?
0
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.
0
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 !!!
0
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?
0
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 ?
0
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
0
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
0
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. .
0
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
0
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.
0
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?
0
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.
0
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?
0
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.
0
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?
0
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.
0
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?
0
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.
0
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?
0
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..
0
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.
0
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
0
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
0
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?
0
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?
0
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?
0
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.
0
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?
0
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.
0
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 ?
0
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?
0
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!!
0
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
0
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)
0
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?
0
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.
0
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?
0
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?
0
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 )
0
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 ) ?
0
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???
0
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
0
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
0
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?
0
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.
0
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.
0
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
0
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? )
0
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 ...
0
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!
0
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?
0
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
0
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
0
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?
0
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.
0
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)
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
0
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 )
0
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.
0
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
0
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?
0
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?
0
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?
0
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?