_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | Graphics bug after build in Unity 3d i made a terrain on unity. I haven't write scripts yet. But i am getting really big render difference between standalone version and editor verison. Please help me, have nice day. In Editor After build (standalone version) |
0 | Unity, VRChat SDK3, Udon Graph (bug?) I'm trying to create a VRChat world in Unity, using VRchat World SDK3. But I'm getting a strange behavior in Udon Graph assets (as shown by the arrows in the screenshot). Steps I took I've installed the appropriate Unity version (2018 04 20f1) via the hub, Then proceeded to importing VRChat SDK 3 (VRCSDK3 WORLD 2020.12.09.04.44 Public.unitypackage), Then on the project tab, I navigated to the quot Udon quot folder, created a subfolder and inside it I created a Udon Graph Program Asset. Finally, I opened Udon Graph and I added a public GameObject variable. The result was as seen in the image seen bellow the GameObject variable displays a buggy text (the text self (GameObject) shows up twice, superimposed on top of itself as indicated by the arrows in the attached screenshot). |
0 | Rotating Object using Unity's Bolt system I want to rotate a object and stop when it reaches a certain angle using Unity's Bolt, visual scripting. |
0 | Is there any way to get PVRTexTool's version from the command line? I am to make an automated task which involves requiring the version of the PVRTexTool that comes with the Unity installed in a machine. Is it possible to get the version of PVRTexTool on the command shell? |
0 | UNITY I want to make my UI text fade in after 5 seconds I know this question has been asked and asked but none of the topics i visited gave me an answer. I'm making a game programmed in c where you control a boat and i want my UI to appear smoothly by fading in after X seconds. May someone help me? |
0 | How to make your own 2D AABB collision system in unity? I can't use the built in unity 2d physics engine for my game, so I tried to make my own using the unity bounds.Intersects, that is working perfectly but my problem is that I don't know how to make the player stop when It collides. Ive tried multiple things like storing the players last position and "teleporting" it back to that position when it collides (That looks choppy). Ive also tried to invert the controls when your colliding (So like W makes the player go down, A makes it go right ect) but that is extremely buggy. How should I do it? |
0 | How can i make fade in out of the alpha color of a material from black to none black? This is script is attached to a black plane. I have a plane and i added to it a material and the plane is in black. When running the game the alpha color of the plane material is changing slowly. The script is working it's getting slowly from dark black to none black. But i want to make some changes It's not my script i took it from the youtube and did some changes the first one converted from js to c second added the fade bool variable. First of all i don't see any meaning setting the variable timer to 10 at the top. Any ideas what is the point ? Second is how can i check when the alpha color value is high enough to do some stuff Enabled true the fpc again. Once it's not black again the fpc is still enabled false. If i want when the alpha color value reached it's max to make automatic fade back to black Now i'm using manual fade bool variable but i wonder how to do it automatic fade in out. using System.Collections using System.Collections.Generic using UnityEngine using UnityStandardAssets.Characters.FirstPerson public class FadeScript MonoBehaviour public float timer 10.0f public FirstPersonController fpc public bool fade true Use this for initialization void Start() Color tempcolor GetComponent lt Renderer gt ().material.color tempcolor.a 1f GetComponent lt Renderer gt ().material.color tempcolor fpc.enabled false Update is called once per frame void Update() timer Time.deltaTime if (timer gt 0) Color tempcolor GetComponent lt Renderer gt ().material.color if (fade true) tempcolor.a 0.1f Time.deltaTime else tempcolor.a 0.1f Time.deltaTime GetComponent lt Renderer gt ().material.color tempcolor |
0 | Make standard Unity 3D objects non transparent I have a problem. When I add a cube or sphere to the scene they are transparent. How can I disable it? I tried adding materials, but it didn t help and even if it would have helped it still a very dumb way of making standard objects non transparent. |
0 | World coordinates on vertical grid game for different aspect ratios (Unity) new to game development and unity so hopefully someone can help. I want to make a 2D portrait mobile game that will have a grid of constant size where units can move on in Unity. This should support different aspect ratios. To do that I was thinking to cut sections at the top and bottom of the screen for smaller aspect ratios. Additionally, I would like the coordinate system to be natural to the grid, so coordinate (0,0) would be the bottom left tile in the grid, (1,0) would be the tile to the right of that,... To illustrate this concept I drew something quickly I tried with a script that resizes the size of the orthographic camera to fit the content horizontally. Problem I had with that is that I couldn't get a good coordinate system on the grid after the camera gets resized depending on the aspect ratio since the number of horizontal world units varies depending on the aspect ratio. Any thoughts on what would be the best way to do this? Thanks! |
0 | In Unity, how do I correctly implement the singleton pattern? I have seen several videos and tutorials for creating singleton objects in Unity, mainly for a GameManager, that appear to use different approaches to instantiating and validating a singleton. Is there a correct, or rather, preferred approach to this? The two main examples I have encountered are First public class GameManager private static GameManager instance public static GameManager Instance get if( instance null) instance GameObject.FindObjectOfType lt GameManager gt () return instance void Awake() DontDestroyOnLoad(gameObject) Second public class GameManager private static GameManager instance public static GameManager Instance get if( instance null) instance new GameObject("Game Manager") instance.AddComponent lt GameManager gt () return instance void Awake() instance this The main difference I can see between the two is The first approach will attempt to navigate the game object stack to find an instance of the GameManager which even though this only happens (or should only happen) once seems like it could be very unoptimised as scenes grow in size during development. Also, the first approach marks the object to not be deleted when the application changes scene, which ensures that the object is persisted between scenes. The second approach doesn't appear to adhere to this. The second approach seems odd as in the case where the instance is null in the getter, it will create a new GameObject and assign a GameManger component to it. However, this cannot run without first having this GameManager component already attached to an object in the scene, so this is causing me some confusion. Are there any other approaches that would be recommended, or a hybrid of the two above? There are plenty of videos and tutorials regarding singletons but they all differ so much it is hard to drawn any comparisons between the two and thus, a conclusion as to which one is the best preferred approach. |
0 | Decelerate moving platform at targets I'm trying to make a moving platform move at a constant speed and then when it is near the target start to slow down, I have trying to do this with Lerp, but I'm not satisfied with the results because of two reasons it goes way too fast between targets, and way too slow near targets. Also, when it reaches a target it immediately boosts off in the opposite direction. What I want to achieve is for the platform to move steadily between targets, decelerate near targets, and when reaching a target start to accelerate back to the steady speed. What is the best way for achieving this? Lerp, Smoothstep, other? Thanks! (I'm using Unity) My current solution dVeloctiy velocity Time.fixedDeltaTime Vector3 newPosition Vector3.Lerp( rigidBody.position, currentTargetPosition, dVeloctiy.magnitude) rigidBody.MovePosition(newPosition) Vector3 dPosition rigidBody.position currentTargetPosition if (dPosition.magnitude gt 0.05f) isTurning false if (dPosition.magnitude lt 0.05f amp amp ! isTurning) currentTargetPosition (currentTargetPosition targetPosition1 ? targetPosition2 targetPosition1) isTurning true |
0 | How can I optimise my game and its game objects? I have a 3D game in Unity and I use blender to design models for it. My game has a feature where if you click a button, an object is cloned. An example from my game is a tree that is cloned around 100 times with different sizes and positions to form a forest. The issue is that after a few presses of the button, the game starts to really lag. Is there a way to optimise the game in Unity or optimise the models in Blender to reduce this lag? I use the instantiate function in Unity to do my cloning. Some useful information for a generic gameobject (all of them are similar in complexity) faces 12,226 triangles 26,116 memory 13.24 mb gameobjects in scene not static CPU usage mostly spent on rendering Here is a screenshot showing my game running, where the blue part on the graph in the middle is when I click the button Here is a detailed look into the spikes you can see |
0 | Mouse click movement I need to make realistic human movement (3D) using mouse click. Get mouse click point using Raycast. Smoothly Slerp to LookRotation. Move transform.forward. Everything works fine, except I have problem with circular movement (close radius). Example If dont move transform.forward while Slerp to LookRotation or MoveTowards instead of transform.forward it will be spinning like whirligig on circular movement. Example If do move transform.forward while while Slerp to LookRotation it will distort trajectory of straight direct movement. Is there any solution to move circular realistic (not spin like whirligig) and move straight direct when needed (not distort trajectory)? I need straight movement from first example and circular movement from second. if (Input.GetMouseButtonDown(1)) Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hits Physics.RaycastAll(ray) foreach (RaycastHit hit in hits) if (hit.transform.tag "Ground") DestinationPosition new Vector3(hit.point.x, transform.position.y, hit.point.z) DestinationRotation Quaternion.LookRotation(DestinationPosition transform.position) break if (Vector3.Distance(transform.position, DestinationPosition) gt 1) transform.rotation Quaternion.Slerp(transform.rotation, DestinationRotation, RotationSpeed Time.deltaTime) transform.position transform.forward MovementSpeed Time.deltaTime transform.position Vector3.MoveTowards(transform.position, DestinationPosition, MovementSpeed Time.deltaTime) animation.CrossFade("run") else animation.CrossFade("idle") |
0 | Moving non local player from local player with Mirror Networking i am using mirror networking which is based on UNet. I can move non local objects easly by assigning their authority to the local player and move them, but i can't assign remove authority for other player's in the game, therefore i can't directly change their velocity. Any ideas how can i change other non local player's velocity from local player ? |
0 | Unity Bowling ball physics I am working on Bowling Ball game for android. And I want the Bowling Ball to feel like a Bowling ball in the real world. I've already tweaked the Rigidbody values and PhysicsMaterial but it's giving me that result. So, how do I make Bowling ball like real BowlingBall in Unity? |
0 | Unity Where are Asset Store assets downloaded on Mac? I'm on a Mac, running Unity 2021.1.5f1 Personal, and am trying to remove an asset I downloaded using Package Manager. So for the asset in question, I want Unity to have to download the package again, from the Asset Store, to my local mac. That option is currently unavailable, because I have downloaded it in the past. I've tried deleting the contents of these folders, to remove the downloaded file, but still no quot download quot option shows up next to the asset. Library Unity Asset Store Cache Library Unity cache MY PROJECT Library PackageCache I also tried clearing the cache in Preferences Gi Cache I looked in the docs for Asset Store cache, and the closest I found was this link |
0 | Trouble Positioning Object In World I have a lightning effect that travels from point A to point B, I am having trouble placing placing point B correctly. As you can see from the object hierarchy the points (LightningStart, LightningEnd) are nested 3 levels deep. parentReaction.affectorWidget.transform.positionis the position I would like the object to be at. As you can see below I have tried setting the position equal to the other widgets transform, I have also tried using transform.InverseTransformDirection and transform.TransformDirection in varying combinations, I have tried many options the code below is just me going back to basics to see what I missed. I am not sure even which object I am supposed to call TransformPoint from, the Widget with the effect )(Point A) or the Widget at Point B? Given the above scenario how would I position LightningEnd so that is at the same position as parentReaction.affectorWidget.transform.position? I understand this is a very common question and I have read many previous questions related to this but two hours later, I would just like to know how its done so I can understand where I am getting this wrong. Thank you. Edit controller is the Widget Running this effect, since it spawns as a child of this I dont need to worry about its position. public override IEnumerator Do(Widget controller, WidgetReaction parentReaction) effect controller.GetComponent lt Widget Effect Comp gt ().AddEffect(effect) while (true) start effect.effectPrefab.transform.Find("LightningStart").transform end effect.effectPrefab.transform.Find("LightningEnd").transform Debug.Log("End Position " effect.effectPrefab.transform.Find("LightningEnd").transform.position) Debug.Log("Widget World Pos " controller.transform.position) Debug.Log("Widget Local Pos " controller.transform.localPosition) Debug.Log("AffectorWidget World Pos " parentReaction.affectorWidget.transform.position) Debug.Log("AffectorWidget Local Pos " parentReaction.affectorWidget.transform.localPosition) effect.effectPrefab.transform.Find("LightningEnd").transform.position parentReaction.affectorWidget.transform.position Debug.Log("End Position " effect.effectPrefab.transform.Find("LightningEnd").transform.position) yield return new WaitForSeconds(2f) public class WidgetEffect ScriptableObject public string effectName public GameObject effectPrefab public WidgetEffect AddEffect(WidgetEffect widgetEffect) if (!activeEffects.ContainsKey( widgetEffect)) GameObject go Instantiate( widgetEffect.effectPrefab) go.transform.parent effectContainer.transform go.transform.position Vector3.zero go.transform.localPosition Vector3.zero activeEffects.Add( widgetEffect, go) return widgetEffect return null Edit Removed Extended Explanation not related to initial question! ! enter image description here |
0 | Creating a master server for Unity game (Unity 2017) I have a basic FPS game made in Unity. I am using the Unity NetworkManager, NetworkManagerUI and NetworkIdentity components that came with Unity. The game is working fine on my local network when I make one pc a client host and other a client. It is also working great using the 'Mulitplayer' service that is free with Unity (for up to 20 max over all games projects etc, and is supposed to be only for testing I believe) I'm 99 sure it is possible to run a 'server version' of my app on a pc in my home, and make this into a dedicated master server, but I cannot find much at all from Unity officially regarding this (It seems to always point me to just extending my deal with them to get more players into the server they provide, for which the costs are 1000x more than the budget I have for the game) Before Unity were offering these pricey services, there was info such as this https unity3d.com master server But it says that is only compatible with Unity 3.x I've asked this question 2 3 times already on the Unity Answers site, and there are no answers at all. I've also browsed it for similar questions and all those seem to be unanswered or way out of date. As I stated last time I ask this, I know thatt Rust game is made with Unity. In past, I downloaded (officially from Facepunch, the devs of Rust) the 'Rust Dedicated Server' application, which I ran on my desktop PC (with fibre network connection) and then I was hosting a server in game. The server ran smooth as silk, so for my game I dont think i would need an actual modern server machine or direct internet connection (otherwise, how did Rust manage it??) So as I say, I have the network functionality all up n running. But the last piece of the puzzle is that I'm using Unity's Mulitplayer Service, and this only allows 20 max concurrent players. This isn't quite enough, as I'd like to have at least 50 if possible. Also I would end up running 10 20 of these so that there is a choice of 'rooms'. Ideally I would be able to let people download and run their own just like Rust. Before I got to this stage, I was trying to make one user become the Client Host, but I couldn't figure out how the other clients would be able to tell what is the IP address for the host. Please can anybody help me, I feel like I've gotten the majority of the way there but now I can't get any further by myself. Many thanks! |
0 | How can I change the script so it will not be with a while loop inside Update or using coroutine instead? The script is working fine as it is and I don't fell any performance problems and yet I wonder if it's a good idea to run a while loop inside the Update function ? The idea is to be able to move an object over a curved lines with a lot of positions in any speed. So I'm calculating how much positions there is next each time and it's working fine I just wonder about the while in the update. using System using System.Collections using System.Collections.Generic using System.Linq using UnityEngine using UnityEngine.AI public class MoveOnCurvedLines MonoBehaviour public LineRenderer lineRenderer public float speed public bool go false public bool moveToFirstPositionOnStart false private Vector3 positions private Vector3 pos private int index 0 private bool goForward true private List lt GameObject gt objectsToMoveCopy new List lt GameObject gt () Start is called before the first frame update void Start() pos GetLinePointsInWorldSpace() if (moveToFirstPositionOnStart true) transform.position pos index Vector3 GetLinePointsInWorldSpace() positions new Vector3 lineRenderer.positionCount Get the positions which are shown in the inspector lineRenderer.GetPositions(positions) the points returned are in world space return positions Update is called once per frame void Update() if (go true) Move() void Move() Vector3 newPos transform.position float distanceToTravel speed Time.deltaTime bool stillTraveling true while (stillTraveling) Vector3 oldPos newPos newPos Vector3.MoveTowards(oldPos, pos index , distanceToTravel) distanceToTravel Vector3.Distance(newPos, oldPos) if (newPos pos index ) Vector3 comparison is approximate so this is ok when you hit a waypoint if (goForward) bool atLastOne index gt pos.Length 1 if (!atLastOne) index else index goForward false else going backwards bool atFirstOne index lt 0 if (!atFirstOne) index else index goForward true else stillTraveling false transform.position newPos |
0 | What's the difference between Destroy() and SetActive(false)? I read about both methods in Unity and wanted to ask about which was the best in efficiency destroying the object or deactivating it. What is the performance difference? |
0 | iOS 8 iPad Mini Orientation thinks It should be landscape despite it being disabled I've only enabled portrait mode in the info.plist and generally the iPad Mini running my game works fine except if I quickly change its physical orientation from landscape to portrait, the app reorients itself incorrectly like what happened to this person http answers.unity3d.com storage temp 33155 screen shot 2014 10 01 at 8.25.25 am.png (see screenshots, but the repro is different in my case). I've tried hard setting the orientation (Screen.orientation portrait, etc, etc) but looks like it's just ignored.. |
0 | HDRP Decals, how to fix streching decals Is there a quick way to fix strenched decals when they don't quite perpend. to the normals in it's entirety? What I do now is to get the normal of the surface and rotate decal accordingly, but with extreme angled corners it gets streched as a result. |
0 | Unity Performance Recycling Pooled Objects OR Re Instantiating? Re using pre instantiated objects in a pool. Destroying then re instantiating objects in a pool. Both pools are limited. When creating loads of objects which is better for performance? |
0 | How to proper manage a world composed by multiple scenes? I have a UI only scene for my game that have only Unity UI elements (those that need a Canvas), separate from the world scene. In the UI scene I have a MonoBehaviour that manage all the effective actions and all the interactions between different UI elements, and In the world scene I have another manager responsible for controlling all the other things in the game scene. This design worked pretty well until I faced the following situation in a specific moment the player need to click in BoxColliders that are in the world scene but it is actually a UI related action. This action of clicking in these BoxColliders are essentially the player clicking in buttons that in this case happen to be 3d objects that need to be composed in the environment, thus need to be in the world scene. In the situation described above the clicks on those BoxColliders should be managed by the UI Manager, that is alive in the UI scene. So the problem is how should I approach this whole situation without breaking a lot of clean code rules? What is tipically done when developing in Unity to solve this kind of problem when you need a reference for an object that lives in another scene without keeping a hard reference for this object (or just calling GameObject.Find in the scene startup)? |
0 | Generate random number in Unity without class ambiguity I have a problem in Unity (C ) where I would like to create a random number. I wanted to use System.Random (reference using System) but Unity complains that it's ambiguous to their own UnityEngine.Random. I can not specify the reference (using System.Random) as random is not a namespace. How do I specify that I want to use the system random and not the Unity one? |
0 | Animation imported from Maya has interpolation issues I have imported animation from Maya (.fbx) and the curves for the animation in Unity are very different than in Maya. I can clearly notice a flicker for few seconds when I am scaling the object (0 to 1) in loop. The curve for scaling is shown below. The rest in the animation work fine except for the scale. The problem is that Unity adds interpolation automatically to these curves which is why it creates an issue. I have selected the keys in the curves for the scale attribute and quot Both Tangets gt Constant quot , but it did not have any effect. How can I fix this? |
0 | Problem in player Rotation in Unity I am trying to rotate game camera using my android device orientation.Like this Using accelerometer input of device this may be done. But I don't know how to do this. I tried lot of methods, but failed. Anybody please help. I am using unity 5.3 with C . |
0 | Why is my color on my obj not showing in Unity! I've been trying to import my full color obj files to unity for a while now, but I can't get them to be in color. All of the colors show up in Meshlab, but not in Unity. All of the youtube videos I have watched have said that I need some sort of texture file but my obj doesn't have one. It is just the obj and it somehow has color in Meshlab. Is there some sort of setting I need to change in Unity? If I need a texture file for it to work, is there a way I can extract the texture file(s) from the obj? |
0 | My game crashed... Access Violation (0xc0000005) I guess this is the first official crash I've had in Unity (that is not just an infinite loop.) The game works just fine in the editor but when build and run it, the game won't even start. I just keep getting this error message So I check the folder specified but I have no idea what I'm looking at if I'm completely honest with my self. I see a bunch of directories and stuff but that's about it. I don't know how to read an error log but I'd like to. This whole game is a learning experience so I would to learn how but Idk what to do. this is the error log Here If need be I'll put it in the question but I'd like to avoid making this too long. If you have any questions about my code you need to know let me know. |
0 | How to put the output of one game into another? I want to add the screen of vrchat into a unity game environment so that I could play vrchat from a screen inside the unity environment. Is that possible? If not, why not? |
0 | How to increase the difficulty setting as close as possible to maximum difficulty automatically? I have a simple 2D version of Mini golf. The goal is to manage to clear each level in the least amount of shots, the ball is bouncing at most 3 times (stops on the 4th hit) from a wall but not reducing in speed, there is no out of bounds and no obstacles that would remove the ball. Now I would like to add some water instant death obstacle at the most annoying places. How do I find those places? The player can aim in a 360 radius, if I set the goal of managing a given level in 2 shots, there are 129,600 ways of how the player could shoot the ball. While it should be possible to simulate all of those shots fairly easy, I don't want to add randomly water and check if the level is still possible to clear, rather simulate the level, record all places the ball went over and place on the spots with the most hits water. What is the best strategy a good algorithm to blockade the most ways but to guaranty that at least one way stays clear? Does the strategy change significantly if moving obstacles (on a fixed path, same rule for bouncing as normal wall) are included? |
0 | SmothStop Function doesn't work as expected i'm trying to create a smothstop function i need it to control time variable on my lerp function used to move character and so on...what i have is this private float SmothStop(float t) return 1 (1 t t t t t) problem here is that will start slow then accelerate... same as smothstart function.. that i already tested and work on that way.. so.. what i'm missing up? |
0 | Converting shader to ShaderGraph Is there a way to convert the below piece of shader code to shader graph? I am not sure how to find float2(i, i) in shader graph. fixed4 frag (v2f input) SV Target float2 res MainTex TexelSize.xy float i offset fixed4 col col.rgb tex2D( MainTex, input.uv ).rgb col.rgb tex2D( MainTex, input.uv float2( i, i ) res ).rgb col.rgb tex2D( MainTex, input.uv float2( i, i ) res ).rgb col.rgb tex2D( MainTex, input.uv float2( i, i ) res ).rgb col.rgb tex2D( MainTex, input.uv float2( i, i ) res ).rgb col.rgb 5.0f return col |
0 | LOD culled gameobject still interacts with raycast The camera is sort of top down and the player can move objects around, rotate them, delete them etc. I use a raycast to check what was hit when the player clicks. But some objects are culled by the LOD group when far away, but the LOD group only disables the renderer, not the colliders, so it still interacts with the raycast. This means a player can move or delete an object that they can't even see. I've tried looping through all the renderers in the lod group and using renderer.isVisible but it doesn't solve the problem of collision and raycasts. I'd really rather not poll isCulled every frame in update either because there are thousands of gameobjects, that would be horrible for performance. LODGroup lodGroup GetComponent lt LODGroup gt () LOD LODs lodGroup.GetLODs() for (int i 0 i lt LODs.Length i ) LODRenderers LODs i .renderers bool isCulled true for (int i 0 i lt LODRenderers.Length i ) if (LODRenderers i .isVisible) isCulled false |
0 | How to detect when the mouse is over a particular enemy collider, without falsely selecting bullet colliders? I have an enemy shooting around. My game mechanic involves hovering over the enemy with the mouse to drain its health. While the enemy is moving, you need to follow it with your mouse. If you don't succeed to follow it and the mouse leaves the enemy's collider, the enemy's health should be refilled. The trouble is that the enemies' bullets have also a collider, and OnMouseOver acts weird when more colliders appear on top of each other. How can I only select a particular Layer for the enemy to detect only that layer without acknowledging the bullets layer? My Code so far public class FightDarkalls MonoBehaviour Header("Guidance Light On?") public bool guidanceLight false Header("Target Settings") public GameObject monster public GameObject targetEffect public Animator TargetEffectAnim public LayerMask monsterLayer int layer Space Header("Damage Darkall") public float damage 0.1f public float damageSpeed 2.5f Header("OBJs to deactivate when Darkall dead") public GameObject deactivateOBJsOnDeath Header("Health Settings") public GameObject healthBar public float startingHealth public float health public GameObject deathDarkallParticle Animator private Animator anim Vector2 mousePosition public LayerMask interactLayer private void Start() targetEffect.SetActive(false) anim GetComponent lt Animator gt () TargetEffectAnim targetEffect.GetComponent lt Animator gt () private void Update() CheckIfGuidanceIsActive() healthBar.transform.localScale new Vector2(health, 1f) deathDarkallParticle.transform.position Vector2.Lerp( deathDarkallParticle.transform.position, monster.transform.position, 100f Time.deltaTime) SetMousePosition() void CheckIfGuidanceIsActive() if (GameObject.Find(" GuidanceLight").GetComponent lt FollowCursor gt (). guidanceActivated true) guidanceLight true else guidanceLight false private void OnDrawGizmos() Gizmos.DrawSphere(mousePosition, 1f) private void OnMouseOver() if ( guidanceLight) DAMAGE health damage Time.deltaTime damageSpeed anim.SetBool("TakeDamage", true) Activate Target Effect targetEffect.SetActive(true) TargetEffectAnim.SetBool("OnDarkallOver", true) Damage the target Kills the target if (health lt 0f) foreach (GameObject dOBJs in deactivateOBJsOnDeath) dOBJs.GetComponent lt SpriteRenderer gt ().enabled false Change Cam Shake to another OBJ GameObject.Find("Main Camera").GetComponent lt CameraShake gt ().CamShakeEffect(0.1f, 0.5f) health 0f deathDarkallParticle.SetActive(true) deathDarkallParticle.GetComponent lt ParticleSystem gt ().Play() monster.gameObject.SetActive(false) Destroy( monster.gameObject, 3f) private void OnMouseExit() anim.SetBool("TakeDamage", false) If failed to kill, reset health health startingHealth Deactivate Target targetEffect.SetActive(false) TargetEffectAnim.SetBool("OnDarkallOver", false) void SetMousePosition() mousePosition Camera.main.ScreenToWorldPoint(Input.mousePosition) |
0 | How can I color in only specific regions of my scene? I am interested in having large portions of my game be grayscale, but I'd like certain parts of the scene to have full color. Something like this Is this something that is possible with shaders or the like within unity? What sort of techniques would I need in order to leech color from most areas like in my screenshot above? |
0 | Is it possible to get a Vector3 from a single Input Action in Unity's Input System? I'm trying to implement moving up down (R F), left right (A D), forwards backwards (W S) all at the same time using Unity's new Input System. There is an Action type for Vector3, but there doesn't seem to be a corresponding type for it. The way movement works right now means that it would be a lot better to get the whole vector at the same time for it to work smoothly. Is there a way to do this with a single Input Action, or will I just need multiple? |
0 | Unity Messages in Compound Colliders Lets say I have a 2D character with two colliders a circle collider that represents the feet, and a box collider that represents the body. Lets say that the character is currently standing on the ground, i.e. only the feet collider is in contact with the ground collider. According to the Unity manual, I will receive an OnCollisionEnter2D message. That message contains a Collision2D object that contains an otherCollider field of type Collider2D. I don't see anything in that object that would tell me which of the two colliders the body or the feet initiated the message. So my question is this how do you figure out which collider in a compound collider initiated a collision trigger message? |
0 | How Lots of ComputeBuffers at Once Affect Performance Unity How will lots ComputeBuffer instances affect performance? And why? I know that I should call ComputeBuffer.Release() on every ComputeBuffer I create, but will it affect performance if I were to have lots of open ComputeBuffers at once? and by "lots" I mean hundreds to thousands. It of course goes without saying that all of those ComputeBuffers will be released at some point, possibly at the same time. |
0 | Calculate heading required to turn ship so that its weapon can fire at target I have a ship, the ship travels towards a heading (vector3, blue arrow) with an arbitrary speed. The ship has a weapon on the side, the weapon can point in any direction, except straight forward backwards from the ship heading. (In example image the weapon is a perpendicular 90 right). The weapon has a firing arc, in n degrees (so, n 2 degrees in either side from the weapon "point direction"). Given a target at any position on the same side of the ship as the weapon (red circle), how do I rotate the ships heading so that when oriented towards the new heading (in this example, the yellow arrow), the target is inside the bounds of the firing arc? (The ship cannot rotate on the spot, it turns by driving forward towards a heading, like a simplified aircraft) While my game is set in full 3D, I think a 2D solution will be more than enough. I use Unity, and C , but I'm thankful for any solutions. Edit To clarify, I am looking for the "math based" solution, collision checks etc isn't really feasible. |
0 | Creating a curved mesh on inside of sphere based on texture image coordinates In Blender, I have created a sphere with a panoramic texture on the inside. I have also manually created a plane mesh (curved to match the size of the sphere) that sits on the inside wall where I can draw a different texture. This is great, but I really want to reduce the manual labor, and do some of this work in a script like having a variable for the panoramic image, and coordinates of the area in the photograph that I want to replace with a new mesh. The hardest part of doing this is going to be creating a curved mesh in code that can sit on the inside wall of a sphere. Can anyone point me in the right direction? |
0 | Detecting a mouse click While in a Trigger Why does the following code not working? (weird, sometimes it works sometimes not ) I want to move player by touching on the screen and change the color of gameObject when detect trigger and release mouse click. quot Drag and move quot script works correctly I just add following code and sometimes it works sometimes not private void OnTriggerStay2D(Collider2D colider) if (Input.GetMouseButtonUp(0) amp colider ! null) colider.gameObject.GetComponent lt SpriteRenderer gt ().material.color Color.blue There is a full script private Camera cam private Vector3 daragOfset SerializeField private float speed 4.55f private bool isEntered false void Update() if (Input.GetMouseButtonDown(0)) daragOfset transform.position GetMousePos() private void OnTriggerStay2D(Collider2D colider) if (Input.GetMouseButtonUp(0) amp colider ! null) colider.gameObject.GetComponent lt SpriteRenderer gt ().material.color Color.blue void Awake() cam Camera.main void OnMouseDrag() transform.position Vector3.MoveTowards(transform.position, GetMousePos() daragOfset, speed Time.deltaTime) Vector3 GetMousePos() var mousePos cam.ScreenToWorldPoint(Input.mousePosition) mousePos.z 0 return mousePos |
0 | How to animate an arc from the middle in both directions I have been able to make an arc that animates from one end to another using the following coroutine IEnumerator AnimateArc(float duration) float waitDur duration pts for (int i 0 i lt pts i ) float x center.x radius Mathf.Cos(ang Mathf.Deg2Rad) float y center.y radius Mathf.Sin(ang Mathf.Deg2Rad) arcLineRend.positionCount i 1 arcLineRend.SetPosition(i, new Vector2(x, y)) ang (float)totalAngle pts yield return new WaitForSeconds(waitDur) How can I animate this arc from the middle in both directions at a constant speed with an ease (animates slightly faster in the middle and slows down towards the end) |
0 | Unity 2D Inconsistent jump height in game window Whenever I start the unity editor and play it in the Game windows, sometimes the object can jump higher sometimes it is just small jump. I didn't change any value in my script nor changed it in inspector window. It usually happens when I restart the unity editor or having my computer shutdown restart and reopening the project. Here are the jump code void jump() if (isInGround) float currentJumpForce jumpForce Mathf.Abs(rigidBody.velocity.x) 3.53f rigidBody.AddForce(Vector2.up currentJumpForce) animator.SetTrigger("isJump") I place the code inside the FixedUpdate method, for what I have read the physics calculation should be inside FixedUpdate right? private void FixedUpdate() if (Input.GetKeyDown(KeyCode.UpArrow)) jump() I have read many are having similar problem, but it really doesn't answer this question. UPDATE I forget to explain it in the question. The jumpForce is calculated based on the velocity of the gameObject has. I capped the velocity to certain speed based on this code void accelerate() if (rigidBody.velocity.x lt maxSpeed) rigidBody.AddForce(Vector2.right acceletateForce) where maxSpeed is a constant. I know this is probably not the accurate way to cap the velocity, or is it? Maybe this is where it gets messed up? I just kinda assume the velocity is the capped from the camera movement and the 'display' or the movement of the screen. It seems the same to me. |
0 | In unity, some part of mesh doesn't show only in play mode This is screenshot of not playing mode. You can see the the speedloader and bullets inside of the revolver. And this is when playing mode. As you can see, I can see the speedloader and bullets in scene view, but not player's camera. Sometimes, it disappears in scene view either! I made this model same as other weapons, but others are working fine. Only this weapon causes this problem. All weapons that I made are based on same model and rigs, and I kept the weapon's scale fit as same as possible. I tried move the camera and scale down a little bit, but still couldn't saw. Why this is happening? How do I solve this? Any advice will very appreciate it. |
0 | Queueing with Unity's NavMeshAgent I have created a strategy game where the units use Unity's NavAgent pathfinding and flocking algorithms. This works well. However, I need to add queueing so that units will queue sensibly. This works most of the time, but it isn't perfect and I want to know if there's a better way of doing it. My first draft was to simply check which unit is closest to the destination, but this caused issues because a group might be navigating around an obstacle and the unit closest is at the back of the queue... so the whole group stops. Second draft checked the distance to destination based upon the length of the path each unit had to take. This works far more often, but sometimes still has issues. Sometimes the same problem happens, but much less often. The one who is supposed to be moving stops, and so the entire group stops. There's also a problem I've noticed, where the waiting units could sometimes benefit from rotating, even if they shouldn't be moving. Unfortunately they sometimes get stuck and will wait before they can move, to rotate. If they could rotate when forbidden from moving it'd help considerably too. What I need to know... How can I make Unity NavAgent's queue, so that they will wait for the other agents closest to the destination to move first? How can I ensure that this does not stop agents from rotating while in a queue (rotating may move them into a better position in the queue). Code Unit Movement Function private void Movement() Unit is moving. if (moveVectors.Count gt 0) navAgent.isStopped false Check for whether to wait in queue. Vector3 nextVector transform.position nextVector transform.forward speed Time.deltaTime foreach (Unit unit in list) if (unit ! this amp amp unit.moveVectors.Count gt 0 amp amp Vector3.Distance(unit.transform.position, nextVector) lt (unit.footprint footprint) amp amp PathDistance(unit) lt PathDistance(this)) navAgent.isStopped true return There's a bit more to Movement, but it's not relevant so we'll ignore it for now. PathDistance Function private float PathDistance(Unit unit) Vector3 startPosition unit.transform.position Vector3 endPosition unit.moveVector Vector3 lastPosition startPosition Vector3 path unit.navAgent.path.corners float distance 0 for (int i 0 i lt path.Length i ) distance Vector3.Distance(lastPosition, path i ) lastPosition path i distance Vector3.Distance(lastPosition, endPosition) return distance Is there a better way of achieving the result I want? |
0 | Get width of a 2D GameObject in Unity I'm trying to get the width and height of a 2D GameObject. My GameObject is simply a prefab created using sprite. I have tried solutions from other posts but they don't work for me Vector2 size myGameObject.GetComponent lt CircleCollider2D gt ().bounds.size float width size.x float height size.y and Vector2 size myGameObject.GetComponent lt Collider2D gt ().bounds.size float width size.x float height size.y My prefab has a Circle Collider 2D but x and y always returns 0 I'm using Unity 5.5.0f3, not sure if previous solutions apply to this version. |
0 | Instantiating a GameObject at my desired position not working I'm sure I am misunderstanding something about Unity vectors or something here. I am brand, brand new to Unity so this is part of the problem. I am trying to make a simple atomic model and I am trying to model valence electrons. I've got a game object with two children the symbol (which is working perfectly), and a child electron. If an atom has more than 1 valence electrons, I add those as additional child objects. All of this is working just fine except for one part. I have a default position for the original child valence electron, but when I try to add additional children and set their positions, they're not anywhere near where they should be. For example My Model My base electron My additional electrons look like this And here is my output obviously not right So here's my function to add additional electrons void addElectrons(Rigidbody2D atom) AtomData.AtomData atomData atom.GetComponent lt Atom gt ().atomData if (atomData.ValElec gt 1) for (int i 1 i lt atomData.ValElec i ) GameObject electron Instantiate(electron obj, new Vector2(0.2f, 0), Quaternion.identity) as GameObject electron.name "Electron " (i 1).ToString() electron.transform.localPosition new Vector3(.02f, 0, 0) electron.transform.localScale new Vector3(.05f, .05f, 0) electron.transform.parent atom.transform I've tried Vector2 (currently shown above), a new Vector3 in transform.localPosition (shown and commented out), as well as in transform.position (not shown, but similar to localPosition). What exactly am I doing wrong here? I am strongly guessing that I am misunderstanding the vector math or something here. |
0 | Unity UI making it responsive I am attempting to create a simple Jeopardy game using the UI features of Unity However as im trying to change the size of the screen it does not seem that my UI is responsive Here is it in 16 9 Here it is in 600x900 My Question is. is there a way to make it responsive? Is it even nessary to do so in unity or am i thinking way to much web based? ) Hope someone is able to help me and guide me abit |
0 | Finding a moving target in a maze I'm making a game that is a bit of a mix of snake and pacman. Basically, two players go through the maze and each time they pick up a piece of candy, a cube is added to their tail. If one player touches the other's tail, he steals that piece for himself and the game is over when one player has all the pieces. Right now they both move randomly unless there's a piece of candy one space away that is not their tail. I'm trying to find a method algorithm (preferably a different method for each player) for both players to target avoid the other player. Any advice? |
0 | Precision timing in Unity3d I am trying to implement a method which should be called each 10ms with a precision not less than 0.1ms (better 0.05ms). This method is very complex and it is generating sound samples which are placed to float buffer to be played with OnAudioFilterRead function. I have tried both Coroutines and InvokeRepeating both are bad, because they can call the method with period from 7ms to 13ms which is not acceptable. The only idea I have is another Task with while() cycle checking the Time.realtimeSinceStartup permanently. But I feel like this is a bad idea. Can you help me? Thanks. |
0 | Unity 3d Animation Flickering We are using 3d bus model for our game in Unity 3d.Animation works perfectly fine on Samsung s3 but some kind of texture flickering occurs on Nexus device.Please help us out how to solve this problem. Thank you |
0 | unity Rigidbody jump I absolutely don't know what is the problem with this code and I have tried everything without any success. I need help. void FixedUpdate() if (Physics.Raycast(transform.localPosition new Vector3(0f,0.1f,0f), transform.up,0.2f) ) grounded true else grounded false if (Input.GetButtonDown ("Jump") amp amp grounded) rb.velocity Vector3.up jumpSpeed Some time it jumps and some time it doesn't jump with no visible pattern. |
0 | How can I uniquely identify a GameObject in Unity? I'm trying to serialize and deserialize my custom classes with Unity. I've got an ISerialize interface that mandates the class can Load() and Save(), so then I setup one master class to iterate across everyone and find the ISerialize components and trigger them to Load() and Save() correctly public class SerializationTest2 MonoBehaviour, ISerializationCallbackReceiver GameObject gameObjects null Start is called before the first frame update void Start() gameObjects UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects() comment Update is called once per frame void Update() public void OnBeforeSerialize() Debug.Log("Unity is serializing... saving state!") foreach (GameObject gameObject in gameObjects) Save(gameObject) public void OnAfterDeserialize() Debug.Log("Unity finished serializing... loading state!") foreach(GameObject gameObject in gameObjects) Load(gameObject) private void Load(GameObject gameObject) Debug.LogFormat("Found 0 ", gameObject.name) ISerialize serializers gameObject.GetComponents lt ISerialize gt () foreach (ISerialize serializer in serializers) serializer.Load() int nChildren gameObject.transform.childCount for (int i 0 i lt nChildren i ) Load(gameObject.transform.GetChild(i).gameObject) private void Save(GameObject gameObject) Debug.LogFormat("Found 0 ", gameObject.name) ISerialize serializers gameObject.GetComponents lt ISerialize gt () foreach(ISerialize serializer in serializers) serializer.Save() int nChildren gameObject.transform.childCount for(int i 0 i lt nChildren i ) Save(gameObject.transform.GetChild(i).gameObject) So this works GREAT and exactly as intended I get a list of all the top level root objects on Start(), then I get the serialize deserialize callback. I iterate down the tree of GameObjects for each root and get everyone. The idea here is that this class will eventually open an XML file and save to that file for serializing or will load from that file for deserializing. I need to build that XML hierarchy, though. I could have multiple instances of a class scattered across a bunch of different GameObjects, so I need some way of identifying which GameObject I've currently got so I can serialize deserialize to the correct components for that GameObject. The problem is that, when I use the above code, I get UnityException GetName is not allowed to be called during serialization, call it from Awake or Start instead. Called from MonoBehaviour 'SerializationTest2' on game object 'Registrar'. See "Script Serialization" page in the Unity Manual for further details. So, then, how do I uniquely identify the GameObject I'm currently on? If I can't call gameObject.name, what should I be calling? EDIT As an example, consider two enemies one has a scale of 2x the other and a hitDamage of 2x the other, but they otherwise use the same EnemyAttack script. I need to deserialize the hitDamage values to the correct GameObject, but if I can't use the GameObject's name during the serialization process then I don't know how I'm supposed to distinguish the two. |
0 | Using Steering Wheel in Unity Is there any way to use a steering wheel in Unity? All I find online is people with the same problem. The numbering on the axis are not the same as with keyboard input. In some cases left is 1 and as you turn it more to the left it gradually goes down to 0 even though you are still turning left |
0 | Use raycast to fix bullet's direction? Player cam has a raycast. I need it to work as pointer for player's bullet direction. If the ray hits any kind of object this spot will be the aim of player's bullets. Here is my script public class camraycast MonoBehaviour Camera mycamera GameObject prefab public int bulletSpeed 10 public GameObject angle camera public GameObject players void Start () prefab Resources.Load("bullets") as GameObject mycamera GetComponent lt Camera gt () void Update() if (Input.GetMouseButtonDown(0)) Vector3 camScreen new Vector3(0.5f, 0.5f, 0f) center of the screen float rayLength 100f Ray ray mycamera.ViewportPointToRay(camScreen) RaycastHit hit Debug.DrawRay(ray.origin, ray.direction rayLength, Color.red) if (Physics.Raycast(ray, out hit, rayLength)) print ("Looking at " hit.transform.name) GameObject bullets Instantiate(prefab) as GameObject bullets.transform.position players.transform.position angle.transform.forward 0.1f Rigidbody rb bullets.GetComponent lt Rigidbody gt () rb.AddForce((hit.point angle.transform.position) bulletSpeed) Destroy(bullets, 9f) Vector3 camScreens new Vector3(0.5f, 0.5f, 0f) center of the screen float rayLengths 100f Ray rays mycamera.ViewportPointToRay(camScreens) Debug.DrawRay(rays.origin, rays.direction rayLengths, Color.red) |
0 | How to properly rotate a Turret? I'm having problems understanding how to properly rotate a Turret. Using Unity Editor, I've simulate turret movement, so I take note that turret can move with this clamp factor (for instance) ( value expressed in euler angles ) X 1 4 Y 0 0 Z 98 100 I've write this code but it not works properly float rotX Random.Range (Cannon1MinX, Cannon1MaxX) float rotY Random.Range (Cannon1MinY, Cannon1MaxY) float rotZ Random.Range (Cannon1MinZ, Cannon1MaxZ) Cannon1.transform.Rotate (new Vector3 (rotX, rotY, rotZ),Space.World) Every time I've to work with rotation i become mad ( What is wrong ? Thanks |
0 | How do you create hitboxes that will detect stationary targets too? I've created a basic attack combo system that chains 3 attacks together. When the player clicks the mouse button, it enables a boxCollider2D attached to the player. The boxCollider is a trigger and will cause damage to a valid target using OnTriggerEnter2D. This doesn't seem to be very responsive, and often will not work if the target is stationary. I've thought about trying Raycasts as an alternative but am looking for advice on how to handle this properly. public class Attack MonoBehaviour private int comboIndex public float lastAttack private Animator animator private string attackName private float comboResetTimer private BoxCollider2D hitbox private void Awake() attackName new "Attack1", "Attack2", "Attack3" animator GetComponent lt Animator gt () hitbox GetComponent lt BoxCollider2D gt () private void Update() var canAttack Input.GetMouseButtonDown(0) if (canAttack amp amp comboIndex lt attackName.Length) animator.SetTrigger(attackName comboIndex ) hitbox.enabled true comboIndex comboResetTimer 0f if (comboIndex gt 0) comboResetTimer Time.deltaTime if (comboResetTimer gt lastAttack) animator.SetTrigger("Reset") comboIndex 0 hitbox.enabled false |
0 | Stencil based mask with alpha I'm trying to create a fog effect like civ 5 I tried creating a StencilSet shader that receives a mask and sets the stencil buffer to 1. I would render the following on every unexplored tile using this shader. White is full alpha, black is 0 alpha, gray is in between. Then I created a StencilUse shader that would display the cloud as one big texture, but will test that stencil value is 1. This way the cloud will only be shown on top of the unexplored tiles ( a bit of overlap outside the tile, per the mask sprite). This is what I got The problem is that I can't produce the fading effects towards the end of the cloud. It's either fully visible or not visible at all. How would I be able to use the grey areas when determining the alpha value of the cloud? Any ideas? (I'm using Unity) |
0 | Intellisence doesn't show the ECS API Summaries I am not sure if this is more of an ECS topic problem or packages in general. but it would be really helpful for ECS programming with all the summaries the Unity has provided. For unity engine methods, intelligence show me descriptions and summary of classes and methods, but it doesn't work on packages I guess. I have tested this with all IDEs, AutoComplete doesn't show the description for methods and classes. However, I can go to the declaration of packages source code and see the summary. for example, Below you can see a screenshot in the Jetbrain Rider IDE, as you see when I mouse over OnCreate method it doesn't show the description. |
0 | ArgumentException The Object you want to instantiate is null I am trying to copy data over from a binary file but when trying to instantiate a gameobject, it comes out as "null". static void LoadBuildings(SaveBuilding buildings) if (buildings.Length 0) return foreach(SaveBuilding b in buildings) if(b.type.ToString() "Farm") Farm build Instantiate(Resources.Load("Farm")) as Farm Debug.Log("Build " build) build.position.x b.positionX build.position.y b.positionY build.level b.level build.levelText build.GetComponentInChildren lt Text gt () The debug line shows there is no object and when the next line tries to execute I get an error ArgumentException The Object you want to instantiate is null. I initially had it as Farm build Instantiate(build.prefab) as Farm as I get an error "Use of unassigned local variable". I tried adding a prorperty above the if statement "GameObject build", I tried doing Farm build new Farm() above the if statement also but still get the initial error. I have a folder titled "Resources" and confirmed a prefab labelled "Farm" is there also. Could it have anything to do with the "static" prefix for the method? |
0 | How to apply force towards direction using mouse drag and or touch input direction and input speed? I've to object. I can move object 1 (my Player) using mouse (or Touch for smartphone version). I want apply a force to object 2 when object 1 hit it. Force direction must be mouse vector direction or touch vector direction. For Mouse input i'm using event OnMouseDown and OnMouseDrag to determine mouse original position. But I think this is not the best approach. Behaviour is not what i am expecting void OnMouseDown() mouseDragStartPosition Input.mousePosition translate the cubes position from the world to Screen Point screenSpace Camera.main.WorldToScreenPoint(transform.position) calculate any difference between the cubes world position and the mouses Screen position converted to a world point offset transform.position Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z)) void OnMouseDrag() keep track of the mouse position var curScreenSpace new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z) convert the screen mouse position to world point and adjust with offset var curPosition Camera.main.ScreenToWorldPoint(curScreenSpace) offset transform.position new Vector3(curPosition.x, ClampY, curPosition.z) void OnCollisionEnter(Collision collision) Debug.Log("OnCollisionEnter") if (collision.collider.tag "Disc") ApplyForce() void ApplyForce() Vector3 direction mouseDragStartPosition Input.mousePosition direction new Vector3(direction.x, ClampY, direction.z) ClampY used to not allow Y DiscRb.AddForce(direction 1, ForceMode.Impulse) |
0 | Can't interact with anything in UI canvas, although it was working previously I'm working on a menu with several buttons and input fields. For a while everything was working fine, but suddenly every button and input field is not reacting to being clicked on, as if everything's been disabled. This problem is only occurring in one of my scenes. My canvas has a graphic raycaster and my buttons have methods attached to them. |
0 | FPS drops when I maximize the game tab in Unity Editor I have a simple unity scene with some primitive objects like cubes and spheres. Most of the objects are static and I made backed GI for lighting, The light is a point light. I also used unity post processing asset for the depth of field. FPS in normal game window size is about 500 but when I maximize the Game tab, FPS goes around 30. Why does this happen? FPS 500 FPS 30 |
0 | How to make a long highway in unity? I'm planning to make a long highway for a Racer game. What is the best way to do it ? Do you make it in a single scene which I think is difficult to manage ? Or do you make multiple scenes or anything else ? |
0 | Ouya build experiencing odd graphical artifacts, screen half black I'm witnessing very odd graphical artifacts when I run my Unity game on Ouya. After the Unity splash screen, the game loads with the screen half black. This seemingly has started occurring out of the blue. It also doesn't occur in the editor or the standalone build, only on Ouya. I can't think of a single reason why this would be happening. If I open the Ouya menu screen and close it, the game returns to normal somewhat, as there may be some artifacts lingering but the screen isn't half black like in the screen shot above. I know there's not much to go off of, but any insight into why this may be happening is greatly appreciated. |
0 | Make object face another object on a sphere I have a game I'm working on in Unity where there are two objects on a sphere at random locations (and random rotations). I want one of the objects to always rotate so that if it were to fire a bullet (the end goal) that it would fire at the other object along the shortest arc around the sphere. The problem I'm facing is that I don't know how to create a rotation for an object that is on the surface of a sphere, and have it point towards the other object. I can also see an issue after this where I would need it to point towards the other object in the shortest distance because there will always be two directions it can point towards. Has anyone done something like this? Definitely stuck on this one. |
0 | Unity3D Cost of accessing a script via a static reference to the instance I saw this pattern around and I was wondering what would be the pros and cons about it. Does this suffer performance issues ? If so what would be a better alternative? using UnityEngine using System.Collections public class SomeClass MonoBehaviour public static SomeClass instance void Awake () instance this And in an other script use it like so SomeClass.instance.SomeMethod() |
0 | Why are my animated objects (from Blender) always playing at the global origin in Unity? I created and animated a sledgehammer in Blender 2.67b using an armature. The sledgehammer has one animation (created using the Action Editor) called "Idle". I parented the imported sledgehammer to an empty GameObject and set the sledgehammer's position to (0, 0, 0). I then moved the parent GameObject to where I want it in the scene. When I launch the game, the animation plays but the sledgehammer child always re positions itself to be at the global origin, no matter where I place the parent GameObject. See the image below Notice how the sledgehammer's position goes from (0, 0, 0) to ( 1087, 3, 1149). The armature has a single bone and has the sledgehammer object as a child. I've spent about 4 hours looking this up on the Internet, but it seems like parenting the animated mesh to an empty GameObject worked for everyone else except me. Anyone else experience this? I've tried both .fbx and .blend files. |
0 | Set the start orientation of the gyroscope to initial phone orientation I am making a mobile VR project in Unity, and I have a 360 degree video that starts playing where I can look around using a VR headset. I am trying to set the start rotation of the video to the same rotation as my phone. So no matter where I look when I start the video, that should be my start rotation. I used Input.gyro.attitude in the start but that did not fix my problem. I think I am using it wrong. This is my code (on the camera inside the sphere) using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class Gyroscope MonoBehaviour private bool gyroEnabled private Gyroscope gyro private GameObject cameraContainer A camera container for my main camera private GameObject videoSphere The sphere my video is in private Quaternion rot private void Start() videoSphere GameObject.FindGameObjectWithTag("Video") cameraContainer new GameObject("Camera Container") gyroEnabled EnableGyro() cameraContainer.transform.position transform.position put the cameracontainer into the sphere cameraContainer.transform.rotation Input.gyro.attitude here I want to set the cameracontainer to the rotation of my phones gyroscope transform.SetParent(cameraContainer.transform) make my main camera a child of the camera Container videoSphere.transform.localRotation cameraContainer.transform.rotation Here I wanted to set my sphere rotation to the camera rotation Debug.Log(videoSphere.transform.localRotation) private bool EnableGyro() if (SystemInfo.supportsGyroscope) Input.gyro.enabled true turn on my gyroscope cameraContainer.transform.rotation new Quaternion(0, 90, 90, 0) rotate my camera container so the video shows good rot new Quaternion(0, 0, 1, 0) set the variable rot so that you can turn your device return true return false private void Update() if (gyroEnabled) transform.localRotation Input.gyro.attitude rot this makes you turn the device and it recognizes the input of the phones gyroscope |
0 | Detect Collision on Child Object I've created an obstacle prefab. The Prefab has following hierarchy. The player must die if he collides with Enemy. But It detects collision with parent object. I am also uploading the screen shot of property of enemy(Child Object) and Parent Object. What should I change to let player collide with Child Object (Enemy). |
0 | Quaternion Slerp and Lerp implementation (with overshoot) I am working with Unity (C ) and was looking for an implementation of Slerp and possibly Lerp that allow overshoot (progress not strictly limited to 0..1 range). I want to do some tweening animation using an elastic ease out function. My ease out function returns values slightly outside the 0..1 range in order to get an oscillating around the target effect. The problem is that Unity's Quaternion Lerp and Slerp functions appear to clamp the progress input in the 0..1 range. Implementation code in any language would be helpful. I don't know enough about Quaternion math to write this myself. |
0 | Make a background Image to fit multiple objects? In the Hierarchy, I have a GameObject named "Buttons" to which I added an Image component. I would like that the ok sprite to cover (be background of) all the buttons START GAME, OPTIONS, CREDIT and EXIT. But the ok sprite is somewhere in the top left corner behind the START GAME button on its left side and is very small. This happened when I clicked in the Inspector in Image on Set Native Size. I want to make it big enough to cover all the buttons but I'm not sure how. |
0 | How to modify the Unity sprite renderer (or create a custom one) that can display the sprites on the X Z plane? Prefix I am NOT trying to rotate a sprite 90 degrees by it's transform, this changes what is up down and forward backwards for the object. I need the sprite displayed on the X Z plane in comparison to the default X Y plane in it's natural state in the game world with rotation transforms of 0. I'm trying to use 2D sprites on the X Z plane, how do I go about either modifying the built in sprite renderer to do this, or creating my own custom sprite renderer component? |
0 | UI background animation makes camera render beyond canvas, need fix? I have a background animation for a menu where I have to make the background larger than the canvas and drag it over it. Even though I am using a panel the same size as the canvas as a mask, this causes the camera to render beyond the canvas. How can I get this same effect while only rendering what's on the canvas? w o mask (so you can see how big this background is) w mask running in editor (looks good) running build of the game from executable (camera shows more than it should but nothing was changed) The camera bounds are fixed to the canvas, as it should be, if I remove the animated background, so that is the major cause. (BTW, I know the gifs look crappy but the animation is seamless I just had to crop the gifs to reduce file size.) Also, you guys might not be able to see, but the tiling pattern has a slight white border where the tiles meet (the sprite it uses is only like 227x227 on "repeat"), does anybody know how to avoid that? UPDATE 1 12am PST upscaling turd texture to 256x256 eliminates white border, as suggested by trollingchar. |
0 | How to rotate an object based on the movement and angles of Lifters I have Lifters that quot carry quot an object. I want the object to move and rotate based on how those Lifters move. Requirements include Supporting 1 4 Lifters at any side of the Object (e.g., both on one side, opposite, so on can't make any guarantees about their positions relative to the object) Supporting any orientation of the Object (e.g. the Object could be flipped on its side, sideways, or upside down can't make guarantees that Forward is always facing forward, etc) As such I implemented this by having the object move by setting its velocity to the average of the Lifters' velocity. Now, if not all of them move (or if there's a disparity in their velocities), I want the object to rotate, like so This is done by keeping track of how much an individual lifter has moved in a frame from the Object's position, and calculating the angle via m Angle Vector3.SignedAngle(lastPos transform.position, currentPos transform.position). This quot movement angle quot I add up for every Lifter and then at the end, Rotate the Object via Transform.Rotate(Vector3.up, m Angle). However, this approach has some problems Calculations are done along the Y axis and therefore does not angle the Object up or down if the Lifters have different vertical positions, m Angle actually overshoots, but I found simply dividing m Angle by the number of Lifters made it perfectly accurate. I do not know why this works. Because I want this to rotate the object in quot 3 dimensions quot , I have attempted to calculate the quot euler angles quot of each Lifters' movement via Vector3 oldDisplacement lastPos transform.position Vector3 newDisplacement currentPos transform.position Quaternion rotation Quaternion.FromToRotation(oldDisplacement, newDisplacement) m EulerAngles rotation.eulerAngles And then at the end, I rotate the Object based on these quot movement angles quot transform.Rotate(m EulerAngles, Space.World) This works in three dimensions, however it is off in the same way that m Angle was before I divided it. It rotates the object too far. On top of that it seems to produce rotations along axes that have no displacement. I want the object to only rotate exactly by the angle created by the Lifter's movement. This should keep it quot synced quot to Blue instead of rotating past as you see here. When I check how much rotation Blue is adding per frame, I get an output like so Blue is adding (0.000, 359.507, 0.066) on movement ( 0.015, 0.000, 0.000) Despite moving solely on the x axis, there is a z euler angle being created, and the y euler angle of 0.493 degrees is too much for 0.015f movement. I do not know why rotation.eulerAngles is inaccurate in my usage. The only issue I can perceive is that since the Object's position is also moved at the end, the angle calculation assumes it is not moving and generates a larger angle (e.g., perhaps newDisplacement should be something like currentPos (transform.position m Body.velocity Time.deltaTime) ). However, removing the Object's movement from the finalPosition of the Lifter seemingly has no effect. Or perhaps there is some finite precision in Quaternion.FromToRotation? Or my math is incorrect in some way? I'd love a sanity check on the code or approach or if I should approach this problem from a different perspective. EDIT Here's an example gif of the functionality with m EulerAngles code (so the rotation overshoots, but works in 3D also I recorded the gif at lower fps that's not the game's framerate) |
0 | Control the Transform component of an object while the animation is playing It seems the the animation controls the Transform component of the gameobject, hence making it not possible to control the transform properties while the animation is playing. Is there any way to control the Transform component of an object while the animation is playing, like rotating it for example? |
0 | How to draw texture with unlit effect on surface base texture I am writing a shader to my Unity game and I want to have effect this type of effect Base texture, for example, skin of character is a texture that will use shadows, lighting. Second texture, unlit, it will not be using shadows, it will be moving and changing alpha intensity. Second texture will be drawn after base texture. Only unlit or surface shader looks bad, I think I must connect those two shaders, to make nice looking effect. I wrote something this and I am stuck Shader "My SurfaceUnlitBlend" Properties MainTex("Base", 2D) "white" MainColor("Main Texture Color", Color) (1,1,1,1) SecTex("Second Texture", 2D) "white" SecColor("Second Texture Color", Color) (1,1,1,1) SecTexAnimHSpeed("Second Texture Animation Horizontal Speed", Float) 0 SecTexAnimVSpeed("Second Texture Animation Vertical Speed", Float) 0 BlendValueModifier("Blend Value Modifier", Range(0.5, 2.0)) 1 Glossiness("Smoothness", Range(0,1)) 0.5 Metallic("Metallic", Range(0,1)) 0.0 SubShader Tags "RenderType" "Opaque" LOD 200 CGPROGRAM pragma surface surf Standard fullforwardshadows pragma target 3.0 struct Input float2 uv MainTex float2 uv SecTex sampler2D MainTex sampler2D SecTex fixed4 MainColor fixed4 SecColor fixed SecTexAnimHSpeed fixed SecTexAnimVSpeed fixed BlendValueModifier half Glossiness half Metallic UNITY INSTANCING CBUFFER START(Props) UNITY INSTANCING CBUFFER END void surf(Input IN, inout SurfaceOutputStandard o) Albedo comes from a texture tinted by color fixed2 moveVector fixed2( SecTexAnimHSpeed, SecTexAnimVSpeed) moveVector Time 1 set blend modifier according to time float blendLevel (cos( Time 1 ) 1.5) BlendValueModifier set colors fixed4 col1 tex2D( MainTex, IN.uv MainTex) MainColor 2 fixed4 col2 tex2D( SecTex, (IN.uv SecTex moveVector) 15) SecColor blendLevel blend colors fixed4 result col1 col2 o.Albedo result ENDCG FallBack "Diffuse" Because I don't know what to do, to have unlit effect in second texture. |
0 | Unity Google VR reticle pointer weird behaviour I'm using Unity 2017.3.1f1 and Google VR SDK 1.150.0. I added GvrEditorEmulator and GvrEventSystem to the hierarchy, created an empty object and put main camera inside. I also added GvrRecticlePointer as a child of the camera. Then I added a spinning cube and added EventTrigger script onto it. When I point reticle at the cube in the game mode the reticle pointer start shaking. I'm wondering why is that? |
0 | Exposing type definitions to modders in Unity Note that this question is not about modding assets data and not about security, I plan to rely on community trust. I don't know much about DLL's and I was wondering how I can provide interface and attribute definitions for modders. For Kerbal Space Program modders only have to reference the Assembly CSharp.dll, UnityEngine.dll and UnityEngine.CoreModule.dll files of a games build, to create and compile their own DLLs. Are there certain things I have to do, to mimic this behavior, or does this work out of the box? Are there gotchas to this approach? Will a mods DLL, that was compiled using an older version of Assembly CSharp.dll, break if the Assembly CSharp.dll is updated, even though no types relevant to the mod changed? Will modders be able to use Visual Studios debugging features for their DLLs? Is there a better approach to provide type definitions? My question is related to this question. But I would argue that that question is kind of broad, while mine is about one specific aspect. Might not be needed for the question, but here are the two levels of modding that I would like to support for my game 1. Easier modding I want to compile .cs files of modders that implement special interfaces like IAbility, IItem, etc. I will use Roslyn or cs sript to do so. 2. More advanced modding I also want to load .dll's that modders compiled, allowing them to register their own Types in the games DI Framework, mark methods classes with attributes like CallMethodOnLevelLoad and use Harmony. |
0 | Food Game using Online Searchs I am thinking of making a simple game with Unity. The aim would be to keep a person healthy by feeding it well balanced food and drinks. Rather than hard codding every single type of food or drink I can think of I was thinking of letting the player choose any type of food he wants and then screen the internet for it's calorific value, saturated fat, sugars etc ... This would make the game much more enjoyable than being limited by the foods I can think of. I was wondering how you would go about doing that ? Could I use an API to extract data from google or wikipedia. I noticed that when you type " food calories" in Google you get a return from the Wikipedia page like this Obviously, there is a way of extracting the data from Wikipedia and I could automate the searchs by taking the player's entry as a string and running a search with it. How would one recommend going about this ? Also, is it safe ? Thanks |
0 | No intellisense with with Unity 5.5, Visual Studio Code integration, OSX 10.12.1 I get this with the listed software. It doesn't recognize object types and I can't use reference finding. I have the Omnisharp plugin installed and updated. Just wondering if this is supposed to work properly yet. I'm opening it with Assets Open Project In Code. |
0 | Unity in c errors with "the type does not contain a constructor that takes 0 arguments" This is the problematic line datosAguardar datos new datosAguardar () Here is my code public class estadoJuego MonoBehaviour public int puntuacionMaxima 0 public static estadoJuego estadojuego private string rutaArchivo void Awake () rutaArchivo Application.persistentDataPath " datos.dat" if (estadojuego null) estadojuego this DontDestroyOnLoad (gameObject) else if (estadojuego ! this) Destroy (gameObject) Use this for initialization void Start () cargar () Update is called once per frame void Update () public void guardar () BinaryFormatter bf new BinaryFormatter () FileStream file File.Create (rutaArchivo) datosAguardar datos new datosAguardar () datos.puntuacionMaxima puntuacionMaxima bf.Serialize (file, datos) file.Close () void cargar () if (File.Exists (rutaArchivo)) BinaryFormatter bf new BinaryFormatter () FileStream file File.Open (rutaArchivo,FileMode.Open) datosAguardar datos (datosAguardar)bf.Deserialize (file) puntuacionMaxima datos.puntuacionMaxima file.Close () else puntuacionMaxima 0 Serializable definiendo la clase class datosAguardar ISerializable propiedades de la clase public int puntuacionMaxima metodo de la clase constructor de la clase public datosAguardar (int puntuacionMaxima) base (puntuacionMaxima) this.puntuacionMaxima puntuacionMaxima This is the constructor Serializable definiendo la clase class datosAguardar ISerializable propiedades de la clase public int puntuacionMaxima metodo de la clase constructor de la clase public datosAguardar (int puntuacionMaxima) base (puntuacionMaxima) this.puntuacionMaxima puntuacionMaxima |
0 | Gameobject with Canvas child (Unwanted inspector behavior) When I try to focus (by double clicking or pressing f) on gameobjects in my scene which have a Canvas as a child, the scene view zooms out to show the Canvas. I would like to be able to see the gameobjects themselves when focusing on them. Is there a way to do this? |
0 | How can I add a glow effect around a pair of wings in Unity without post processing? Basically I want to use post processing and then I found a tutorial to achieve my goal. However, the artist want a pure shader to achieve this, without any C script hanging in the main camera. Any idea to implement? |
0 | Keeping high scores on Unity web player I want the player to be able to save his score when she makes it into top 10 of high scores. Upon success, player will be asked for a name to submit. This does not need to be unique per player. I just want a basic global score board available for everyone who plays the game via web player (from github.io page of the project). When searched for how to keep high scores, I came across PlayerPrefs. On Web players, PlayerPrefs are stored in binary files in the following locations Mac OS X Library Preferences Unity WebPlayerPrefs Windows APPDATA Unity WebPlayerPrefs As far as I understood, the results are kept in local machine and won't be same for everyone. So it's good for keeping track of your own score, locally. As a placeholder in the current version of the game, I keep the scores in a local .txt file in the project directory. Can I succeed with this approach and use the github.io server to maintain a global scoreboard or do I necessarily need a database to achieve this goal? |
0 | Adding some new velocity to player in FixedUpdate. Should I use FixedDeltaTime or nothing? I am trying to learn how to move objects in Unity without using the built in features like AddForce etc. Some tutorials on Unity website (and other places) is where I have got most of my 'knowledge' so far from. This script for moving players (in topdown Space SHMUP) has been working fine for me and includes acceleration and artificial drag (basically 'smooth' movement, or like being on ice). I'm sure this code is overly long, bloated, inefficient and in most cases downright wrong, but it is written for me to understand it, rather than simply using Unity Prefabs and AssetPackages i download from Store. QUESTION Do I need the Time.fixedDeltaTime mutlipiers when calculating my 'delta v' values here. And also what about on the drag part at the bottom. As usual all help and comments are greatly appreciated. Thanks! public class Player Movement SpaceShooter TopDown MonoBehaviour public Vector2 maxVelocity public float drag public float moveForce private Rect moveBounds private Rigidbody2D rb private void Start() rb GetComponent lt Rigidbody2D gt () moveBounds Game Manager.instance.ScreenBounds private void FixedUpdate() float input h Input.GetAxis("Horizontal") float input v Input.GetAxis("Vertical") Vector2 delta v Vector2.zero delta v.x input h moveForce Time.fixedDeltaTime delta v.x Mathf.Clamp(delta v.x, maxVelocity.x, maxVelocity.x) delta v.y input v moveForce Time.fixedDeltaTime delta v.y Mathf.Clamp(delta v.y, maxVelocity.y, maxVelocity.y) Vector2 pos rb.position Vector2 vel rb.velocity if (pos.x lt moveBounds.xMin) pos.x moveBounds.xMin vel.x 0f if (pos.x gt moveBounds.xMax) pos.x moveBounds.xMax vel.x 0f if (pos.y lt moveBounds.yMin) pos.y moveBounds.yMin vel.y 0f if (pos.y gt moveBounds.yMax) pos.y moveBounds.yMax vel.y 0f rb.position pos rb.velocity vel delta v rb.velocity rb.velocity (1 Time.fixedDeltaTime drag) It appears to me that if FixedUpdate was somehow slowed down, the velocity would get changed slower, the same with the enemy movement but I don't know how that would effect the gameplay and if how the slowing down would occur |
0 | Unity new Input system lists actions and compare them to current input I have a scriptable object called Move that had a list with keycodes (for example to make a Hadouken) easy to use and compare with the current input made it with the old system, but with the new input system I don't know how to make a list of actions (actions that are in my Input Action Asset not new ones) and compare that with the current inputs (and also I do not have any idea how to make buffering inputs like the last input repeats 3 frames). I already tried and not worked (InputMa is my InputActionAsset generated class) InputActions InputMa InputMa.PlayerActions InputActionReferences this seems the correct option, but I don't know how to get the reference from the current input. |
0 | Unity WebGL how to copy to clipboard text from an inputField? I would like to know if there is a solution to copy paste the text from to an InputField in a WebGl Unity app. Edit for security reason, Unity WebGL doesn't allow text copy and paste in from browser. Thanks |
0 | Why the transform.localPosition never equal to the begin position of the transform? using System.Collections using System.Collections.Generic using UnityEngine public class MoveScrollView MonoBehaviour float seconds Vector3 begin Vector3 end Vector3 difference public static bool go false public static bool goBack false public static bool atOriginPos false void Start() seconds 0.5f begin transform.localPosition end new Vector3(0, 1, 0) difference end begin void Update() if (go) if (transform.localPosition.x lt end.x) var mx transform.localPosition.x transform.localPosition new Vector3(mx seconds Time.unscaledTime, 1, 0) difference end transform.localPosition if(goBack) if (transform.localPosition.x gt begin.x) var mx transform.localPosition.x transform.localPosition new Vector3(mx seconds Time.unscaledTime, 1, 0) difference end transform.localPosition if(transform.localPosition begin amp amp goBack) atOriginPos true At the Start the begin position is ( 540.0, 1.0, 0.0) also the transform.localPosition is at the same position. Then at this line 39 if (transform.localPosition.x gt begin.x) The value of the x of the transform.localPosition is 3.039021 and the x of the begin is 540 So it's getting inside and move the transform. Then when the transform has finished moving I see on this line if (transform.localPosition.x gt begin.x) The transform.localPosition x value is 540.7267 and the x value of the begin is still 540 So now it will not get inside and will not move the transform anymore. But two wrong things happened The transform stopped moving but it didn't move to it's original position only close to it. Because it didn't move to it's exact original position then the localPosition x and the begin x are never equal so the this will never be true if(transform.localPosition begin amp amp goBack) And the flag atOriginPos is never true. I want the transform to move back to it's original position and then when it's reached the original position set the flag atOriginPos to true. |
0 | How to render a grid of dots being exactly 1x1 pixel wide using a shader? I would like to render a grid with many dots, all equally spaced and being exactly 1 pixel wide. What I was able to achieve so far is this What I would like is (simulated using image editing program) Here is the shader I wrote (which give result of 1st image). This is rendered as a giant quad. Shader quot Custom Grid quot SubShader Pass CGPROGRAM pragma vertex vert pragma fragment frag include quot UnityCG.cginc quot struct vertInput float4 pos POSITION float4 uv TEXCOORD1 struct vertOutput float4 pos SV POSITION float4 uv TEXCOORD0 vertOutput vert (vertInput input) vertOutput o o.pos mul(UNITY MATRIX MVP, input.pos) o.uv input.uv return o fixed4 frag (vertOutput output) SV Target float4 uv output.uv float x step((uv.x 100.0 0.025) 1.0, 0.05) float y step((uv.y 100.0 0.025) 1.0, 0.05) float c min(x, y) return float4(c, c, c, 1.0) ENDCG Is it possible to achieve what I want using a shader ? What is needed from first draft is to control the size of each dot. I have tried to use partial derivatives (ddx and ddy) but was not able to make it work. |
0 | How do I run functional tests against my Unity3D game? Context I am continuing some legacy code for a game in Unity3d, and I want to write some functional tests meant for regression, to ensure I don't break things when implementing new things or when refactoring. I already know there is the 'Unit Test Tools' suite for Unity3d available as an asset. I have used it as a unit test suite, so I test my models (classes). Example of what kind of test I am thinking about For "functional test" I mean things like this Run the program When in the menu scene, assert there is a button that says "start" Click it Then assert a new scene is loaded Assert pixel XXX is red Click in coordinate XXX Assert now that the pixel changed to green etc. Questions Q1 How do I write and run functional tests for my game? Is this also typically done in the UnityTestTools (UTT)? Q2 If UTT is more for Unit Testing, then is there a separate suite for functional testing? Which one? Notes I'm targetting Android, and running Unity5.3.1f1 |
0 | Can't change materials of model from FBX I was used 5.x before, and that version when I loaded FBX, Unity generated each material automatically, so I can change them like assigning textures or change shader. And now I switched to 2017.3, and when I imported FBX, now Unity didn't generate materials anymore. I can see the properties of each material but every parameter is locked. It seems materials are inside of model and can't change like animation clips. Some of model has multiple materials, so I can't generate manually and assign them. I'm creating mobile game so I really need to change the shader to mobile shader, not standard(PBR). How to change materials of model from FBX in Unity 2017.3? Note that model created from Blender 2.7c and exported as FBX. |
0 | How is Unity's Command supposed to behave? Here's a very simple class call hierarchy public class NetworkPlayer NetworkBehaviour public static NetworkPlayer localPlayer get private set Command public void CmdTurnDone() Debug.Log("Turn done! isServer " isServer " isClient " isClient " isLocalPlr " isLocalPlayer) public class SomeMonoBehaviour MonoBehaviour void Update() NetworkPlayer.localPlayer.CmdTurnDone() When Update() gets executed on the host, it outputs as expected Turn done! isServer True isClient True isLocalPlr True Now, when Update() is executed on the remote client it outputs the following at the remote client's log only. However, the message does not appear at the server's logs Turn done! isServer False isClient True isLocalPlr True What puzzles me is why the message appears at the remote client's log only. If I'm not mistaken, calling CmdTurnDone() at the remote client should execute it on the server. But why does the log message appear at the remote client's log instead of on the server's logs where it is executed? Is it valid to call CmdTurnDone() from a MonoBehaviour? Do you have any ideas why it's behaving like this? Is this the intended behavior? Thank you. |
0 | How to displace a segmented line along a sine wave with Shader Graph? I have a mesh made of three identical cylinders (conceptually just line segments with a non zero thickness) crossed over each other at 60 degree angles, so the ends describe the points of a regular hexagon. The cylinders are divided into a lot of segments, which I'd like to displace in a sinewave pattern. The pivot is in the center of the mesh. My concept is pretty straightforward Subtract object position from vertex position to get vertex position relative to the pivot (VPR). Normalize VPR and swap the X and Y to get a vector in the XY plane perpendicular to the orientation of the cylinder. Take the magnitude of VPR, multiply by a V1 parameter (Waviness), then take the sine. Multiply the sine by the perpendicular orientation vector to get the displacement. Add the displacement to the vertex position. Assign result to master node's vertex position. This really feels like it should work. Each cylinder should be distorted along a sine wave, with the magnitude of the distortion increasing the further it gets from the center, so I end up with three wavy lines crossed over each other at 60 degree angles. Increasing Waviness should increase the frequency of the wave, as the base value is multiplied by it before feeding into the sine node. Instead, things curve just a little bit at a low Waviness, but as I increase it the cylinders get both thicker and longer, neither of which should be happening, and start wrapping themselves around the mesh in weird patterns. I have no idea what I'm doing wrong! Here's my graph setup, with the mesh assigned to the preview so you can see what a mess it's making of it Any ideas how I can fix this? |
0 | Unity Mesh and Collider not aligned on rotation I have a GameObject with a mesh and a collider. When I rotate the object the mesh and the colider do not act the same way and when the GameObject is rotate 65 degrees on the z axis the mesh and the colider are no longer aligned. This must affect game play. I don't understand why this happens and how it is supposed to be fixed. |
0 | Player with Character Controller and children colliders won't collide properly I have a player that consists on a root object with the Character Controller attached and some children with its components. Those have box colliders attached. When moving the player I want to be able to collide with other objects using the box colliders, but it won't, instead it will only collide with the Character Controller. As you can see in the image, the red object didn't stop when the collider crashed with the framed cube, but it did when it did with the Character Controller. There is any way to use the player colliders instead of the Character Controller for collision detection? |
0 | How do I cover a plane in a bumpy foam material effect? I need to fill a weapon bag with foam material. This is what it should look lik The material in the upper part of the bag looks like this I'm using HDRP. How could I do this? Thank you! Edit I have played around with Parallax Occlusion mapping, and I got this result. Edit2 I am not sure if I use the Pixel Displacement as it has been suggested to me. Also, I'm not sure if I use it the correct way I have created a Height map and put it into the Height map slot. This doesn't create any effect. I have to put the same map into the Base map slot in order to see the effect. If I put a black image into the Base map slot or if I choose Black as the Base color, no effect is visible. I don't understand why this is so. I think even if my Base map is black, the Shader has pixels that it can move. This is my height map Edit 3 It was suggested that I should use a normal map. This doesn't look at all what I expected. The normal map was created from the Height map using an online tool By Philipp's answer I found out that the normal map alone is not enough. |
0 | How to pause audio playback when a breakpoint is hit or resume afterward? When my code hits a breakpoint, audio that was previously started (via an AudioSource) continues to play while the threads are paused. I'm using a coroutine to query the status of the AudioSource, and update my UI. Because the audio continues to play, then after I've spend some time stepping through code the next frame tick when Unity gets control back runs the next iteration of this coroutine, which updates the UI. I never get to see the in between states. Because it's a relativley short audio clip it's usually finished playing before I've finished stepping through the code. I'm using Unity 2018.4 with VSCode and the Debugger for Unity extension, if that helps. I'm quite lost at what to try here. Looking for issues with Unity's AudioSource and breakpoints yields a lot of varied information about audio issues in general in Unity. I've tried using Debug.Break(). It pauses the Unity editor, which can be useful but has the following caveats it requires extra effort on each breakpoint that requires enabling (if the call is not there already) it requires manual intervention to resume the editor once you've finished stepping through code because it is code, it cannot be added after Unity is playing, e.g. to additional breakpoints that are added once debugging has started Does Unity have a mechanism that enables this behaviour that I've just missed? If not, what's an appropriate alternative approach? |
0 | AudioSource.Play() outputs only noise from the sound clip I'm trying to reproduce a sound clip on the AudioSource of a game object by using the .Play method. What i'm trying to do is a card game of sorts, but with each card being a different section of a song of a genre. I combine different cards with different genres and when i press play, the combination should start playing, but now when the play button is pressed, only noise comes out. The code for the start method looks like this public class AudioStart MonoBehaviour AudioSource thisAudioSource Start is called before the first frame update void Start() thisAudioSource this.GetComponent lt AudioSource gt () Update is called once per frame void Update() if (playButton.playPressed) thisAudioSource.Play() else thisAudioSource.Stop() The way i'm doing it is by having a button that on click changes a bool to true or false depending if there is sound playing (the truth check on the if statement). The AudioSource outputs to an AudioMixer on a specific group under the master group (which group depends on the slot that the card is dropped in). The AudioStart script is attached to different game objects with a different audio clip each. I've also noticed that when i try to reproduce two cards, only one AudioSource gets played. Any help would be appreciated. Thanks! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.