_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | How to get the loudness of the real world environment using the device's microphone in Unity? I am trying to create a game where the character's movement is dependent on the loudness of the real world environment. So if the person playing the game screams or do something loud the character will move accordingly. What I need is a function returning the loudness of the real world environment and use it in the Update() to control the character. Is there such a function or if not how can I make one? |
0 | How do you make objects be pushed away from you? like pain from naruto, I wanna be able to press a button and be able to push objects here's my push method void DoPush() Collider colliders Physics.OverlapSphere(transform.position, pushRadius) foreach (Collider pushedObject in colliders) if (pushedObject.CompareTag( quot Enemy quot )) Rigidbody pushedBody pushedObject.GetComponent lt Rigidbody gt () pushedBody.AddForce( transform.forward 500, ForceMode.Force) the problem with this method is when I go behind the objects I push, they go towards me |
0 | 3D player movement with Unity's new input system So, I trying to get used to the new Unity input system. "Back in the days" I just got the Vertical Horizontal axis, put them into a Vector3, multiplied them by a certain value and then moves the player. Now, with the new input system, that changed quite a bit. So, what I'm trying to do is, to get the input of a 2D Vector, earlier called DPAD in the new system. My approach was, like private void Awake() InputAction.performed ctx gt Movement(ctx.ReadValue lt Vector2 gt ()) InputAction.canceled ctx gt Movement(ctx.ReadValue lt Vector2 gt ()) private void OnMovement(Vector2 dir) moveDirection dir This performed in FixedUpdate private void Move() transform.position moveDirection moveSpeed Time.deltaTime Buut, you know, kinda worked, but not really. The player did unintended things like keep moving or not reacting at all to my button press. Maybe I set something wrong up. You might help me please, thanks! |
0 | How to set "useGravity" for Rigidbody to entities in Unity For the position you can use this Inject private ComponentDataFromEntity lt Position gt position But cant use it for Rigidbody. How to access the parameters for Rigidbody for entities? |
0 | Behaviour Trees How to clean up when a sequence is interrupted? I'll try to show my problem on a minimal example, in reality it's more complex It's a simple behaviour, that repeats quot an action quot that has a certain animation. If a player gets close, this sequence gets interrupted and the AI executes the quot Flee quot action. The interruption happens because the top level selector is quot dynamic quot which in Unity NodeCanvas means, that its higher priority nodes get executed every frame and if they succeed they interrupt the lower priority ones. My problem is shown via the red arrow if the quot action quot gets interrupted, the clean up (in this case quot stop animation quot ) doesn't execute. What is the best practice to handle the clean up? Is my setup flawed? Or should I just be using a different interrupting mechanism? Thanks for any help! |
0 | How to create a high score in Unity from a Time.deltatime float? When I play my game, it sets my score to 0 and does not change, no matter how high my float gets. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class highscore MonoBehaviour public Text Highscore void Start () Highscore.text PlayerPrefs.GetFloat ("Highscore", 0).ToString() This is where the next page starts using UnityEngine using UnityEngine.UI public class Score MonoBehaviour public Text ScoreText public float playerScore 0 void Update () playerScore Time.deltaTime 10 ScoreText.text playerScore.ToString("0") private void OnCollisionEnter (Collision collisionInfo) if (collisionInfo.collider.tag "Obstacle") PlayerPrefs.SetFloat ("Highscore", playerScore) |
0 | Using .svg in unity(2D) Creating resolution independent sprites is tough and memory consuming. How can .svg assets be used in unity for any kind of 2d game? What are alternatives to .svg that can be used in unity? Can sprites with various shapes be generated within unity? Would like creating universal art asset that'll support all devices with different resolutions.(we'll handle the aspect ratio ) |
0 | Component Class Renderer Class I found some code I needed online, but I want to understand how it works. Renderer c (Renderer)b What is this (Renderer)b action called so I can Google about it? It looks like it's trying to get a Renderer instance from b, but isn't b a Component of type Renderer already? Or is this because Renderer is a subclass of Component? void SetTargetInvisible(GameObject Target) Component a Target.GetComponentsInChildren(typeof(Renderer)) foreach (Component b in a) Renderer c (Renderer)b c.enabled false Code is from https forum.unity.com threads how to make all children invisible.27259 Thanks for taking the time! |
0 | How to handle multiple enemies with the same script? i'm working on a basic Top Down Shooter, kind of like... Nuclear Throne or The Binding of Isaac, but since i'm new to Unity, and it's something i'm required to do for school, i'm quite in a rush so i didn't have enought time to look at all the documentation i should've, so i apologize if i'm asking too much. The thing is like this I have the Player that moves around, and a Sword that rotates in the mouse direction, clicking the mouse activates a Trigger Collider around the Sword, and it's suposed to Hit all enemies inside its range The problem How should i "plan" my Scripts? i mean, i have a Sword script that handles the click and the OnTriggerEnter, and it should, somehow (Working on it), check if it hit an enemy, and access the Enemy Script to modify its Life Points, but how do handle the GameObject Enemy GameObject.FindObjectWithTag("Enemy") ... ? since this just gives me one enemy... I apologize again since i'm really bad at focusing on one point, i dont think it's neccessary to provide all the code since i dont really need you to provide me with code, just... guidelines or a basic pattern of doing this kind of things. Thank you a lot!. |
0 | Reducing disk space needed to use TextMeshPro in AssetBundles My game uses AssetBundles, and quite often each of those bundles use TextMeshPro. The project is at a stage where it would be unwise to change to Addressables. Anyway, I noticed that when a bundle has TextMeshPro involved, it easily adds roughly 2mb to the bundle I assume it's a copy of all the dependencies to make it work. Ideally all bundles should simply point to one copy which is guaranteed to always be present in the game, which I think Addressables sort of does, but as mentioned we cannot use it for this project for various reasons. One way is to create add the TextMeshPro components at runtime (e.g. have some kind of "placeholder dummy" component that, upon Awake() will add TextMeshPro with various preset attributes). That would work fine, and I'm willing to do that but perhaps there are less tedious alternatives (other than Addressables) that I haven't thought of. The goal is to be able to reduce the disk space required for each bundle just because it is using TextMeshPro components. |
0 | How to figure out what's moving my GameObject? I have a GameObject as part of a complex scene with a handful of interconnected parts, that's moving when it shouldn't be. I've tried running under the debugger and setting breakpoints on all of the script points that are supposed to move its Transform, and ensured that none of them are firing. There seems to be some "spooky action at a distance" going on, some rogue script doing something I don't want it to be doing, but I can't for the life of me figure out where it is. What I'd really like is some way to set a "breakpoint" on the object's Transform that will break me into the debugger when it gets moved by any script, but that doesn't appear to be supported. Is there any way to figure out exactly what it is that's moving my object around when it shouldn't be? (And before anyone says "trial and error, disable components and see when it stops moving," I already know exactly which component to disable to make it stop moving. Unfortunately, that isn't helping track down the problem because the movement isn't coming directly from that component's MonoBehaviour script.) |
0 | Why is my texture array getting only the last link index? Here's my code SerializeField GameObject uitex new GameObject 3 void GetTextureFromServer() string dealer img "" for (int i 0 i lt PlayInfo.Instance.gametablelist.Count i ) dealer img PlayInfo.Instance.gametablelist i .dlrimage dealer img "," Debug.Log("HERE ARE THE LINKS " dealer img) string links dealer img.Split(',') for (int j 0 j lt links.Length 1 j ) Debug.Log("HERE ARE THE NEW LINKS " links j ) new BestHTTP.HTTPRequest(new System.Uri(" amazonaws.com resources " "dealer pic " links j ), (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res) gt for (int k 0 k lt uitex.Length k ) var tex new Texture2D(20, 20) tex.LoadImage(res.Data) uitex k .GetComponent lt UITexture gt ().mainTexture tex ).Send() The problem with this code is that it's only getting the last index of my links. What could be the problem on my iteration? Here's an approach that works that shows what the expected behavior is for (int i 0 i lt tzPlayInfo.Instance.bc gametablelist.Count i ) dealer img tzPlayInfo.Instance.bc gametablelist i .dlrimage dealer img "," string newLinks dealer img.Split(',') new BestHTTP.HTTPRequest(new System.Uri(" .amazonaws.com resources " "dealer pic " newLinks 0 ), (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res) gt var tex new Texture2D(20, 20) tex.LoadImage(res.Data) uitex 0 .GetComponent lt UITexture gt ().mainTexture tex ).Send() new BestHTTP.HTTPRequest(new System.Uri(" .amazonaws.com resources " "dealer pic " newLinks 1 ), (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res) gt var tex new Texture2D(20, 20) tex.LoadImage(res.Data) uitex 1 .GetComponent lt UITexture gt ().mainTexture tex ).Send() new BestHTTP.HTTPRequest(new System.Uri(" .amazonaws.com resources " "dealer pic " newLinks 2 ), (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res) gt var tex new Texture2D(20, 20) tex.LoadImage(res.Data) uitex 2 .GetComponent lt UITexture gt ().mainTexture tex ).Send() new BestHTTP.HTTPRequest(new System.Uri(" .amazonaws.com resources " "dealer pic " newLinks 3 ), (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res) gt var tex new Texture2D(20, 20) tex.LoadImage(res.Data) uitex 3 .GetComponent lt UITexture gt ().mainTexture tex ).Send() It's working perfectly, but now the problem is that it is not very clean code. |
0 | How can I get the Selector dialog to include my prefabs When setting a variable for an object in Unity, for built in types there is an option on the right hand side to bring up a dialog that lists the possible values that can be chosen for that variable, for example when selecting a Sprite for a Sprite Renderer Is it possible, and if so what do I need to do, to have that list populated with the prefabs within my project? In this example, there are a number of Item prefabs (both inside and outside the Resources folder if that makes a difference), however they do not appear in that dialog. Is there an attribute I am missing that needs to be specified on the Item class, or something else to enable this? using UnityEngine using System.Collections.Generic public class Item MonoBehaviour, IIdentifiable, IFilterable SerializeField private int IdField SerializeField private bool ActiveField public int Id gt IdField public bool Active gt ActiveField public class ItemRandomiser MonoBehaviour, IWeightedObject SerializeField private List lt string gt NamesField SerializeField private List lt Item gt ItemTemplatesField |
0 | How to prevent an object with high velocity from passing through a collider? Consider a simple 2D platformer. I have a BoxCollider2D on the player object and a TilemapCollider on the ground below(grid). I created a quot jump quot script for the player through which the player object jumps and comes back to the ground, clean. But when the player object goes relatively high and comes down with a high velocity, it doesn't collide with the ground(grid) instead it goes right through the tilemap collider and into the void. How can this behaviour be prevented? |
0 | Latitude and Longitude to Vector3 Not Aligning I am trying to align a marker sphere to certain places on a bigger Earth sphere based on the inputted latitude and longitude. The following is my code for this conversion, this code is based on the code here void createLand() double radius radiusEarth 2 double latitude rad latitude Math.PI 180 double longitude rad longitude Math.PI 180 double xPos (radius Math.Sin(latitude rad) Math.Cos(longitude rad)) double yPos (radius Math.Cos(latitude rad)) double zPos (radius Math.Sin(latitude rad) Math.Sin(longitude rad)) move ObjectMarker to position ObjectMarker.position new Vector3((float)xPos, (float)yPos, (float)zPos) radiusEarth 6371f I am also using a Mercator projection texture for my Earth object. Here is what it looks like for the coordinates of London, UK, 51.509865, 0.118092. As you can see, the marker is in almost the correct position but not quite there. Here is what it looks like for the coordinates of Chennai, India, 13.067439, 80.237617. As you can see here, the marker is completely off, it's been placed somewhere on top of Russia, although it does seem to be directly on top of Chennai. Is there any way I can fix this and make the marker more accurate? |
0 | How to make progress bar adapt to various aspect ratios in Unity3d Can anyone help me with this problem I want to make a time progress bar in my game. I have two textures progressBarFrame and progressBar. Currently I'm doing the following void OnGui() GUI.DrawTexture ( Rect(x,y,width,height), progressBar ) It works, but it doesn't adapt to different screen sizes. I also tried this Create GUITexture in the hierarchy and add a texture to it, after adjusting its size and location as I need, progress bar stretches squishes with different aspect ratios and keeps its position relative to other GameObjects (that's what I want). But I don't know how to animate it properly because the figure of the textures is not a simple line. |
0 | Keep a rigidbody velocity constant I have a "board" with a ball (rigidbody) moving over it and colliding with obstacles. I want its velocity magnitude to remain constant throughout time. How do I achieve this? What I've tried achieved so far My first guess was to use OnCollisionExit to set the velocity manually, but that lead to weird physics. I don't see how to use AddForce to do this since the previous movement would still be factored. To be clear, what i want is to set the velocity at all times to rigidbody.velocity.normalized x magnitude, where magnitude is a float I set previously. This would allow the physics engine to make all impact math to decide the direction of the ball after the collision, but my math would keep the velocity intact. I then decided to add UpdatedFixed and on every call set the velocity as stated above. It's working, but feels like a bad hack because I'm updating the velocity every frame and forsaking the physics engine. |
0 | Ball always showing in Unity Some weird "ball" is showing when I select an element in Unity, preventing me to see the object itself I've tried to hide some layers, but even with all layers hidden it's still here Do you know how to hide this thing? Any idea is greatly welcomed ) |
0 | why use Resources.Load() in changing the animator controller? I wanted to change the AnimatorController of a gameobject during runtime, and when I searched for the method, it used this code animator.runtimeAnimatorController Resources.Load( quot main colors controllercolors ControllerRED quot ) as RuntimeAnimatorController My question is, why don't we use a public AnimatorController and assign it from the animations folder, then set this equal to the runtimeAnimatorController ... Why use Resources.load? .. What's wrong with making a public variable rather than loading it from the Resources file? I am asking cause no one on the forums or any other websites used the public variable method, which suggests that means that the first way is better. public AnimatorController ac anim.runtimeAnimatorController ac |
0 | Download Progress bar from Firebase Storage Im trying to make a progress bar based on downloaded images from Firebase storage, now firebase does provide a snipper which works per image Create local filesystem URL string localUrl quot file local images island.jpg quot Start downloading a file Task task reference.GetFileAsync(localFile, new StorageProgress lt DownloadState gt (state gt called periodically during the download Debug.Log(String.Format( quot Progress 0 of 1 bytes transferred. quot , state.BytesTransferred, state.TotalByteCount )) ), CancellationToken.None) task.ContinueWithOnMainThread(resultTask gt if (!resultTask.IsFaulted amp amp !resultTask.IsCanceled) Debug.Log( quot Download finished. quot ) ) but i would like to make that appear on a UI text based on the percentage of the Bytes downloaded like starting from 0 to 100 .Now i have come to this function so far which does work in the sense of downloading from storage and i do get the percentage in the console but im not sure how to convert that to a percentage to show on UI. if (CheckConnectivity) if the device is connected to the internet, initiate download. Debug.Log( quot Initiating download of quot platform file) if (!File.Exists(localPath)) Task task storageRef.GetFileAsync(localPath, new StorageProgress lt DownloadState gt (state gt called periodically during the download Debug.Log(String.Format( quot Progress 0 of 1 bytes transferred. quot , state.BytesTransferred, state.TotalByteCount )) ), CancellationToken.None) await storageRef.Child( child).Child( file).GetFileAsync(localPath).ContinueWithOnMainThread(files gt if (!files.IsFaulted amp amp !files.IsCanceled) if download is successful. Debug.Log( quot file saved as quot localPath) else otherwise report error. Debug.Log(files.Exception.ToString()) ) else Debug.Log( quot files Exist quot ) else otherwise don't bother. Debug.Log( quot Cannot Download file due to lack of connectivity! quot ) in which case my debug is this Progress 1731 of 52804 bytes transferred. Which i would like to say 0 and counting up to 100! Thanks! |
0 | Mesh Generation In Code My camera looks like this I am trying to add 2D polygons to the screen based on the percentage that they take up of a 1920x1080 pixel canvas. Therefore, I calculate this and then use Camera.ViewportToWorldPoint() to determine the world point for the mesh vertices. Below you can see how I declare vertices and uvs (I am confident my triangles are correct) for the polygon. foreach (var point in poly.path) uv.Add(new Vector2((float)(point.X envelope.left) (envelope.right envelope.left), (float)(point.Y envelope.bottom) (envelope.top envelope.bottom))) I assume this is the correct way to calculate the uvs since they are basically the percentage that vertices lie within the bounds of the polygon's bounding envelope. Here is what I am not so sure on. When I set the vertices like so (assume temp is the array of vertices used) var temp new List lt Vector3 gt () var envelope GetEnvelope() foreach (var point in path) var vect new Vector3((float)(point.X envelope.left) (envelope.right envelope.left), (float)(point.Y envelope.bottom) (envelope.top envelope.bottom), 1.0f) temp.Add(camera.ViewportToWorldPoint(vect)) return temp.ToArray() everything works and the polygon is displayed to my screen except it scales so that the polygon draws as though the viewport is the entire envelope. I expect this, however it is not the functionality I want. So instead I try and declare vertices like so in order to have the polygon displayed in its correct relative position on the screen var temp new List lt Vector3 gt () foreach (var point in path) var vect new Vector3((float)point.X 1920, (float)point.Y 1080, 1.0f) temp.Add(camera.ViewportToWorldPoint(vect)) return temp.ToArray() however when I set the vertices this way, I no longer see the meshes being rendered. My goal with changing the code to this is to have the polygons be their true size on the screen as they are on the 1920x1080 canvas rather than being skewed as they are in the code that I said was working. Am I misunderstanding how vertices and uvs relate? Thank for any help! |
0 | How can I wait for all lines and instances to finish moving and then to destroy them? void Update() if (animateLines) counter for (int i 0 i lt allLines.Length i ) endPos allLines i .GetComponent lt EndHolder gt ().EndVector Vector3 startPos allLines i .GetComponent lt LineRenderer gt ().GetPosition(0) Vector3 tempPos Vector3.Lerp(startPos, endPos, counter 500f speed) allLines i .GetComponent lt LineRenderer gt ().SetPosition(1, tempPos) instancesToMove i .transform.position Vector3.MoveTowards(startPos, endPos, counter 25f speed) for (int i 0 i lt allLines.Length i ) if (instancesToMove i .transform.position endPos) DestroyImmediate(instancesToMove i ) DestroyImmediate(allLines i ) else counter 0 foreach (GameObject thisline in allLines) thisline.GetComponent lt LineRenderer gt ().SetPosition(1, thisline.GetComponent lt LineRenderer gt ().GetPosition(0)) When doing for (int i 0 i lt allLines.Length i ) if (instancesToMove i .transform.position endPos) DestroyImmediate(instancesToMove i ) DestroyImmediate(allLines i ) It's destroying only some of the lines and instancestomove and then give the exception MissingReferenceException The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. |
0 | how can i create a snake with a single piece look I want to create a 3d snake with a single piece look, i have tried separate head and body parts following each other with Vector3.SmoothDamp but some quaternion issues occurred (when y axis gt 90, pieces turning upside). What I want is exactly like in the video https youtu.be uWlMvHU2wfQ Could you tell me the unity components I need to know research? Are the snake models in the video rigged? |
0 | How do I load a specific Asset Bundle Manifest, but not the Asset Bundle itself? I have a bunch of Asset Bundles. I load the generic Asset Bundle Manifest to get the names of all of my asset bundles. I want to load only a specific asset from the bundle, but I need to retrieve the names of the assets so I can choose which one. The names of these assets are in the asset bundles manifests associated with each asset bundle. How can I load just the manifest for a particular asset bundle? This is the closest I have come, but it does not work private IEnumerator LoadAssetNames() foreach (var bundleName in assetBundleNames) string url "my server " bundleName ".manifest" var www UnityWebRequest.GetAssetBundle(url) yield return www.Send() if (www.isError) Debug.LogError(www.error) yield break var bundle ((DownloadHandlerAssetBundle)www.downloadHandler).assetBundle www.Dispose() assetNames bundleName bundle.GetAllAssetNames() It returns to me a failed to decompress error Error while downloading Asset Bundle Failed to decompress data for the AssetBundle 'my server bundleName.manifest'. I can download the manifest directly as a string or set of bytes, but then how can I cast it to an AssetBundleManifest? |
0 | Predicted trajectory becomes less accurate in a side on collision In my 2D billiards game, I have it so that when the user clicks and drags with their mouse, a Physics2D.CircleCast is projected from the cueball to wherever the mouse is. If the circle happens to hit the red ball, a line is rendered from the red ball's position to the direction of the normal of the collision. So it's supposed to predict where the red ball will go when it gets hit by the cueball. If you look at the first gif below, you'll see that it works if the red ball gets hit at its center (or close to it). The red ball ends up moving more or less along the predicted line. However, if you look at this second gif, you'll see that if the red ball gets hit closer to its edge, the predicted line is much less accurate. Why is this and how can I fix it? This is the prediction code I use if (Input.GetMouseButton(0) amp amp cueBall) Vector2 mousePos cam.ScreenToWorldPoint(Input.mousePosition) var direction (mousePos (Vector2)cueBall.position).normalized var hit Physics2D.CircleCast(cueBall.position, radius, direction, Mathf.Infinity) if (hit) lineMain.Draw(cueBall.position, hit.point) ghostBall.SetPosition(hit.point (direction radius)) lineTarget.Draw(hit.point, hit.point hit.normal) This is the predicted trajectory. |
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 | Can't refer mesh size after using .BakeMesh() in Unity I can't figure out how to refer to the size of a particular mesh. The mesh is created through .BakeMesh(), then a box collider is added. Unfortunately the box collider has a scale of 1 by 1 by 1, regardless of how big the mesh I'm adding it to seems to be. This doesn't match my understanding of how creating a box collider should work, so I've set up a Debug.Log that outputs the mesh size. Here the plot thickens. The mesh's size just comes back at 0, 0, 0. My attempts at getting the size of the object are as follows objectToMeasure.GetComponent lt Renderer gt ().bounds.size objectToMeasure.GetComponent lt MeshFilter gt ().mesh.bounds.size objectToMeasure.GetComponent lt MeshFilter gt ().sharedMesh.bounds.size Assuming I'm referring to the size of the object in the correct way, this seems like it must be an issue created by baking the object. Do I need to wait a frame (via starting a coroutine) before trying to access the size of the object, or am I referring to the wrong component of the object, or is the BoxCollider setting it's size based on objectToMeasure's scale rather than it's size in the world? I feel sure that objectToMeasure.GetComponent().mesh.bounds.size should be right, since the script I use to bake to the mesh is meshToBake.BakeMesh(meshToMeasure.GetComponent().sharedMesh) I've been driving myself to the edge of sanity for 24 hours with this script not working, so advice is greatly appreciated. |
0 | Unity Event Pause Unpause jump frame Hello, I would like to get in a script the event whenever we click on the pause button, or the Jump frame button. I have already manage the Pause button private void OnEnable() EditorApplication.playmodeStateChanged HandleOnPlayModeChanged private void OnDisable() EditorApplication.playmodeStateChanged HandleOnPlayModeChanged private void HandleOnPlayModeChanged() if (EditorApplication.isPaused) do stuff when the editor is paused. else do stuff when the editor is unpaused But How to get the "jump frame" button ? Thanks ! |
0 | Blender mesh mirroring screws up normals when importing in Unity My issue is as follows I've modeled a robot in Blender 2.6. It's a mech like biped or if you prefer, it kindda looks like a chicken. Since it's symmetrical on the XZ plane, I've decided to mirror some of its parts instead of re modeling them. Problem is, those mirrored meshes look fine in Blender (faces all show up properly and light falls on them as it should) but in Unity faces and lighting on those very same mirrored meshes is wrong. What also stumps me is the fact that even if I flip normals in Blender, I still get bad results in Unity for those meshes (though now I get different bad results than before). Here's the details Here's a Blender screen shot of the robot. I've took 2 pictures and slightly rotated the camera around so the geometry in question can be clearly seen Now, the selected cog wheel like piece is the mirrored mesh obtained from mirroring the other cog wheel on the other (far) side of the robot torso. The back face culling is turned of here, so it's actually showing the faces as dictated by their normals. As you can see it looks ok, faces are orientated correctly and light falls on it ok (as it does on the original cog wheel from which it was mirrored). Now if I export this as fbx using the following settings and then import it into Unity, it looks all screwy It looks like the normals are in the wrong direction. This is already very strange, because, while in Blender, the original cog wheel and its mirrored counter part both had normals facing one way, when importing this in Unity, the original cog wheel still looks ok (like in Blender) but the mirrored one now has normals inverted. First thing I've tried is to go "ok, so I'll flip normals in Blender for the mirrored cog wheel and then it'll display ok in Unity and that's that". So I went back to Blender, flipped the normals on that mesh, so now it looks bad in Blender and then re exported as fbx with the same settings as before, and re imported into Unity. Sure enough the cog wheel now looks ok in Unity, in the sense where the faces show up properly, but if you look closely you'll notice that light and shadows are now wrong Now in Unity, even though the light comes from the back of the robot, the cog wheel in question acts as if light was coming from some where else, its faces which should be in shadow are lit up, and those that should be lit up are dark. Here's some things I've tried and which didn't do anything in Blender I tried mirroring the mesh in 2 ways first by using the scale to 1 trick, then by using the mirroring tool (select mesh, hit crtl m, select mirror axis), both ways yield the exact same result in Unity I've tried playing around with the prefab import settings like "normals import calculate", "tangents import calculate" I've also tired not exporting as fbx manually from Blender, but just dropping the .blend file in the assets folder inside the Unity project So, my question is is there a way to actually mirror a mesh in Blender and then have it imported in Unity so that it displays properly (as it does in Blender)? If yes, how? Thank you, and please excuse the TL DR style. |
0 | Sprite Image in Canvas not displaying correctly (distorted) I have a problem with displaying images in my Canvas, as they're not displaying exactly like the imported image. In the image below, the sprite on the left is how it looks when it's imported. The sprite on the right is how it looks in the canvas. Notice that some of the pixels have incorrect colours, like the lighter pink in the center of the staff's top is gone, the eyeball is a darker shade, some of the colouration under the hood is wrong, and other errors. ( The sprite is just a test I took from somewhere else, not what I intend to use as a final product. ) The project is 3D (going for a 2.5D look with billboard sprites) set to 384x224 resolution, orthographic camera size of 3.5, no anistropic textures, no anti aliasing. Is there some setting I missed somewhere to ensure that images display 100 exact like the source sprite when used in the Canvas? EDIT Sprite in the Inspector (Seems to also not be correct) EDIT Added entire inspector |
0 | Unity3D Where to put external files? I want my game to be user translated friendly.I put .text file to Data folder from where strings will be read. What is Editor alternative for data folder ? Also i know compiler ignore some files, how i can tell compiler to include this one ? thanks. |
0 | C Events in Unity to separate GameObject features into Components Broadly speaking, this is a question about how to separate my game object's code into distinct feature components that can be added and removed as needed. More specifically, I am trying to achieve this using C events in Unity. But I am open to other solutions. Scenario We have enemies that have health. When their health reaches zero, they die. Some enemies (think asteroids) may spawn a number of child enemies (think smaller astroid pieces) when they die. Others however, just die. I want to have two scripts EnemyHealth Tracks the enemy's health and kills the enemy when its health reaches zero. EnemyChildrenSpawner Spawns child enemies after the enemy's death This way, all enemies will have the EnemyHealth script, and some enemies will have the EnemyChildrenSpawner script in addition. My idea is to have the EnemyHealth script raise an event when the enemy dies, and have EnemyChildrenSpawner subscribe to said event to spawn the children. What would be the best way of achieving this? Here's my attempt. It works. Just not sure if this is good practice, especially using the GetComponent in the second script? EnemyHealth.cs public class EnemyHealth MonoBehaviour The event to invoke when this enemy died public event EventHandler OnDied Gets called when this enemy's health reached zero private void Die() Invoke the died event OnDied?.Invoke(this, EventArgs.Empty) Destroy this enemy EnemyChildrenSpawner.cs public class EnemyChildrenSpawner MonoBehaviour private void OnEnable() GetComponent lt EnemyHealth gt ().OnDied SpawnChildren private void OnDisable() GetComponent lt EnemyHealth gt ().OnDied SpawnChildren private void SpawnChildren(object sender, EventArgs e) Spawn children |
0 | Unity Change scene by drag How do I change the scene like you do on common android home screens? I know i could detect if the player swipes to the right and then change the scene but this would not look as smooth as android home screens. |
0 | How to get the closest "visible" object from my "player"? I'm using Unity 3d and i have to accomplish the following task get the closest "visible" object to my player in forward direction. It is a sort of radar. I don't know where to start. Any advice is welcomed. Thanks |
0 | Get the scene that MonoBehaviour belongs to (multi scene setup) Is there a way to get the scene that a MonoBehaviour component belongs to? The MonoBehaviour is part of a setup with several additivly loaded scenes. What I'm looking for is not the currently active scene but an additionally loaded one. |
0 | Rotate player to vector3 point? I want my player object rotate to face vector3 point on terrain. public Vector3 RocketPointer public Transform pointer,Player public bool rocket , button move Update is called once per frame void Update() if (button move true) Ray mouseRay Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit mousePoint if (Physics.Raycast(mouseRay, out mousePoint, 100)) RocketPointer mousePoint.point pointer.transform.position RocketPointer if (button move true amp amp Input.GetMouseButtonDown(0)) rotate player object to face rocketpointer point rocket true button move false if (button move false amp amp Input.GetMouseButtonUp(0)) rocket false public void move button() UI button button move !button move |
0 | Frustum culling with a single large object I am helping to optimize performance in a mobile game. The artists who built a particular scene added a wall around the scene. The wall is a single mesh with 100k triangles. Because it goes around the entire scene, at least some of the wall is visible from all angles and is always being rendered. While running the game in the Editor with the Statistics panel enabled, I can see that hiding the GameObject containing the wall always reduces the current number of tris by 100k regardless of how much of the wall is actually visible. Does this mean that the entire wall is always getting rendered, rather than only the triangles that are actually in front of the camera? Obviously the artists need to reduce the overall polygon count of the wall, but I'm wondering if they should also break it into several separate pieces so that the entire wall doesn't need to be rendered at once. |
0 | In a JRPG Battle system. Who executes the selected action? Throughout the JRPG history, we've seen the introduction of many a battle system type. Like the classic turn based. The ATB. The action battle system (Most Notable is Kingdom Hearts) In these systems, there's a variety of skill handlers like a queue or gauge to determine turn. My question put simply is who handles the executing of skills? Is it the Battle system? The Players? The Skill queue if there is one? Right now I'm working on an ATB styled Final Fantasy in Unity. I'm leaning towards either the player or the battle system executing the commands. I have my players with each a separate state machine (WAIT, COMMAND, ACTION) And a command queue that holds the queued up actions. I can either have the player in the ACTION state and the battle system process the logic(Execute whatever queued up action). Or the player handle that. Outside of that. I'm curious how it works for the other types of battle systems since I hope others in the future with a similar question can see this. |
0 | How to use a .mtl file in Unity? I want to use a .mtl file to draw my objects in unity. Can I somehow convert a .mtl file into a normal Unity material? My .mtl file is like this newmtl phongE1SG illum 4 Kd 0.00 1.00 0.00 Ka 0.00 0.00 0.00 Tf 1.00 1.00 1.00 Ni 1.00 Ks 0.50 0.50 0.50 Is this the same as a Unity material which has the sliders "albedo", "metallic", "smoothness", etc? Or is there any shader to do it? |
0 | How to Make a Ladder Climbing Script I'm inexperienced and I'm trying to understand the mechanism for using a ladder with my character or climbing over small walls. To move I use a Rigidbody, not Kinematic, but with AddForce. I tried to create an object to simulate a ladder to climb on. To get my character into contact with the ladder I inserted a Collider trigger on the ladder and called the OnTriggerStay function. After working a bit, I used a bool such that my character can go up or down the ladder when he's close enough, but I don't understand some things. First of all, is the script better to put on the character or create one on the ladder? The second thing is once you get to the top how do I insert a function correctly and make my character complete the climb, making it arrive above the object where the staircase is located? Do I have to get to the top, destroy the game object and respawn at a point just above the ladder? What is the best way to do this? Here's my code private Rigidbody rb public bool ladderClimb false void Start() rb GetComponent lt Rigidbody gt () void Update() if(ladderClimb) directionRot new Vector3(0, 0, 0) direction of rotation movement new Vector3(0, Input.GetAxisRaw( quot Vertical quot ), 0).normalized object movement rb.useGravity false else rb.useGravity true void OnTriggerStay(Collider collider) if(collider.gameObject.tag quot ladder quot ) if(Input.GetKeyUp(KeyCode.E)) ladderClimb !ladderClimb void OnTriggerExit(Collider collider) if(collider.gameObject.tag quot ladder quot ) ladderClimb false |
0 | Is it possible to push real world, real time data into Unity? I'm pretty new to this, and I'm having trouble figuring out where to even look. If there's relevant terminology that'll be google able, that would be a great help. Suppose I want to have a monitor in game that displays the output from a camera that's in the same room as the player. Are there libraries for grabbing and rendering that data? |
0 | How to prevent cube intersecting with other objects when moved around with mouse? I want to allow the player to freely place cubes anywhere they like in 3D space, but the cube being moved around is not allowed to intersect with other objects. Currently I do a ray cast based on where the mouse is (ScreenPointToRay), and position the cube at the hit point. This allows me to move the cube around, but it's possible to intersect other objects if the raycast hit is right next to an object. I see that there is a Physics.BoxCast method, but I can't get this working based on where the mouse position is. Am not sure if this is even the best solution. I was thinking of ray casting out from each 4 points of each face on the cube (4 up, 4 down, 4 right, 4 left, 4 forward, 4 back), but I feel this is a lot of raycasts just to prevent intersecting on movement and placement for a cube. How can I prevent a cube that is being moved around, and then placed with the mouse from intersecting other objects? |
0 | The camera goes up and down when following a rolling sphere I have this CameraController script attached to my camera, to follow a sphere that moves using WSAD. public class CameraController MonoBehaviour public GameObject player private Vector3 offset Start is called before the first frame update void Start() offset transform.position player.transform.position Update is called once per frame void FixedUpdate() transform.position player.transform.position offset It follows the object fine, but it bounces up and down on the Y axis when it's moving, and I don't know how to stop the camera from doing it. |
0 | How to enable disable GameObject I have child object with ParticleSystem component. I want to have particles disabled until I press button. I unchecked child object to make it disabled but when I press play it enables automatically(with no scripts attached). Then I made this script below (with .SetActive(false) part only) and it worked. But then I needed to activate it somehow, which I did, but now when I press play, object is automatically enabled activated again. Is there another way of doing this because I need it haha. var particle1 GameObject var particle2 GameObject var particle3 GameObject public var triggered boolean false function OnTriggerEnter() triggered true function OnTriggerExit() triggered false function Start() particle1.SetActive(false) particle2.SetActive(false) particle3.SetActive(false) function Update() if (triggered amp amp Input.GetKeyDown(KeyCode.JoystickButton1)) particle1.SetActive(true) particle2.SetActive(true) particle3.SetActive(true) |
0 | World position into local position I want to understand how I can convert world position of an object into local position. Especially how to deal with a rotation of objects. I'm testing transform.InverseTransform(...) methods. When parent and child has 0 rotation, this methods easily convert world into local position. I don't know how to deal with a situation, when one of the objects has not zero rotation. In the example below my parent object has (0,0,10) position and (0,0,0) rotation. Child position (0,0,0) and rotation (90,0,0). Debug.Log (string.Format ( quot World position 0 nLocalPosition 1 nInverseTransformPoint 2 nInverseTransformVector 3 nInverseTransformDirection 4 nTransformPoint 5 nTransformVector 6 nTransformDirection 7 quot , transform.position.ToString (), transform.localPosition.ToString (), transform.InverseTransformPoint (transform.position).ToString (), transform.InverseTransformVector (transform.position).ToString (), transform.InverseTransformDirection (transform.position).ToString (), transform.TransformPoint (transform.localPosition).ToString (), transform.TransformVector (transform.localPosition).ToString (), transform.TransformDirection (transform.localPosition).ToString ())) The example debug result World position ( 1.0, 0.7, 10.0) LocalPosition ( 1.0, 0.7, 0.0) InverseTransformPoint (0.0, 0.0, 0.0) InverseTransformVector ( 1.0, 10.0, 0.7) InverseTransformDirection ( 1.0, 10.0, 0.7) TransformPoint ( 2.1, 0.7, 9.3) TransformVector ( 1.0, 0.0, 0.7) TransformDirection ( 1.0, 0.0, 0.7) What should I add to transform.InverseTransformPoint (transform.position) to get transform.localPosition? |
0 | Unity 2D Sprite Bending between Hinge Joints I've created a tentacle that consists of multiple game objects, each attached to eachother using HingeJoint2D's. Gameplay wise this multiple segmented approach is great because I can use Unity's built in physics, but it doesn't look very good art wise. Is it possible to 'bend' 2D sprites, so the tentacle segments look like they're attached to eachother? Or perhaps take a single image and bend it using splines of some sort? I would prefer to keep using multiple game objects to represent the tentacle. |
0 | (Unity) Physics based movement vs Straight position change Unity provides a cool physics engine for game development and I want to utilize it in my game. Shorter version I want to use physics engine for everything else other than character movement because trying to use physics engine for player movement doesn't yield the perfectmovement speed that I want move x units per second. If I use physics engine for character movement, it gets complicated. I would rather just add "moved distance" to the position to have things done simple. Is doing something like this wrong? All the learning sources I read recommend to use physics engine for movement if the game incorporates physics engine. I am nervous am I wrong? Longer version The following description is where I use "physics", why I need physics engine. In my game a player fires a bullet. When enemies collide with bullet, they get pushed back slightly. A strong blast can push enemies far back so that they even bounce back from hitting wall. A recommend, a proper way, I was told, to utilize this physics engine for character movement is to add force to the direction I want to move. But doing so(adding force to the direction I want to move) will result in truck like slowly warming up by adding velocity. To avoid "truck like movement" I was told to apply greater force at the beginning. Doing so result in change in velocity like the below picture. However problem is not over yet, you must consider a situation where you change direction of movement while the character is running. If you started to move backward, all of the sudden while running forward, you will need to slow down forward movement burn velocity by adding backward force. Thus rotation burns velocity. So a solution is to find out perpendicular velocity to your desired direction, then find out needed amount of force to "burn off" the undesired velocity. This seems way too complicated for a character to simply move around. I would rather just move character to desired direction by simply adding "constant X distance" to the character's position. But I can't find a source of example where it utilizes both "simple movement by directly adding moved distance to the position" and "using physics engine for the game". All the sources of learning(using Unity physics) I find say use this complicated way of having character to move around. I wonder is there a reason why people don't just add moved distance to the position? |
0 | How to rotate a rigidbody with a Pid controller I would like someone to describe me how to use a PID controller to rotate a rigidbody with AddTorque to a specific position. (like a spacecraft that rotates the Y axis of rotation towards Camera.forward for example). Can anyone show it to me with a script? Actually I already use this script to rotate with AddTorque but the object almost never stops at the precise point. Vector3 camForward Camera.main.transform.forward Vector3 rbForward rb.transform.forward Vector3 torqueY Vector3.Project(torque, Vector3.up) Vector3 torque Vector3.Cross(camForward, rbForward) rb.AddTorque(torque) rb.AddTorque( rb.angularVelocity) |
0 | Destroying copy of DontDestroyOnLoad GameObject? I have a Main Menu with level selecter up to 5 different scenes on one Map. I also have a MenuManager which doesn't get destroyed between the scenes to gather the bool information of level finished or not. When I start the game and change for example level 1 and move back to the Main Menu again the MenuManager gets copied. I tried this at first public static GameObject menuInstance void Awake() if ( menuInstance null) menuInstance this.gameObject else Destroy(gameObject) My problem with that is that the copied GameObject that get's destroyed is the wrong one. This is the copy that gets created after I switched the scenes and back to Main Menu. This is the original MenuManager that should be the menuInstance Object and the other one should be destroyed. How can I not delete the original one and delete the one without the references? I come up with something but I am not sure if this is the right way to do this. I changed the code in the Awake() function to void Awake() if ( menuInstance null) menuInstance this.gameObject I checked one of the missing references to be null and then destroy the fake copy. Update() if( startTheGame null) Destroy(gameObject) |
0 | Any problems with flipping a sprite by scale? (2d Platformer) I am wondering if there are any problems with flipping a sprite on the x axis using vector2 to tell which direction it is facing flip. Though doing this helps me write less code for Ray cast direction and creating single states with a single animation (using 1 animation player facing right than using 2 animation facing left and right). If there is a better solution please tell me and thanks. Btw I am still pretty new and learning. |
0 | StartCoroutine function inside TriggerOnEnter2D not working unity kinect So i'm using Kinect with unity to track user's hand movements, and let the user's hand act as a mouse, I have written the code to detect a collision between a button (sprite object) and the hand cursor using OnTriggerEnter2D, but I want the hand cursor to remain on the button (sprite object) for atleast 3 seconds for it to be considered as a button click action. The WaitForSeconds coroutine doesn't seem to be working. What am i doing wrong? public class MenuSelect MonoBehaviour private string btnName private string themeName Use this for initialization void Start () gestureListener Camera.main.GetComponent lt GestureListener gt () Update is called once per frame void Update () void OnTriggerEnter2D(Collider2D col) print("Collision Detected") StartCoroutine(WaitTime(3)) if(col.gameObject.tag "Button") btnName col.gameObject.name switch(btnName) case "musicBtn" Application.LoadLevel("Menu Music") break case "startBtn" Application.LoadLevel("Menu Select") break case "instructBtn" print("Instruction Clicked") break case "exitBtn" Application.Quit() break case "themeBtn" Application.LoadLevel("Menu Theme") break case "backBtn" Application.LoadLevel("Menu LoadScreen") break IEnumerator WaitTime(float waitTime) yield return new WaitForSeconds(waitTime) print("seconds up already") |
0 | Video playback in Unity I'm not satisfied with the quality of video playback in Unity (Movie texture which I run after converting video with Miro converter and importing it to Unity),... so, is there any chance that there is a 3rd party library which I can integrate inside Unity to play my movie file? My movie is full HD intro movie to my 3d app which can be played from application menu. I've tried to use Media Player Classic (MPC) as external application, but the problem is, when I run MPC as new Process from application menu, my menu minimizes and this looks awkward for one stand alone app. When intro finishes, I have to maximize my menu by clicking on application icon placed on Windows taskbar. |
0 | Not able to connect to Photon(PUN).photon unity networking error I'm new to photon Networking. My game was working great suddenly this is appearing Cannot send messages when not connected. Either connect to Photon OR use offline mode! UnityEngine.Debug LogError(Object) |
0 | Generating mesh along path I'm currently trying to generate a path along an array of points (Vector3) This is the result I'm currently getting The dark gray points are the given path The red points are the generated vertices And the triangles are obviously the mesh I failed to generate correctly And from the bottom it looks like this, which is odd, because I'd expect all the missing triangles to be at the bottom. But some of them just don't exist here's the code i wrote that generates the path mesh Removed code since there's no need in showing something that doesn't work And here's a quick example of what it looks like when I drag a path SOLUTION FOUND As the accepted answer states, I was skipping triangles in my triangle for loop. Here is my new working code public static Mesh extrudeAlongPath(Vector3 points, float width) if (points.Length lt 2) return null Mesh m new Mesh() List lt Vector3 gt verts new List lt Vector3 gt () List lt Vector3 gt norms new List lt Vector3 gt () for (int i 0 i lt points.Length i ) if(i ! points.Length 1) Vector3 perpendicularDirection new Vector3( ( points i 1 .z points i .z ), points i .y, points i 1 .x points i .x).normalized verts.Add (points i perpendicularDirection width) norms.Add (Vector3.up) verts.Add (points i perpendicularDirection width) norms.Add (Vector3.up) else Vector3 perpendicularDirection new Vector3( ( points i .z points i 1 .z ), points i .y, points i .x points i 1 .x).normalized verts.Add (points i perpendicularDirection width) norms.Add (Vector3.up) verts.Add (points i perpendicularDirection width) norms.Add (Vector3.up) m.vertices verts.ToArray () m.normals norms.ToArray () List lt int gt tris new List lt int gt () Changed i 3 to i for(int i 0 i lt m.vertices.Length 3 i ) if(i 2 0) tris.Add(i 2) tris.Add(i 1) tris.Add(i) else tris.Add(i) tris.Add(i 1) tris.Add(i 2) m.triangles tris.ToArray () m.name "pathMesh" m.RecalculateNormals () m.RecalculateBounds () m.Optimize () return m |
0 | Assigning valid moves on board game I am making a board game in unity 4.3 2d similar to checkers. I have added an empty object to all the points where player can move and added a box collider to each empty object.I attached a click to move script to each player token. Now I want to assign valid moves. e.g. as shown in picture... Players can only move on vertex of each square.Player can only move to adjacent vertex.Thus it can only move from red spot to yellow and cannot move to blue spot.There is another condition which is if there is the token of another player at the yellow spot then the player cannot move to that spot. Instead it will have to go from red to green spot. How can I find the valid moves of the player by scripting. I have another problem with click to move. When I click all the objects move to that position.But I only want to move a single token. So what can i add to script to select a specific object and then click to move the specific object.Here is my script for click to move. var obj Transform private var hitPoint Vector3 private var move boolean false private var startTime float var speed 1 function Update () if(Input.GetKeyDown(KeyCode.Mouse0)) var hit RaycastHit no point storing this really var ray Camera.main.ScreenPointToRay (Input.mousePosition) if (Physics.Raycast (ray, hit, 10000)) hitPoint hit.point move true startTime Time.time if(move) obj.position Vector3.Lerp(obj.position, hitPoint, Time.deltaTime speed) if(obj.position hitPoint) move false |
0 | Gizmos not being drawn until GameObject selected I have implemented Scene loading in my game and have three scenes Persistent, Main Menu and Game By default, the player is loaded into the Persistent scene, which immediately loads the Main Menu, and when the player clicks on Play, Main Menu is unloaded and Game is loaded. Now, the two active scenes are Persistent and Game. However, I have a script with OnDrawGizmos on a GameObject in the Game scene. It seems that by default gizmos only begin to be drawn when I click on that GameObject, sort of activating it, and everything works fine. This used to just work before because Game was my only scene and Unity automatically selected that first GameObject. Now, with multiple scenes, no GameObject is selected by default and my gizmos won't draw until I manually click on it. How can I solve this? |
0 | How to get Entitas components from gameObject.getEntityLink() I'm new to Entitas. I have a DamageSystem that should Physics.Raycast() toward the target and if tag is enemy it should reduce enemy health. I have HealthComponent public class HealthComponent IComponent public float value In DamageSystem I wanna do something like if(Physics.Raycast(target, direction, out hit)) tag.gameObject.entity.health.value currentHealth damage But after Physics.Raycast(), I have only the gameObject and getEntityLink() method that return EntityLink without actual components... I guess that getEntityLink() returns only abstract components, and there is no way to get HealthComponent from EntityLink? Does someone know how to get components from EntityLink, in a clean manner? Thanks! |
0 | How to get button component in Unity 2019.3 I have a simple class attached to a button in Unity Canvas using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UIElements public class AudioButtonPlay MonoBehaviour public Button button void Start() button gameObject.GetComponent lt Button gt () But on the line button gameObject.GetComponent lt Button gt () I get the following message GetComponent requires that the requested component 'Button' derives from MonoBehaviour or Component or is an interface How can I access the "Button" component? |
0 | Card displacement in Unity Following a tutorial on Youtube, https www.youtube.com watch?v P66SSOzCqFU, I'm trying to make a card game that uses dragged cards. When I drag a card it's supposed to stay centered with the mouse, but it's showing up on the edge of the screen when I start to drag it. How do I make it so the card drags with my mouse instead? Currently I'm using two scripts, one for a drop zone and one for "draggable". When I tried to debug the draggable section it kept referring me back to a line in my drop zone script that just had a ' '. I'm working in Unity 5.6.0f3 and Visual Studio 2017. My drop zone code looks like this public class DropZone MonoBehaviour, IDropHandler, IPointerEnterHandler, IPointerExitHandler public void OnPointerEnter(PointerEventData eventData) Debug.Log("OnPointerEnter") if (eventData.pointerDrag null) return Draggable d eventData.pointerDrag.GetComponent lt Draggable gt () if (d ! null) d.placeholderParent this.transform public void OnPointerExit(PointerEventData eventData) Debug.Log("OnPointerExit") if (eventData.pointerDrag null) return Draggable d eventData.pointerDrag.GetComponent lt Draggable gt () if (d ! null amp amp d.placeholderParent this.transform) d.placeholderParent d.parentToReturnTo public void OnDrop(PointerEventData eventData) Debug.Log(eventData.pointerDrag.name "was dropped on" gameObject.name) Draggable d eventData.pointerDrag.GetComponent lt Draggable gt () if(d ! null) d.parentToReturnTo this.transform And my Draggable code looks like this public class Draggable MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler public Transform parentToReturnTo null public Transform placeholderParent null GameObject placeholder null public void OnBeginDrag(PointerEventData eventData) Debug.Log("OnBeginDrag") placeholder new GameObject() placeholder.transform.SetParent(this.transform.parent) LayoutElement le placeholder.AddComponent lt LayoutElement gt () le.preferredWidth this.GetComponent lt LayoutElement gt ().preferredWidth le.preferredHeight this.GetComponent lt LayoutElement gt ().preferredHeight le.flexibleWidth 0 le.flexibleHeight 0 placeholder.transform.SetSiblingIndex(this.transform.GetSiblingIndex()) parentToReturnTo this.transform.parent placeholderParent parentToReturnTo this.transform.SetParent(this.transform.parent.parent) GetComponent lt CanvasGroup gt ().blocksRaycasts false public void OnDrag(PointerEventData eventData) Debug.Log("OnDrag") this.transform.position eventData.position if(placeholder.transform.parent ! placeholderParent) placeholder.transform.SetParent() int newSiblingIndex placeholderParent.childCount for(int i 0 i lt placeholderParent.childCount i ) if(this.transform.position.x lt placeholderParent.GetChild(i).position.x) newSiblingIndex i if(placeholderParent.transform.GetSiblingIndex() lt newSiblingIndex) newSiblingIndex break placeholder.transform.SetSiblingIndex(newSiblingIndex) public void OnEndDrag(PointerEventData eventData) Debug.Log("OnEndDrag") this.transform.SetParent(parentToReturnTo) this.transform.SetSiblingIndex(placeholder.transform.GetSiblingIndex()) GetComponent lt CanvasGroup gt ().blocksRaycasts true Destroy(placeholder) In the draggable code, if(placeholder.transform.parent ! placeholderParent) placeholder.transform.SetParent() is commented out because that's where I stopped in the tutorial in order to go back and fix my displacement issue. |
0 | Roatating a Game Object downward In my game I have a rocket which is traveling horizontally across the screen. What I am trying to do is when the player runs out of fuel, the rockets engine stops (already coded) and then the rocket will slowly rotate to point at an almost 45 degree angle and fall down off the screen as gravity takes its affect. How do I do this? |
0 | Offsetting ground texture doesn't work in WebGL so I've created a 2D sidescroller game, the technique I used is to keep the player on the same place, and move the obstacles towards him. I also offset the ground and backdrop constantly to create the illusion of player moving. The ground texture is on a quad, and the texture wrap mode is set to repeat. In the editor everything is running fine as I wanted, however when I build it (WebGL), in the browser the ground doesn't seem as if it is set to Repeat but rather Clamp. Here's how it looks You can see from the left part of the image the ground doesn't repeat, the strange thing is that, after the game runs for a few more seconds it fixes, and then in a few seconds becomes like that again. heres the code attached to the ground to keep it offsetting constantly using System.Collections using System.Collections.Generic using UnityEngine public class Offset MonoBehaviour public float scrollSpeed public Material mat private float offset Use this for initialization void Start () mat GetComponent lt Renderer gt ().material Update is called once per frame void Update () offset Mathf.Repeat(Time.time scrollSpeed, 1) mat.mainTextureOffset new Vector2(offset, mat.mainTextureOffset.y) What may I be doing wrong, and how can I fix it? Thanks in advance! |
0 | How to check for mesh overlap? I'm creating a level editor in Unity. I need to detect when an object is intersecting another as I don't want to allow the user to place an object when it is colliding with something else. In the below diagam, there is a corner road piece and a tree. The dashed red line represents the mesh bounds of the road and the blue dashed line represents the mesh bounds of the tree. My current approach is to use Physics.OverlapBox with mesh.bounds. In the diagram, visually, it is clear that the tree does not overlap the road. However, the bounds do overlap, therefore I cannot place the tree there. Whats the best way to check if they are actually colliding in an efficient way? The level editor could potentially have thousands of objects. EDIT I have since tried using Physics.ComputePenetration. Primitive primitive checks work ok, primitive mesh collider checks work ok, but mesh collider mesh collider checks fail. From what I understand a concave mesh collider cannot interact with another concave mesh collider. Is there a workaround for this or must I momentarily make it convex before checking overlap? I just don't want to lose the accuracy of the concave collider. |
0 | Object pooling with collisions in Unity I am trying to create doodle jump like game with object pool for platforms. I have created an empty object with box 2D collider attached to it. This object moves with player and should be gathering platforms which exit its collider, but it isn't. public class PoolGrabber MonoBehaviour Tooltip("Field for game manager.") SerializeField private GameObject gameManager private void Awake() gameManager GameObject.FindGameObjectWithTag("GameManager") private void OnTriggerExit2D(Collider2D collision) if(collision.tag "PooledObject") collision.gameObject.SetActive(false) gameManager.GetComponent lt LevelGenerator gt ().objectPool.Add(collision.gameObject) It also doesn't work with OnTriggerEnter2D. I have also tried private void OnBecameInvisible() gameObject.SetActive(false) on a platform. Doesnt work either. I have discovered that for all those methods above object required to has Rigidbody2D component. But what if I don't want any phisycs calculations to be handled. I don't need physics on those platforms at all. Also, an object doesn't become invisible if you see it in the editor window. Isn't very convenient. |
0 | Custom 2D physics on unity I have seen a lot of people think that for a 2D platformer game, Unity2D physics is not really the best approach, and recommend implementing your own physics. I found the idea interesting, but I don't know how to approach the issue. Using 2D Rigidbodies, and setting them as kinematic, allows you to ignore unity's physics. But how would collisions be handled without relying on Unity collision system? |
0 | Frequent stuttering, high FPS spikes with VSync option turned on in Unity standalone build I'm experiencing an issue using Unity 4.3.2 and standalone builds. If I turn on VSync in the project's Quality settings, running the game at the native monitor resolution, I'll frequently get high framerate spikes (over 100FPS), and a strong stutter for a few frames, and then it drops back down to 60FPS and runs normally. If I run the game at a lower resolution (800x600 for example), the framerate stays at around 500FPS and the stuttering is consistent. However, if I turn off VSync in the Quality settings, and force it on in the Nvidia Control Panel, I don't experience any stuttering or framerate spikes, nor when I turn off VSync completely (but lots of screen tearing, which is very ugly and distracting). Can anyone explain this behavior? Is there anything that can be done to circumvent it? I'd imagine other Unity developers have used the built in Unity VSync with success before (or maybe not?!) so I'm hoping I'm just doing something wrong on my end. |
0 | Some UI button script not working in apk build! There are a lot of posts regarding this problem in various website and even in this one but no one has given a feasible solution to this problem. I have a button that has a custom sprite. I also have a custom script attached to that button which when pressed down (IPOINTER DOWN) changes the color of particular sprite renderer. All this works in pc but not on apk build. Why? I have two canvas, so I thought there might be raycasting issues, so I disabled one but still no luck. The buttons are in world space in canvas. So, I thought I might not use a canvas but IPointer only works on clickable UI elements. The scene looks like this, star is the clickable button and the borders are a sprite(district). The script attached to the button is using UnityEngine using System.Collections using UnityEngine.UI using UnityEngine.EventSystems Required when using Event data. public class OnHighlighted MonoBehaviour, IPointerClickHandler, IPointerDownHandler required interface when using the OnPointerEnter method. HoldByeach button private GameObject correspondingImage void Start () correspondingImage GameObject.Find(gameObject.name) public void OnPointerClick(PointerEventData pointerEventData) GetComponent lt Image gt ().color new Color32 (36,53,53,255) correspondingImage.GetComponent lt SpriteRenderer gt ().color new Color32 (36,53,53,255) public void OnPointerDown(PointerEventData pointerEventData) GetComponent lt Image gt ().color new Color32 (47,255,0,255) correspondingImage.GetComponent lt SpriteRenderer gt ().color new Color32 (47,255,0,255) |
0 | To split or not to split large 3D objects? I have a fairly simple question for which I'm seeking guidance Should large 3D objects be splitted into smaller ones? By wide, I mean an object that would be as wide as a game level is, below is some mountain, the first picture shows it as a single mesh, the second picture shows it as multiple meshes. Facts I've considered (might be wrong) a large object simplifies the scene hierarchy with less objects in total, but at the same time it might be rendered more often than necessary since it will be considered as visible a large object made out of smaller objects makes the scene hierarchy more bloated, but at the same time on a performance aspect is better since only visible parts of it by the camera will be rendered, the rest being culled Note, these objects aren't complex by today standards, that mountain is less than 1K triangles and a complete level is likely to be less than 30K triangles. Ideally, I would like to have the least amount of objects in the scene hierarchy to keep it simple, but at the same time I am wondering whether or not over simplifying the level might put extra problems on the table I haven't thought about. |
0 | How to select parent of currently selected object? When i select an object, i can't find a function to select its parent. Does this basic feature exist ? I want to select the parent of selected object and then step up to find parent of parent so on without using the hierarchy window. |
0 | Creating Unity Handles without any visible game objects at given regions I am trying to create handles without any visible game objects. The image below from a sample scene shows rects (top left rect is at position ( 2, 4), size is (1, 1)) of the handles I want to appear when the mouse is hovered over the rectangular areas. So basically in a scene with no game objects I want to be able to hover over with the mouse to show the squares below as handles. I believe the issue is most likely with the Raycast in UpdateHandlePosition(). The handles only appear when there are objects on the screen and they appear at the wrong places. Please see the relevant code below. static void UpdateHandlePosition() if( Event.current null ) return Vector2 mousePosition new Vector2( Event.current.mousePosition.x, Event.current.mousePosition.y ) Ray ray HandleUtility.GUIPointToWorldRay( mousePosition ) RaycastHit hit if( Physics.Raycast( ray, out hit, Mathf.Infinity, 1 lt lt LayerMask.NameToLayer( "Default" ) ) true ) Vector3 offset Vector3.zero if( EditorPrefs.GetBool( "SelectBlockNextToMousePosition", true ) true ) offset hit.normal CurrentHandlePosition.x Mathf.Floor( hit.point.x hit.normal.x 0.001f offset.x ) CurrentHandlePosition.y Mathf.Floor( hit.point.y hit.normal.y 0.001f offset.y ) CurrentHandlePosition.z Mathf.Floor( hit.point.z hit.normal.z 0.001f offset.z ) CurrentHandlePosition new Vector3( 0.5f, 0.5f, 0.5f ) static void DrawHandlesCube( Vector3 center ) Vector3 p1 center Vector3.up 0.5f Vector3.right 0.5f Vector3.forward 0.5f Vector3 p2 center Vector3.up 0.5f Vector3.right 0.5f Vector3.forward 0.5f Vector3 p3 center Vector3.up 0.5f Vector3.right 0.5f Vector3.forward 0.5f Vector3 p4 center Vector3.up 0.5f Vector3.right 0.5f Vector3.forward 0.5f Vector3 p5 center Vector3.up 0.5f Vector3.right 0.5f Vector3.forward 0.5f Vector3 p6 center Vector3.up 0.5f Vector3.right 0.5f Vector3.forward 0.5f Vector3 p7 center Vector3.up 0.5f Vector3.right 0.5f Vector3.forward 0.5f Vector3 p8 center Vector3.up 0.5f Vector3.right 0.5f Vector3.forward 0.5f You can use Handles to draw 3d objects into the SceneView. If defined properly the user can even interact with the handles. For example Unitys move tool is implemented using Handles However here we simply draw a cube that the 3D position the mouse is pointing to Handles.DrawLine( p1, p2 ) Handles.DrawLine( p2, p3 ) Handles.DrawLine( p3, p4 ) Handles.DrawLine( p4, p1 ) Handles.DrawLine( p5, p6 ) Handles.DrawLine( p6, p7 ) Handles.DrawLine( p7, p8 ) Handles.DrawLine( p8, p5 ) Handles.DrawLine( p1, p5 ) Handles.DrawLine( p2, p6 ) Handles.DrawLine( p3, p7 ) Handles.DrawLine( p4, p8 ) |
0 | Unity Direct Compute Setting a struct of arrays The NVIDIA Direct Compute programming guide lists some best practices for memory management on the GPU. One tip they give on page 8 ("Structured Buffers") is to use a 'structure of arrays' (SOA) layout rather than the typical 'array of structures' (AOS) one struct Particle float4 position float4 velocity RWStructuredBuffer lt Particle gt particles vs struct Particles RWStructuredBuffer lt float4 gt position RWStructuredBuffer lt float4 gt velocity Particles particles (At least, as far as I understand) AOS layout seems to be the most popular (maybe even only) way to manage lists of stuff in the compute shader. I haven't found a way to implement SOA from the CPU side, Unity's ComputeShader.cs doesn't have a set struct function or similar. Does Unity expose a way to set SOA structs from the CPU side at all? |
0 | How can I trigger to start timeline using distance and not OnTriggerEnter Exit? using UnityEngine using UnityEngine.Playables public class GenericTrigger MonoBehaviour public PlayableDirector timeline Use this for initialization void Start() timeline GetComponent lt PlayableDirector gt () void OnTriggerExit(Collider c) if (c.gameObject.tag "Player") timeline.Stop() void OnTriggerEnter(Collider c) if (c.gameObject.tag "Player") timeline.Play() The idea is to create some kind of cut scene. Once the player (First person, in the screenshot i'm just showing the door on the left where the player will come from and the soldiers ) exit the door on the left and is in a specific distance from the soldier the first soldier the closet one will start moving to the player. Later I will make that it will change to close up view on the soldier with some text conversion. That's the main goal. But the script the original script by the unity tutorial is using triggers. I'm not sure if I should using this way or using somehow by calculating the distance between the player and the soldier to start the timeline ? And how to do it. After the soldier is moving walking to the player at some point I will make it to change to a close up view on the soldier with blurry background something like this But first how should I approach to the triggering part ? |
0 | Unity 5 Time Remaining displaying in scene but not in Game I'm currently learning game development in Unity from this course on Lynda.com. Currently I'm trying to displaying the time remaining in the game after it has been set to 5 minutes initially. When I look at the scene, I can see the text for the timer displayed in the top left corner of the canvas, but when I run the game, I'm not seeing it at all. I made a script for a game manager which is derived from a Singleton class. The game manager contains a private variable (and an accessor method) for the time remaining. I have another script that accesses the value for the time remaining and displays it on screen. In the Unity editor, I added a UI game object for the text box and then added the text box to the GUI representation of the timer label attribute. It seems like everything should be working but since I'm still very new to this, I'm probably missing something simple. Here is the code for both scripts GameManager.cs public class GameManager Singleton lt GameManager gt private float timeRemaining public float TimeRemaining get return timeRemaining set timeRemaining value private float maxTime 5 60 In seconds. Use this for initialization void Start () TimeRemaining maxTime Update is called once per frame void Update () TimeRemaining Time.deltaTime if(TimeRemaining lt 0) Now Deprecated Application.LoadLevel(Application.loadedLevel) SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex) TimeRemaining maxTime UpdateUI.cs public class UpdateUI MonoBehaviour SerializeField private Text timerLabel Use this for initialization void Start () Update is called once per frame void Update () timerLabel.text FormatTime(GameManager.Instance.TimeRemaining) private string FormatTime(float timeInSeconds) return string.Format(" 0 1 00 ", Mathf.FloorToInt(timeInSeconds 60), Mathf.FloorToInt(timeInSeconds 60)) EDIT Canvas Settings in the inspector Image of the Time Remaining displayed in the scene |
0 | Agent trying to reach same position as other agents, instead start spinning in place I create units in my game and have a rally point where they should walk to when created, like Age of Empires. My problem is that since they compete for this position after a while, sometimes they end up doing this https gfycat.com decentquestionableandeancondor https gfycat.com densehonoredgalapagosalbatross As you can see one of the guys cant reach the rally point, so he starts rotating. I realize this has to do with stopping distance, but no matter how high I set the stopping distance this eventually becomes a problem when there are many enough units. And if I set it too high they dont walk to the rally point at all, since its not THAT far from the building they spawn from. Is there any way to manage this scenario? i.e just making him go as close as he can, and then stop? My AI Script using UnityEngine using UnityEngine.AI RequireComponent(typeof(NavMeshAgent)) public class BaseAi MonoBehaviour HideInInspector public NavMeshAgent agent HideInInspector public NavMeshObstacle obstacle float sampleDistance 50 Transform mTransform private void Awake() agent GetComponent lt NavMeshAgent gt () obstacle GetComponent lt NavMeshObstacle gt () mTransform transform private void Start() agent.avoidancePriority Random.Range(agent.avoidancePriority 10, agent.avoidancePriority 10) void LateUpdate() if (agent.isActiveAndEnabled amp amp agent.hasPath) var projected agent.velocity projected.y 0f if (!Mathf.Approximately(projected.sqrMagnitude, 0f)) mTransform.rotation Quaternion.LookRotation(projected) lt summary gt Returns true if the position is a valid pathfinding position. lt summary gt lt param name "position" gt The position to sample. lt param gt public bool SamplePosition(Vector3 point) NavMeshHit hit return NavMesh.SamplePosition(point, out hit, sampleDistance, NavMesh.AllAreas) public bool SetDestination(Vector3 point) if (SamplePosition(point)) agent.SetDestination(point) return true return false public void Teleport(Vector3 point) agent.Warp(point) lt summary gt Return true if agent reached its destination lt summary gt public bool ReachedDestination() if (agent.isActiveAndEnabled amp amp !agent.pathPending) if (agent.remainingDistance lt agent.stoppingDistance) if (!agent.hasPath agent.velocity.sqrMagnitude 0f) return true return false public void ToggleObstacle(bool toggleOn) agent.enabled !toggleOn obstacle.enabled toggleOn void OnDrawGizmos() if (agent null) return if (agent.path null) return Color lGUIColor Gizmos.color Gizmos.color Color.red for (int i 1 i lt agent.path.corners.Length i ) Gizmos.DrawLine(agent.path.corners i 1 , agent.path.corners i ) |
0 | Unity Assets folder is empty after opening package from the asset store I downloaded the following Survival Shooter Tutorial from the Asset Store https www.assetstore.unity3d.com en ! content 40756 I was prompted to open it in Unity so I did and began following this tutorial https www.youtube.com watch?v lP6epjupJs I am only 2 minutes into the first video and am stuck. In the tutorial there are lots of folders in the assets folder. I took a screenshot of what my screen looks like to show that it is empty. |
0 | How to run different animations with same suffix for different public objects? I would like to be able to run the corresponding animation (ending with "Get" in the title) for whatever item GameObject I plug into this treasurebox. I made 2 prefabs for "item get" animations today. Both GameObjects consist of 3 sprites The image representing the item, and 2 lightray images that I enable disable in alternation to get a halo effect (see animation below). You can see the 2 prefabs and their corresponding animation components in the Project panel These next two images show how similar the animations are they even both require two of the same sprites, flareA and flareB. Here is the code I am currently using to set the state of the ItemBox GameObject and run the animations. You can see that while the itemGet prefab is public (that is, I can plug in whatever gameobject I want in the editor), line 27 explicitly calls for the animation belonging only to the turd item. using System.Collections using System.Collections.Generic using UnityEngine public class ItemBox MonoBehaviour bool disabled false private Animator anim public GameObject itemGet null void Start() anim GetComponent lt Animator gt () if (!disabled) anim.Play("ItemBoxIdleState") void OnTriggerEnter (Collider other) if (!disabled amp amp other.gameObject.tag "Player") anim.Play("ItemBoxGetItemState") GameObject itemClone Instantiate(itemGet, transform.position new Vector3(0, 0.375f, 0), Camera.main.transform.rotation) itemClone.GetComponent lt Animator gt ().Play("turdGet") Destroy(itemClone, 1.6f) disabled true How can I change line 27 (the line before 'Destroy') so that it runs the appropriate " Get" animation for whatever itemGet object I plug into the inspector? I think I am already close. I intend to make more items (not too many for now) and the animation I want to play will always be structured like "Get". UPDATE 07 29 19 I tried making a public AnimationClip object in the ItemBox script and putting that name in quotes for line 27 and thw script still works, but now I get an index error saying the animation state was not found. I don't think I can plug the name of the public variable into the .Play("") quotes and make it work I think it only worked because there is only one animation for that item anyway. I ended up removing this new variable and just keeping the .Play("") part as empty quotes and it still works. I might decide to add more animations to these item objects later so I still need to know how to specifically play the animation that ends in "Get". |
0 | Play two different audio sources depended on code behind How can I play two different audio clips in Unity depended on the code behind? Into my object I've added two audio sources namely 'Player GunShot' and 'outOfAmmo'. Into the same object I've also added a C script whit this code public currentBullets 1 private AudioSource gunAudio private AudioSource outOfAmmo void Awake() gunAudio GetComponent lt AudioSource gt () outOfAmmo GetComponent lt AudioSource gt () void Update() if (currentBullets 0) outOfAmmo.Play() else gunAudio.Play() Can this code give any problems because in the Awake methode? I've not defined with audio source the variable must be. So which source go he take to play? |
0 | How do I know the data has arrived at server without requesting every frame of the game? I have a game where I have to get data from the server but the problem is I don't know when the data will become available on server. So I decided to use co routine and hit server at after specific time or on every frame. But certainly this is not the right, scale able and efficient approach. Now my question is that how do I know that data has arrived at server so that I can use this data to run my game. Or how should I direct the back end team to design the server in an efficient way that it responds efficiently. Our back end team currently uses REST Web services with JSON with Python. And they want to push data to my unity player without my frequent requests. |
0 | Unity c Interface object never equals null I've created an interface class for some mechanic I'm using to interact with things in my game. Now, I noticed that checking if that value is null never returns true. Here's a screenshot of where this happens The error I get is the following MissingReferenceException The object of type 'InteractiveItem' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. InteractiveItem.CurrentGameObject () (at Assets Scripts Interactive InteractiveItem.cs 10) Interactive.ManualStopInteract () (at Assets Scripts Interactive Interactive.cs 30) The line where this fails is if (IsInteracting() amp amp this.interacting.CurrentGameObject().GetComponent lt InteractiveUtilityChest gt () null amp amp !MainReferences.UIReferences.IsAnyMenuWindowOpen()) do something The IsInteracting() check is for some reason returning true here because the last line (InteractiveItem.cs 10) is in the method interacting.CurrentGameObject() I don't get how this can happen or how I should solve it. As far as I know, an interface is a nullable type. |
0 | Follow behaviour with transform.LookAt on Unity2d So i've been trying to make an enemy follow my player on Unity2d using transform.LookAt. While it does follow the player, It also rotates the enemy as well in 3D but my sprite is made for 2d so the sprite just vanishes. Any ideas? follows player transform.position Vector2.MoveTowards(transform.position, target.position, speedEnemy Time.deltaTime) make enemy look towards player transform.LookAt(target) |
0 | Unity add InputTracking to my script I'm new to unity and 3D world developement so I'm following Unity's tutorial for beginners right here. And I'm in the section with title "Camera Nodes" where they gave me a c script to attach it to the camera object. I did attach it to the camera but the problem with the script when I debug it I get an error of undefined class The name 'InputTracking' does not exist in this context And this is the script using System.Collections using System.Collections.Generic using UnityEngine public class UpdateEyeAnchors MonoBehaviour GameObject eyes new GameObject 2 string eyeAnchorNames "LeftEyeAnchor", "RightEyeAnchor" Use this for initialization void Start () Update is called once per frame void Update () for (int i 0 i lt 2 i) If the eye anchor is no longer a child of us, don't use it if (eyes i ! null amp amp eyes i .transform.parent ! transform) eyes i null If we don't have an eye anchor, try to find one or create one if (eyes i null) Transform t transform.Find(eyeAnchorNames i ) if (t) eyes i t.gameObject if (eyes i null) eyes i new GameObject(eyeAnchorNames i ) eyes i .transform.parent gameObject.transform Update the eye transform eyes i .transform.localPosition InputTracking.GetLocalPosition((VRNode)i) the error is this line eyes i .transform.localRotation InputTracking.GetLocalRotation((VRNode)i) and this one This is the link of the class InputTracking in Unity's API, but I don't know how to add it to my script ) Thanks in advance. |
0 | how are semantics used when declaring a struct? I don't understand how semantics are used in shaders. While reading Unity's shader tutorials, I come across this struct v2f float worldPos TEXCOORD0 half3 worldNormal TEXCOORD1 float4 pos SV POSITION and also this struct v2f float3 worldPos TEXCOORD0 half3 tspace0 TEXCOORD1 half3 tspace1 TEXCOORD2 half3 tspace2 TEXCOORD3 float2 uv TEXCOORD4 float4 pos SV POSITION Microsoft's documentation says A semantic is a string attached to a shader input or output that conveys information about the intended use of a parameter. I know there is some kind of interpolation of data because vertices and pixels aren't one to one, thus I think semantics are used for telling the graphics library what to do about the data. But here it uses TEXCOORDX for things like world position and tangent space vectors. They don't seem to have anything to do with UV coordinates. So how are these semantics actully used? |
0 | How can I make the gun rotate and shoot like lost control and shooting all around? The shooting part I will make later. Now I'm trying to make the rotations part. The first thing I did is to rotate the gun barrel and this is working fine. The next thing I want to do is to rotate the gun body 360 degrees randomly so when the gun will shoot it will shoot randomly all around like lost control. This is a screenshot of the gun barrel And the gun body By rotating the gun body 360 degrees randomly I want to create a lost control effect so it will shoot all around hitting randomly. The script is attached to the top parent Drone using System.Collections using System.Collections.Generic using UnityEngine public class Rotate MonoBehaviour public Transform wings public Transform propellers public Transform gunBarrel public Transform gunBody public float propellersSpinSpeed 50 public float wingsSpinSpeed 50 public float gunBarrelSpeed 50 private float angle 360.0f Start is called before the first frame update void Start() Update is called once per frame void Update() for (int i 0 i lt propellers.Length i ) propellers i .Rotate(0, propellersSpinSpeed Time.deltaTime, 0) for (int i 0 i lt wings.Length i ) wings i .Rotate(0, wingsSpinSpeed Time.deltaTime, 0) gunBarrel.Rotate(0, 30 gunBarrelSpeed Time.deltaTime, 0) gunBody.Rotate(Vector3.zero, angle Time.deltaTime 1.0f) I tried to do gunBody.Rotate(Vector3.zero, angle Time.deltaTime 1.0f) But it does nothing not rotating it 360 degrees and I didn't use yet the Random. The gun barrel keep rotating but the lost control shooting all around is not working yet not sure how to do it. Update This is the current code using System.Collections using System.Collections.Generic using UnityEngine public class Rotate MonoBehaviour public Transform wings public Transform propellers public Transform gunBarrel public Transform gunBody public float propellersSpinSpeed 50 public float wingsSpinSpeed 50 public float gunBarrelSpeed 50 Start is called before the first frame update void Start() Update is called once per frame void Update() for (int i 0 i lt propellers.Length i ) propellers i .Rotate(0, propellersSpinSpeed Time.deltaTime, 0) for (int i 0 i lt wings.Length i ) wings i .Rotate(0, wingsSpinSpeed Time.deltaTime, 0) gunBarrel.Rotate(0, 30 gunBarrelSpeed Time.deltaTime, 0) gunBody.localEulerAngles new Vector3(Mathf.Clamp(gunBody.localEulerAngles.x, 0f, 90f), 0, 0) The gunBody is now facing down. This is a screenshot of what I want the gunBody to do I changed the gunBody on X and Z rotations a bit and this is the behaviour I want it to do randomly rotating on X and Z but not to pass too much up down and left right degrees. The Z to be in range more or less 150, 205 and the X range of 55,100 And make it moving smooth randomly on this ranges. I'm not sure to the float point if those are the ranges but more or less this is what I mean by randomly moving in circles 360 degrees shooting all around like lost control. Same behaviour of a turret trying to shoot on target and rotate 360 degrees in any direction the same thing here but only looking forward not backward. This is the logic I mean moving in circles and shooting around to the front. |
0 | How do set a layer on an ECS entity? I'm using Unity ECS entities to draw out some tiles. I would like to determine the layer (or sortOrder) of the rendered tile so that if a tile is placed over another at the same position, the tile with the higher layer value will be visible. It appears random at the moment. I tried entityManager.SetSharedComponentData(entity, new RenderMesh mesh mesh, material mat, layer level ) But it didn't seem to do anything. |
0 | Coroutine wrong Behavior when scene is loaded. Ok so I have this coroutine IEnumerator ShowCharTraits() while(!hasPlayerChosen) yield return null traitPanel.SetActive(true) hasPlayerChosen false traitPanel.SetActive(false) Debug.Log("Got called! job done") It's being called like this from the awake method in my GameManager players GameObject.FindGameObjectsWithTag("Player") foreach (GameObject g in players) ui Controller.StartShowCharTraits() g.GetComponent lt PlayerToken gt ().isTurn false StartShowCharTraits() is a simple method that does this public void StartShowCharTraits() StartCoroutine("ShowCharTraits") Now, I have checked the tags, no null reference exception, actually no errors or warnings are being thrown. If i load the scene in the editor and then play it everything works fine. traitPanel.SetActive(true) get called and my panel shows up. However when I load my scene from another scene using SceneManager.LoadScene(1) the above mentioned line is never reached. Any ideas why this is happening ? |
0 | Moving the rendered object the projection perspectives based on an AR marker I saw this video and now I am trying to making it. I have used Vuforia AR Camera Pulgin, and so far tracked the image on a marker but the problem is getting the four projections of the 3D object on a screen. Here is an example of what it looks like. I have used Viewport Rect method with four cameras but that does not seem to change the projections as I move the marker. |
0 | How can I make an infinte terrain with object pooling in Unity? I am currently making a 3D endless runner game in unity in C . I now need to make the platform(3D Tiles) infinite but I don't know how. I already did some research but I don't find the right tutorial. I already asked a similar question and I got the answer that I need to do it with object pooling but I don't find any good tutorial for object pooling. Does someone know how to make an infinite terrain with object pooling in unity? Thanks using System.Collections using System.Collections.Generic using UnityEngine public class TerrainScript MonoBehaviour public GameObject tilePrefabs public Transform playerTransform private float spawnZ 4500.56f private float tileLength 2.0f private int amtOfTilesOnScreen 2 void Start() for (int i 0 i lt amtOfTilesOnScreen i ) SpawnTile(0) void Update() if (playerTransform.position.z gt (spawnZ amtOfTilesOnScreen tileLength)) SpawnTile(0) private void SpawnTile(int prefabIndx 0) GameObject go go Instantiate(tilePrefabs prefabIndx ) as GameObject go.transform.SetParent(transform) go.transform.position Vector3.forward spawnZ spawnZ tileLength |
0 | How to program (architecturally organize) a set of customizable changes to a game? The floor of my game (tower defense) is composed by a set of cubes. I wish to change these on some of the waves. I have a list of the changes that need to be made on each wave in a floorController class. However, in order to decide which floor cubes should appear or disappear on each round, I had to assign each cube a bool for each wave (if this is set to true the floor changes in that wave). However this process is tedious and not ease to change and customize in order to experiment with the level. From an architectural programming perspective how can I better structure this system? |
0 | Unity GUITexture or GUIText not showing up Currently I've got a little 2.5D platformer with the camera tracking the player. Now when I go to insert a GUITexture or GUIText game object into the scene, it comes up absolutely fine in the Editor view, but when I go to play it there's absolutely nothing to be seen! At first I thought it may have been a script I was using on the GUI, but I've tried it out with a completely bland GUITexture object that has no interaction with the rest of the game and I still get the same effect. I'm wondering if my camera is messing it up somehow, but I assumed that all GUI objects are drawn to screen space and just stay with the camera. I've been really stuck for the past few hours so if any one could offer some insight, I'd be very, very grateful! Ray |
0 | Why does my gameobject fly of into the air when the screen is touched? I am encountering a peculiar problem when updating a piece of code that translates my gameobject left and right based on mobile touch input. To provide context, the platform upon which the gameobject, which is a sphere in my case, translates, is this The platform is 10 units wide, with the sphere in the center. In its original form, the code looks like this void FixedUpdate () if(Input.touchCount 1) float touchXComponent Input.GetTouch(0).deltaPosition.x transform.Translate(Vector3.right Time.smoothDeltaTime touchXComponent 0.5f) It provides the desired left and right movement, but it has a tendency to allow the ball to leave the platform, and then start moving up and down in the air with each further touch. To combat that, I tried editing the code as follows void FixedUpdate() if (Input.touchCount 1) float touchXComponent Input.GetTouch(0).deltaPosition.x transform.Translate((Vector3.right Time.smoothDeltaTime touchXComponent 0.5f).x, transform.position.y, transform.position.z) This, however, causes the ball to fly of the screen the second it is touched, leaving me with this error in the console Assertion failed Invalid worldAABB. Object is too large or too far away from the origin. I would have thought that the update I made to the code would keep the ball stationary on the y and z axes, while allowing it to translate freely on the x axis. Why is that not the case? Thank you. |
0 | How to return the scene view camera to the default view By the quot scene view camera quot I don't mean a GameObject with a Camera component, I mean the camera used to draw the Scene window in the Unity editor, controlled by this quot Scene Gizmo quot widget The default view shows an almost isometric perspective, where all three X Y Z axes are visible. But when I clicked the green Y cone, my view changed to look straight down the Y axis, and I can't seem to return to the 3 axis view. Clicking the other cones on this widget just switchest to look along the X or Z axis instead, and clicking the cube in the middle or the quot Top quot label just toggles between orthographic and perspective projection. How can I get back to the default 3 axis view? |
0 | Movement in grid in Unity I am a beginner at Unity. I want to make a game like Lightbot, but in 2d (without the z axis movement) with some obstacles. Before making the function system of the Lightbot, I want to make the in game character move on a grid by the set of key inputs (e.g. WASD) by the player. But I'm stuck here. I searched on Tilemap which makes a grid, but I have no idea how to save the set of input keydowns and move my character on this grid at once. Suppose my character is on the (0, 0) square for example. After the player taps WWDD, then my character should move to the following squares, in the following order (0, 1) (0, 2) (1, 2) (2, 2) How can I achieve my goal? |
0 | Would landscape left right make difference when developing Google VR CardBoard Game with Unity? I'm trying to make a simple VR cardboard game using Google VR SDK for Unity. I'm really confused about the problem as my title. Will the values got from GvrViewer.Instance.HeadPose.Orientation.x change when the orientation of smartphone change from Portrait to Landscape Left Right? The following code works in Unity demo (after press play button and use alt right click to trigger head movement simulation), but I don't have a cardboard so I'm not sure whether it will still work on smartphone with landscape left or right attached to a cardboard. private void Update() forward if the value is positive. float forwardValue GvrViewr.Instance.HeadPose.Orientation.x turn left if the value is negative. float turnValue GvrViewr.Instance.HeadPose.Orientation.y private void Move() Vector3 movement transform.forward forwardValue m Speed Time.deltaTime Apply this movement to the rigidbody's position. m Rigidbody.MovePosition(m Rigidbody.position movement) private void Turn() Determine the number of degrees to be turned based on the input, speed and time between frames. float turn turnValue m TurnSpeed Time.deltaTime Make this into a rotation in the y axis. Quaternion turnRotation Quaternion.Euler(0f, turn, 0f) Apply this rotation to the rigidbody's rotation. m Rigidbody.MoveRotation(m Rigidbody.rotation turnRotation) |
0 | How do I convert distance covered from meters to kilometers, in Unity? I am developing a game in Unity where I have to find a distance in kilometers, to find a passenger's fare based on the covered distance. This is what I have tried private Vector3 previousPosition public float cumulatedDistance void Awake() initialize to the current position previousPosition transform.position Update is called once per frame void Update () cumulatedDistance (transform.position previousPosition).magnitude previousPosition transform.position How can I determine the distance covered, and convert it to kilometers? |
0 | Is Godot's NavMesh viable for dynamic pathfinding (e.g. avoiding moving enemies)? I am a novice (read low budget) designer looking at moving from Pygame to a real engine, and between Unity and Godot it looks like the latter has a much better 2D engine 1, 2, 3 . I would be happy to support Godot's open source model except that, as far as I can tell, its built in navigation mesh is purely static i.e. it can't update its path to account for dynamic obstacles 4, 5 while Unity's pathfinding system can 6 . So my question is Am I "stuck" with Unity? Or is there functionality that I haven't yet been able to find? Or, alternatively, is GDScript significantly faster than Python such that basic algorithms like fixed grid A would do the job? Edit By "stuck" with Unity I don't mean that it's a bad option or that there aren't good options I mean, 'if I need good pathfinding, do I have to give up on Godot and use what would otherwise be a second choice engine?' |
0 | Unity, OnMouseOver blocked by another gameobject with a collider in front of it I have two gameobjects, both with 2D colliders. One of them can be behind the other, and because of this its OnMouseOver can be blocked from firing as the GameObject in front blocks it from triggering. What is a way around this? I really like the ease of using OnMouseOver, and would rather not use raycastAll. Asked this question on SO, maybe it should be asked here. |
0 | How to use MaterialPropertyBlocks to randomly change the color of multiple materials on an object? I have a character prefab for a civilian with 5 materials. Each one should be a random color but I don't want a new material for every civilian in the game. I asked a question earlier and had a good answer. However I was pointed towards this question with MaterialPropertyBlocks. This is the code I currently have void Start () Color newShirtColor shirtColor Random.Range(0, shirtColor.Length) MaterialPropertyBlock props new MaterialPropertyBlock() props.AddColor(" Color", newShirtColor) GetComponent lt SkinnedMeshRenderer gt ().SetPropertyBlock(props) It works really well but the color is assigned to the whole mesh. How can I do this for each of the 5 materials on the object so that it only changed the color for the assigned parts of the mesh, with only one material for each section? |
0 | Switching between world and battle scene with no or minimum loading? I am making a strategy game where the player roams a grid map. When the player encounter enemy on the map he is transferred to a quot battle quot scene where two armies are fighting in turn based battle. Imagine Heroes 3 like game. My question is Should I load the battle scene in additive mode and temporary hide the quot world map quot and when the battle is finished to just show the quot world map quot and hide the quot battle quot scene? Or i should unload the world scene and load the battle scene, and when the battle is over gt unload the battle scene and load the world scene ? I think the 1st approach will give me less loading time between the two scenes, but will require more RAM ? Second approach is standard one, but i will have loading between the scenes ? My idea is to have no or minimal loading between battle and world scenes. What do you guys thing ? Did you know what is the best practice in this case ? By the way, i am using Unity as a engine. |
0 | How to make a changeable color constant for editor materials? Due to the nature of a project I'm working on, the models I got have a bunch of redundant materials on them. I have to fiddle around with some of the colors, but every time I want to change the colors, I have to change each material to the exact same color. Is there any way to declare some kind of swatch that I can change and have those changes just apply to the materials or anywhere else? For instance, in code, you'd just make a readonly Color mainColor, that you'd use wherever you need and could change at will. I'm looking for this kind of behavior in the editor itself. |
0 | Rigidbody2D loses speed on collisions I'm trying to create a simple Breakout style game. In my game, the ball strikes a paddle that moves with the player's mouse. Depending on the position of the strike, the ball changes its direction. This allows the player to aim the ball. The problem I'm having is that each time I set the position, the ball loses velocity. I've tweaked every Physics2D setting I could find, but I'm not seeing any changes. Here's what my Ball class looks like using System.Collections using System.Collections.Generic using UnityEngine public class Ball MonoBehaviour public float initialVelocity public float collisionAngleRange public Paddle paddle private Rigidbody2D body public void Start() body GetComponent lt Rigidbody2D gt () body.velocity VectorUtilities.AngleToVector2(135) initialVelocity When colliding with the paddle, use the position of the strike to adjust the ball's position. public void OnCollisionEnter2D(Collision2D collision) Ignore the object if it's not the paddle. if (!collision.gameObject.CompareTag("Paddle")) return Get the collision coordinates Bounds bounds collision.gameObject.GetComponent lt BoxCollider2D gt ().bounds float left bounds.min.x float right bounds.max.x Vector2 contact collision.contacts 0 .point Interpolate the contact point and determine the angle. float interpolation (contact.x left) (right left) float angle 90 collisionAngleRange 2 collisionAngleRange (1 interpolation) Change the direction of the ball without affecting its speed. body.velocity VectorUtilities.AngleToVector2(angle) body.velocity.magnitude Log what's happening with the velocity Debug.Log(body.velocity.magnitude) The VectorUtilities class looks like this using UnityEngine A set of utility methods and extensions for Vector2 and Vector3. public static class VectorUtilities public static Vector2 AngleToVector2(float degrees) return new Vector2(Mathf.Cos(degrees Mathf.Deg2Rad), Mathf.Sin(degrees Mathf.Deg2Rad)) Here are my Ball game object's Rigidbody2D and CircleCollider2D settings The paddle's settings The material settings Physics2D settings I recognize I could solve this problem by multiplying the ball's normal vector by my desired speed, but it's more important to me to understand why this is happening and to fix the underlying problem. Why does the ball lose speed on every collision, and how can I prevent that from happening? |
0 | Screen Space vs World Space Canvas When should I use one over the other? I'm pretty sure I understand the key differences, but I'm not sure which use cases would prefer one over the other. For example, let's say I have objects on the ground in my 3D game and they have UI Images above them with the objects' names. Which method is better? Should I stick to world space for objects which are located in the 3D world and screen space for overlay type stuff? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.