_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | smoothly recenter view over time I'm currently using the Google Cardboard SDK for Unity to build a fighter pilot simulator. What I'm currently trying to do is recenter the view(CardboardHead) smoothly over time when the user looks away from the screen. This is because I want to put HUD elements out of the main central view that can be quickly seen with a "head jerk". I don't want to let the camera be free from constraints because I feel piloting is much better when the view is fixed and doesn't wobble about with every slight movement of the player's head. The Head already has a horizontal constraint that does not allow any later movement, but now I want to put a semi constraint on the vertical axis so that the player can quickly look up or down to see something like i.e. a fuel economy indicator and then have the view quickly "follow his gaze" and recenter itself. I noticed that the Cardboard plugin already does this type of constraint on the Head roll input when playing "in editor" and works as follows When you press and hold Ctrl and move the mouse left right the view rolls left right. Upon release of Ctrl the view smoothly rolls back to 0. This is the code in the Cardboard script bool rolled false if (Input.GetKey(KeyCode.LeftControl) Input.GetKey(KeyCode.RightControl)) rolled true mouseZ Input.GetAxis("Mouse X") 5 mouseZ Mathf.Clamp(mouseZ, 80, 80) if (!rolled amp amp autoUntiltHead) People don't usually leave their heads tilted to one side for long. mouseZ Mathf.Lerp(mouseZ, 0, Time.deltaTime (Time.deltaTime 0.1f)) var rot Quaternion.Euler(mouseY, mouseX, mouseZ) var neck (rot neckOffset neckOffset.y Vector3.up) NeckModelScale headView Matrix4x4.TRS(neck, rot, Vector3.one) How could I implement this for vertical rotation of the Head? In the Update method of the script that controls the Head it simply does transform.localRotation Cardboard.SDK.HeadRotation This is what I've tried but it doesn't really do anything except some jerky movements transform.Rotate(new Vector3(Mathf.Lerp(rot.eulerAngles.x, 0, Time.deltaTime (Time.deltaTime 0.1f)),0,0)) (I put this in the same Update function for the Head after the above line) Any ideas?? |
0 | How do I get the position and rotation of an animated object in Unity? I have this object which is being animated, the animation moves a arm and hand. I want it to look like it's holding something but I can't move the object to the hand because even though the animation appears to move the world position of the animation object stays the same, the objects parent is the hand but it's still not moving to it. So how do I move the object to the animations hand while it's being animated in unity? Maybe this could help to visualize what my problem is I found another way around the problem attached the object as a child of the bone instead of the hand mesh. I still don't know why it didn't move with the hand. |
0 | Should I use a database to store 10 000 names in a sports game? I'm working on a single player sports game for a year or so and this doubt came up how should I treat store big amounts of data, like player names. Let's take an arbitrary number as example 10000 names, 5000 first names and 5000 surnames. These names would be equally divided between 100 countries, which give us 50 first names and 50 surnames per country. Should I have a local database with these names (or even these countries) considering this data will be needed to generate new players names during the course of the game? Would that introduce limitations, considering I want to make my game moddable by players, as much as possible? These doubts can be extended to other, more complex game entities, such as Players each one with their own face, attributes, team etc... Teams each one with its own crest, kit, squad etc... In my previous research about that, the SQLite popped up as a seemingly viable solution. It happens that I have almost no experience with DB's (specially in games) and would like to know if this is a good direction before start to study and try to implement it. |
0 | how to switch cameras with one button? using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class cameraswitch MonoBehaviour public Camera cam1 public Camera cam2 void Start () cam1.enabled true cam2.enabled false Button Button gameObject.GetComponent lt Button gt () Button.onClick.AddListener(baz) void baz () cam1.enabled false cam2.enabled true this is my code . how to switch between the cameras with one button . and Thank You. |
0 | How to link my weapons with their corresponding ammo supply in the Unity Inspector? In my game I would like to implement a universal ammo and weapon system that would be usable for any kind of weapon. So I declared an ammo class using System.Collections using System.Collections.Generic using UnityEngine System.Serializable public class Ammo public int MaxAmmo public int CurrentAmmo public Ammo(int maxAmmo) MaxAmmo maxAmmo public void MaxOutType() CurrentAmmo MaxAmmo public void GetAmmo(int amount) CurrentAmmo amount public void UseAmmo(int numOf) CurrentAmmo numOf Then I created a script to hold different Ammo types using System.Collections using System.Collections.Generic using UnityEngine public class AmmoSystem MonoBehaviour SerializeField public Ammo Basic new Ammo(200) public Ammo Rockets new Ammo(50) public Ammo AirRockets new Ammo(75) public Ammo Cells new Ammo(150) To organize my project I decided to make two weapon scripts one for nonphysical(Raycast) projectiles called RaycastingWeapon and an another for physical ones(like a rocket launcher) called PhysicalProjectileWeapon My plan was to create unique weapons using these two scripts from the inspector. These would use different kinds of ammo but would share the same script with different properties. The essential aspect here is that I would like to be able to select an ammo type from the inspector using a dropdown menu for example. Is it possible somehow or are there a better way of doing that? |
0 | Is async image loading possible? Can anyone tell me if there is a async version of LoadImage() method? I found about Resources.LoadAsync, however the method doesnt work. Thank you |
0 | How do I find the name of the current audio clip being played? I have a title scene and a credits scene that use the same music. When I start my game the title scene music plays, and I have my game set up so the audio manager is not destroyed on load. When I enter my credits scene I do not instruct any new music to play, but each time I reload my title scene the title music restarts because a script in the scene tells it do so. How can I get the name of the current audio track so that I will only play audio if it differs from what's currently being played? This is my "LevelMaster" script which is responsible for handling the audio in each scene. public class LevelMaster MonoBehaviour private AudioManager AudioManager SerializeField private string trackName private void Start() AudioManager GameObject.Find("AudioManager").GetComponent lt AudioManager gt () AudioManager.Play(trackName) public void PlaySound(string soundName) AudioManager.Play(soundName) public void StopSound(string soundName) AudioManager.Stop(soundName) |
0 | How can I avoid updating my Unity projects when I have two versions installed? I currently have two versions of Unity on my Windows computer. I would like to not update my projects to avoid compatibility issues like I had in the past. Installation in another folder goes just fine, but when I try to open Unity, it says that another Project is already opened and that if I want to continue I must update it. If I close this window, Unity aborts as well. Is there a way to avoid this behaviour? |
0 | How do I safely change properties on my skybox? Usually in Unity, when your scripts make changes to something at runtime, those changes are not persisted back to design time. This is generally considered a good thing. But for whatever bizarre technical reason, this does not apply to shader properties on materials. If you change something while the game is running, it stays changed! Generally the way to get around this is with a MaterialPropertyBlock, which also helps avoid generating a lot of garbage. But MaterialPropertyBlocks work with Renderers, which leaves out one rather important material the skybox. Right now, I have code that says RenderSettings.skybox.SetFloat( quot PropName quot , value) , and it's incredibly aggravating because it always needs to be reset afterwards. RenderSettings doesn't have a SkyboxRenderer property that I can use in conjunction with a MaterialPropertyBlock, so how can I change shader settings on my skybox and make them not persist after I exit play mode? |
0 | How to distort 2d perlin noise? I am using Unity's 2D Mathf.PerlinNoise(x, y) function and I would like to make it distorted. What I mean is described with this picture I made How can I do that? What transformations should I apply to Mathf.PerlinNoise(x, y) to achieve this effect? |
0 | Why doesn't the Camera.pixel(Height Width) match the Canvas size? I am making an app that has a custom viewport Rect like so When I check the sizes of this viewport rectangle in pixels with Camera.pixelHeight Camera.pixelWidth, I get the following values 743px, 770px. This looks correct. Now when I check my canvas in the Editor, I see the following values for the width and height Now I have a script that gets the width and height of the canvas. This is correct I get again the 743px and 770px. But when I position my UI element, it is outside because the positioning refers back the the incorrect values displayed in the canvas rectangle transform properties. What is happening here and how do it make the canvas use the correct values? |
0 | How can i scale a cube on one side on x only? I have in the Hierarchy a empty GameObject and a cube as child of it. The cube the child is at position 0,0,0 and scale 1,1,1 But when running the game the scaling is on both sides of the cube. I put the cube as child of the empty gameobject and scaling the empty gameobject but still it's scaling the cube on both sides. The script is attached to the empty GameObject using System.Collections using System.Collections.Generic using UnityEngine public class Walls MonoBehaviour Vector3 originalScale Vector3 destinationScale void Start() originalScale transform.localScale destinationScale new Vector3(100.0f, 0, 0) private void Update() if (transform.localScale.x ! 100.0f) transform.localScale new Vector3(1, 0, 0) This is a working solution using System.Collections using System.Collections.Generic using UnityEngine public class Walls MonoBehaviour public Transform objectstoScale private void Update() if (objectstoScale 0 .localScale.x ! 100.0f) objectstoScale 0 .localScale new Vector3(1, 0, 0) But i want to make that the same cube will also scale one side on the z. So the cube will be scaled on both x and z but without filling it one be like frames. So i tried this using System.Collections using System.Collections.Generic using UnityEngine public class Walls MonoBehaviour public Transform objectstoScale private void Update() if (objectstoScale 0 .localScale.x ! 100.0f) objectstoScale 0 .localScale new Vector3(1, 0, 0) objectstoScale 1 .localScale new Vector3(0, 0, 1) And i have now two cubes childs of the empty gameobject one cube position is 0.5,0,0 the second is 0,0,0.5 but what i'm getting is What i want to do is to create automatic a rectangle scaling a cube on 4 sides at the same time not filled rectangle. For example like this |
0 | unity2D swipe control's bool for animator doesn't work i was trying to make a control where the animation plays upon swiping one direction. each time i've make a tap swipe control, it just keeps popping messages like this. the tap animation works fine, but the animation for swipe controls just doesn't work well, the bool for them has assigned but did not make it 'true' when i swipe a direction, but the bool for the tap works, which is weird.(ignore the miss bool in the animator) it says that i need to assign the anim variable of the Swipe script in the inspector. but there is nothing left for me to assign, which doesn't make much sense for me. (refer to Region Animation) i've tried to make some adjustment with the script, but the results is the same, and it has no problems when build. which is why i need help for the animation stuff. using System.Collections using System.Collections.Generic using UnityEngine public class Swipe MonoBehaviour public Animator anim public bool tap, swipeUp, swipeDown, swipeLeft, swipeRight public bool isDragging false public Vector2 startTouch, swipeDelta private void Update() tap swipeUp swipeDown swipeLeft swipeRight false region Standalone Input if (Input.GetMouseButtonDown(0)) tap true isDragging true startTouch Input.mousePosition Debug.Log("Tapped") else if (Input.GetMouseButtonUp(0)) isDragging false Reset() endregion region Mobile Inputs if (Input.touches.Length gt 1) if (Input.touches 0 .phase TouchPhase.Began) tap true isDragging true startTouch Input.touches 0 .position else if (Input.touches 0 .phase TouchPhase.Ended Input.touches 0 .phase TouchPhase.Canceled) isDragging false Reset() endregion region Animation if (Tap) anim.SetBool("Tap", true) if (SwipeDown) anim.SetBool("Down", true) if (SwipeUp) anim.SetBool("Up", true) if (SwipeLeft) anim.SetBool("Left", true) if (SwipeRight) anim.SetBool("Right", true) endregion calculating the distance swipeDelta Vector2.zero if(startTouch ! Vector2.zero) if (isDragging) if (Input.touches.Length gt 0) swipeDelta Input.touches 0 .position startTouch else if (Input.GetMouseButton(0)) swipeDelta (Vector2)Input.mousePosition startTouch did we cross the deadzone? if (swipeDelta.magnitude gt 125) which direction? float x swipeDelta.x float y swipeDelta.y if (Mathf.Abs(x) gt Mathf.Abs(y)) left or right if (x lt 0) swipeLeft true else swipeRight true else Up or down? if (y lt 0) swipeDown true else swipeUp true public void Reset() startTouch swipeDelta Vector2.zero isDragging false anim.SetBool("Tap", false) anim.SetBool("Down", false) anim.SetBool("Up", false) anim.SetBool("Left", false) anim.SetBool("Right", false) public Vector2 SwipeDelta get return swipeDelta public bool Tap get return tap public bool SwipeUp get return swipeUp public bool SwipeDown get return swipeDown public bool SwipeLeft get return swipeLeft public bool SwipeRight get return swipeRight |
0 | Unity OnRenderImage hides UI I have a component which renders a few different cameras and the images. However, this obscures my UI when in Screen Space Overlay mode. I can put the canvas in WorldSpace mode, which works, but then the UI is affected by the image effect I've built and is, of course, not locked to the camera. Suggestions? Update additional details At design time, the OVR camera rig contains a single camera centered between the "eyes." This component is attached to the camera rig's centerEyeAnchor. At run time, the rig creates two additional cameras one for each eye. These aren't supposed to be modified by user code. (Among other things, their projection matrices are pretty weird.) I need to modify the image per eye. I created a new component which create two additional cameras per eye. One renders a low res version of the entire scene, the other renders a high res image of a portion of the screen, each to a dedicated RenderTexture. Pseudocode void Update() called once per frame called twice per frame once per eye void OnPreRender() called twice per frame once per eye void OnRenderImage(RenderTexture source, RenderTexture destination) low res render of entire scene var camOuter m cameras ... hi res render of part of the scene 10 20 of original image area var camInner m cameras ... update cameras to match current eye camera camOuter.copyFrom(Camera.current) camOuter.targetTexture m outerTexture render scene to low res texture camOuter.Render() camInner.copyFrom(Camera.current) camInner.targetTexture m innerTexture target texture that the Oculus wants to render to var ovrTexture Camera.current.targetTexture save projection matrix var originalProjectionMatrix camInner.projectionMatrix var scale new Vector3(m innerTexture.width 1.0f ovrTexture.width, m innerTexture.height 1.0f ovrTexture.height) zoom pan matrix to clip to part of the scene var gazeMatrix Matrix4x4.Scale(scale) offset projection gazeMatrix.m03 (1 2 gaze.x) scale.x gazeMatrix.m13 (1 2 gaze.y) scale.y camOuter.projectionMatrix gazeMatrix amp originalPRojectionMatrix render hi res portion of the scene centered at gaze pixel camOuter.Render() restore projection matrix cam.projectionMatrix originalProjectionMatrix composite images m material.SetTexture("InnerTexture", m innerTexture) m material.SetTexture("OuterTexture", m outerTexture) Graphics.Blit(null, destination, m material) (I'm also worried that there may be additional scene renders happening in the background.) The problem is that the UI does not render if set to Screenspace Overlay or Screenspace Camera. I can get it to render in Worldspace, which may be the only way to do this, but then it seems I'd need to create yet another hi res texture matching the viewport dimensions and render the UI layer to that, and keep it locked to the current eye's camera position. Alternatively, I could re use one of the current cameras, I guess, and just tweak its settings. Is there a better way to do this? Ideally, I'd like to have the engine just render the UI as it does in other applications without having to jump through hoops. However, at this point, I'll take anything I can get that works and looks good. Update the 2nd Okay, it looks like the UI is rendered perfectly if I use a regular camera instead of the OVR rig. ( Having the rig in the scene, though, prevents it from drawing at all. |
0 | How to make a cartoon like trail particle system? I'm currently working on an little Android game, it's a reaction casual game. Because the user needs to tap some balls flying around at the right moment, I want to add some new effects to them. So I looked at some other games and found this cool looking cartoon like effect. As you can see the ball there has an cool tail. So my question is, does anyone know how to recreate such a trail with the Unity particle effects or some other tools? |
0 | Unity 5 Texture Material rendering issue I am working on a Minesweeper clone that started as a Unity 4.6 project and ended up as a Unity 5 project. I have cube objects that use Legacy Shaders Diffuse. I am new to Unity 5, so I am not fully aware of the changes to the shaders. The following texture on cube objects does not render as it is (I think it used to). I want the flag appear on the cube as it is. What causes this output and how do I fix it? |
0 | No intellisense on my classes I've been using Monodevelop's current version and Unity 4. I don't get intellisense on the classes I've created but I do have intellisense on classes that are in Unity's framework. Bug or its just as it is? I use UnityScript class SomeClass extends ScriptableObject public function Test() return "" In another class, when I use a variable typed as this class I get no intellisense. |
0 | Unity Display array of Objects in inspector I have an array of ScritableObject's, which should only be displayed in the inspector if a boolean is true. How would I do this? With my current code, I get an error saying Cannot implicitly convert type Tile to Tile This is my current code using System.Collections using System.Collections.Generic using UnityEditor using UnityEngine CreateAssetMenu (fileName "Data", menuName "Tiles Map", order 1) public class Tile ScriptableObject public ETile eTile public Sprite sprite Space(5), Header("Variety") public bool variety Range(0f, 1f) public float varietyChance public Tile varietyTiles lt This should be hidden if variety is true public enum ETile Water, Grass CustomEditor(typeof(Tile)) public class MyScriptEditor Editor override public void OnInspectorGUI() var tile target as Tile tile.variety EditorGUILayout.Toggle("Hide Fields", tile.variety) if (tile.variety) tile.varietyTiles (Tile)EditorGUILayout.ObjectField("Tile", tile, typeof(Tile), allowSceneObjects true) |
0 | How to instantiate GameObject on client without network? When I NetworkServer.Spawn(ob) a gameobject and make it a child of a transform.parent after it spawns on both the server and client it usually lags, meaning it takes some secs to align with the transform.parent which is the player Example Instantiating a GameObject containing a ParticleSystem which gives the parent somewhat an effect, smoke or something in that direction, in the host client every object usually has a smooth movement where as in the connected client it goes very rough and slow, like every gameobject having a low fps except the main client player prefab So i was thinking spawning the same effect on both clients so it wouldn't have to sync from the server to the client which uses it instead it only would have to sync inside the clients game, it might not have the same particle movements but it wouldn't make a difference Here's the child's prefab network identity and transform |
0 | How to stop an animation on last frame until condition is met in Unity? I have an animation (fishing) I want to play backwards when the player catches something or cancels the action. Playing the animation backwards is as simple as setting the speed to 1, ie anim.SetFloat("direction", 1.0f) However, my fishing animation keeps playing until I have caught something, or cancel the animation. This means that the last frame of the animation is showing, but the time of the animation is still going. So the animation reaches the last frame then I stand there for 8 seconds, I catch something, so I change anim speed to 1 anim will now reverse those 8 seconds I was "standing still" first, before it even reaches the actual animation. I need to stop the animation time on the last frame (without leaving the animation), so that reverse will be instant. And to not exit the animation until the reverse is finished. Maybe there is some other way to do it, but I can't figure it out. I could create a seperate animation for when I want it to go backwards, but that seems sloppy. |
0 | How do I move a Unity object with velocity instead of force? I have a 2d car in Unity that I want to move, but Unity does this using relative force amp I want to use velocity. As we know if we add force, an object will move and never stop. I want to use velocity to control movement, because then the car will stop when its velocity is zero. using System.Collections using System.Collections.Generic using UnityEngine public class GamePlay MonoBehaviour public GameObject player public Rigidbody2D rb public float speed, steering void Start() void FixedUpdate() rb.AddRelativeForce(Vector2.up speed) rb.velocity Vector2.up Touch touch Input.GetTouch(0) if (Input.touchCount gt 0) if (touch.phase TouchPhase.Moved) Vector2 v Camera.main.ScreenToWorldPoint(touch.position) float pos touch.position.y player.transform.Rotate(0, 0, pos steering) |
0 | How to make a 2D semicircle sprite in Unity? I followed this answer https answers.unity.com questions 1008644 semi circle 2d collider.html and was able to create a semicircle collider But is there any way I can just crop the circle sprite to make it a semicircle? I tried looking for other documentation, but couldn't find any.. |
0 | Unity2D Rendering multiple sprites as a single one I'm creating NPCs in Unity 2D using C , and I have 16x16 sprites for body, helmet, clothes and weapon. All these have a tile set which has been split in unity. I'd like to be able to render one of each part together, so I can drag the sprite to the field, and then it will be rendered on the NPC. IE, I drag a helmet sprite into the helmet field and that is the rendered helmet. I intend on having multiple NPCs, so I'd prefer to minimise the child objects. Multiple sprites will need rendering, however there's only one sprite renderer. Is it possible for me to combine the sprites (in code), and then render the final sprite? Or is there perhaps a better way? Thanks in advance! |
0 | Disabling, overriding or hooking a VS warning to Unity's Vector's ToString()? I've just spent 2 hours debugging a misbehaviour because ToString() truncates to 1 digit by default. I want to disable the parameterless version so I won't use it by accident and I will always have to define how much truncation I want. Or if this isn't possible I want to redefine it, so it will truncate to 3 digits for example. Or somehow hook a custom warning to it, so Visual Studio will tell me that I'm using it? Is this possible? |
0 | Exported shapekeys to unity don't play correctly (unity 2019 blender 2.79) Hopefully someone can shed some light on this I select all relevant parts of the mesh and armature etc and export to FBX 7.4 for use in Unity3d The model itself displays fine and so does the armature animations but the shapekeys come out really weird. Any ideas or do you need more info? |
0 | How can I stop this fixed update from executing so I want this FixedUpdate() Method to stop executing when the Method OnMouseDown() is executed. A bool doesn't work a if() statement also doesn't work Please use my whole code Please help ) Thanks, private void FixedUpdate() int random Random.Range(1, 4) if (random 1) m SpriteRenderer GetComponent lt SpriteRenderer gt () m SpriteRenderer.color Color.green if (random 2) m SpriteRenderer GetComponent lt SpriteRenderer gt () m SpriteRenderer.color Color.blue if (random 3) m SpriteRenderer GetComponent lt SpriteRenderer gt () m SpriteRenderer.color Color.yellow private void OnMouseDown() shouldexecute false |
0 | Unity AI issue with recalculating NavMesh at runtime I am using Unity NavMesh to control my units. I am running into an Issue when updating Navmesh at runtime, It seems agents re calculate their path whenever it is modified, which makes sense, but it causes this line (check if unit is on last corner) to return an IndexOutOfBounds error agent.steeringTarget agent.path.corners agent.path.corners.Length 1 I guess something is happening while re calculating path that might mess with this for 1 frame. I solved this by putting a try catch around it, but is there some better way I can manage this so I don't get the error at all? |
0 | Unity3D Using AddRelativeForce to push an object forever in zero gravity environment Ok, I use AddRelativeForce to basically push an object. But it suppose to keep flying and keep accelerating as I hold down the key because I didn't set gravity. I just started Unity3D last month, so pls give me some advice. Force of individual thrusters public float thrusterForce 10000 Whether or not to add force at position which introduces torque public bool addForceAtPosition false private bool thrusterIsActive false private Transform objectTransform private Rigidbody objectParentRigidbody void FixedUpdate() if (thrusterIsActive) if (addForceAtPosition) objectParentRigidbody.AddForceAtPosition (objectTransform.up thrusterForce, objectTransform.position) else objectParentRigidbody.AddRelativeForce (Vector3.forward thrusterForce) |
0 | 2D physics on game object made up of components Say you want to let your users create a 2D airship (side view) made up of components. One component could be a floating balloon, another could be a storage room, etc. And say you want this airship to have physics applied to it as a whole, with each component playing a part in this. For example, balloons would take away from its down force and other compartments would apply down force to it. At the same time, the whole airship works as a whole (or at least the only physical separation would be between floater components and the others, which apply weight), so physics are applied to it as if it was one body. Now, how can this be managed? How can I customize a game object via a script, giving it different components with different weights, and have it behave like it was a single premade object? I'm sorry if the question is simple, but I'm only getting started with unity. Thank you very much! TL DR Customizable airship gameobject with different components that have different weights. How to make it behave as a single physics entity and manage its different components? |
0 | Is there any way to use events without breaking class and component separation? I just started using events, and got stuck a little. I have a problem with the following code class InputHandler public delegate void Shooting() public static event Shooting OnShoot void Update() if( fireButtonPressed) OnShoot() Rest of the class. class Weapon void Shoot() Do the shooting. void OnEnable() InputHandler.OnShoot shooting void OnDisable() InputHandler.OnShoot shooting class UI void UpdateBulletsCount(int bulletsLeft, int magSize) Update the UI. void OnEnable() InputHandler.OnShoot UpdateBulletsCount clearly can't do that. void OnDisable() InputHandler.OnShoot UpdateBulletsCount My UI class has a method to update the bullet count when you fire, reload or change the weapon. As you can clearly see, it takes in different parameters. This allows me to change the UpdateBulletsCount() to accept no parameters, and find the weapons info through GetComponent or Find, in order to update UI. However, then the UI class will depend on the Weapon class, which breaks the separation of classes and components that I am trying to achieve. Is there any way to use events without breaking class and component separation? |
0 | Trouble creating fog and lighting in unity I am trying to create a model in unity that looks like this picture by Escher I can create the lattice, however, I can not create the fog and background lighting effect. When I adjust the fog in Lighting the cubes just get more of the supposed fog color. Also I don't know how to eliminate the sky and make the lighting more like it is in the picture. Does anybody know how to great the fog and lighting effect I am looking for Thanks I previously posted this on unity Q and A and got no answer I can not post my other image with no fog because i do not have enough reputations. It is basically the image I posted just with more shadow and gray cubes. |
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 | vuforia how do I force objects into a 2D plane I'm working on a game in which cards are placed on a table and then rendered in augmented reality. These objects have 3D physics attached to them which doesn't work as well if they are either rotated or if the system mistakes them for being higher or lower then they really are. Is there a good method to force Vuforia Unity to place all items in the same 2D plane and keep all of them upright compared to that plane? I currently have the following code using UnityEngine using System.Collections public class projectioncode MonoBehaviour Vector3 p1 Vector3 p2 Vector3 p3 Vector3 v1 Vector3 v2 Vector3 normal use a plane with the following 3 coordinates public void setPlaneByPoints(Vector3 point1,Vector3 point2, Vector3 point3) p1 point1 p2 point2 p3 point3 v1 p2 p1 v2 p3 p1 normal getNormal(v1,v2) public Transform projectTransform(Transform input) input.position projectPoint (input.position) return input projects a 3d point into space Vector3 projectPoint(Vector3 point) Vector3 vOToPoint point p1 vector between origin and point float dist Vector3.Dot (vOToPoint, normal) distance plane to point return point dist normal caclulates the normal of 2 vectors Vector3 getNormal(Vector3 v1,Vector3 v2) Vector3 res (Vector3.Cross (v1, v2)) res.Normalize() return res This seems to project objects onto a plane but the results tend to be inaccurate and result in weird movements, particularly when moving the camera around. This is what it looks like |
0 | How to play a sound by C that is linked to the object with AudioSource? I trying to play a sound while the player is ontriggerenter. The sound is linked to the object with a AudioSource component. But notting happened. using UnityEngine using System using System.Collections public class FloatBehavior MonoBehaviour Vector2 floatY float originalY public float floatStrength 1 AudioSource triggerAudio Reference to the AudioSource component. void Start () this.originalY this.transform.position.y triggerAudio GetComponent lt AudioSource gt () Debug.Log (triggerAudio) void Update () transform.position new Vector3(transform.position.x, originalY ((float)Math.Sin(Time.time) floatStrength), transform.position.z) OnTriggerEnter 2D void OnTriggerEnter2D(Collider2D other) If gameObject comes in contact with player if (other.gameObject.tag "Player") Play the hurt sound effect. triggerAudio.Play () Trying to debug, but the triggerAudio object will retrieve woodstump 3 (UnityEngine.AudioSource) UnityEngine.Debug Log(Object) FloatBehavior Start() (at Assets C Objects FloatBehavior.cs 17). What am I missing in my script? Should I use AudioClip also? |
0 | FBX model from Blender doesn't show it's surface in Unity3D I've create a model from Blender and exported it as .FBX file. However when I import this into Unity, the surface is missing.how can i fix? Screenshot attached in Blender it look like this in Unity it look like this which only shows it inside |
0 | adapting a Unity gravitational script to allow moons I'm using this script http wiki.unity3d.com index.php Simple planetary orbits to get a solar system going in Unity, but it doesn't seem to support creating bodies that orbit other moving bodies (or I am using it incorrectly). Any idea about how to modify it so that it does (or just use it correctly)? I've been beating my head against this problem for a couple hours, and I really don't feel like I have any idea what I'm doing. Thanks in advance. |
0 | Buggy behavior on basic hinge joint (pinball flipper) I'm trying to make a pinball flipper, but before I begin working on the script to incorporate user controls, I want to get the rotational movement working. Basically it rotates in a circle around the left most point. Clearly one option is to make half the flipper invisible. This is the easiest way but it leaves me still not really understanding how to work with rotation. For example lt o gt where o is the midpoint. I want it to rotate along the same axis, but without the left half of the shape o gt I have tried watching this video a couple times but am coming short of understanding how the hinge joint works. I attached one my left flipper and set the axis to 0,1,0 so it rotates along the y axis (remaining parallel to the playfield). I also moved the anchor to the leftmost position. I have left the rest of the hinge joint at its default configuration. Here is some evidence the placement of the hinge joint (it's the little yellow arrow at the left of the flipper) the hinge joint config The buggy behavior The left paddle's rigid body (it is locked on all position and all rotation except y) What I'm really trying to do is have the flipper rotate from it's leftmost point as the origin. I just want it to free rotate when the ball hits it. |
0 | Unity3D, how much code do you write? I'm curious to know the workflow when creating a game in Unity3D? Does it generate a lot of code for you? My understanding is that you describe the game in Unity and do scripting on the back end to do the logic. Kind of like you use Unity to describe the puppets and you use a scripting language as the puppet master. |
0 | sample project that mix unityscript and c I like the simplicity of unityscript, at same time I also like the plenty of c library and open source projects. I prefer to put my model controller logic flow in unityscript using standard unity3d sdk and invoke c extension library. Is there any sample project demonstrate how to mix the two scripts in one project? Your comment welcome |
0 | Unity Ragdoll Colliders don't collide I have a humanoid character with Ragdoll setup in Unity. However the box capsule colliders on the various parts of the body don't collide with other static geometry. They do collide with the ground but not with any other static meshes. Is it possible to use them as colliders towards static meshes and what do I need to do for it to work? |
0 | Rigidbody freeze rotation around global Y My player is a cube that moves in all directions, but cannot jump. I want to achieve that the cube cannot rotate around global Y axis, but can rotate around global X and Z. This cannot be simply done by freezing the local Y rotation, since the cube can fall from higher ground and rotate mid air after that the local and global y axes are not parallel anymore and some other axis should be frozen. Currently, I am using this line transform.rotation Quaternion.Slerp(transform.rotation, Quaternion.Euler(transform.rotation.eulerAngles.x, Mathf.Round(transform.rotation.eulerAngles.y 90) 90, transform.rotation.eulerAngles.z), 1f) which is located in the FixedUpdate(). The resulting movement is shown in this video. Clearly, this always snaps the axis that is parallel to the global Y to the closest 90 angle. This solution, however, has a few unwanted side effects. One of them is clipping with the terrain or other player cubes, the second one is that the cube randomly rotates if walking over the edges or corners, and the third one is that if one cube is on top of another and both have this script attached, they start lagging, jittering and sometimes spinning. I also tried by freezing the rotation based on what side of the cube is quot on the bottom quot , but this does not work OK, since it often happens that the cube does not rotate for exact 90 when it drops from higher ground and ends up frozen standing on only one edge, just slightly off from being on the ground with the whole bottom side. What is the quot to go quot solution for this type of movement? |
0 | Xcode project runs on device, but not simulator I built a 2D game using Unity3d 5.1.1. When i build and run the project with iPhone connected, the game runs fine on the device. But when i select simulator instead of device, i get an error " does not have an architecture that can execute" . I run the game on iPhone 4S, but cannot run on the iPhone 4S simulator. Similarly, i selected iPhone 6, 5 etc and get this error every time. |
0 | How to push an object? I would like to "push" an object using a raycast. With the following code, the problem is that depending of player rotation, i don't push the object but i pull it. What am i wrong ? Vector3 fwd transform.TransformDirection(Vector3.forward) if (Physics.Raycast (RayCastSpawnOut.transform.position, fwd, out hit, 5)) if (hit.transform.tag "MyObjectTag") GameObject myobj hit.transform.gameObject Rigidbody myobj rb myobj.GetComponent lt Rigidbody gt () Vector3 dir transform.position myobj rb.transform.position dir.Normalize() Normalize to get the correct direction myobj rb.AddRelativeForce (dir 0.5f, ForceMode.Impulse) |
0 | Angle between start and current rotation I'm facing problem of the operations on rotations. I have a wheel with a start rotation of (0, 0, 0). The player has to rotate wheel 270 degrees in Y axis either left or right. During the rotation slider should indicate progress of the rotation. For example if player rotated 135 degrees in right direction, slider is 50 filled to the right. The thing is that I'm not sure how to get the value of which the player rotate the object. For example when I start rotating right my angle changes from (0, 0, 0) to (0, 359, 0). How can I resolve this issue so it knows that change from (0, 0, 0) to (0, 359, 0) means player rotated only 1 degree? |
0 | How to seamlessly handle multiple procedural 2D levels in Unity3D? I have a dungeon generating algorithm, but I would like to generate X levels, which are all connected somehow. I have a few approaches, but all of them has problems and questions, and I wonder how i.e. Diablo II handles them so seamlessly. 1. Approach Upon leaving a level, generate the next one on the fly. This would be the easiest, but would result in a relatively long loading screen everytime the player enters a new level. So generating the levels should be at the beginning of a new game, thus the next level will just have to be loaded, which is much faster. In theory not even a loading screen is necessary. 2. Approach Generate every level at the beginning of a new game and store them. Okay, now levels just have to be loaded, which could be done under half a second. No loading screen is necessary, maybe just a fade out fade in. How do I store them? Make custom files (i.e. scriptable objects) for them, or is there a simpler way? 3. Approach Generate and load every level at the beginning. Zero loading time, because everything is already generated and loaded into the tilemap. But how do I guarantee that levels don't collide, and the player can't see level Y from level X if there are lots of levels? And wouldn't it affect the performance? Because everything is loaded all the time. Yes, renderers, rigidbodies, scripts, etc can be turned off, improving the performance a lot... but still... this seems wrong. What is the best way to solve this problem? |
0 | How would I apply force to a bullet in 2D? I wrote the code below in order to try to get a bullet to fire at a specific angle for my top down shooter. However when I press space the bullet just spawns in front of the game object despite it having a bullet speed. I made sure that my bullet prefab has a rigidbody and I am calling to it in my script. using System.Collections using System.Collections.Generic using UnityEngine public class FireAway MonoBehaviour private Vector3 mouse pos private Vector3 object pos private float angle private float bulletSpeed 1 public GameObject ammo private Rigidbody2D rb2D void Start() rb2D ammo.GetComponent lt Rigidbody2D gt () Update is called once per frame void FixedUpdate() Point the cannon at the mouse. mouse pos Input.mousePosition mouse pos.z 0.0f object pos Camera.main.WorldToScreenPoint(transform.position) mouse pos.x mouse pos.x object pos.x mouse pos.y mouse pos.y object pos.y angle Mathf.Atan2(mouse pos.y, mouse pos.x) Mathf.Rad2Deg 90 Vector3 rotationVector new Vector3(0, 0, angle) transform.rotation Quaternion.Euler(rotationVector) if (Input.GetKeyDown("space")) GameObject BulletPlayer (GameObject)Instantiate(ammo, transform.position, transform.rotation) bullet.transform.LookAt(mouse pos) rb2D.AddForce(BulletPlayer.transform.forward bulletSpeed) |
0 | Fast zoom in and out in Unity Editor Is it possible to zoom out and zoom in in Unity Editor in Scene View faster than just with the help of scroll wheel on the mouse? I hope there are exist some shortcut for that. Am I right? |
0 | 360 degree viewer for AR I want to implement a 360 degree viewer for Augmented Reality in Unity. Augmented Reality means in this case, that I want to place an image like an interface mockup in my viewer which has transparency. The transparency is getting filled with the real world. So the real world part is working without problems, but that is also the reason, why a sky box is not possible since the sky box would block that. So I already had 2 approaches A sphere with a shader which rendered only the inside (turned the normals), worked on my MAC, but didn't render anything on my vr ar device (Samsung GearVR)... Here a picture how it should look like and does look like in the Unity Editor. But nothing of this "crosshair" is showing up on the GearVR A sphere or cylinder where I turned the normals beforehand in Blender, didn't apply the texture correctly and didn't show anything in Unity and on Device except a blank color. |
0 | Wheels not facing right direction when car faces different directions I am creating a real time multiplayer driving game in Unity. I am using google play's real time multiplayer service. I am having an issue where the wheels of the cars that are over the network are not facing the right direction. What I am currently trying to do is just add the calculated steering angle to the current rotation of that particular player's car, but for some reason the wheels face the wrong way and rotate incorrectly if the car is facing certain directions. Logically I thought what I have is correct. Basically for each wheel I use this code car.transform.rotation Quaternion.Euler(0, car.transform.rotation.y steerAngle, 0) So I find the rotation of that car and then I add the steer angle to it. Why wouldn't this work? |
0 | How can I detect that the mouse is over a button so that I can display some UI text? I have a scene, where a panel containing 24 buttons. I need to show some piece of text when hover a mouse cursor over the button. For example, for detecting clicks, I'm using onClick event trigger, but I can't find anything related to something like a onHover event. I have Googled and read the docs, but could not find anything. Can anybody help me with that? Code var button panel.GetChild(0).GetComponent lt Button gt () |
0 | Unity create Animated Tilemap? Im trying to create an Animated Waterfall Tilemap from a tutorial video. In his video when the author right clicks he can see a Animated Tile under CREATE option. But In my case its not there !! Please see picture below. |
0 | 3D Studio Max biped restrictions? I have a stock biped character in 3D studio max which has a jump animation. The problem I have with the jump animation is that there is actual y offset happening inside it which makes it awkward to play while the character is jumping since it's not only jumping in the game world but the jump animation is adding its own height offset. I'm tryuing to remove the jump animations height offset, so far I've found the root node and deleted all its key frames which has helped a bit. The problem I'm having now is that the character still has some height offset and if I try to lower it it has a fake 'ground' that isn't at 0 and the limbs sort of bend on the imaginary floor, si there a way to remove this restriction just for the jump animation? Here's what I mean http i.imgur.com qoWIR.png Any idea for a fix? I'm using Unity 3D if that opens any other possibilities... |
0 | Offset input sent to blend tree based on Character's Local Rotation I am developing a top down twin stick shooter. I am running into a issue where if I change my character's rotation, the Unity Blend Tree animation does not play the correct animation that corresponds to that relative rotation. For example if my Character is facing north and I walk forward, the animation plays fine, but if I rotate my character 180 degrees (facing south), when I walk forward it will play the backwards animation. https media.giphy.com media cmx1aOm0UOjCed8MJT giphy.gif I believe this is because I am just sending the inputs from the analog stick, and not offsetting the values based on the rotation of the character. I am using 2 floats (horizontal and vertical) to control the blend tree. How can I offset the float values from the input based on the character's local rotation? Current code below, void Update() if (!ReInput.isReady) return Exit if Rewired isn't ready. This would only happen during a script recompile in the editor. if (player null) return GetInput() Move() Look() private void GetInput() Get the input from the Rewired Player. All controllers that the Player owns will contribute, so it doesn't matter whether the input is coming from a joystick, the keyboard, mouse, or a custom controller. mhorizontal player.GetAxis("Move Horizontal") get input by name or action id mvertical player.GetAxis("Move Vertical") lHorizontal player.GetAxis("Look Horizontal") lVertical player.GetAxis("Look Vertical") fire player.GetButtonDown("Fire") void Move() if (mhorizontal ! 0 amp amp mvertical ! 0) Vector3 rightMovement right moveSpeed Time.deltaTime mhorizontal Vector3 upMovement forward moveSpeed Time.deltaTime mvertical Vector3 heading Vector3.Normalize(rightMovement upMovement) transform.forward heading transform.position rightMovement transform.position upMovement animator.SetFloat("Vertical", mvertical, 0.1f, Time.deltaTime) animator.SetFloat("Horizontal", mhorizontal, 0.1f, Time.deltaTime) void Look() if (lVertical ! 0 amp amp lHorizontal ! 0) float cameraFacing Camera.main.transform.eulerAngles.y Vector3 inputVector new Vector3(lHorizontal, 0, lVertical) Vector3 turnedInputVector Quaternion.Euler(0, cameraFacing, 0) inputVector transform.LookAt(turnedInputVector transform.position) |
0 | How to apply Collider to Particle and what components are needed for particles? i want to apply collider to particle system because if i applied the collider to particle ,if any other game object touched to that particle its gives some action or do some operation.so only i need. |
0 | How can I change the parents rotation so the childs rotation is looking at a specific direction I have a child object which is always having different positions and rotations (thats my VR Headsets Eye Gameobject) I cannot modify the position and rotation of that. I want to set my view to a certain "startposition" and "startrotation" so the player always has the same view at the start of the game. The childs local position is always set to some values. So I cannot unparent it. If I unparent it, I change his position. now.. It works with the position. Parent.transform.position 2 ParentStartPostion Eye.localPosition This line of code here sets my parent object so that my Gameobject "eye camera" is where i want it to be. For the rotation part, i would do following Eye.parent null unparent the eye to the world Parent.transform.position Eye.position set my Parent to the same position as Eye Eye.parent transform parent it back. Local Eye should be 0.0.0 now. Parent.transform.rotation Quaternion.LookRotation(StartForward, StartUp) i can rotate the at the direction I want it. But after I unparent my Eye the position of the local(which is also global) is set to a different value. And after I parent it back, its set to the old value again. Eye.parent null unparent my eye to the world Eye moves anyway because its movend by SteamVR Parent.transform.position Eye.position set my Parent to the same position as Eye (works) Eye.parent transform parent it back. Local Eye moves back where it was and there is a distance between parent and eye again. Parent.transform.rotation Quaternion.LookRotation(StartForward, StartUp) the rotation changing my eyes position because its parented. Also the rotation is wrong. And now i dont know anymore how to solve this problem. so... i painted my problem in paint for better understanding |
0 | How should I animate sprites with separate body parts? I am not an artist. I have a 2D Sprite broken up into different body parts that I want to animate. I know how to do it in Unity, but every artist I know would prefer to use Flash. I am trying to figure out if I should do it in Unity, or learn how to do it in Flash. My understanding is that in Unity, I'd have to animate directly, or Flash would output sprite sheets. Is there anything Flash offers for animating sprites that Unity does not? Is there a benefit to using sprite sheets over animating directly? Is there an option I should consider over Flash and Unity? |
0 | About tiles in games I'm trying to learn how to develop games in Unity and my base is tiled games, I would like to know if a simple tile is an image (sprite in 2D) or a game object in 3D. Since I'm trying to do some kind of 3D tiles with interaction with the user like press to do something an animation, I would like to know how it works. |
0 | How to Make Border of 2D Game in Unity I have a border by default. But, I'm having trouble detecting if my object collides with the border. I am looking for efficient ways to do this, and I am not sure what should I use. I thought using a Tilemap might work. But, it was only giving me a grid, not a Tilemap. Even then, I was unable to figure out how to use the grid. How should I go about creating this? |
0 | How can I use one method and also switch between a coroutine and the main method? Now I'm using two methods, one as StartCoroutine and one not. What I want to do is to have just one method and when I set the StartCoroutine variable to true or false when the game is running I want it to switch between the coroutine and the main. Is there a simple way to do it with one method and not two, if not, how do I achieve this? using System.Collections using System.Collections.Generic using UnityEngine public class Grid MonoBehaviour public GameObject gridBlock public int worldWidth 10 public int worldHeight 10 public bool StartCoroutine false public float spawnSpeed 0 void Start() if (StartCoroutine) StartCoroutine(GenerateGridSC()) else GenerateGrid() private void GenerateGrid() for (int x 0 x lt worldWidth x ) for (int z 0 z lt worldHeight z ) GameObject block Instantiate(gridBlock, Vector3.zero, gridBlock.transform.rotation) as GameObject block.transform.parent transform block.transform.name "Block" block.transform.tag "Block" block.transform.localPosition new Vector3(x, 0, z) IEnumerator GenerateGridSC() for (int x 0 x lt worldWidth x ) yield return new WaitForSeconds(spawnSpeed) for (int z 0 z lt worldHeight z ) yield return new WaitForSeconds(spawnSpeed) GameObject block Instantiate(gridBlock, Vector3.zero, gridBlock.transform.rotation) as GameObject block.transform.parent transform block.transform.name "Block" block.transform.tag "Block" block.transform.localPosition new Vector3(x, 0, z) |
0 | How to rotate and move an object in precise time frame My task is to rotate and move an object into a new position and rotation in a given time. Say I have to move a cube from (0,0,0) (0,0,0) to (1,1,1) (0,90,0) in 5 seconds. Could anyone explain to me please how to achieve that? My experiment is private IEnumerator DoMove( float time, Vector3 targetPosition ) foreach(WayPoints wp in tposes) float counter 0 float duration wp.timeStamp while (counter lt duration) counter Time.deltaTime Vector3 curpos cube.transform.position Quaternion crot cube.transform.rotation float time Vector3.Distance(curpos, wp.position.position) (duration counter) Time.deltaTime cube.transform.position Vector3.MoveTowards(curpos, wp.position.position, time) cube.transform.rotation Quaternion.Lerp(crot, wp.position.rotation, time) yield return null Debug.Log( quot Reached position quot wp.position.position quot in time quot Time.time) The cube gets to its position in time, but rotation is late. The end position of the cube should be (2,2,2) (0,120,0), but it stops moving at (2,2,2) (0, 110,0). There are two positions I want the cube to be in (1,1,1) (0,90,0) in 5 seconds (2,2,2) (0,120,0) in next 4 seconds |
0 | How can I change view to orthographic using a menu? I'm writing the custom menu using MenuItem and I'm stuck trying to make scene view orthographic when 5 is pressed. What is the object or method I can use to set scene's view to orthographic (I don't mean the main camera, but the main view shown in the window). This is a C code of what I was trying to achieve MenuItem("View SetOrtho 5") static void SetOrtho() var scene ... assign scene scene.setOrtho(true) set orthographic view to the scene |
0 | Unity Animator animations fail to play only when triggered by user input I have a unity animator setup like so. When the game runs, I can trigger each state in the state machine with user input. I can use HasExitTime flag to trigger the animation, and it will play through and loop infinitely as expected. However, when I try to use the GearChange trigger, the state machine progress bar plays, the correct box is triggered, but the animation itself doesn't play! I'm at a total loss as to what the problem is here, as everything else is exactly the same, minus the user input. The console isn't showing any errors, the animation simply doesn't respond to the state machine. What am I missing here? Unity version 2020.1.0f1 So I deleted the animator, and setup everything again the exact same way. Now the animation won't play, period. The state machine progress bars are still triggered as expected, but the animation won't play. In the transition preview, the animation won't play there either. |
0 | If a 3d surface is occluded by another 3d surface, does this have any effect on the performance and rendering speed? We have a 3D character who is wearing a gauntlet on his forearm and visibility of which can be turned on and off. Would it be better to create two versions of arm, one without extra triangles that are hidden beneath the gauntlet? Or we can just one model with gauntlet as separate object which can be turned on and off ? Does the hidden triangles have any effect on rendering or are they completely ignored by engine? We are using Unity 3D. |
0 | Manipulating an animation towards a target object (ie. The hand and arm lean towards the target) I am trying to make a boxing game just for fun (I dont expect the end product to be anything decent lol) . I have my boxers in the ring and they are animated quite well so far, with Idle, and punch Left and Right. They also rotate so they are always looking at each other. What I want to do is give the punch some aim towards the head. I will give the punch a set amount which it can move from the standard animation and move the hand bone in the direction of the targets head object. But I don't know how to do this S So far i have used dragged the 3 animation files into Mecanim and coded it to do the animations when a button is pressed. Is there a way to manipulate the animation in this way? (ie. actually make the arm reach towards the target object ) |
0 | How to build a C library for Unity as a pure Visual Studio project The aim is to build a relatively simple (2D) game in Unity with most of the game logic in a non visual AI. The AI needs a lot of testing and debugging independently of any visuals (which is best done using VS tools), and the API connecting them is one class and a few methods properties. A future version might not even use Unity. So the question is how to set up a VS solution file to build the AI for testing and debugging while remaining compatible with the Mono build environment used by Unity. Yes, I know it has to be C 4, but beyond that? At present I'm copying CS files around and that doesn't feel right. Just to make it crystal clear, the AI has no dependency on Unity and will be built in a project that has VS testing and code analysis but no Unity tools or imports. In future it may be used with a different engine. |
0 | Is it efficient to use colliders on UI canvas in Unity? Basically I have a task where the player will be able to drag an object (as UI Image), and place it inside a bag (another UI image). What's the best optimized way to do so? As I researched, I do not think that using colliders for images is the "best" way to do it. Additionally, I was thinking about checking if the position of the image while dragging overlaps an element however, I do think that would be performant as that would require checking the position on each frame instead of "OnTriggerEnter". What would be the best way to implement such function? Thanks amp Regards, HurpaDerpa |
0 | Creating a simple countdown timer in unity Hello's I was looking for a way to do a countdown timer in unity and stumbled across this solution public float timeRemaining 10 private void Update() if (timeRemaining gt 0) timeRemaining Time.deltaTime else WinGame() Which at first seemed pretty elegant and easy to use, however, I was thinking about it, and wouldn't this be inconsistent for players with different FPS? For example, if the player has 60 FPS vs 30 fps it would take longer for the player having 60 FPS to reach 0 on time remaining. |
0 | Load large quantities of data in Unity3D I'm building an Android app using Unity3D where users can visualize data immersively. The data is immutable and stored using a MySQL database hosted on cPanel. When the user clicks a button in the environment, it starts the creation of a chart. First, contacts a .php file present in the server responsible to query the database, fetching the data and make it available to the Unity controller which then adds the points to the chart. This works fine for small quantities of data. To increase performance, thought of exporting from MySQL as CSV and transform to one JSON, instead of querying a database or try to make MySQL transform to JSON, but I'm afraid this won't be enough. Could also extract as CSV and use a 3rd party for reading it. How would you load the data in such case to have the best performance? |
0 | Health bar without image collapsing to the centre in Unity 2D I am trying to create a health bar that collapse symmetrically to the centre. The color palette of my game is minimal and the health bar is only one color that does not change with size. I am new to Unity and am not sure how to achieve this. This video uses a GameObject with an Image component, adds the health bar sprite to the image, makes the Image type fill and then changes the fill amount from the script. I have two questions for my particular case, I would prefer not to use an image. Since the bar is one color I can use color selector to make the bar, but then it does not have the fill type. Is there a way to do using only color? The the bar is anchored at one end left or right. I want to anchor it at the centre. One work around is to use two objects side by side and fill them in opposite directions to get the desired effect. Is there a better way? |
0 | moving ball on spawn I'm working on some special pick ups on an arkanoid like game. Currently, I have one that should spawn several balls all in a row, right after the original ball hits the paddle. All the additional balls should spawn just above the paddle and then they are passed the vector from the original ball, in which case they should follow that vector, essentially causing a line of balls all traveling in the same direction. The problem I am having is the ball's spawn just above the paddle, but they are spawning in place. Gravity pulls them down, and when they hit the paddle, that seems to be when the vector becomes active and the ball takes off like it should have when it spawned. I'm not sure what I am doing wrong here to keep it from just taking off like that as soon as it spawns. Can anyone see anything here that could be causing this behavior? This is the code for spawning a ball and setting the vector. Instantiate(newBall, new Vector3(paddle.transform.position.x, (paddle.transform.position.y 1), 0), Quaternion.identity) newBall.GetComponent lt Ball gt ().hasStarted true GameManager.pickUpManager.allBalls.Add(newBall.GetComponent lt Ball gt ()) newBall.GetComponent lt Rigidbody2D gt ().AddForce(mainBallVector, ForceMode2D.Impulse) use the original ball's vector3 to follow it directly Here is where mainBallVector gets set, it is a vector3 mainBallVector mainBall.GetComponent lt Rigidbody2D gt ().velocity |
0 | Placing Zones in Cities Skylines I'm trying to build a mod that places zones on a keypress. How would I accomplish this? So far I've detected the keypress. But when I modify m blocks in ZoneManager by calling block.setZone(x,y,zone) The block appears to have changed, but only for the moment. When I run the keycommand again, the data appears to have been reset. I never see the zone change in game, only when I print it to the console. string outtext quot quot uint blockCount Singleton lt ZoneManager gt .instance.m blocks.m size outtext quot start n quot for (int index 0 index lt blockCount index ) var block Singleton lt ZoneManager gt .instance.m blocks.m buffer index if (block.m valid ! 0) block.SetZone(1, 1, ItemClass.Zone.Industrial) block.RefreshZoning(0) outtext quot valid quot block.m valid quot position quot block.m position.ToString() quot zone quot block.GetZone(1, 1) quot n quot outtext quot quot Debug.Log( quot OUTTEXT quot outtext) I've tried calling block.refreshZoning() as well, but I'm not sure how to calculate the blockid (. |
0 | How to use base.Function() in Unity I am using 3 classes EnemyBullet MonoBehavior EnemyBulletType1 EnemyBullet EnemyBullet Class void FixedUpdate() this.gameObject.transform.rotation Quaternion.Euler (new Vector3 (0,0,90)) EnemyBulletType1 Class override void FixedUpdate() base.FixedUpdate () Do something else here The reason is I'll have many EnemyBulletType classes and I want them all to do a common thing and then do something on their own. Question This code isn't working Error virtual or abstract members cannot be private How is FixedUpdate() defined in the MonoBehviour and how to change it to help my usecase? |
0 | Why I can't do a build for Linux? I'm using Unity 5.3.x (free version) on a Windows machine. I would like to build my simple desktop game either for Windows and Linux, but Linux (and Mac) build is disabled. Am i missing something ? Thanks |
0 | Using Lerp to zoom in on an object inside an if statement I'm trying to zoom in on an object once the raycast hits it in the Update method, I am using the Lerp method to make the camera movement smoother but it's not working properly. The object only lerps for a single frame. I also tried using a coroutine but the result is still the same. I can't simply just place it outside the if statement because I only need to change the field of view once the raycast hits an object. Here's a sample of my code if (Input.GetMouseButtonDown(0)) ray mainCam.ScreenPointToRay(Input.mousePosition) if (Physics.Raycast(ray, out hit)) if (hit.collider.tag.Equals("Building")) SetTarget(hit) mainCam.fieldOfView Mathf.Lerp(mainCam.fieldOfView, newFOV, Time.deltaTime smooth) |
0 | Launching projectile from a "canon" I'm working on "Scorched earth" like game just for learning purpose. I can't figure out how to launch the projectile from my tank's position, with a power of X ( 0,100 ),at an angle of Y ( 180,180 ). |
0 | Object doesn't instantiated right spot I have weird glitch in my game. When player shoot the gun, bullet is instantiated something called "ShootPoint" transform. This is the ShootPoint's position And this is the code of firing bullet RigidbodyProjectile CreateBullet() GameObject bullet Instantiate(bulletPrefab, shootPoint.position, shootPoint.rotation) RigidbodyProjectile projectile bullet.GetComponent lt RigidbodyProjectile gt () projectile.rigidbody.AddForce(shootPoint.forward.normalized bulletSpeed, ForceMode.VelocityChange) return projectile Simple script to just instantiate bullet prefab in ShootPoint.transform. However when I run the game, bullet generated totally wrong place That picture captured right after creation, even before push the bullet. Here's the updated code for capture that moment, I intentionally throw the error so that makes game stop RigidbodyProjectile CreateBullet() GameObject bullet Instantiate(PrefabManager.GetPrefab("bullet"), shootPoint.position, shootPoint.rotation) Throw the exception throw new System.Exception("DIE") So codes under here will not work RigidbodyProjectile projectile bullet.GetComponent lt RigidbodyProjectile gt () projectile.rigidbody.AddForce(shootPoint.forward.normalized bulletSpeed, ForceMode.VelocityChange) return projectile I don't get it, why my bullet doesn't generated in ShootPoint.transform? I literally removed all components in Bullet and tried again but still had same problem. Funny thing is that this is not always happening, it only happens in certain angles, especially looking down. I already checked hundreds that ShootPoint pointing something wrong direction or reference of ShootPoint was wrong, but no, there was no problem at all! What should I check in this case? It's really annoying issue, because when I shoot little lower angle, it always hit the ground almost instantly after fire. Anyone who knows about this issue, if could be great what should I check, thanks. Additional Info about Bullet I forgot to mention about bullet. It has parent and child, and parent has rigidbody and child has mesh to display. This is because basically bullet wasn't pointing forward so I rotated it to pointing forward and wrapped by empty game object so that eventually it pointing forward direction even mesh is rotated. Here's the screenshot to explain this |
0 | Unity3d Rotating a sphere so point lines up with the camera I'm trying to make a world map in Unity that contains a rotating globe with landing sites on the perimeter. What I want is that when a player clicks on the landing site the globe rotates so that the landing site is centered. I've been trying to find the right way to use the Quaternion class but not much luck. Here is my latest attempt which doesn't work. The landing sites are parented to the globe but the camera and globe are separate. void Update() if ( selectedLandingSite ! null) var rotation Quaternion.FromToRotation( selectedLandingSite.transform.localPosition, MainPlanet.transform.forward) var trans Game.Game.Instance.MainCamera.gameObject.transform var lookDirection new Vector3(trans.position.x, trans.position.y, trans.position.z) lookDirection rotation lookDirection var lookRotation Quaternion.LookRotation( selectedLandingSite.transform.localPosition) rotate us over time according to speed until we are in the required rotation MainPlanet.transform.rotation Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime 1) MainPlanet.transform.rotation Quaternion.RotateTowards(MainPlanet.transform.rotation, targetRotation, 1) |
0 | Unity Efficient way to get the average pixel color for a portion of the camera viewport At it's core, the problem I'm trying to solve is this I have a camera (not main) that I would like to project to a 2 pixel RenderTexture. I would like the first pixel to be the average color of all pixels in the left portion of the camera viewport (or a close approximation). And the second pixel to be the average color of all pixels in the right portion of the camera viewport. So far I've looked into doing this via OnRenderImage(src, dest) but I'm open to any suggestions. Same goes with camera resolutions, 256x256 seems like a good starting point but open to suggestions here too. It's worth mentioning that I just threw together a brute force non threaded approach that works but totally tanks FPS (nothing surprising) Any help would be greatly appreciated. This doesn't seem like an incredibly weird downscaling approach but I can't seem to find anything regarding it. There might be a clever way of dealing with this via a shader but I have yet to find it. Bilinear downscaling (which I think is what unity uses by default) sadly does not give the appropriate result. System compatibility is not an issue, Win 10, DX 12. |
0 | Color bands over tile when scaling texture in shader I want to have tiles with different sprites on the back. Initally I thought I will mix two textures together and then apply mixed texture to game object. I thought that should be easy, but google returned discussion about shaders and their superiority. After reading about shaders I decided to use shaders instead. Also I am using rather big sprites and I am scaling them down in shader. Kind of want to be sure that tiles look good on big screens also. Also to be sure that game works on smaller screens I change camera distance when game does not fit in the screen. Everything is working nice when tile is "near". But when tile is far away it starts to show artifacts over all surface of tile. It appears that scaling is done not pixel by pixel but in some chunks. Modified shader code (I commented out mainTex because it does not change anything from "bug" perspective) Shader "Custom TwoTextureShader3" Properties Color("Color", Color) (1,1,1,1) MainTex("Main Texture Color (RGB)", 2D) "white" MainTex2("Overlay Texture Color (RGB) Alpha (A)", 2D) "white" Glossiness("Smoothness", Range(0,1)) 1 Metallic("Metallic", Range(0,1)) 0.2 OffsX("Offset X", Range( 2, 2)) 0 OffsY("Offset Y", Range( 2, 2)) 0 Scale("Scale", Range(0, 10)) 1 SubShader Tags "RenderType" "Transparent" LOD 200 CGPROGRAM Physically based Standard lighting model, and enable shadows on all light types pragma surface surf Standard alpha fullforwardshadows Use shader model 3.0 target, to get nicer looking lighting pragma target 3.0 sampler2D MainTex sampler2D MainTex2 fixed OffsX fixed OffsY fixed Scale struct Input float2 uv MainTex float2 MainTex2 half Glossiness half Metallic fixed4 Color void surf(Input IN, inout SurfaceOutputStandard o) float4 mainTex tex2D( MainTex, IN.uv MainTex) fixed2 offsetUV fixed2( OffsX, OffsY) float4 overlayTex tex2D( MainTex2, IN.uv MainTex Scale offsetUV) half3 mainTexVisible mainTex.rgb (1 overlayTex.a) half3 overlayTexVisible overlayTex.rgb (overlayTex.a) float3 finalColor (mainTexVisible overlayTexVisible) Color o.Albedo finalColor.rgb o.Albedo overlayTex.rgb o.Metallic Metallic o.Smoothness Glossiness o.Alpha max(mainTex.a,overlayTex.a) o.Alpha 1 ENDCG FallBack "Diffuse" Tiles looks good when they are near Tiles looks awfull when they are far away Currently I am thinking about using two Meshes for single tile, so that game never hints about what is on the back of the tile even when graphics hardware really want to. |
0 | Quaternion.slerps resets camera rotation to (0,0,0) when i go to play mode help! i am building a camera rotation script like in fps. Everything is setup and working except that camera rotation resets to zero at the start of game which i dont want. This is the camera rotation i have set This is rotation of character my script is attached to And after hitting play it resets camera rotation to (0,0,0). i want it to remain how i have set it in inspector. i am using quaternion.slerp to rotate camera around to rotations on the basis of touch inputs. After reset to (0,0,0) everything works fine.please help, i have always had a hard time understanding quaternions. this is the script public class ScreenCharacterController MonoBehaviour private Camera mainCamera private CharacterController character private int leftFingerID 1 private int rightFingerID 1 private Vector2 leftFingerInput private Vector2 rightFingerInput private float xAxisRotation private float yAxisRotation SerializeField private float minXRotation SerializeField private float maxXRotation SerializeField private float minYRotation 25f SerializeField private float maxYRotation 25f SerializeField private float cameraRotationSpeed 20f void Start() mainCamera Camera.main void Update() for touch TouchInput() for calculating rotation vaues CalculateAndClampRotation() RotateCamera() void TouchInput() foreach (Touch touch in Input.touches) if (touch.phase TouchPhase.Began) Left Touch if (touch.position.x lt Screen.width 2) leftFingerID touch.fingerId Right touch else rightFingerID touch.fingerId else if (touch.phase TouchPhase.Moved) Left Touch if (touch.position.x lt Screen.width 2) if (leftFingerID touch.fingerId) Right touch else if (rightFingerID touch.fingerId) rightFingerInput touch.deltaPosition Time.smoothDeltaTime else if (touch.phase TouchPhase.Ended touch.phase TouchPhase.Canceled) if (touch.fingerId leftFingerID) leftFingerID 1 else if (touch.fingerId rightFingerID) rightFingerID 1 rightFingerInput new Vector2(0, 0) void RotateCamera() Quaternion currentRotation mainCamera.transform.localRotation Quaternion targetRotation Quaternion.identity targetRotation Quaternion.Euler((mainCamera.transform.localRotation.x yAxisRotation), (mainCamera.transform.localRotation.y xAxisRotation), 0f) mainCamera.transform.localRotation Quaternion.Slerp(currentRotation, targetRotation, 0.5f) void CalculateAndClampRotation() xAxisRotation rightFingerInput.x cameraRotationSpeed yAxisRotation rightFingerInput.y cameraRotationSpeed xAxisRotation Mathf.Clamp(xAxisRotation, minXRotation, maxXRotation) yAxisRotation Mathf.Clamp(yAxisRotation, minYRotation, maxYRotation) |
0 | How unity works on Web How Unity can work on Web if the code is written in C ? I understand that you can compile the C code to a shared library and use it in Java (for Android) in ObjectiveC (for iOS) to enable Unity on multiple platforms, but you cant use shared library on JS. Does Unity do language to language translation from C to JS to enable Unity on Web? As I understand now starting from Unity 5.0 it even doesn't use Unity Web Player. |
0 | View individual UI Rect boxes when multiple UI elements are selected? I have 2D UI layout with multiple text boxes over the canvas, I need to easily be able to see where the Rect boxes for each are positioned, so that I can see where the safe areas are for placing buttons etc. Selecting each individual item shows its own individual Rect box, but selecting multiple items just shows one big box around all of them. Is there a way of selecting multiple items and see each individual Rect box? It's extremely time consuming having to go and check each one individually. |
0 | Unity Render an animated texture to a screen I'm looking for a way to write a typed text on a texture, and then render it on a screen in the game it's just the screen of a computer where a scientist is typing text on. The texture will be already generated it will have several textures in it. I can't find any obvious way to do a simple render to texture with unity, how could I do that ? |
0 | SSAO in my unity games has flickering lines at the top and right side of the screen I've tried both the built in unity ambient occlusion that comes with the post processing stack, as well as another one ported from the Microsoft MiniEngine by someone https github.com keijiro MiniEngineAO. Both of them have the same issue pictured below with these dark lines and the occlusion on the faces around the lines seem to flicker as the camera moves. I've been trying to solve this issue by using the Microsoft MiniEngine AO and changing the compute shader. In one of my attempts, I changed the output of the shader from the calculated occlusion Occlusion OutPixel lerp(1, ao, gIntensity) to the depth texture UV to be sampled Occlusion OutPixel QuadCenterUV.x (QuadCenterUV probably being the center of the UV to sample for the 4 depth texture samples ) Fetch four depths and store them in LDS ifdef INTERLEAVE RESULT float4 depths DepthTex.Gather(samplerDepthTex, float3(QuadCenterUV, DTid.z)) else float4 depths DepthTex.Gather(samplerDepthTex, QuadCenterUV) and this was the output With a similar effect on the Y axis. I think that may be the cause, as the distortion of the UVs matches the distortion of the effect. I don't know how to fix this, because I don't have enough knowledge about RWBuffers or compute shaders. My terrain is generated by a noise function as a 2D array, constructed into a mesh, the mesh runs Mesh.RecalculateNormals(), and then is sent to the Mesh Filter. What is the issue here, and how can I fix it, or can anyone fix it for me? |
0 | Instantiate a prefab on button press and keep it dragged So far the gameObject is created, but I need to click on the object a second time, in order to start the Drag event. Here's the script where I use the button to spawn a prefab public void SpawnPrefab(Transform prefab) clicked false Vector3 mousePosition, targetPosition mousePosition Input.mousePosition targetPosition Camera.main.ScreenToWorldPoint(new Vector3(mousePosition.x,mousePosition.y,distance)) prefab.position targetPosition if(isAlreadyClicked false) Instantiate(prefab, prefab.transform.position, prefab.transform.rotation) isAlreadyClicked true Debug.Log(clicked) I call this Drag event from another script inside the spawned gameObject though void OnMouseDrag() cursor.setGrab() if(this.transform.parent null this.transform.parent ! null) drag the component Vector3 curScreenPoint new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z) Vector3 curPosition Camera.main.ScreenToWorldPoint(curScreenPoint) offset transform.position curPosition if(this.gameObject.CompareTag("Component")) mainCanvas.transform.GetChild(1).gameObject.transform.GetChild(0).gameObject.transform.GetChild(4).gameObject.SetActive(false) if(this.gameObject.CompareTag("NewComponent")) mainCanvas.transform.GetChild(1).gameObject.transform.GetChild(0).gameObject.transform.GetChild(4).gameObject.SetActive(true) Hope it's clear enough. Any ideas? Thanks in advance! EDIT So I found out that the SpawnPrefab() only works when mouse button is released. Is there any way I can make the buttons work on mouse pressed? |
0 | How to handle global Data within a state machine setup? (C ) I am currently building a turn based framework (Unity,C ) I was tired of my former tight coupled systems and opted for a state machine this time, basically all components subscribe to the state Enter and state Exit event. I am aiming for scalability and structure. But I ran into a problem. If the components cannot communicate directly, how to store and forward data in between states? Example The game starts with unit placement. The player has the option to select a unit in his pool via the ui and place it on the board. The Unit creation logic is and should(?) be handled inside the level script. How does it know where to create which unit? Ive done a workaround with a static container class, with is basically my clipboard. The player assigns a grid cell for his selected unit and the game leaves the state. While leaving the state the level scripts scans the clipboard and creates any assigned units. But I feel like a cheated my attempt to really work strictly within a firm structure this time to guide the design process. Is there a better way? |
0 | Serialize ScriptableObject without creating an asset out of it? Is it possible to do something like this? public class SomeScriptable ScriptableObject public MyScriptable myScriptable public void OnValidate() if (myScriptable null) myScriptable ScriptableObject.CreateInstance lt MyScriptable gt () public class MyScriptable ScriptableObject public int MyVar1 public string MyVar2 I tried this but am getting a "Type Mismatch" error in Unity. |
0 | How to stop all character movement when jumping against the side of a platform? My Sprite is Moving against a platform. I have a script and an unusual one (that's what one of the member said.) My isGrounded isn't using any rayCasting. I didn't have any problem with it but when I created a platform and jump against it My character would fall down slowly. If I try to move against the platform, I would be able to move and it would appear as if the character was flying. So question is, how can I stop all my movements, jumping everything, when I collide like this with a platform? My Code is using System.Collections using System.Collections.Generic using UnityEngine public class pScript MonoBehaviour public Rigidbody2D rb SerializeField public Transform Points SerializeField public float radius SerializeField public LayerMask layer public bool jump public bool isgrounded false SerializeField public float MoveSpeed SerializeField public float jumpHigh public bool facingRight public Animator animator public Object CallfPanel public Object CallfText public float Move 8f public Vector3 Dir public Vector3 tart Use this for initialization void Start () rb GetComponent lt Rigidbody2D gt () animator GetComponent lt Animator gt () CallfPanel GameObject.Find ("Panel") CallfText GameObject.Find ("Text") Update is called once per frame void Update () RaycastHit hit Debug.DrawRay (transform.position, Vector3.right, Color.white, Move) tart new Vector3 (200, 300, transform.position.z) Dir Vector3.right if (jump true) if (Physics.Raycast (tart, Dir, out hit, Move)) jump false float horizontal Input.GetAxis ("Horizontal") animator.SetFloat ("speed", Mathf.Abs (horizontal)) isgrounded isGrounded () rb.velocity new Vector2 (horizontal MoveSpeed, rb.velocity.y) if (Input.GetKeyDown (KeyCode.Space)) jump true if (isgrounded amp amp jump true) isgrounded false rb.velocity new Vector2 (0, jumpHigh) if (isgrounded false) jump false changeDirections () private bool isGrounded() if (rb.velocity.y lt 0) foreach (Transform points in Points) Collider2D collider Physics2D.OverlapCircleAll (points.position, radius, layer) for (int i 0 i lt collider.Length i ) if (collider i .gameObject ! gameObject) return true return false public void changeDirections() float horizontal Input.GetAxis("Horizontal") Vector3 theScale transform.localScale if (theScale.x 1) facingRight true else facingRight false if (horizontal gt 0 amp amp !facingRight horizontal lt 0 amp amp facingRight) theScale.x 1 transform.localScale theScale public void showTextDuration() float lifetime 4.0f Destroy (CallfPanel, lifetime) |
0 | How can I provide an instance of a certain script to all scripts that need it? Problem Whenever a player is added to the game (in the form of the server instantiating a player Game Object with a Player component), I want to provide it to every script that needs a reference in other words, dependency injection. Potential Solutions I thought I'd create an IPlayerRequester interface and have the Player script look up all implementing scripts on the client when it's created, but Unity has no interface searching equivalent of FindObjectsOfType lt gt (). More Info The game is multiplayer, where 1 player is the host a client and the server that is joined by other clients. I'm using Mirror. When a new client is added, the Player script's (that was just spawned) callback OnStartLocalPlayer() is invoked, and so far, that's the only way I've found to access the local environment. But because this is the same Player that I'm trying to inject into requesting scripts, I can't just raise an event in that method, so that's out. What would be a good solution here? |
0 | Unity3D Creating Sharing light baked levels without updating the game I want to give myself freedom to add more levels after releasing the game. For creating levels I broke down structure and created a tilemap like a structure. here's an example I will add them up to create a level and send it to server from where I can download the JSON in game and read it at run time to place things around. The problem is I want to also use Global Illumination. What I can do is send lightmap data with created level to server and download and use it for lighting after generating level. But what If my map is huge?? I don't want to have lightmap size. The other thing I can do is create light baked prefabs, suggested by this article, https unity3d.com how to light baked prefabs on mobile. But every single object has to be attached to a surface and baked because of shadows. Is there a better approach? Thank you. |
0 | How to make an object that has no rigidbody2d component smoothly fall on the ground in Unty2d? I have two character in my game enemy and main character. Enemy can throw different objects into the main character. For this moment i am doing this action in such way void FixedUpdate() if (CanMove) transform.position Vector2.MoveTowards(transform.position, TargetPlayer.transform.position, 15 Time.deltaTime) public void StartMove(bool canMove) CanMove canMove TargetPlayer GameObject.FindGameObjectWithTag(Tag).transform rigidbody2D.gravityScale 0 This script is attached to the prefab of the object that will be thrown into main character by the enemy. This script is working, but in this case the object that was thrown will follow by main character all the time, because of this line of code transform.position Vector2.MoveTowards(transform.position, TargetPlayer.transform.position, 15 Time.deltaTime) To my mind this is not good, because i want to give my player the opportunity to escape from the object that was thrown at him. For example run away. When the object reaches the player position (and the player is on the new position) he will simply fall onto the ground. I did this, but this wasn't looking nice, because when the object was reaching his position, he was hanging in the air. Can anyone give me an advice how to make this process more good looking? Edit I need to make good looking movement of the object, that was thrown by the enemy into main character. Every frame i am moving the instantiated object to the current player position. So the player can't escape from that object, because he always knows current player position. I think that this is not good idea, and i want to give to player an opportunity to run away from that object. In this case i am saving the position of the player into variable, and then every frame i am moving the instantiated object to that position. So when the player run away, the object, that was thrown doesn't know anything about new position of my player. But this is looking not good, because when the object is reaches its destination position he hangs in the air(( Edit 2 I was thinking about destroying that object anyway, but to my mind this will not look good the object is moving and suddenly disappears from screen(. May there is some ways how to make him smoothly fall onto the ground? The problem is in that this instantiated object has no Rigidbody2d component attached to it, so it will never fall down by itself. |
0 | Dynamic frame rate in Unity I'm developing a 3D visualization tool based on Unity, targeting WebGL. The user rarely interacts with the 3D scene and when he does it's only about adjusting the camera like rotating or zooming the view. I disabled vSync (QualitySettings.vSyncCount) and locked the frame rate to 30 (Application.targetFrameRate) to reduce the CPU usage at least a bit while still having an acceptable level of responsiveness when the user moves the camera around. With 30 fps I get a CPU usage of around 30 . Considering lower end hardware this seems still too high. In order to further decrease CPU usage, I introduced two 'modes' Interactive runs with 30 fps Idle runs with 10 fps I wrote some lines of code to switch between those modes depending on user interaction. So when an input is detected, the application uses more fps and after a certain amount of time without any interaction, the application uses less fps again. It works pretty well so far The app uses 30 in interactive mode and 8 to 10 of the CPU while in idle mode. Setting the idle frame rate to 1, CPU usage is reduced to 1.5 while in idle mode. This is really great. But as expected there's a problem. Basically I locked all the Update() methods to be called only once per second. When the user interacts with the camera, the event will be processed with an expected delay of something around one second. Now the question How can I detect user input immediately while having the application run with a low frame rate and also immediately apply a new frame rate (say 30) without any noticeable delay? Originally I wanted to have some sort of on demand rendering. I've read some posts about how people render to a texture to reduce rendering cost in less interactive scenes. But setting the frame rate dynamically seems like a cleaner solution in my opinion. I also tried to use the FixedUpdate() method to check for inputs and switch to interactive mode, but that didn't work either. Note Also worth mentioning, this approach produces errors in the browser, indicating that the application frame rate should be 0 (not in terms of Unity's target frame rate but as in 'let the browser handle the frame rate'). While this might be a different question it's still related to this topic. Maybe someone has an answer for that as well! Edit 1 As mentioned in the comments below, Unity provides the callbacks MonoBehaviour.OnApplicationPause and MonoBehaviour.OnApplicationFocus to detect whether the application is about to receive or lose focus. However, the problem is this My application nearly never loses focus. While this is a nice additional optimization it doesn't really help me too much. My problem is that the app is idle most of the time while also having focus. It's really just the user staring at the window most of the time. Just to make some more sense I'm targeting WebGL. Unity's sole purpose is to visualize some stuff while the user mainly interacts with some HTML controls. In the rare case he wants to interact with the 3D scene, I want to set the frame rate to say 30. The idea is quot I don't re render the scene too often as long as you don't interact quot . To emphasize In my most relevant use case the application never loses focus. This means, the only reliable indicator to determine when to switch between frame rate profiles is based on user input. Sorry if I wasn't too clear about that ) Edit 2 I posted this topic on the Unity Feedback Page. If you're interested, check it out and leave a vote. Maybe this request gets enough attention to get supported by the Unity developers. |
0 | How to disable script component while in game? I'm trying to make a C script to disable the First person controller script component for my character. I'm doing this so that while I'm controlling something else such as a vehicle, the only control script enabled at the time is the vehicle, and vice versa for when I'm not in the vehicle. I did find a tutorial on the Unity Web site for Enabling and Disabling components but it uses a light component as an example, and I have no idea of how to do the same thing with a script component. I really appreciate any help I can get to solve this problem. Thank you This is the code in C provided by the tutorial public class EnableComponents MonoBehaviour private Light myLight void Start () myLight GetComponent lt Light gt () void Update () if(Input.GetKeyUp(KeyCode.Space)) myLight.enabled !myLight.enabled |
0 | Managing Unity Scenes during refactoring? Most of my Unity project code is in a visual studio project, and I use Unity for UI Rendering wiring things together. I renamed some fields in an object and suddenly the game, when run in unity, became unrunnably buggy. It turned out that a field I had set in the unity frontend had been unset when I renamed it. What's a good way to avoid these sorts of problems when working with unity? I was using version control and could have reverted to an old build in the worst case, but I couldn't find any human readable Unity Scene files that could have just shown me what I changed. |
0 | Visual Studio IntelliSense syntax highlighting not recognizing Unity types Frequently when I open a Unity C script in Visual Studio, the built in Unity Engine types aren't recognized, so I don't get syntax highlighting or code completion hints for things like MonoBehaviour. Sometimes if I delete the script and create a new one it works, but lately nothing I do solves the problem. Is there something I can do? |
0 | Push Notification to start a scene I was wondering whether I can use APNs in iOS to trigger an event in my game, like start a scene without user clicking the notification. Is it possible to use remote push notifications for events like this? |
0 | Stop animation from playing while waiting to destroy object I'm working on functionality in Unity where if a game object's health is zero, it does and the object is destroyed. This works fine as is, I reduce the health to zero, the die animation plays and the game object is destroyed. I want to have the script wait a certain amount of time and then run the destroy method. I thought using WaitForSeconds() would do the trick, and technically, it does, but the death animation continues to play until the object is destroyed. My question is, how do I get the animation to stop playing as the script waits to destroy the object? C void Die() GetComponent lt Animation gt ().CrossFade(die.name) If the current animation time is greater than 90 of the entire animation length, destroy the object. if(GetComponent lt Animation gt () die.name .time gt GetComponent lt Animation gt () die.name .length 0.9) StartCoroutine(RemoveBody()) IEnumerator RemoveBody() yield return new WaitForSeconds(5) Destroy(gameObject) |
0 | How can I fill the white color image to fill within that border in a shape of a glass? I'm using this in 2D canvas. Because I'm doing a health bar and it suppose to fill from the bottom to up but I don't know where to start from here. |
0 | In Unity3D, how do I create an efficient scratch card effect? I want to create a scratch card like effect in new Unity UI's new Image tag. I know it's possible with setPixels, but that's prohibitively expensive on mobile devices. Something like this I'd like the user to be able to drag on any part of the image to "scratch off" the top layer and reveal the content underneath it. How can I do this? |
0 | Raycast will not hit generated box colliders at initialization In my map class I have an algorithm that is generating and merging box colliders together. These belong to the layer "Ground". After that, in some places on my map I'm generating some new cubes on the fly, and some of these cubes I don't want to generate at all. So, I'm doing a raycast to determine if they should be added or not. I'm doing these raycasts to check if the position they should be generated at have free space to the left and right. For both rays I'm checking if they hit a collider beloning to the layer "Ground". But I don't get a hit at all! I've tried to create two cubes in the editor and assign them to the layer "Ground". If I run the game then I get a hit between these two cubes. But I will never get a hit checking against my generated colliders. I do this logic in the Start method, is there any certain method in the life cycle when I can start to use my generated box colliders? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.