_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | Create and serve AssetBundle at runtime What I am developing is not a game, but is done in Unity3d, so I believe here is a good place to ask. Context The unity application runs in the WebPlayer inside a web application Case User uploads a file on the website Webserver processes the file, does conversion and business stuff. Ends up with a DAE(Collada) file The DAE file that has been generated on the server needs to be loaded and shown in the Web player inside the browser of the one who uploaded it Now, I am not very well versed in Unity, so I just want to lay out what I expect to do, and then hope to get feedback on whether that is smart, or whether there is a better approach. So starting from top down, here's my thinking In order for the Web Player to find the file and use it as an asset, it should be an AssetBundle, which I can load with UnityWebRequestAssetBundle.GetAssetBundle that shouldn't be much trouble. If the AssetBundle is stored somewhere that the web app can serve it, I expect that to just work? I see in docs that Unity can load "AssetBundles from the project folder", but I don't expect that "project folder" is part of the game when loading from a URL. How would it? In order to generate the AssetBundle, I would need to have a Unity application running on the server (a headless build of unity), which would pick up the generated DAE file and use BuildPipeline.BuildAssetBundle to create the AssetBundle and store it where the web app can serve it The communication between browser, unity web player, web app server, and unity server instance is something I can manage on my own. I can work with sockets and jslibs to sort out my needs, so that doesn't need to be described here Instantiating the GameObject after loading the AssetBundle into the Web Player, I expect to be simple, just following the docs for the AssetBundle Extra credit Sources for how to do the headless unity instance would be great. Sort of like a game server, but not really caring about clients connecting, but rather working with the filesystem on the server |
0 | Where how do I store configuration files in Unity development? I am transitioning from working with cocos2d iphone to Unity. One particular thing I loved were the .plist files you could easily put any sort of configuration data you wanted for game levels, stats, etc. Now, with Unity, I am not entirely sure if I am supposed to be using such files. I suppose I can, but I'd rather adapt myself to whatever Unity developers use. What is the equivalent to property list files in Unity development? Plain text files? |
0 | Position and rotate a 2D point array into a 3D world I have a set of 2D points (defining a flat 2D 'connect the dots' shape). I want to calculate the 3D positions for these 2D points at a specific 3D position and rotation. For example, say I have five 2D points forming the shape of a 2D hexagon. I want to place this hexagon shape at a specific location in my 3D world, at a specific rotation. I need to calculate new 3D coordinates for each of the 2D points. If it matters, the 2D points will center around (0,0). What magic formula do I need to do to accomplish this translation? Is there a built in method (in Unity) to do this? Each point will be perpendicular to the rotation angle direction, so will I need to calculate the cross product? Then somehow use this to remap each 2D point? I should have paid more attention to this in school, all those years ago (I can't even remember if I actually learned this before!). Any help will be appreciated. Thanks. Here's some basic code to illustrate Vector3 position Where in 3D to place the 2D shape Quaternion rotation What 3D rotation to apply to the 2D shape. Should be a Vector3? Vector2 shapeIn List of 2D points defining shape Vector3 shapeOut List of updated 3D points at its new position and rotation shapeOut new Vector3 shapeIn.Length for (int p 0 p lt shapeIn.Length p ) shapeOut p MagicFormula(shapeIn p ) |
0 | How to delete a score after collecting all collectibles I'm making a small game for my English class, and in the beginning, you have to collect rocks. I already have the code for counting how many rocks have been picked up, and the GUI to display while the game runs. After the player collects all 9 rocks I would like for the GUI to disappear or delete itself since it won't be used anymore throughout the game, and for new text to appear at the top of the screen saying "Go To The Lottery" I'm still very new to Unity so posting the code, and then following up with a brief explanation as to what does what would be majorly appreciated (but not at all demanded) Both codes are in JavaScript pragma strict static var currentScore int 0 var offsetY float 40 var sizeX float 100 var SizeY float 40 function OnGUI () GUI.Box (new Rect (Screen.width 2 sizeX, offsetY, sizeX, SizeY), "Rocks Collected " currentScore) This is my GameMaster script, which is in a empty game object galled " GM" pragma strict function OnTriggerEnter (info Collider) if (info.name "Player") GameMaster.currentScore 1 Debug.Log ("Picked stone up") Destroy (gameObject) This is my RockCollection script and it's what actually tells the GameMaster script to add 1 to the score and then delete the rock so you can't continuously pick it up |
0 | Wheels not facing right direction when car faces different directions I am creating a real time multiplayer driving game in Unity. I am using google play's real time multiplayer service. I am having an issue where the wheels of the cars that are over the network are not facing the right direction. What I am currently trying to do is just add the calculated steering angle to the current rotation of that particular player's car, but for some reason the wheels face the wrong way and rotate incorrectly if the car is facing certain directions. Logically I thought what I have is correct. Basically for each wheel I use this code car.transform.rotation Quaternion.Euler(0, car.transform.rotation.y steerAngle, 0) So I find the rotation of that car and then I add the steer angle to it. Why wouldn't this work? |
0 | How can I implement UI in Unity using Chromium? I'm looking for an alternative to UI Builder. Ideally I'd like to have basically a Chromium instance atop Unity3D which would have its JS calls somehow land in the C (maybe in the quot Update quot loop it listens to a constant stream of potential calls and the parameters will correspond to function names in my Unity code, I don't know) here's what I found which doesn't quite live up to my expectations Unity WebView doesn't support Windows. 3D WebView for Windows and macOS (Web Browser) requires the UI to be served on an actual live URL and for Unity to access it via that URL and for all interaction to be handled via API, impractical or slow at best. PowerUI HTML CSS is interesting, but was made in 2011. The documentation is all gone. the support for css feature is probably incredibly slim. Embedded Browser looks pretty good, but I'm unsure that it could be bent into a UI system. I want it to frame my game, not to cover it. Coherent Gameface looks probably the best, although the CSS implementation seems a tad lackluster. Also this project was started in 2012, it's probably carrying very old, very slow code. This Unity forum thread may be relevant. Chromium Embedded Framework was a tool used by some assets on the asset store to create chromium UI but it has been removed. If not using these assets, how can I implement my idea of using Chromium as my UI layer? |
0 | What is the "Unity" way to approach tech design for a 2D game like this? So I come from C land where I've always done every little thing myself. Now I'm getting into Unity and C and I'm ironically overwhelmed with the domain. I'm starting off with this simple little 2D game and I'm wondering... if someone can point me to the correct tools that would lead to a successful implementation of this game. Here is a quick mock up I did in paint These are the parts of Unity I've investigated Tilemap Canvas GridLayout Prefabs GameObjects (these seem fundamental to Unity, heh). After researching these topics, and playing around a bit, here are my initial questions How do you approach Canvases in Unity? I could see this being split into 5 separate Canvases, one for each local body of UI. Or 1 Canvas for the game board, and 1 canvas that contains a single overlay with all of the other UI components. But then how do those components typically get positioned? Is it common practice to place by absolute coordinates? I guess I'm getting hung up on.. how do I place my canvas for the game board in that position relative to all the other UI elements? I'm a C application developer so if I'm doing UI at all I'm used to layout systems. I'm not sure how common that is in this ecosystem. Should I even use TileMap for this? It doesn't seem like I need that kind of power. My grid is finite and fits on screen. My gut reaction is that I should just instantiate a bunch of colored squares at first. But I'm not really sure the best approach to that either. GridLayout on a canvas? Absolute coords? TileMap? What other tools should I be looking at? By tools I mean Unity concepts I didn't mention above. My initial thought is to just have a backing data structure that holds all the data for the grid, and then I just render... prefabs? based on that data? Maybe I just want someone to tell me I'm on the right track or quot no you're doing it totally wrong use this other thing quot , heh. |
0 | How can I play an animation only using C , without animation controller, or create an animation controller at runtime entirely from script? I've been looking around for a while trying to figure out how to play simple animations with Unity via ONLY C script, with no drag and drop involved. So far I've found various tutorials explaining how to manually set up a animation controller for each object, then manually select each animation state and manually create a transition then manually set the transition length to the most minimum possible etc... I was wondering if there's a simple way to just do something like... gameObject.playAnimation( "stand still which would be the name of the action state created in blender or other animation software ", "loop") ...WITHOUT creating an animation controller manually at all, I haven't been able to find any resource to do this simple thing yet. |
0 | How do I determine distance of a point within a ProBuilder mesh? As in the title, I have an effect prepped for my game which applies certain derived parameters to a post processing effect after the player enters a boundary I created with ProBuilder. Finding how far inside the bound the player is that is, how far the player would have to travel, at minimum, to leave it would help me scale this effect. It is not an axis aligned boundary, and its sloped shape is fairly important. Having the effect go full on on crossing the boundary would be jarring to the player. I'm tempted to resort to traditional edge testing with this, but I would like to highlight that it will be done at least once per frame on multiple objects, so I would like to keep it as simple, and non home rolled, as possible. The other possibility would be to keep track of time exposed and scale it by that but this isn't ideal and I'm seriously curious as to whether a penetration depth testing method exists out of box. A requested image of my setup It is laterally symmetric, and that is unlikely to ever need to change. However, future volumes are likely to have varying angles and heights. Depth is more or less irrelevant, as while I'm using 3D, this game has the physics of a 2D platformer so you can consider it to have infinite depth if you need to. As you can see on the right, I've added almost nothing to it, other than the MagneticField.cs custom script (which does not even reference the mesh, only whether it's been crossed) and a debug class, TriangleReport.cs, that I'm working on right now. One thought I had was to get triangles for the top, bottom, left, and right edges, use them to define planes, and then determine the distance from those planes but if you've got something better I am all ears! |
0 | Why don't we assign a class for each gameobject type in unity? I used to create games from scratch with C . There, people would create a "class Bullet", and add functionality to that class so that we can instantiate objects of class Bullet at runtime. However, in Unity (which I'm new to), we need to create a Bullet GameObject in the editor, and then assign "class BulletBehaviourA MonoBehaviour" to the Bullet GameObject. I don't really grasp this logic. Why don't we have a class for the Bullet in Unity? |
0 | Unity game crashing when dialogue with NPC initiated I have 3 NPCs in my "Game". When the player walks up to any of them, they're supposed to have their own dialogue I've tested this, and they do. I tried to create a display that shows this dialogue text using a TextMeshProUGUI attached to a blank GameObject called dialogDisplay (tagged DialogDisplay). There is one DialogDisplay object in the scene that I'm trying to get each of my NPC's to use. I tried to make the display object inactive in the NPC Start() function, and enable it when it's time to display the NPC's next sentence. When I run my game, I get an error on line 21, where SetActive() is called "Object Reference Not Set to an Instance of an Object". Here's the NPC script (DisplayNextSentence() is at the bottom, where dialogDisplay is used) public class NPC Character private bool charInRange public Dialogue dialogue public bool talkedTo false private Queue lt string gt sentences public TextMeshProUGUI textPro public GameObject dialogDisplay private bool isTalking Use this for initialization void Start () charInRange false textPro FindObjectOfType lt TextMeshProUGUI gt () dialogDisplay GameObject.FindGameObjectWithTag("DialogDisplay") dialogDisplay.SetActive(false) Update is called once per frame void Update () if player is in range and presses space, triggers NPC dialogue if (charInRange amp amp Input.GetKeyDown(KeyCode.Space)) TriggerDialogue() if Player gameObject is in NPC collider, player is in range void OnTriggerEnter2D(Collider2D other) if(other.gameObject.tag "Player") charInRange true if player exits NPC collider, player is not in range void OnTriggerExit2D(Collider2D other) if (other.gameObject.tag "Player") charInRange false if NPC has been talked to before, displays next sentence if not, loads dialogue and displays first sentence private void TriggerDialogue() if (!talkedTo) talkedTo true StartDialogue(dialogue) else DisplayNextSentence() loads a queue with lines from Dialogue and displays first sentence public void StartDialogue(Dialogue dialogue) sentences new Queue lt string gt () foreach (string sentence in dialogue.sentences) sentences.Enqueue(sentence) DisplayNextSentence() displays next sentence in the queue public void DisplayNextSentence() string sentence bool done false if last sentence in the queue, display it again if (sentences.Count 1) sentence sentences.Peek() textPro.text sentence Debug.Log(sentence) return sentence sentences.Dequeue() textPro.text sentence dialogDisplay.SetActive(true) while (!done) Debug.Log("In WHile Looop") if (Input.GetKeyDown(KeyCode.A)) done true dialogDisplay.SetActive(false) Grateful for any insight or tips you can provide. Happy to provide further information if it helps. Thank you! |
0 | Unity's "Stats" window displays bizzare number of triangles and vertices In my Unity scene I have 7 8 Barrels (with lids) each at about 2 400 triangles. 4 planes, each at at the very most 200 triangles camera, 3 lights, a FPS controller When I turn on the "Status" button in the lower left view port, it reports "14.1K triangles and 12.k vertices" I've double checked everything, there's no way the elemens in the scene can amount to so many triangles. The barrels in both Blender and Unity report having the number of triangles I've specified above Here's a Blender screen shot And here's one from Unity I've also checked the Hierarchy panel to see if I haven't accidentally duplicated stuff which might get to be on top of stuff (such as 100 barrels all in the same position so as to look as if there's just one there), and this is not the case. So my question is am I misinterpreting the Unity stats window? Is it a bug in the reported triangles count there? Or am I just completely missing how all this works ? |
0 | Unity3d CarController character positioning issue I use the unity standard asset components CharacterController and Car and put an empty gameobject onto the car where the camera should be placed when i am inside the car. The empty gameobject is called "Driver". The character controller has an empty called "Head" where its head is. When i get in the car i perform the following operation GameObject car GameObject.Find("Car") transform.position car.transform.Find("Driver").transform.position Vector3.up 1 transform.parent car.transform.Find("Driver").transform Camera.main.transform.position car.transform.Find("Driver").transform.position Camera.main.transform.rotation car.transform.Find("Driver").transform.rotation and to get out of it, i use the following GameObject car GameObject.Find("Car") transform.position car.transform.position transform.parent null transform.rotation Quaternion.identity Camera.main.transform.position transform.Find("Head").transform.position My problem is when i get into the car and out again, the character is positioned at the position where i have entered the car, so it doesnt seems to update its position with the car movement. What am i doing wrong? Thanks in advance |
0 | How do I move a game object instead of the entire scene in Unity? I'm trying to move GameObject between scenes but when I do it moves my whole scene instead of just that one game object. How do I move just the game object and not the whole scene? I have tried SceneManager.MoveGameObjectToScene(UIRootObject, sceneToLoad) and DontDestroy but it keeps moving my whole scene new scene. |
0 | Can you use a standard multi thread if only reading unity objects? First of all I know about coroutines and how to use them (they're awesome). A friend of mine was telling me about the way the he implemented his saving system in a game he was working on, after asking him what he was using I found out that he is using system.threading and not coroutines to save data. I know that Unity isn't thread safe but apparently he has had no issues with saving which leads me to wonder if it is ok to use normal threads as long as you're only reading data and no pre existing data is modified in the gameworld? would this affect the game at all (other than some moving objects being slightly ahead of where they should be because of the time it took to get to that object and save it)? |
0 | Controlling Unity 3D cube with remote gyroscope This probably will go into conceptual things as well, but what I would like to do is take a Raspberry Pi (with a Sense Hat), transmit the gyro values to Unity, and effectively have a 1 1 realistic representation of orientation changes. I have no problem transmitting values from the Pi to Unity (though learning about hidden firewall rules was fun), however I am lacking some understanding of how to transform raw gyro values to something representative in Unity. I have not calibrated the Sense hat recently, but know that is something that should be done. For example, I am transmitting the pitch roll yaw values from the Pi (resting normally, these are about 100.30272132022793, 351.3885231076573 354.9306950697191). I have a cube gameobject that I've flattened out and set to the origin. My question is basically, what is the best way to translate raw values from some anonymous object to the Unity coordinate system, and have it rotate appropriately? I don't necessarily want its position to change, just rotation. Screenshot for reference. Raspberry Pi sending gyro data is on the left, Unity is on the right. Tabletop (flattened cube) is what I'd like to rotate to simulate a ball balancer. |
0 | Simple Game Feasibility Unity Turbo Squid 0 ? I've been coding 2D games exclusively for a while, partly because I have very limited graphics skills, partly because it takes less effort to make something look great, and partly because I have very limited time in which to code. I have an idea for a very simple 3d kids game that I'd like to build it would be based around a player roaming a randomly generated city and looking for a particular building (eg. dollar store, grocery store, bank, etc.) My question is Would it be feasible to build this in Unity, using only free models and animation (presumably from Turbo Squid), in a decent time frame? In terms of features, this would range in extremes from "generate some random buildings, paths, and select one as the winning building to locate" to adding people to talk to, objects to interact with (water, ladders, keys and locks, ropes, etc.) I haven't touched 3D modelling for years (I used 3D Studio Max 3.x back in high school), and I don't have 3 4 hours to spend creating, rigging, and animating models. That's really the crux of my doubt. I also don't have cash that I can spend on models animation. So to summarize, my main two questions are Is it feasible to create a decent quality game using free stuff from Turbo Squid? Are many most all of the models from TS compatible with Unity? |
0 | Stop Camera up movement I am developing 3D game , the main camera is child of player. When player jumps camera too gets move up with player as its child of player.Is there anyway to stop this behavior? The only thing I can guess is to make camera separate gameobject and let it follow player EDIT After applying Everless Drop 41's script, here is what main problem arises |
0 | How do I check if animation is of Animation Type "Humanoid"? One can set the Rig Animation type of an animation to quot Generic quot , quot Humanoid quot , etc. How could I check by script if an animation rig has been set to type quot Humanoid quot ? |
0 | why does my objects only spawn once or really slowly? public GameObject fallingRockPrefab public Vector2 spawnsMinMax float randX float randY void Update() if (Time.time gt nextSpawnTime) float SpawningInBetween Mathf.Lerp(spawnsMinMax.y, spawnsMinMax.x, Difficulty.GetDifficultyPercent()) print(SpawningInBetween) nextSpawnTime Time.time SpawningInBetween randX Random.Range( 5.6f, 5.6f) randY 5.57f SpawnPosition new Vector2(randX, randY) Instantiate(fallingRockPrefab, SpawnPosition, Quaternion.identity) I set the quot spawnsMinMax quot over at the inspector in Unity as high as I can like (25 or 30 etc) but it still spawns once or like 1 or 2 per second. Even I set the number as low it can go, it still spawn in the same way. How do I fix this? |
0 | Keypress Left is called twice in Update when key is pressed only once I have a piece of code that is changing the position of player when left key is pressed. It is inside of Update() function. I know, Update is called multiple times, but since I have an ifstatement to check if left arrow is pressed, it should update only once. I have tested using print statement that once pressed, it gets called twice. Problem Position updated twice when key is pressed only once. Below given is the structure of my code void Update() if (Input.GetKeyDown (KeyCode.LeftArrow)) print ("PRESSEEEEEEEEEEEEEEEEEEDDDDDDDDDDDDDD") How can I fix this? |
0 | Why is my enemy kill code not working? I'm trying to make an enemy for my game, and everything works, except for the bit of code where the enemy is supposed to die. My player attacks but nothing happens. I filled in the prefabs, I have the right tags, I tried remaking it and I can't find anything that is wrong. What am I doing wrong? pragma strict var EnemyItself GameObject var EnemyCorpse GameObject function OnTriggerEnter(other Collider) if (other.gameObject.tag "Hero Punch") EnemyItself.SetActive(false) EnemyCorpse.SetActive(true) |
0 | Instances in the Unity Profiler Timeline What do Instances mean when you click on an operation in the Timeline section of Unity Profiler? In this example Total 11.90 ms (10 Instances) |
0 | Adding 90 degree Y rotation into script I'm using the following script to move a spray bottle around a head. It should looke like in a barber shop. The code works fine I have assigned the script to the spray bottle, and I have set the head as the target. One thing that is wrong is that the spray bottle needs to have a 90 yaw rotation in order to face the head. I have tried the wildest things to include these 90 degrees, all produced weird results. Could anybody state how to include this 90 Y rotation into the script? Thank you very much! using UnityEngine using System.Collections AddComponentMenu("Camera Control Mouse Orbit with zoom") public class MouseOrbitImproved MonoBehaviour public Transform target public float distance 5.0f public float xSpeed 120.0f public float ySpeed 120.0f public float yMinLimit 20f public float yMaxLimit 80f public float distanceMin .5f public float distanceMax 15f private Rigidbody rigidbody float x 0.0f float y 0.0f Use this for initialization void Start () Vector3 angles transform.eulerAngles x angles.y y angles.x rigidbody GetComponent lt Rigidbody gt () Make the rigid body not change rotation if (rigidbody ! null) rigidbody.freezeRotation true void LateUpdate () if (target) x Input.GetAxis("Mouse X") xSpeed distance 0.02f y Input.GetAxis("Mouse Y") ySpeed 0.02f y ClampAngle(y, yMinLimit, yMaxLimit) Quaternion rotation Quaternion.Euler(y, x, 0) distance Mathf.Clamp(distance Input.GetAxis("Mouse ScrollWheel") 5, distanceMin, distanceMax) RaycastHit hit if (Physics.Linecast (target.position, transform.position, out hit)) distance hit.distance Vector3 negDistance new Vector3(0.0f, 0.0f, distance) Vector3 position rotation negDistance target.position transform.rotation rotation transform.position position public static float ClampAngle(float angle, float min, float max) if (angle lt 360F) angle 360F if (angle gt 360F) angle 360F return Mathf.Clamp(angle, min, max) |
0 | Retractable object in unity I'm trying to get the physics of a retractable object in unity, So I will be able to quot launch quot an elastic cable (similar to rope physics) out of an object (e.g. A gun), And the cable will gradually exponentially quot roll back quot into the object. A good reference would be Batman's grapple gun. I thought of utilizing it using a spring joint, but I can't really get the exact mechanics I'm trying to achieve. Any ideas? Thank you in advance. |
0 | Why is clicking too fast giving me a missingReferenceException in Unity? I made a small method that will quickly give the player a "flashlike" display when a sheep is killed. However clicking too fast will trigger a missingReferenceException. Because it registers the raycast a second time. Is this due to the delay on the DestroyObject() or something else? private IEnumerator startFlashing(GameObject sheep) sheep.gameObject.GetComponent lt Rigidbody gt ().freezeRotation true sheep.gameObject.GetComponent lt Rigidbody gt ().velocity Vector3.zero sheep.SetActive(false) yield return new WaitForSeconds(theTimeBetweenFlashes) sheep.SetActive(true) DestroyObject(sheep.gameObject, 0.1f) |
0 | JSON Parse (Invalid Value) My settings.json (generated with JsonUtility.ToJson) "masterVolume" 0.10000000149011612, "fullScreenMode" 1, "cheatsEnabled" false Offending line SettingsData sd JsonUtility.FromJson lt SettingsData gt (Application.dataPath " Settings settings.json") My SettingsData class. System.Serializable public class SettingsData SerializeField public float masterVolume SerializeField public int fullScreenMode SerializeField public bool cheatsEnabled public SettingsData(float masterVolume, FullScreenMode fullScreenMode, bool cheatsEnabled) this.masterVolume masterVolume this.fullScreenMode (int)fullScreenMode this.cheatsEnabled cheatsEnabled I really can't fathom why it's having trouble reading this back in, I even tried to save the enum as an int instead, but still no luck. |
0 | Unity Objects become black when size is changed to smaller While working with Unity 5.4, my models become black when I resize them to a smaller scale. When I make the models bigger they are fine. I am using a directional light . On the image below as you can see on the left the model is fine. But the others are black. HOPE YOU CAN HELP. |
0 | Button Press Detection not working while detecting collision I am trying to make a sign that brings up a panel when you press Enter while the player is over the sign. The code I have written is using System.Collections using System.Collections.Generic using UnityEngine public class SignScript MonoBehaviour public GameObject Panel void OnTriggerEnter2D(Collider2D other) if (other.tag "Player") UnityEngine.Debug.Log("Triggered1") if (Input.GetAxis("Submit") 1) UnityEngine.Debug.Log("Triggered2") if (Panel false) Panel.SetActive(true) UnityEngine.Debug.Log("Triggered3") I added code that prints "Triggered1", "Triggered2", and "Triggered3" to the Debug Log when you reach certain parts of the code. When the player is over the sign and is pressing Enter, it should print "Triggered2". For some reason, it is not doing this. Does anyone know why? |
0 | Generating the distance of an intersection through a box from the camera in Unity C So, I recently saw this fantastic video by Sebastian Lague about planetary generation https www.youtube.com watch?v lctXaT9pxA0 amp t 1100s And I decided to replicate it, however, on a flat plane, not a sphere.In the video, (at timestamp linked) he uses some mathematical expression to figure out the distance of the camera's vector through an arbitrary sphere, and uses this to shade the ocean. I can't figure out how to write a similar estimator for an arbitrary rectangular prism. Anyone have any ideas? EDIT I have shifted to using surface shaders, but I can't figure out how to compensate for distance in depth Shader quot Custom SurfaceDepthShader quot Properties ColorShallow ( quot Color Shallow quot , Color) (1,1,1,1) ColorDeep ( quot Color Deep quot , Color) (1,1,1,1) MainTex ( quot Albedo (RGB) quot , 2D) quot white quot Glossiness ( quot Smoothness quot , Range(0,1)) 0.5 fadeDepth( quot Base Alpha quot , Range(0,1)) 0.5 InvFade ( quot Soft Factor quot , Range(0.01,3.0)) 1.0 SubShader Tags quot Queue quot quot Transparent quot quot RenderType quot quot Transparent quot LOD 200 CGPROGRAM Physically based Standard lighting model, and enable shadows on all light types pragma surface surf Standard vertex vert alpha fade nolightmap Use shader model 3.0 target, to get nicer looking lighting pragma target 3.0 sampler2D MainTex struct Input float2 uv MainTex float4 screenPos float3 worldPos float eyeDepth half Glossiness half Metallic fixed4 ColorShallow fixed4 ColorDeep sampler2D float CameraDepthTexture float4 CameraDepthTexture TexelSize float InvFade float fadeDepth void vert (inout appdata full v, out Input o) UNITY INITIALIZE OUTPUT(Input, o) COMPUTE EYEDEPTH(o.eyeDepth) void surf (Input IN, inout SurfaceOutputStandard o) Albedo comes from a texture tinted by color fixed4 c tex2D ( MainTex, IN.uv MainTex) ColorShallow smoothness come from slider variables o.Smoothness Glossiness float rawZ SAMPLE DEPTH TEXTURE PROJ( CameraDepthTexture, UNITY PROJ COORD(IN.screenPos)) float sceneZ LinearEyeDepth(rawZ) float partZ IN.eyeDepth float dist distance( WorldSpaceCameraPos, IN.worldPos) float fade 1.0 if ( rawZ gt 0.0 ) Make sure the depth texture exists fade saturate( InvFade (sceneZ partZ)) o.Albedo lerp( ColorShallow, ColorDeep, fade) c o.Alpha c.a fade fadeDepth ENDCG FallBack quot Diffuse quot |
0 | First object jumps on re entry of second colliding object The scenario is that I have two objects Object A and Object B. The Object A is lying on the ground and when Object B enters the collider of Object A, the Object A moves (only X and Z axis) with Object B. The movement works well with the script shown below. The issue is that most of the time, the Object A's initially position shifts by few meters whenever Object B enters its collider. I feel it is related to offset position. What should happen is that, Object A should be the same position when Object B enters the collider and move along with Object B only when Object B moves. So how do I fix this? private Vector3 offsetPosition public Transform ObjectB public bool ObjectB Collision false void Start () offsetPosition ObjectB.transform.position this.transform.position void ObjectB HasEntered() offsetPosition ObjectB.transform.position this.transform.position Update is called once per frame void LateUpdate () if (ObjectB Collision true) this.transform.position new Vector3 (ObjectB.transform.position.x, this.transform.position.y, ObjectB.transform.position.z) new Vector3 (offsetPosition.x, 0, offsetPosition.z) public void OnTriggerEnter (Collider col) if (!enabled) return if (col.gameObject.name quot Object B quot ) ObjectB HasEntered() ObjectB Collision true public void OnTriggerExit (Collider col) if (!enabled) return if (col.gameObject.name quot Object B quot ) ObjectB Collision false |
0 | How to get position of next object that closest to player,when player is move forward to nearest every time? I have a scene that looks like the following picture The Player has a RigidBody2D and all the steps have a BoxCollider2D. All steps are tagged with a 'step' tag. I would like to let the player move to the next step, every time the user presses a key. In this case, I'll need to get the position of the next step that is the closest to the player, every time the player moves to the next position. I have tried the following so far using UnityEngine using System.Linq public class Box MonoBehaviour the rigidbody of the box private Rigidbody2D player2D Start is called before the first frame update void Start() player2D GetComponent lt Rigidbody2D gt () void Update() if (Input.GetKeyDown(KeyCode.Space)) Vector2 targetPosition GetNextTargetTransform(player2D.position ) here set trajectory to move from current position to target position Vector2 trajectory SetTrajectory(player2D, targetPosition) player2D.AddForce(trajectory, ForceMode2D.Impulse) after reach the position update player position to current position player2D.position targetPosition public Vector2 GetNextTargetTransform(Vector2 player2Dposition) GameObject step GameObject.FindGameObjectsWithTag("step") here is the code to get the nearest object using LinQ var nearest step.OrderBy(t gt Vector2.Distance(player2Dposition, t.transform.position)).FirstOrDefault() Transform nearestPosition nearest.transform Vector2 targetPosition new Vector2(nearestPosition.position.x, nearestPosition.position.y) return targetPosition I am able to get the position of the first step when a button is pressed, but when I press the key again, I am unable to get the position of the next step (and thus remain on the first position). I've added player2D.position targetPosition after AddForce(...) and the player will directly appear on the first step and move to the next one, which is not the result I want. Question How do I get the position of the nearest step, every time the player moves to a new step? |
0 | Unity How to make script work with duplicated objects? I have an object in my game that, when clicked, causes the player to move toward it. It does this by sending its position to the player's SetTarget function. The player's Move function then heads toward the position. This is working, but when I duplicate the object and click on it, the player still moves toward the original object's position. When I print debugging statements to the console, it appears that both positions are being calculated, but the original position is the last one and wins out. (I'm using the object's this.transform.position to send the position to the player's SetTarget function.) Can I not duplicate objects like this and expect the script to work? Do I need to use a prefab? If so, how? I know how to create prefabs but am not sure what I would need to change with the script or other settings when they are created. Thanks. Here's the code public class PotController MonoBehaviour private GameObject chefObject void Start () chefObject GameObject.Find ("Chef") void Update() if(Input.GetMouseButtonDown(0)) print ("pot clicked!") ChefController chefScript chefObject.GetComponent lt ChefController gt () print (this.gameObject.transform.position) chefScript.SetTheTarget (this.gameObject.transform.position) public class ChefController MonoBehaviour private Vector3 target public float speed 2 Use this for initialization void Start () target this.transform.position private void MoveTowardsTarget() Vector3 targetPosition new Vector3(0,0,0) targetPosition target Vector3 currentPosition this.transform.position check distance to target if(Vector3.Distance(currentPosition, targetPosition) gt 0.4f) Vector3 directionOfTravel targetPosition currentPosition directionOfTravel.Normalize() this.transform.Translate( (directionOfTravel.x speed Time.deltaTime), (directionOfTravel.y speed Time.deltaTime), (directionOfTravel.z speed Time.deltaTime), Space.World) void Update () MoveTowardsTarget () public void SetTheTarget (Vector3 position) target position |
0 | Images disappear when camera zooms in there is no problem when the camera is away, but as I zoom in to the game, the images disappear and I can't see the game properly. What is the reason ? |
0 | Can the GUI be used to create game objects? I want to be able to position 10 various game objects (sprites) within the area of the screen which will be dynamically sized accordingly to the screen size of the device. The area in which I want to position the items will be about 70 of the screen. The objects will be rectangles with irregular size (slightly irregular). The object should be positioned randomly (or in grid) within this area but they should not overlap. The objects will be a drop targets for other object which I will drag onto them. To summarize I need The area in which I can place objects. Random object position er. As I have been reading and watching various tutorials I have become very confused about how should I approach this. Should I use a Rect to draw the area on which I will then place the objects, or should I use GUI UI elements i.e. panel? Are the GUI UI elements suitable for achieving this or are they meant to be only used to create games menus not for actual game play? |
0 | How to apply a script to multiple Objects in Unity? In Unity, I've almost 200 or more objects. I wish to apply single script to all those objects. I'm a beginner amp learning scripts in Unity. Edit At the time of editing the scene itself. |
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 | Real Time Speech Verbal Communication with a Mecanim Character What would be the simplest method of integrating real time verbal communication within a mecanim character that is already being used in a Unity app project? Something like an SDK or toolkit? I have such a character that is animated by a motion capture device, so the user puts on the suit and the Unity character is driven by receiving live motion data. This is the non verbal part for research in Social Sciences amp Psychology. I tried integrating the Virtual Human Toolkit into my Unity app to use its real time speech amp lip sync amp facial gestures, but their character is set up in a complicated way, so I still cannot animate it by using my motion capture device. So, now I am thinking what is the next best thing to do with a Unity mecanim character to make it say something, etc...? |
0 | Why is unity's RaycastHit2D contact point is slightly off This is a small test I made, basically I have a simple BoxCollider2D that has the top surface aligned with the x axis. It's just a 1x1 cube placed at (0, 0.5). Now when I cast a ray down from position (0, 1) I would expect the resulting RaycastHit2D's contact point to be (0, 0) however when I log the contact point, it shows it is slightly over the actual surface at (0, 2.384186E 07). So the question is, why does this happen? Also, can it be fixed somehow (like tweaking settings or something)? |
0 | Convert a modified Transform.forward to world space I am trying to make an electricity system, where it is given the start and end points, and it works out a random sequence of points in the rough direction of the end point. These points are set as vertices on a line renderer, and it should end up joining up as a bolt of electricity. My problem is that it needs to move 'forward' from start to end. The easy solution is that the electricity comes from a game object, which is set to LookAt the end point. Then, every time it sets a 'nextPoint', it adds to the transform.forward. nextPoint new Vector3 ((startingPoint.forward.x divergence.x), (startingPoint.forward.y divergence.y), distance) divergence is a Vector3 containing a random increase on the x and y axis, and 1 on the z axis. This works, in a way. The problem is that it then assumes these are world space coordinates. So the line will go from starting point, to (eg. 0.3, 0.75, 1), and then back to the end point. I can't find a localToWorld conversion for a vector though, so I am not sure how to get the transform.forward whatever, converted from local to world space. |
0 | How can I call Schedule() on interface that inherits from IJob So I have a voxel terrain engine, and I have an interface that all meshing jobs should inherit from. That looks like this (simplified from the actual) public interface IMesherJob IJob VoxelDataVolume lt byte gt VoxelData get set NativeArray lt MeshingVertexData gt OutputVertices get set NativeArray lt ushort gt OutputTriangles get set One example of a meshing job is marching cubes, which looks like this public struct MarchingCubesJob IMesherJob So here's my question If I have a reference to an IMesherJob, can I somehow call Schedule on it? If I have a reference to MarchingCubesJob, I can call Schedule on it This works MarchingCubesJob myMeshingJob GetMeshingJob() JobHandle handle myMeshingJob.Schedule(voxelCount, 64) But this does not work IMesherJob myMeshingJob GetMeshingJob() JobHandle handle myMeshingJob.Schedule(voxelCount, 64) I noticed that Schedule() is an extension method for T where T struct, IJob so that might be interfering with it, but it should still work because IMesherJob inherits from IJob |
0 | What is causing my 3rd person camera to lose rotation on the z axis? I've been working on a 3rd person camera on unity for a couple weeks, but I've pretty much hit a wall, specifically to do with my camera's rotation. When I rotate it on its x and y axis it won't have a problem, but when it gets to the z axis (180 degree's on the x axis), it loses the ability to rotate at all. This is the code I've been using void Start() controlls camera relevent to player position offset new Vector3(Player.position.x 3.0f, Player.position.y 2.0f, 0) offset transform.position Player.position localtoworldY transform.TransformPoint(Vector3.left) void Update() need to give proper rotation of the camera around the player offset Quaternion.AngleAxis(Input.GetAxis("Mouse X") turnSpeed, Vector3.up) offset offset Quaternion.AngleAxis(Input.GetAxis("Mouse Y") turnSpeed, localtoworldY) offset transform.rotation Quaternion.LookRotation(offset, Vector3.up) transform.position Player.position offset transform.LookAt(Player.position) print(transform.rotation) If the y axis go to 6.4 positive, it should stop but not stop working, same as if the camera hits a mesh or terrain. If the camera changes in any direction regardless of x or y axis,player should be able to move relative to the direction that the player is pressing (IE when the player press left, the Homicida malorum will move left regardless of the angle of the camera). Any advice or an explanation as to why this is happening would be much appreciated. |
0 | Unity Grid Layout causing multiple draw calls We are developing a game in Unity 4.6.6 for both Android and iOS. Currently I am building the game UI with the new Unity UI system. In particular I am building a button list to create kind of inventory slots using the Grid Layout. I have noticed that my draw call count is increasing considerably despite having my UI in an atlas (using Sprite packer) and using the same font all over the UI. After some tests I noticed that one draw call is generated per each UI Text and UI image present in the scene composing each button when using a Grid Layout Group, when the Grid Layout is not used the draw calls are reduced noticeably. 7 elements without Grid Layout, results in 2 draw calls (Screenshots taken in play mode) 7 elements WITH Grid Layout, resulting in 14 draw calls (Screenshots taken in play mode) I have no idea if it is possible to reduce the number of draw calls when using the Grid Layouts. |
0 | How does Application.genuine work? In Unity, does anyone know exactly what is behind the scenes of Application.genuine? More specifically, I would like to understand its exact process so I can understand If I can use it safely without "false negatives". If it considers text (or other) assets stored in a Resources folder (e.g. my level config files). Just for context, I want to say that my target platform is iOS. |
0 | Tilemaps not showing up on Android build I'm having trouble developing a 2d game for Android. I use tilesmaps for the ground and a few other things. On the editor, everything works fine and dandy. But, when I deploy to a phone(Build and Run), the tiles aren't there. It's like they never existed. I go back to the editor and they're there. I play the game directly from the editor and they're there. I even play the game while running unity remote, on the test phone, and the tiles are there. No idea what's going on. This only happens with tilemaps. Everything that isn't a tilemap is visible. I'm running Unity 2019.3.0f6 |
0 | Script not working (Function not changing value) I have this script that I made for an FPS character. public class Player Movement MonoBehaviour public CharacterController controller public Transform camera public float gravity 9.81f public Transform groundCheck public float groundDistance 0.4f public LayerMask groundMask bool grounded public GameObject joystick public bool isMoving public float speed 12f public float turnSmoothTime 0.1f float turnSmoothVelocity public float jumpHeight public Vector3 yPosition public bool jumpAble true Update is called once per frame void FixedUpdate() grounded Physics.CheckSphere(groundCheck.position, groundDistance, groundMask) if (grounded) yPosition.y 2f jumpAble true Vector3 direction new Vector3(joystick.GetComponent lt Joystick gt ().inputDirection.x, 0f, joystick.GetComponent lt Joystick gt ().inputDirection.y) isMoving direction.magnitude ! 0 ? true false if (isMoving) controller.Move(direction speed Time.deltaTime) yPosition.y gravity Time.deltaTime UnityEngine.Debug.Log(yPosition) controller.Move(yPosition Time.deltaTime) public Vector3 Jump() UnityEngine.Debug.Log(jumpAble) UnityEngine.Debug.Log(grounded) if (jumpAble amp amp grounded) jumpAble false yPosition.y Mathf.Sqrt(jumpHeight 2 gravity) UnityEngine.Debug.Log(yPosition.y) UnityEngine.Debug.Log(yPosition) return yPosition return yPosition The game operates on mobile touch controls, and the Jump() is called when the jump button is pressed. However, the character does not jump when I press the button, even though the function is being called, and the yPoisition is being changed in the function. I know that changing the yPosition should make the player jump, as when I add this code to the Update if (Input.GetKey(KeyCode.Space) amp amp jumpAble) fallDown.y Mathf.Sqrt(jumpHeight 2 gravity) Everything works fine. Why is the new yPoisition value not being passed to Update, and why is this happening? |
0 | Why is transform.up behaving differently for different functions? Can anyone please explain to me what i'm doing wrong here? As I see it the raycast is the only one using transform.up correctly, though why not Debug.DrawLine() and lineRenderer.SetPosition(1, transform.up maximumBeamLength) using UnityEngine RequireComponent(typeof(LineRenderer)) public class LaserBeam MonoBehaviour SerializeField private float maximumBeamLength 5f private LineRenderer lineRenderer private void Start() lineRenderer GetComponent lt LineRenderer gt () void Update() lineRenderer.SetPosition(0, transform.position) RaycastHit2D hit Physics2D.Raycast(transform.position, transform.up) Debug.DrawLine(transform.position, transform.up maximumBeamLength, Color.blue) Debug.DrawLine(transform.position, transform.up , Color.red) if (hit.collider) lineRenderer.SetPosition(1, new Vector3(hit.point.x, hit.point.y, transform.position.z)) else lineRenderer.SetPosition(1, transform.up maximumBeamLength) |
0 | Painting a Wall and Calculating the Paint Percentage in Unity I'm trying to paint a wall in Unity by following this tutorial however I don't know how can I calculate the paint percentage and not paint the lines that have been already painted, and also not go beyond plane boundaries. Painting needs to be using swerve mechanics. What would be the approach to accomplish this? |
0 | Why does my mesh move when i add an avatar? I've imported a wall model into my scene, it snaps to the other walls fine until I add an avatar to the model to animate it, then it moves. here's some picture to explain The first picture in the scene This picture is in the game |
0 | MotionBuilder Actor attached to Mocap moves fluently, but Character using Actor as source jitters and has joints occasionally pop out I'm trying to get a MotionBuilder animation to work in Unity on my custom character. I've downloaded Motionbuilder FBX mocap files with Actors already attached from http dancedb.eu main performances The thing is that when I put the Actor as the Input source for my own (Characterized) character model and hit play on MotionBuilder, my model follows the animation 80 correctly but for the other 20 my character jitters and shakes and occasionally even quot breaks a limb quot when a joint randomly pops out of its place for a second. Does anyone have suggestions on how to get the animation smoother for my Character? |
0 | How do I increase the spawn rate of an object as the "difficulty" goes on? I just want my objects to spawn in a faster rate as time goes by. The print(SpawningInBetween) print out shows the percentage of the difficulty overtime. This is the code I have public Vector2 spawnsMinMax Spawn Positions Vector2 SpawnPosition float secondsBetweenSpawn 1 float nextSpawnTime void Update() if (Time.time gt nextSpawnTime) float SpawningInBetween Mathf.Lerp( spawnsMinMax.y, spawnsMinMax.x, Difficulty.GetDifficultyPercent()) print(SpawningInBetween) nextSpawnTime Time.time SpawningInBetween nextSpawnTime Time.time secondsBetweenSpawn ... I was thinking of going like this if(Time.time gt Difficulty.GetDifficultyPercent lt 0.9) but it got a compiler error. |
0 | Black screen after running emulation mode in the Unity Editor for hololens I am having issues with black screen when running the emulation mode or simulator for Microsoft hololens. In the preview the camera shows what the user should see. I see no obvious reason to behave like this and no error warning is given. I am using code snippets from the Origami tutorial,except I chose to use RayCastNonAlloc. Movement.cs public class Movement MonoBehaviour public GameObject person public float seconds private Vector3 point new Vector3(0,0,0) private RaycastHit rayHit new RaycastHit 5 void OnSelect() person.transform.position Vector3.Lerp(person.transform.position, point, seconds Time.deltaTime) Update is called once per frame void Update() if (Physics.RaycastNonAlloc(Camera.main.transform.position, Camera.main.transform.forward, rayHit, Mathf.Infinity, 0) gt 0) foreach (RaycastHit hit in rayHit) point.x Mathf.Clamp(hit.point.x, 290f, 6970f) point.y Mathf.Clamp(hit.point.y, 40f, 1860f) point.z Mathf.Clamp(hit.point.z, 1700f, 140f) Scene.cs using UnityEngine using UnityEngine.XR.WSA.Input public class Scene MonoBehaviour public GameObject cursor public GameObject Focused get private set public Scene Instance get private set private GestureRecognizer recognizer private MeshRenderer Renderer private readonly RaycastHit rayHit new RaycastHit 5 void Awake() Instance this recognizer new GestureRecognizer() recognizer.Tapped (args) gt if (Focused ! null) Focused.SendMessageUpwards("OnSelect", SendMessageOptions.DontRequireReceiver) recognizer.StartCapturingGestures() Renderer cursor.GetComponent lt MeshRenderer gt () void Update() GameObject oldFocused Focused if (Physics.RaycastNonAlloc(Camera.main.transform.position,Camera.main.transform.forward,rayHit,Mathf.Infinity, 0) gt 0) Renderer.enabled true foreach ( RaycastHit hit in rayHit) cursor.transform.position hit.point cursor.transform.rotation Quaternion.FromToRotation(Vector3.up, hit.normal) Focused hit.collider.gameObject else Focused null Renderer.enabled false if (Focused ! oldFocused) recognizer.CancelGestures() recognizer.StartCapturingGestures() |
0 | How to animate clouds in a plane? I'm building a top down strategy 2D game, and i'm stuck animating clouds that will float above the arena, hiding other elements. The effect i want to achieve is something exactly like this How would i go about implementing it in Unity3D? |
0 | How to add post process volume script in unity 2019? i have old unity 2018 project and imported standard character asset. The 3d player has this script post process volume and post process layer. In 2018 i can add this component but not in 2019 . This component is not available in 2019. What is the replacement for this ? or how to achieve the same result for 2019 ? |
0 | How to avoid overwriting a value in Unity? I'm working on a Tower Defence style game, and wondering how best to handle the quot resources quot part. I have multiple enemies on screen at a time, and when an enemy dies, it updates a resource that allows the player to build more towers var tower Instantiate(buildables 0 , center, Quaternion.identity) var controller tower.GetComponent lt TowerController gt () controller.OnKilledEnemy (sender, args) gt int.TryParse(goldAmount.text.Replace( quot , quot , quot quot ), out var curr) curr args.gold goldAmount.text quot curr n0 quot But if 2 enemies die in the same frame, wouldn't the value there miss an update? What ways are there in Unity C to mitigate this problem? |
0 | Switch scenes and continue to receive bluetooth stream from Update I have a scene where I'm connected to a BLE device and receive data in bytes. I want to switch scenes from the current Update and continue to receive the data without disconnecting. How should I do this. Here is my current code in Update case States.Subscribe HM10 Status.text "Subscribing to HM10" BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress ( hm10, ServiceUUID, Characteristic, null, (address, characteristicUUID, bytes) gt float floatprint EnterDataQueue(bytes) Debug.Log("floatprint" floatprint.ToString()) HM10 Status.text "Received Serial " floatprint.ToString() HM10 Status.text "Received Serial " Encoding.UTF8.GetString (bytes) ) And the method outside static float EnterDataQueue(byte bytes) ArduinoHM10Test aTest new ArduinoHM10Test() always load the data byte array in full for (int i 0 i lt bytes.Length i ) aTest.myQueue.Enqueue(bytes i ) Dequeue the queue and check if 4 bytes have been dequeued if (aTest.myQueue.Count gt 4) byte byteArray new byte 4 for (int i 0 i lt byteArray.Length i ) byteArray i aTest.myQueue.Dequeue() if (i 3) break aTest.floatnum BitConverter.ToSingle(byteArray, 0) Debug.Log("floatnum " aTest.floatnum.ToString()) return aTest.floatnum throw new NotImplementedException() |
0 | Activate object that have button component? I'm trying to activate the array object that have button component. public GameObject weapon carry pistol new GameObject 3 public int p1 carry,activeObjects Update is called once per frame void Update() p1 carry weapon carry pistol 0 .GetComponentsInChildren lt Button gt ().Length 6 objects for (int i 0 i lt activeObjects i ) weapon carry pistol 0 .GetComponentsInChildren lt Button gt () i .enabled true This script do activate the button component but not the whole game object. If I change "Button" to "GameObject" I get error .GetComponent requires that the requested component 'GameObject' derives from MonoBehaviour or Component or is an interface. |
0 | Is it better to load all of the scene at once or load small parts of it as the player moves? I want to create a lot of detail in my game but I don t want to kill the frame rate tracking all the models and movements (like all the grass). Will loading them in pieces save the frame rate or will constantly loading and unloading models with every step negate any benefits of loading in pieces? I want to only load what the player will see at that moment and nothing else until the player either moves the camera or walks. I also want to know if loading a scene on Unity uses the gpu or the cpu? |
0 | Getting and playing AudioClips by string name Is there anyway I can get an audioclip by the name it has in the assets folder? Or will I always have to make a reference to it by dragging and dropping the clip on a SoundClip in the inspector? |
0 | Unity project not communicating with my iPhone 11? Connecting to my iPhone 11 with a cool FaceTracking project called FaceCapOSCReceiverExample https github.com hizzlehoff FaceCapOSCReceiverExample works excellent on my laptop, but not on my PC (Windows 10 and ubuntu dual boot. I am using Windows 10 for this project). On my PC the only AntiVirus firewall I have is Windows Defender. On the Inbound and Outbound rules, I deleted everything that had the word 'Unity' in it. I then added custom rules, allowing everything, for the program paths of Unity Hub and all Unity Editor installations. But no luck. The program won't communicate with my iPhone. I even tried turning the firewall completely off and re launching Unity as admin. No luck. I then manually installed the latest drivers for my network adapters (I have both quot Killer E2400 Gigabit Ethernet Controller quot and quot Qualcomm QCA9377 802.11ac Wireless Adapter quot in Device Manager). No luck! I also connected my PC to a personal hotspot from my iPhone. This was a tethered (purely USB) connection that I had running. But, while the tethered Internet worked great on my PC, it still didn't make the Unity project communicate with my iPhone! O I then added a rule to my firewall where I created a TCP port number 60001 and set it so private and public could connect. (I'm very newbie about ports) Then I entered that as the Port number within the Unity project. Still no connection was made... I have no idea what to try from here! Like I said, it works great on my laptop, but my laptop is too dang laggy to use with it, so I would really love to get it running on my PC. |
0 | Why are Visual Studio and VSCode not giving me a dropdown list of methods and options etc? I am using VSCode but I have also tried Visual Studio 2019 to write code for Unity, but when I'm writing the lines I don't get dropdown menus with for example the methods this class holds. Or objects. Or it's properties. etc. basically, IntelliSense is not working. Is there a setting that I need to enable in order to get those? Since I've seen everyone who use VSCode and visual studio get these dropdown menus. |
0 | What are the advantages and disadvantages of exporting spritesheets instead of models from Spriter into Unity? I'm working on a simple 2D platformer in Unity and have been using the Spriter2Unity tool to import my Spriter animations directly into Unity. I have noticed that this creates large hierarchies of gameobjects within the imported prefabs, basically 1 per image piece. Since the animations are fairly simple, I am thinking it would be cleaner to import each of them as a spritesheet and hook them up with a spriterenderer on the player object rather than using the importer tool. Would this actually result in any performance benefit at runtime or are the impacts of animating a lot of game objects at once negligible? |
0 | Is it possible to not pack asset files into archives when building a Unity game? When I build a game in Unity, it packs the assets into strange data files with strange extensions like .split2 or .split1. But what if I want to give the player the ability to replace textures and modify the game without reverse engineering these files? I want the Assets folder as I see it in the editor to be accessible with the same files in the build. |
0 | Unity why game app on Android takes up much more memory than Unity Profiler reports? We are profiling a game app on Android 4.4.2 device via Unity s ADB profiling. We have set up ADB profiling following the official guide http docs.unity3d.com Manual Profiler.html The ADB profiling works fine, when the app is running, Unity Profiler reports its memory usage as following Used Total 100.4 MB Unity 40.5 MB Mono 10.1 MB GfxDriver 34.9 MB FMOD 3.9 MB Profiler 14.8 MB Reserved Total 112.8MB Unity 47.0 MB Mono 15.4 MB GfxDriver 34.9 MB Profiler 15.5 MB Meanwhile, we are also running another performance test tool (i.e. Emmagee, https github.com NetEase Emmagee) to monitor the app, which can monitor CPU, memory, network traffic, battery current and etc. However, the memory usage of the app reported by Emmagee tool is much larger As shown above, Unity Profiler reported 112.8M memory is totally reserved for running the app, but Emmagee tool reported 200M PSS memory is used. Obviously, more than 90M memory taking up is happened somewhere by something that Unity Profiler does not take into account. (We also tried other performance monitoring tool for Android apps, e.g. APT, and the result is similar to what Emmagee reported. The extra memory usage problem remains.) We noticed that the Unity Profiler itself would take up 15M memory, which is included in the profiler s report. Also, we knew that PSS memory includes proportional shared libraries with other processes, but 90M extra is such large amount considering that Unity Profiler only reported 112.8M totally. Our puzzle remained Where does the 90M memory come from? How are they used by the app? Why Unity Profiler does not report the extra memory? What can we do for reducing the extra memory and the total PSS memory of the running app, and or get it close to what Unity Profiler reports? Any help could be appreciated! |
0 | Limit position rigidbody How can I limit the position of a rigidbody, between two values if I use this code public Vector3 dir Rigidbody rb void Awake() rb GetComponent lt Rigidbody gt () void FixedUpdate() rb.velocity new Vector3(0f, 0f, 6f) rb.AddForce(dir 1f, ForceMode.VelocityChange) If I use Vector3.Clamp then the object will shake |
0 | Check if coroutine crashed I can check if coroutine still running by setting boolean variable outside the coroutine and then letting the coroutine itself set the value to true when it runs and set it to false when it decide to stop . But this method of detecting whether coroutine still active or not doesn't work when the coroutine crashed due to error (invalid input, null reference , ect) because the boolean variable remain true while the coroutine itself has stopped due to error. How do i check if coroutine still running or not in current frame ? i can't spend my code checking for next frame . Preferably C , but answer in javascript also accepted. |
0 | Unity2D force of an impact I don't know how to name what I am searching for... Force, Impact? It's easier to explain with an image for me. We have two GameObjects with colliders, A and B. They can move in any direction (top down game with 360 movement possibilities). First case (left) A go to the right at a speed of 2, B to the left at a speed of 1 and they collide. How to calculate that A take 1 damage (from the speed of B in its direction) and B take 2. Second case A go to the right at speed of 2 and B to the right at speed of 1. A take 0 damage and B take 1. I am using Collision2D which doesn't have "impulse" property. I have no idea how to calculate thing like this manually. |
0 | How can I give a MonoBehaviour field a default value that depends on the object? In Unity3D, I have a MonoBehaviour which gets added to game objects. I'm adding a string "name" field to it. I'd like the default value for the name to be the name of the game object the component is added to. Is there an easy way to do this? Some more details The component is an existing one to which I'm adding the name field. In old versions, the name was always the name of the game object, and this is a new feature to allow them to be different. The common case is (still) for the name to be the name of the game object, so having that as the default would simplify the process of adding the component to a new object. Ideally, deserializing an old scene will fill in the default, so updating scenes takes zero effort. I'm less concerned about this than about newly created scenes objects. The component already uses a CustomEditor. I don't care about updating the name in the component if the game object's name is changed, or if the component values are pasted into a different game object. One way I can think of is to add a bool "override name" to the object. If the bool is unchecked, it uses the default name (the game object) if it's checked, it uses the new field. But I'd like to avoid adding complexity to the GUI to support it. The whole point of my request is to add the new functionality (overriding the name) without adding steps to the creation workflow. |
0 | How to trust a UDP Client I'm working on a Unity project with the Lidgren UDP library for connection. I'm new to networking, so I'm not sure on general "best practices" for this area. I'm trying to figure out a good way to be able to quickly trust and verify a received UDP message. I currently keep a dictionary of players with each player assigned an UID (uint) from the server when the player connects. This UID serves as the key in the dictionary. The player is told their UID. Nothing secret being communicated here, like usernames passwords, so I'm not worried about things like that. So I'm having a problem with wrapping my head around how to trust the messages. Things like position updates and user actions will be sent from client server via UDP. I was thinking of a quick way to process these messages is by including the UID at the start of each message, checking the UID, grabbing the corresponding player from the dictionary, and then updating the players position that way. But I'm worried that can be easily spoofed manipulated. All it'd take is some mischief maker to figure it out, and then start inserting random position updates (for themselves or others). Is there an efficient, more fool proof way to ensure the message is from who it claims to be? Do I have to just rely on comparing IPEndPoints to tell? Is there anything specifically to Lidgren I can or should use? Please don't respond if all you have is "don't worry about it" or "why would anyone want to do this?" I'd rather learn proper processes now than down the road when if it becomes a problem. |
0 | Where how should A Star tie breaking occur? I've recently written a path finding script that utilizes a basic implementation of the A Star algorithm. It works fine but is not very fast. This is due, at least in part, to the fact that it isn't optimized at all. Through a bit of searching through this site and others I've realized that at least one thing I need is a tie breaking procedure that updates the heuristic values of nodes in the open list. Currently, whenever the pathfinder function is initiated. The pattern the finder takes pretty much expands outward in all directions from the point of origin until the target node is found. I've seen several videos that show A Star almost immediately traveling towards the target node thus eliminating many checks and ultimately speeding up the process. I believe this is due to a tie breaking procedure. My question is... At what point in the process should I be applying the tie breaking procedure and is there a better modifier to add to the heuristic aside from the below code? Node.heuristic (Mathf.Abs((Node.x endNodeVector.z) (endNodeVector.x Node.z)) 0.001F) This seems to be the most common that I have found. However, for some reason, this doesn't seem to effect the algorithm at all. It still searches in all directions from the origin position. What am I missing to make my A Star favor open list nodes that are closer to the target? |
0 | Align UI element to gameObject in 2D I have a 2d game where I want to display UI element perfectly aligned to specific gameObjects. I have an ortographic camera and I used to Camera.main.WorldToScreenPoint() function giving it the gameobject position modified, for instance, by 1 on X component to get the UI element on its perfect right. My problem is that the element is not on the gameObject's perfect right, but sensibly above. See this schema Expectation G UI element Reality UI element G I tried also to use the WorldToViewportPoint() but it's not giving the desired result. So, I think this is the right way to go but I can't guess what I'm missing. Any clue? EDIT After a little bit more observations it seemed that the UI element alignment depends somehow on it's distance from the center of the screen (of the camera viewport I guess), so that if the gameObject is below half height the UI element y position won't be on the perfect right but slightly below it and if above half heigth will be slightly above the perfect right. Same for x coordinate. Is there a way I could control this? |
0 | How do i easily clamp my cameras rotation when using transform.rotate() I'm making a fps controller, and I'm trying to clamp my cameras x rotation. Here's my code so far using System.Collections using System.Collections.Generic using UnityEngine public class Player MonoBehaviour Start is called before the first frame update SerializeField Camera cam SerializeField float camSpeed SerializeField float walkSpeed SerializeField float jumpSpeed float yaw float camPitch Vector3 direction Vector3 worldDirection Rigidbody myrigbody void Start() myrigbody GetComponent lt Rigidbody gt () Update is called once per frame void Update() camPitch Input.GetAxis( quot Mouse Y quot ) camSpeed cam.transform.Rotate(new Vector3(camPitch, 0, 0)) yaw (yaw Input.GetAxis( quot Mouse X quot ) camSpeed) 360f direction new Vector3(Input.GetAxis( quot Horizontal quot ) walkSpeed, myrigbody.velocity.y, Input.GetAxis( quot Vertical quot ) walkSpeed) worldDirection transform.TransformVector(direction) if(Input.GetKeyDown(KeyCode.Space)) myrigbody.AddForce(new Vector3(0, jumpSpeed, 0), ForceMode.Impulse) private void FixedUpdate() myrigbody.MoveRotation(Quaternion.Euler(0, yaw, 0)) myrigbody.velocity worldDirection I know that I want to clamp my cameras X rotation within a range of 89 to 89, but no matter what I try I can't figure out how to clamp the rotation while using cam.transform.Rotate(). I don't think I can clamp camPitch, because it is reset every frame, and I can't figure out a way to directly clamp the cameras rotation. The cameras rotation is not resetting, so if I could somehow clamp it it would work. Is this possible, or do I need to try a different method? How do i get this to clamp correctly? |
0 | Implementing a 4x4 Game Board I struggle with efficiency in code, and I want to start my game off on the right foot. I have a game that I'm making a 4 x 4 map of 'tiles' that a user can build their 'town' on. To keep track of the tiles, I'm planning on simply having a size 16 array of the type of my 'mapTile' enum. EX enum MapTiles defaultTile, homeBase, farm1, farm2 ...and so on... static MapTiles playerMap MapTiles 16 ... default map setup ... Is there a way that is more efficient or more easy to extend way to implement such a map? I'm using Unity and C mostly, though i'm willing to work with any Unity capable language if you have a clever answer. |
0 | How can I look up an object given only the name of its type? This question came from a fellow developer on Twitter, and I figured StackExchange would be a better format for explaining amp sharing the answer. To paraphrase the question I'm setting up an in game dev console in my Unity game, where a user should be able to call any method on any MonoBehaviour in the scene. I want to use something like FindObjectsOfType lt gt , but because it's coming from a string input by the user, the class name is unknown at compile time. I also want this to work universally, on any MonoBehaviour, not just ones I've specially instrumented or registered with the console system. Is there a way to find instances of a type with a particular name, and call methods on them, using something like reflection? |
0 | Unity Editor equivalent of Playmode Start() I am attempting to draw gizmos for easy debug in the editor. The gizmos code uses an array that gets populated during the start function. The array only needs to be populated once and may cause issues if its modified during runtime. As such, I cant call the method to populate the array in the OnDrawGizmos() method. I could possibly use a singleton populate the array but that would require many other things to be changed as well. I am looking for an equivalent to Start() for when it is in Editor Mode. Is there a method in editor mode that execute once or an attribute for the Start() method to execute in editor mode? |
0 | How do I prevent floating and jittering when on the ground and using spherical gravity? TL DR My ship floats and jitters when it lands on a sphere. To elaborate on the title I'm experimenting with a 3D space game. I have created a sphere, which in turn has a larger sphere overlapping it, within which, gravity will take place. However, once my player's ship (currently using an arrowhead) lands on the planet, it doesn't actually make contact with the surface of the sphere, and then the ship begins to rotate erratically and jitter. Code below. private void OnTriggerStay(Collider other) if (other.CompareTag("SoI")) inSoI true This trigger checks to see if the ship is in the larger overlapping sphere. I have another identical block for OnTriggerExit which sets inSoI to false. I also have a OnCollisionEnter which sets another variable, landed to true, and a OnCollisionExit which sets it to false. private void FixedUpdate() if (inSoI amp amp !landed) gravityVector (planet.transform.position transform.position) rb.AddForce(gravityVector.normalized planetrb.mass rb.mass gravityVector.sqrMagnitude) Simply, if in the larger sphere, then accelerate towards the planet. I tried disabling gravity if in contact with the sphere. It removed a lot of the jitter, however it still floats, and it still rotates side to side. The sphere by the way, is the standard Unity sphere, scaled 10000x in every axis. I don't need code (though it would help), any solution is fine, even if it means abandoning the project. |
0 | Start Position Move Step Problem Swipe Motion Mobile Unity C i am currently trying left amp right, up amp down swipe motion in unity C . I have done the scripting, it all working, but after i debug the script, the object's position suddenly changed to a very weird number from ( 3, 0, 3) changed to ( 3.000004, 0.00000464, 2.99999). And i intend to move just 1 unit every time i swipe, but the unit seems different, it always move around 1 but not exact 1 (Ex maybe like 0.9954, or like 1.002931). How i set the initial position to be exact integer number, and also move only 1 unit every time i swipe? Thanks using UnityEngine public class Player MonoBehaviour private Vector3 startTouchPosition, endTouchPosition private Vector3 startRocketPosition, endRocketPosition private float flyTime public float speed 1f bool canMove void Start() transform.position new Vector3( 3, 0, 3) void Update() if (Input.touchCount gt 0 amp amp Input.GetTouch(0).phase TouchPhase.Began) startTouchPosition Input.GetTouch(0).position if (Input.touchCount gt 0 amp amp Input.GetTouch(0).phase TouchPhase.Ended) endTouchPosition Input.GetTouch(0).position float xDifference Mathf.Abs(endTouchPosition.x startTouchPosition.x) float yDifference Mathf.Abs(endTouchPosition.y startTouchPosition.y) if ((endTouchPosition.x lt startTouchPosition.x) amp amp xDifference gt yDifference amp amp transform.position.x gt 5.5f) StartCoroutine(Fly("left")) MoveLeft() else if ((endTouchPosition.x gt startTouchPosition.x) amp amp xDifference gt yDifference amp amp transform.position.x lt 0.5f) StartCoroutine(Fly("right")) MoveRight() else if ((endTouchPosition.y gt startTouchPosition.y) amp amp yDifference gt xDifference amp amp transform.position.z lt 5.5f) StartCoroutine(Fly("up")) MoveUp() else if ((endTouchPosition.y lt startTouchPosition.y) amp amp yDifference gt xDifference amp amp transform.position.z gt 0.5f) StartCoroutine(Fly("down")) MoveDown() if (canMove) transform.position Vector3.Lerp(startRocketPosition, endRocketPosition, speed Time.deltaTime) canMove false startRocketPosition transform.position endRocketPosition new Vector3(startRocketPosition.x 10f, 0, transform.position.z) canMove true void MoveRight() startRocketPosition transform.position endRocketPosition new Vector3(startRocketPosition.x 10f, 0, transform.position.z) canMove true void MoveUp() startRocketPosition transform.position endRocketPosition new Vector3(startRocketPosition.x, 0, transform.position.z 10f) canMove true void MoveDown() startRocketPosition transform.position endRocketPosition new Vector3(startRocketPosition.x, 0, transform.position.z 10f) anMove true |
0 | Error when using GetComponent (Object reference not set to an instance of an object) I'm using a textmesh to check variables in real time. Thing is if I use AddComponent within Update(), it obviously starts spamming and slows the game. If I try with GetComponent the error is the following NullReferenceException Object reference not set to an instance of an object DebugCombo.Update() (at Assets DebugCombo.js 9) which points to the text.text assignment. This is the script from DebugCombo.js, from which I call the Combo class (from Combo.js) pragma strict public class DebugCombo extends MonoBehaviour function Update () var text gameObject.GetComponent(TextMesh) var combo gameObject.GetComponent(Combo) text.text quot Current quot Time.time quot Limit quot combo.comboTime How do I get rid of this error? |
0 | 2D Driving Game with Unity I'm trying to make a 2D car driving game in Unity and I'm having problems with my code. I am able to move forward,backward,turn left right using arrow key from my present code using UnityEngine using System.Collections public class CarControll MonoBehaviour Use this for initialization float speedForce 15f float torqueForce 200f float driftFactorSticky 0.9f float driftFactorSlippy 1 float maxStickyVelocity 2.5f float minSlippyVelocity 1.5f bool move false public bool forwardArrow false public bool backwardArrow false public bool rightTurn false Use this for initialization void Start () void Update() move true Update is called once per frame void FixedUpdate () Rigidbody2D rb GetComponent lt Rigidbody2D gt () float driftFactor driftFactorSticky if(RightVelocity().magnitude gt maxStickyVelocity) driftFactor driftFactorSlippy rb.velocity ForwardVelocity() RightVelocity() driftFactor if( Input.GetButton("Accelerate") Input.GetButtonDown("Forward") Input.GetKeyDown(KeyCode.UpArrow)) Debug.Log ("Uparrow....................................................") rb.AddForce( transform.up 20) if( forwardArrow true) rb.AddForce(transform.up 0.5f) if(backwardArrow true) rb.AddForce( transform.up speedForce 25f ) if(Input.GetButton("Brakes") Input.GetButton("Backword") Input.GetKeyDown(KeyCode.DownArrow)) rb.AddForce( transform.up speedForce 2f ) float tf Mathf.Lerp (0, torqueForce, rb.velocity.magnitude 2) rb.angularVelocity Input.GetAxis ("Horizontal") tf Vector2 ForwardVelocity() return transform.up Vector2.Dot( GetComponent lt Rigidbody2D gt ().velocity, transform.up ) Vector2 RightVelocity() return transform.right Vector2.Dot( GetComponent lt Rigidbody2D gt ().velocity, transform.right ) public void MoveForward() forward button forwardArrow true backwardArrow false public void MoveBackward() backward button backwardArrow true forwardArrow false public void RightTurn() right button rightTurn true I have added four button(Forward,backward,right,left).Now I need to move the car using this button. The car is moving Forward,backward using the button but when Press the right left button the car is not Turing left right while move.But its working perfectly on key press.Can anyboady help solving this issue |
0 | reseting timer unity So I have been trying to reset this timer but for some reason I can't figure out why it isn't resetting. Thanks, public class controlborder MonoBehaviour varibles public static int time lt here I create my timer public static int random public static bool boolreset true varibles get objects public SpriteRenderer m spriteRenderer get objects public void Start() m spriteRenderer this.GetComponent lt SpriteRenderer gt () StartCoroutine(Changecolortimer(2f)) IEnumerator Changecolortimer(float loopdaelay) while (boolreset) yield return new WaitForSeconds(1) time lt here is set a interval if(time 3) boolreset false resettime() public void changeColor() if (random 1 amp amp time 1) m spriteRenderer.color Color.blue else if (random 2 amp amp time 2) m spriteRenderer.color Color.red else if (random 3 amp amp time 3) m spriteRenderer.color Color.green else if(random 4 amp amp time 4) m spriteRenderer.color Color.yellow public void Update() random Random.Range(1, 4) changeColor() public void resettime() time 0 boolreset true Debug.Log(time) |
0 | What is a faster alternative to a GetComponent from a RaycastHit? I have a basic AI car script which needs to interact with other cars around it. I would like to access variables from the other cars to help one car identify what the other cars are doing so they can avoid jams and crashes better. One way to do this would be a raycasthit (ignore any errors there, you know what I mean) if(Physics.Raycast(...)) hitCar hit.transform.gameObject.GetComponent lt Car gt () However, I know that GetComponent can be very performance taxing especially if it's done every time there's an intersection with the raycast. Another way would be to save all of the cars in an array or list before hand, and then test the name of it against all the names in the array or list. if(Physics.Raycast(...)) for(int i 0 i lt listOfCars.length i ) if(carName listOfCars i .name) hitCar listOfCars i However, I've heard that string comparisons (again, especially if there's a lot of intersections with the raycast) can also be taxing on performance. What's the best way to do this? |
0 | How do I slow down my character while running? void Movement() transform.Translate(Vector3.forward 10 Time.deltaTime) if(Input.GetKey(KeyCode.S)) transform.Translate(Vector3.forward 3 Time.deltaTime) if(Input.GetKeyUp(KeyCode.S)) transform.Translate(Vector3.forward 10 Time.deltaTime) I tried this code but seems to me, it didn't work as I expected it to. What I expect my character moves along at a speed of 10 automatically when the S key is held, the character slows down to a speed of 3 instead when the S key is released, the character goes back to their default speed of 10 What I observe the character does not slow down when the S key is pressed How can I fix this? |
0 | SpriteRenderer.flipY not functioning The problem I'm having is that my script, which has access to the spriterenderer on my gameobject, won't flip the sprite when I directly type quot sprite.flipY true quot at the end of my FixedUpdate() function. if (transform.position.x lt player.transform.position.x) facingright false if (transform.position.x gt player.transform.position.x) facingright true sprite.flipY !wasfacingright Heres all of the code if you need it using System.Collections using System.Collections.Generic using UnityEngine public class GunController MonoBehaviour public Transform player public CharacterController2D playercontroller public float smoothness 0.125f public float winglength 2 private Vector2 difference private bool facingright true bool wasfacingright true public GameObject bullet public int maxammo public int ammo public Transform rightNozzle public Transform leftNozzle public SpriteRenderer sprite public Sprite normalGun public Sprite emptyGun public GameObject emptyBottle public Animator reloadAnim Start is called before the first frame update void Start() player transform.parent.transform sprite.sprite emptyGun Update is called once per frame void Update() private void FixedUpdate() doMovement() tryShooting() tryReloading() private void tryReloading() if (Input.GetKey(KeyCode.R) amp ammo lt 0) Instantiate(emptyBottle, transform.position, Quaternion.identity) StartCoroutine(reload()) ammo maxammo private void tryShooting() if (Input.GetMouseButton(0) amp ammo gt 0 ) ammo 1 if (facingright) Instantiate(bullet, rightNozzle.position, transform.rotation) else Instantiate(bullet, leftNozzle.position, transform.rotation) private void doMovement() wasfacingright facingright if (transform.position.x lt player.transform.position.x) facingright false if (transform.position.x gt player.transform.position.x) facingright true sprite.flipY !wasfacingright if (wasfacingright ! facingright) playercontroller.Flip() difference Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.position float rot Mathf.Atan2(difference.y, difference.x) Mathf.Rad2Deg Vector3 pos Camera.main.ScreenToWorldPoint(Input.mousePosition) player.position pos.z 0 Vector3 desiredpos player.position (winglength pos.normalized) Vector3 smoothpos Vector3.Lerp(transform.position, desiredpos, smoothness) transform.position smoothpos transform.rotation Quaternion.Euler(0, 0, rot) IEnumerator reload() sprite.sprite emptyGun reloadAnim.Play( quot Reload quot , 0, 0) yield return new WaitForSecondsRealtime(0.5f) sprite.sprite normalGun public void die() gameObject.SetActive(false) |
0 | How to set rotations to 0,0,0 in 3ds max for exporting in unity? I'm a modeler in 3ds max and the unity programmer ask me that the object must have pivot with Y up rotations at 0,0,0 but every object that I export in fbx he says don't have rotations at 0,0,0. I tryed different solutions as reset xform freeze rotation rotation to zero .rotation eulerangles 0 0 0 but in unity he have values like this 4.577637e 05, 1.525879e 05, 0 or 90, 1.525879e 05, 0 and so on It's a problem that can I fix in max or the programmer has to fix it in unity? Thanks |
0 | Converging at position and angle using motor based rigidbody movement I am given a rigidbody positioned in mathbb R 2 . It is a box of length l and height epsilon . The position of the box's left center is described by vec p , and its angle from the x axis is theta . The body is in a vacuum (no friction), and its mass is m (uniformly distributed). Here's a quick diagram. Next, I am given a target position and angle to reach. It is not guaranteed that the body will reach the target position and angle the next time frame. I need to calculate the necessary force F and torque T that will push the body closest to the target. I am given constraints for max force and max torque. To make things complicated, the body might be affected by external forces. One of them is gravity F g , which will always remain constant. Sometimes, normal forces exist as well. The applied forces or the total force is unknown, but the velocity or the angular velocity is available. I tried to solve this problem using steering behaviors. However, the angle seems to fluctuate constantly. Here's part of my code in C (Unity). vec p 0 transform.position theta 0 transform.eulerAngles.z vec p t position theta t angle private RigidBody body public float SlowDownRadius 2f public float MaxVelocity 50f public float MaxForce 10000f public float SlowDownDelta 15f public float MaxAngVelocity 180f public float MaxTorque 10000f public void Next(Vector3 position, float angle) angle in degrees force Vector2 to position var from (Vector2) transform.position var desired to from var dist desired.sqrMagnitude desired desired.SetMagnitude(dist lt SlowDownRadius SlowDownRadius ? MaxVelocity Mathf.Sqrt(dist) SlowDownRadius MaxVelocity) Vector2 vel body.velocity var steering desired vel var mass body.mass Vector2 force mass UnityEngine.Physics.gravity var time Time.deltaTime var newForce (time lt 0 ? new Vector2() (mass time steering)) force body.AddForce(newForce.Clamp(MaxForce)) limits magnitude of newForce to MaxForce torque var toAngle angle var fromAngle transform.eulerAngles.z var desiredAngle AngleDistance(fromAngle, toAngle) var distAngle Mathf.Abs(desiredAngle) if (distAngle lt 1f) transform.eulerAngles new Vector3(0, 0, angle) return desiredAngle Mathf.Sign(desiredAngle) (distAngle lt SlowDownDelta ? MaxAngVelocity distAngle SlowDownDelta MaxAngVelocity) Mathf.Deg2Rad var angVel body.angularVelocity.z in radians var steeringAngle desiredAngle angVel var newTorque (time lt 0 ? 0f (mass time steeringAngle)) body.AddTorque(0, 0, Mathf.Sign(newTorque) Mathf.Min(Mathf.Abs(newTorque), MaxTorque)) public static float AngleDistance(float from, float to) var dist (to from 180f) 360f 180f return dist lt 180f ? dist 360 dist If I made any errors, please let me know. Thank you in advance! |
0 | Help with a snake like movement I am looking for an algorithm that moves an object at a regular speed in a snake circular like movement. This movement should look pseudo random and smooth, later on I am going to add other body parts, but so far this is the essential. My try so far has consisted in having a random value t that chages each frame t Random.Range(t 20f,t 20f) and according to it I was employing a direction. The result should be more directions that are smoothly different, so that the movement itself is smooth. I would score the solution with 7 10, and moreover, it doesn't describe like short circles, but rather larger ones and the negative result is that the object exits the scene quite fast. What is your algorithm solution? On the internet I found solutions where the player moves the head of the snake, but here the object acts like an autonomous object. |
0 | Calling and functions methods from different Classes in Unity I am learning some of the basics with Unity and am running into calling sending code to a different script. For example, the code below is a basic menu of options. I have a different Scene set up in Unity for each one of the menu options. As you can see from the if else if statements, depending on which option a user checks, will take them to a different portion of the program. At this point it will obviously not compile because the 4 methods for each menu option are not referenced anywhere. Lets say the user selects option 1 which is the StudyScreen() method. Now in the StudyScreen.cs script that I created, how do I link those so when option 1 is selected, it goes to the StudyScreen.cs and runs what I need it to run. using UnityEngine using UnityEngine.UI using System.Collections public class MainMenu MonoBehaviour public Text menu Use this for initialization void Start () menu.text "Main Menu Options r n r n" "1. Study r n" "2. Quiz r n" "3. Test r n" "4. Exit r n" Update is called once per frame void Update () if (Input.GetKeyDown(KeyCode.Alpha1)) StudyScreen() else if (Input.GetKeyDown(KeyCode.Alpha2)) QuizScreen() else if (Input.GetKeyDown(KeyCode.Alpha3)) TestScreen() else if (Input.GetKeyDown(KeyCode.Alpha4)) ExitScreen() I hope I was able to make it clear as to what I was trying to accomplish. Please let me know if anything is unclear. Thanks in Advance. Curtis |
0 | Is there a way to use Post Processing Effects on Mobile? I tried to use the built in unity Post Processing stack, I simply just want a vignette effect for my game, but it when I tested it on my phone it ran lt 25 fps, which is too low in my opinion. Is there a way to recreate the effect for better performance? |
0 | snap an object to another object? so I have some walls which are cubes stretched along a direction.and I have some windows and doors that are suppose to snap to a wall and don't let go until the desired location is out of the snapping range.and in the meantime I want the Objects to move along the wall but never detach from it. if I wasn't clear enough let me know. |
0 | Design basics for Unity game sport management type I am planning the classes for my game and I am having problems to figure out the best way to connect them. In my game I do not have the classic structure of say a FPS where you have the player class with stats, and AI class with enemy AI. my game is more like a sport simulation manager type so there are various entities The player which take over a team (or play in a team) The NPC other players, managers, people that work in the club. The team (club) itself where either the player take control of it, so NPC will join it, or will play in it, so the team will have both player and NPCs. Competitions self explanatory team participate in it. I was thinking to make different base classes, one for team, NPC, player and competitions, but then I need to establish relations between them. This look more like a DB with relation between tables, compared to a standard FPS game, where everything is strictly divided and you don't get class that "belong" to some other class. I am using Unity BTW, so far I ahve the GameManager class which initialize the main menu, the scene manager and UI manager. Then I have 4 different class (player, NPC, competition and team), and this is where I am stuck. Should I create references to other classes, so when I instantiate for example a team class then I will put in it a dataset to represent the NPC classes and the player class? Or should they not know about each other at all, and all the interaction and logic should go in the gamemanager class? |
0 | How do you unzip a Texture2D from image or string from txt from a zip file using SharpZipLib How do you unzip a Texture2D from image or string from a txt file contained in a zip file using SharpZipLib or System.IO.Compression? |
0 | AudioSource not working. Empty Exception I'm trying to load and play an wav file that exists in my Application.dataPath but when the game gets to the line GoAudioSource.PlayOneShot(audioLoader.audioClip) It justs throws a empty exception and no sound is played. I've already checked if the path is correct and it is. I've also tried uploading this wav file to an FTP and loading it via HTTP instead of File but nothing changes. This is my full code private IEnumerator WriteResponseAudio(ResponseModel res) File.WriteAllBytes(Path.Combine(Application.dataPath, FILENAME RESPONSE), Convert.FromBase64String(res.intent.audio.content)) string path "file " Application.dataPath " " FILENAME RESPONSE WWW audioLoader new WWW(path) yield return audioLoader try GoAudioSource.PlayOneShot(audioLoader.audioClip) catch (Exception ex) Debug.LogError("Erro " ex.Message) This is the version with HTTP request private IEnumerator WriteResponseAudio(ResponseModel res) File.WriteAllBytes(Path.Combine(Application.dataPath, FILENAME RESPONSE), Convert.FromBase64String(res.intent.audio.content)) string path "http www.raphaelrosa.com response.wav" WWW audioLoader new WWW(path) yield return audioLoader try GoAudioSource.PlayOneShot(audioLoader.audioClip) catch (Exception ex) Debug.LogError("Erro " ex.Message) This is the console |
0 | In Unity, what's a better solution than having a bunch of singleton static managers? (SceneManager, UIManager, SfxManager, PfxManager) I always hand a bunch of public static manager classes in my game GameManager (singleton) for reading and writing persistent data and gamestate across scenes SceneManager for holding scene data (coins picked up, score, are we in a cutscene) UIManager for dealing with HUD stuff SfxManager for sound effects PfxManager for particle effects On the gameobject that holds these manager classes, there are also subordinate classes (e.g. HUDManager, a smaller class that managers tasks specific to HUD, and then delegate those tasks into other smaller scripts) in order to avoid monolithic manager classes. Is this method frowned upon in Unity game development and if so, what are some better solutions than this approach? |
0 | Does Unity have a built in pathfinding system? I know that there a lot of plugins available for pathfinding in unity but I was just wondering if unity has a built in pathfinding system ? |
0 | Baking lights causes weird seams on meshes. How to avoid it? I'm trying to bake lightning in the simple scene with some imported geometry. The result is weird seams near the edges of the meshes even there is no free space between them. How to avoid it and just simply bake that lightning? This is just something that should not be. |
0 | How to prevent Dynamic Rigidbody2d with large mass pushing another Rigidbody2d into BoxCollider2D I'm making a prototype for a game idea but hitting a problem ( Quite new to Unity and feel like this should be relatively easy to solve, but keep going around in circles, and hoping to get some help ) Video https gfycat.com candidplushemeraldtreeskink GameObjects Red box has BoxCollider2D Duck has BoxCollider2D, Rigidbody2D (dynamic), some scripts Wall has BoxCollider2D, Rigidbody2D (dynamic), some scripts Rules Red box doesn't move, everything should stop when colliding with it Duck moveable by player, can't push quot Wall quot Wall moveable by player, can push quot Duck quot To get quot Wall can push Duck, but Duck can't push Wall quot working, I set the Mass for Wall to be Infinity. However, this seems to have a side effect where Wall can now push Duck through Red box. Note even increasing mass to something like 500 has this side effect too If the mass for Wall is smaller, then it won't push Duck through Red box. However, with the smaller mass, Duck can then push Wall (which I don't want). The script for moving Wall is private void FixedUpdate() https learn.unity.com tutorial world interactions blocking movement?uv 2019.2 amp projectId 5c6166dbedbc2a0021b1bc7c 5ce3cdabedbc2a3ce61754e8 Vector2 position rigidbody2d.position position.x speed horizontal Time.deltaTime position.y speed vertical Time.deltaTime rigidbody2d.MovePosition(position) Question What should I do so quot Wall can push Duck, but Duck can't push Wall quot holds true, without Duck being pushed into the Red box. Should I be using Dynamic Rigidbody (sort of physics with collisions and pushing), or Kinematic Rigidbody (and handle collisions and pushing manually)? Thanks in advance! |
0 | Is there a way to turn collision detection system off completely in Unity? My world setup is 2D Top Down. All collisions are disabled from the collision matrix. There are no collisions in the scene as I wanted, but as I perceive, Unity is still trying to calculate collisions in the background. So I'm experiencing serious frame rate drops because of Physics2D.Simulate when I have about 2k colliders moving over each other on the scene. I followed the suggestions about colliders and rigidbodies on the API exactly (so I know the stuff about not to move static colliders without rigidbody, that's not the case here), but I somehow can't manage to tell Unity that I don't want her to calculate "possible" collisions. I only want colliders for Raycast2D, OverlapCircle and making movements a bit realistic. Thanks in advance for all suggestions. |
0 | How can i use StartCoroutine to set the speed for each scaling step of the walls? using System.Collections using System.Collections.Generic using UnityEngine public class WallsTest MonoBehaviour using a GameObject rather than a transform public GameObject prefab public Vector3 wallsStartPosition public float width 0 public float height 1 public float length 2 public Camera wallsCamera void Start() wallsCamera.transform.position new Vector3(wallsStartPosition.x, wallsStartPosition.y 100, wallsStartPosition.z 235) StartCoroutine(BuildWalls()) IEnumerator BuildWalls() for (int i 2 i lt 2 i ) GameObject go Instantiate(prefab) go.transform.parent transform Vector3 scale Vector3.one Vector3 adjustedPosition wallsStartPosition float sign Mathf.Sign(i) if ((i sign) 2 0) adjustedPosition.x (length sign) 2 yield return new WaitForSeconds(0.1f) scale.x width scale.y height scale.z length width else adjustedPosition.z (length sign) 2 scale.x length width scale.y height scale.z width adjustedPosition.y height 2 go.transform.localScale scale go.transform.localPosition adjustedPosition What it does now it's creating two walls at once it's just waiting 0.1 millisecond before creating them. But instead i want it to show the scaling of the walls how they scaling and moving same for the else part for the adjustedPosition.z and not only the adjustedPosition.x The problem is it's just waiting until it's placing the walls at once. I want to see the walls being building step by step like it's placing cube after cube. |
0 | Quaternion.slerps resets camera rotation to (0,0,0) when i go to play mode help! i am building a camera rotation script like in fps. Everything is setup and working except that camera rotation resets to zero at the start of game which i dont want. This is the camera rotation i have set This is rotation of character my script is attached to And after hitting play it resets camera rotation to (0,0,0). i want it to remain how i have set it in inspector. i am using quaternion.slerp to rotate camera around to rotations on the basis of touch inputs. After reset to (0,0,0) everything works fine.please help, i have always had a hard time understanding quaternions. this is the script public class ScreenCharacterController MonoBehaviour private Camera mainCamera private CharacterController character private int leftFingerID 1 private int rightFingerID 1 private Vector2 leftFingerInput private Vector2 rightFingerInput private float xAxisRotation private float yAxisRotation SerializeField private float minXRotation SerializeField private float maxXRotation SerializeField private float minYRotation 25f SerializeField private float maxYRotation 25f SerializeField private float cameraRotationSpeed 20f void Start() mainCamera Camera.main void Update() for touch TouchInput() for calculating rotation vaues CalculateAndClampRotation() RotateCamera() void TouchInput() foreach (Touch touch in Input.touches) if (touch.phase TouchPhase.Began) Left Touch if (touch.position.x lt Screen.width 2) leftFingerID touch.fingerId Right touch else rightFingerID touch.fingerId else if (touch.phase TouchPhase.Moved) Left Touch if (touch.position.x lt Screen.width 2) if (leftFingerID touch.fingerId) Right touch else if (rightFingerID touch.fingerId) rightFingerInput touch.deltaPosition Time.smoothDeltaTime else if (touch.phase TouchPhase.Ended touch.phase TouchPhase.Canceled) if (touch.fingerId leftFingerID) leftFingerID 1 else if (touch.fingerId rightFingerID) rightFingerID 1 rightFingerInput new Vector2(0, 0) void RotateCamera() Quaternion currentRotation mainCamera.transform.localRotation Quaternion targetRotation Quaternion.identity targetRotation Quaternion.Euler((mainCamera.transform.localRotation.x yAxisRotation), (mainCamera.transform.localRotation.y xAxisRotation), 0f) mainCamera.transform.localRotation Quaternion.Slerp(currentRotation, targetRotation, 0.5f) void CalculateAndClampRotation() xAxisRotation rightFingerInput.x cameraRotationSpeed yAxisRotation rightFingerInput.y cameraRotationSpeed xAxisRotation Mathf.Clamp(xAxisRotation, minXRotation, maxXRotation) yAxisRotation Mathf.Clamp(yAxisRotation, minYRotation, maxYRotation) |
0 | How can I customize remove the caret from Input Fields in Unity? Goal Change the caret to a non blinking asterisk. Description I'm using the TextMeshPro variant of the InputField, and my Unity ver. is 2019.3. Potential Solutions Remove Caret I could remove the caret and manually add an asterisk at the end and remove it upon submission. Problem I don't know how to do that. Caret width doesn't go below 1, and I've yet to see an option to disable it. Change Caret Self explanatory. However, it doesn't appear that customizing the caret character is an option. Shove The Input Field Off Scree And Copy Its Value To Text On Screen I can still use the Input Field (and I need to), but hide it off screen and put a simple Text field in its place, which will display the Input Field's text the caret ( ). This could work, but I'm hoping there's a less hacky solution. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.