_id
int64
0
49
text
stringlengths
71
4.19k
0
How to set the force applied to RigidBody2D depending on the time user holds touch on screen? I trying to make an object jump from 1 point to another point. How far it jumps depends on how long the player holds the touch anywhere on the screen. It jumps when player releases his touch. At the code below,I able to detect the moment player release his finger. if (Input.touchCount gt 0) Touch touch Input.GetTouch(0) Handle finger movements based on touch phase. switch (touch.phase) Finger start touching the screen case TouchPhase.Began print("Start tapping") break Finger leaving the screen case TouchPhase.Ended when finger release, the object jump float rightForce Time.deltaTime 10000 2 float jumpForce Time.deltaTime 30000 2 box2D.AddForce(new Vector2(rightForce, jumpForce), ForceMode2D.Force) break As you can see I able to get the Time.deltaTime which is I assume is how long the player hold the screen. What I want to do is calculate the rightForce and jumpForce added to the object depending on the Time user hold the touch. float rightForce Time.deltaTime 10000 2 float jumpForce Time.deltaTime 30000 2 Because if I use the 2 line of code above, the result will be almost the same everytime. So what is the correct way to determine the rightForce and jumpForce depending the time user hold touch?
0
How to calculate the reachable space of the end effector in an IK chain? I have an array of points in a 2d worldspace and I want to calculate which points are reachable by the end effector of a limb controlled with a CCDIK chain (with rotation limits applied). It's a limb with 2 hinges (upper arm amp lower arm) The upper amp lower arm have a fixed length The 2 hinges have fixed rotation limits This needs to be recalculated every update (continuously) as the limb is attached to a moving body I work in Unity using C Crude Illustration of the problem My idea sofar is to create a polygon collider along the outer edges of the reachable space, and then look if the points are within the bounds of that collider. But I have no idea if this is the smartest solution, or if so, how to achieve this. How could I solve this issue?
0
How can I toggle between single shots when clicking the mouse left button and automatic none stop shooting when clicking the mouse right button? I'm talking in build not in editor ! using System using System.Collections using System.Collections.Generic using UnityEngine public class Shooting MonoBehaviour SerializeField private Transform firePoints SerializeField private Rigidbody projectilePrefab SerializeField private float launchForce 700f SerializeField private Animator anim SerializeField private bool automaticFire false SerializeField private bool slowDownEffect false private void Start() anim.SetBool("Shooting", true) public void Update() if (isAnimationStatePlaying(anim, 0, "AIMING") true) if (Input.GetButtonDown("Fire1") automaticFire false ) automaticFire false if (anim.GetBool("Shooting") true) anim.Play("SHOOTING") LaunchProjectile() else if ( automaticFire true amp amp Input.GetButtonDown("Fire2")) automaticFire true if(automaticFire true) anim.Play("SHOOTING") LaunchProjectile() private void LaunchProjectile() foreach (var firePoint in firePoints) Rigidbody projectileInstance Instantiate( projectilePrefab, firePoint.position, firePoint.rotation) projectileInstance.AddForce(new Vector3(0, 0, 1) launchForce) projectileInstance.gameObject.AddComponent lt BulletDestruction gt ().Init() bool isAnimationStatePlaying(Animator anim, int animLayer, string stateName) if (anim.GetCurrentAnimatorStateInfo(animLayer).IsName(stateName)) return true else return false I tried to do it in the Update using the automaticFire variable but it's not working fine. When clicking first the left mouse button it's shooting singles but then when clicking the mouse right button it's shooting automatic but then when clicking the left mouse button again it's not back to single shots again it's staying on automatic. The idea is right click mouse button automatic fire left button each time clicking the left mouse button the automatic should stop and then single shots with the left mouse button. And this way to toggle between the Fire1 and Fire2. Fire1 left mouse button click Fire2 right mouse button.
0
blender imported sphere with mesh collider not collided here is the scene i imported a sphere (the blue sphere) from blender (with a hole at back), i added a mesh collider on it but it has no effect, and there is an error message Cooking cookConvexMesh user provided hull must have less than 256 vertices!. any ideas? (update the collider work fine after i retry and retry, but the error message still stay)
0
Images disappear when camera zooms in there is no problem when the camera is away, but as I zoom in to the game, the images disappear and I can't see the game properly. What is the reason ?
0
My Raycast2D doesn't go where I want and it doesn't return a GameObject I want my Objects to teleport when they hit a wall. For that, I want to shoot a Ray backwards and teleport it to where the ray hits the wall, but whatever I try, it always teleports to the centre of the scene and the ray hit doesn't return a GameObject. This version I tried runs on OnTriggerEnter2D RaycastHit2D hit Physics2D.Raycast(transform.position, transform.up, 300) Debug.DrawLine(transform.position, hit.point) transform.position hit.point I tried some other variations too. If you have any idea, please let me know.
0
Find random point on a circle with a radius of x and the players position as center (unity) First of all please note that the game is in 3d and Not 2d The image below is seen from above. What I am trying to do is find a random point 2 3 meters around the player. However I am not quite sure how to achieve it I have tried the following Vector3 randomPointOnCircle Random.insideUnitSphere randomPointOnCircle.Normalize() randomPointOnCircle radius return randomPointOnCircle However I am not sure how to set the player as the center? Star Player Square the general ground Circle A visual representation of where the points should be around the player
0
Unity Raw Image ui not showing when small I have some Images online that I download using WWW class and the use as UI elements. So far all of them where working perfectly but now the one I added recently is acting up. First you should know that all of the images are being downloaded by the same script and handled by that so there should be no difference between their materials and stuff AFAIK (if I'm missing something please tell me). Second , the problem is that this particular image only shows up when it's taking more than one sixth of the screen, for example if I make it bigger by changing it's size in the inspector, or if I go to scene view and zoom in on it, it starts to fade in the larger it gets on the screen. Also, I changed the picture to something that was working properly to make sure it's not from the image. public IEnumerator AddTools(Tool Tool) Texture2D T new Texture2D(4, 4, TextureFormat.DXT1, true) SpriteTool ST new SpriteTool() ST.TheTool new UnityEngine.Texture() ST.ID Tool.ID ST.ToolName Tool.Name ST.Type Tool.Type WWW wWw new WWW(Tool.Url) while (!wWw.isDone) yield return wWw.progress wWw.LoadImageIntoTexture(T) ST.TheTool T ST.TheTool.name Tool.Name SpriteTool PA ObjectTools.SingleOrDefault(p p.ID ST.ID) The SpriteTool Type is a class I made for storing some of the information needed to build the UI element later. private GameObject CreateButton(SpriteTool item null, float angle 0) Texture2D T2D (Texture2D)item.TheTool T2D.SetPixels(T2D.GetPixels(0, 0, T2D.width, T2D.height)) T2D.Apply() GameObject Tool new GameObject() Tool.transform.SetParent(GUICanvas.transform) There was some code for positioning the element and resizing it that I did not include but I can see in the scene view that the size and the position are what they supposed to be so that's not the problem Tool.AddComponent() The type is RawImage Tool.GetComponent().texture T2D the type is RawImage
0
Weird texture applied So I applied the baked texture (on the right side of screen shot) but it shows in this manner. What is the problem? I made the model in Blender and also the baked image. The house consists of multiple separate objects.
0
How to iterate through the frames of an AnimationClip in editor mode I'm working on a 2D game, using spritesheets as the basis for four AnimationClips. (Every frame from the spritesheet is a keyframe in the animation.) I'm trying to step through the frames of these AnimationClips and programmatically create Collider2Ds which fit the dimensions of each frame. The problem is, I'm having an impossible time actually iterating through the frames. My character has an Animator component, with 4 different states. I've tried various inputs to my editor script, but the closest I've gotten has an AnimationClip as input private AnimationClip clip set in inspector private GameObject targetForColliders set in inspector void createColliders() Animation animation new Animation() AnimationUtility.SetAnimationClips(animation, new AnimationClip clip ) foreach (AnimationState state in animation) do useful things here Unfortunately, somehow the animation local variable is null, crazy as that sounds. I've confirmed that by both logging it and attempting to use it, which causes a NullReferenceException every time. I can't access the Sprite containing the spritesheet directly, because I've made manual adjustments within Unity to the keyframes (removing some, duplicating others) and I don't want to have to manually sync my colliders with the modified assets. Has anyone attempted to do something similar to this before? tl dr What's the easiest way to iterate through the frames of a 2D animation in an editor script?
0
Understanding Scriptable Objects I am trying to understand the logic and functionality behind Scriptable Objects. I 've watched the provided video 2 times and I keep getting lost. I tried to follow the code as well but with no luck. Can someone please explain to me what the Scriptable Objects are and how they work in a few lines? EDIT This Video as well as the following answers helped me understand Scriptable Objects and even better incorporate them in my own game.
0
Unity When attaching my custom camera script camera shakes when player starts to move fast Here is my player code. Rigidbody rb Vector3 currMovement public float jumpSpeed 10 public float moveSpeed 10 public float rotSpeed 180 float distToGround public float posSmoothTime 0.5f float currPos float targetPos float posVel public float rotSmoothTime 0.5f float currRot float targetRot float rotVel void Start() rb GetComponent lt Rigidbody gt () distToGround GetComponent lt Collider gt ().bounds.extents.y bool isGrounded() return Physics.Raycast(transform.position, Vector3.down, distToGround 0.1f) void Update() Move() void Move() Rotation smoothing. targetRot Input.GetAxisRaw("Horizontal") rotSpeed Time.smoothDeltaTime if (targetRot gt 360) targetRot 360 if (targetRot lt 0) targetRot 360 currRot Mathf.SmoothDampAngle(currRot, targetRot, ref rotVel, rotSmoothTime Time.smoothDeltaTime) transform.eulerAngles new Vector3(0, currRot, 0) Movement smoothing. targetPos Input.GetAxisRaw("Vertical") moveSpeed currPos Mathf.SmoothDamp(currPos, targetPos, ref posVel, posSmoothTime Time.smoothDeltaTime) currMovement new Vector3(0, 0, currPos) currMovement transform.rotation currMovement if (isGrounded()) if (Input.GetButtonDown("Jump")) rb.velocity Vector3.up jumpSpeed rb.position currMovement Time.smoothDeltaTime I have a Rigidbody attached to my player. I think the problem is with my camera script. Here is my camera script. public Transform player Quaternion targetLook Vector3 targetMove public float smoothLook 0.5f public float smoothMove 0.5f public float distFromPlayer 5, heightFromPlayer 3 Vector3 moveVel void LateUpdate() CameraMove() void CameraMove() targetMove player.position (player.rotation new Vector3(0, heightFromPlayer, distFromPlayer)) transform.position Vector3.SmoothDamp(transform.position, targetMove, ref moveVel, smoothMove) targetLook Quaternion.LookRotation(player.position transform.position) transform.rotation Quaternion.Slerp(transform.rotation, targetLook, smoothLook) The player is not an parent of my camera. When I parent the player to my camera the shake stops. But I want a custom smooth camera movement with my custom scirpt, so I can't make the player a parent of the camera.
0
Overridden movement function doesn't work I moved from C to C so I am a novice in Object Oriented Programming. I wanted to implement OOP in my character movement, but it didn't work the way I expected. My character is instantiated when the scene starts, but it doesn't move (maybe because of bad parameter passing). I just want to control input from derived class which is giving my character the ability to sprint. characterB script is attached to character in Inspector that character is instantiated prefab and is instantiated when scene start inherited script which is overridden is giving ability to sprint to character photon is package for multiplayer games so you don't have to notice it whole source code is so big, so i put there one method for movement and sorry for my weak english skillz works like standard MonoBehaviour public abstract class characterMain MonoBehaviourPunCallbacks declaration of variables public virtual void Start() RB GetComponent lt Rigidbody gt () protected virtual void movement(float horXF, float vertYF, bool sprintB) Debug.Log( quot movement function base class quot horF) NOT responding groundDetect Physics.Raycast(...) if (standOnGround) direction new Vector3(horXF, 0, vertYF) Time.deltaTime speed direction.Normalize() adjustSpeed speed targetSpeed transform.TransformDirection(direction) adjustSpeed Time.deltaTime RB.velocity targetSpeed public class characterB characterMain Header( quot Movement quot ) protected float horXF protected float vertYF Header( quot sprint quot ) private bool sprintB public void FixedUpdate() if (!photonView.IsMine) return Photon MOVEMENT INPUT horXF Input.GetAxisRaw( quot Horizontal quot ) vertYF Input.GetAxisRaw( quot Vertical quot ) JUMP INPUT skokB Input.GetKey(KeyCode.Space) movement(horXF, vertYF, sprintB) Debug.Log( quot movement function quot horF) responding protected override void movement(float horXF,float vertYF,bool sprintB) Debug.Log( quot movement function quot horF) NOT responding if (sprintB amp amp ... ) sprint base.movement(horXF, vertYF, sprintB) sprintB bZrychlenieC amp amp groundDetect amp amp ... if (sprintB) direction new Vector3(0, 0, sprintSpeed) Time.deltaTime
0
Make Unity GUI for mobile phones only? I'm using Unity and I want to make a responsive GUI for portrait resolution only. Now I'd like to know if this is a good or bad idea when I force the user to play my game in portrait mode only. Shall I use autorotate? The problem is that when you use landscape mode my GUI looks really shitty. I have some background images and I'd like to know if I should save them for the highest resolution available in mobile devices (like tablets)? Or shall I ditch the tablets and develop the GUI with the background images for mobile phones only? TIA
0
Is it possible to prevent the collider 2D outline from hiding in Unity? Is it possible to prevent the collider 2D outline from hiding in Unity? I am creating some animations in Unity. To create animations I select different parts of a hero and move them frame by frame. Now I am working on the run animation and would like to see the bottom collider during parts movement for the animation creation. In my case the collider outline is red I don't want the red bottom line (which is the collider outline) to disappear while I am creating animations. Should I research the Unity extensions and maybe write my own which would prevent the collider from hiding or is it possible to achieve what I want out of the box somehow?
0
Line renderer in 3D sorting order I'm using a line renderer as a laser aim for my character. If the aim hits an object it ends at that object. If the aim doesn't hit an object it continues a predefined distance. If I aim at an object it works fine, if I stand behind the object it also works, but if I stand in front of it, the line is rendered behind the object creating the illussion that the character stands behind the object. If I change the sorting order for the line I can make it to be in front of the object, but this is a bit tedious because then it will be in front of this object when it is in fact behind it. In the screenshot below a line is drawn from the picked up C4 which is in front of the pillar, but the line is drawn behind the pillar. Is there any way to solve this issue with a line renderer? I've been thinking of just using a cube and stretch it instead. Thanks in advance! Update 1 I made a cube solution instead, but soon realized that the issue is with a shader that is set to fade transparent and that this is due to sorting order. How can I dynamically change the sorting order in code so that my moving transparent object always appear in the correct place? Update 2 I noticed that my own answer below isn't working 100 . It works for most scenarios but if I'm standing at origo and aiming behind a pillar the sight is rendered in front of the pillar. In the image below it is clearly visible from the top view that I'm aiming behind the pillar. (This is done with a deformed cube, the line renderer had even more issues).
0
Unity 5.5 and Parse 1.7.0 on iOS 64 bit We are using Unity 5.5 and Parse 1.7.0 (and Firebase for notifications) which doesn't have "Parse.Unity.dll" and while on Editor everything is working fine but when we build using "IL2CPP" on iOS while running on device the game produces an error of "MissingMethodException No constructor found for Parse.Common.Internal.FlexibleListWrapper 2". I think it's because of stripping, I've tried to include "Parse.Core" and "Parse.Common" in "link.xml" but still same error while I was looking for solutions I found that there's a file "Parse.Unity.dll" that should have been in the project from the start but when I try to include it in our project another error but this time in Unity Editor that says "System.Threading.Tasks.Task is defined multiple times" and that's because I think the new Parse.Unity.dll and Unity.Task.dll from Firebase, if I try to delete that firebase Dll another error appears.... Please any help is appreciated ( We have to build with il2cpp to upload on the App store, Android version works fine.
0
How to FindGameObjectsWithTag then cast the array of GameObjects to an Array of Interfaces I have a few GameObjects that implement a common Interface IsTree. I need to call the function doTreeThing() on each of those IsTrees after getting a reference to each of them via FindGameObjectsWithTag("tree"). This line complains that it cannot implicitly convert from GameObject to IsTree IsTree trees GameObject.FindGameObjectsWithTag("tree") So then I tried to leave the GameObject an iterate over it to convert each individual object inside to an IsTree. GameObject trees GameObject.FindGameObjectsWithTag("tree") foreach (GameObject tree in trees) IsTree isTree (IsTree)tree isTree.doTreeThing() But this complains that it also cannot convert GameObject to IsTree. Then I got a little desperate and tried to make my IsTree into a GameObject. public class IsTree GameObject public System.DateTime getAge() return null GameObject is a sealed type. (I don't really know what that means besides that this does not work) So how do I get this array of GameObjects into an array of SomeInterface?
0
Why does AudioSource not initializes itself? Why does AudioSource not initializes itself? Here is my code using System using System.Collections using System.Collections.Generic using UnityEngine public class CameraConfig MonoBehaviour public GameObject objToFollow public bool followRabbit Use this for initialization void Start() followRabbit true LevelController.current.cameraWhichLooksForRabbit this setMusicSource() setSoundSources() public AudioClip music, rabbitWalksSound, rabbitDiesSound, rabbitFallsSound, enemyAttacksSound private AudioSource musicSrc, rabbitWalksSrc, rabbitDiesSrc, rabbitFallsSrc, enemyAttacksSrc private void setMusicSource() setClipForSrc(musicSrc, music, true) private void setSoundSources() setClipForSrc(rabbitWalksSrc, rabbitWalksSound, false) setClipForSrc(rabbitDiesSrc, rabbitDiesSound, false) setClipForSrc(rabbitFallsSrc, rabbitFallsSound, false) setClipForSrc(enemyAttacksSrc, enemyAttacksSound, false) private void setClipForSrc(AudioSource src, AudioClip clip, bool loop) src gameObject.AddComponent lt AudioSource gt () src.clip clip src.loop loop void Update() checkMusicAndStopOrStartIfNecessary() if (!followRabbit) return Transform rabit transform objToFollow.transform Transform camera transform this.transform Vector3 rabit position rabit transform.position Vector3 camera position camera transform.position camera position.x rabit position.x camera position.y rabit position.y camera transform.position camera position public void playSoundRabbitWalks() if (!rabbitWalksSrc.isPlaying) rabbitWalksSrc.Play() public void playSoundRabbitDies() rabbitDiesSrc.Play() public void playSoundRabbitFalls() rabbitFallsSrc.Play() public void playSoundEnemyAttacks() enemyAttacksSrc.Play() public void stopSoundRabbitWalks() if (rabbitWalksSrc.isPlaying) rabbitWalksSrc.Stop() public void stopSoundRabbitDies() rabbitDiesSrc.Stop() public void stopSoundRabbitFalls() rabbitFallsSrc.Stop() public void stopSoundEnemyAttacks() enemyAttacksSrc.Stop() private void checkMusicAndStopOrStartIfNecessary() if (SoundManager.Instance.isMusicOn() amp amp !musicSrc.isPlaying) musicSrc.Play() else if(!SoundManager.Instance.isMusicOn() amp amp musicSrc.isPlaying) musicSrc.Stop() Here are screenshot of the exceptions in console and inspector view
0
How to make animation in unity Dots hybrid? I'm working on isometric game in 2D but didn't find any good tutorial in how to handle animation...any help?
0
How to keep player rotated toward a sphere when within a certain radius? In my game the player can fly to multiple spheres, I want to make it so that when the player gets within a certain distance of the sphere, (maybe using a bigger is trigger sphere collider around it?) their feet will stay pointing towards the sphere until they leave the radius, (maybe using a quaternion?) then if they get within the radius of a different sphere, their feet will point towards that too. How can I make this work? I don't know too much about c , so any example code would help a lot too!
0
How to return the scene view camera to the default view By the quot scene view camera quot I don't mean a GameObject with a Camera component, I mean the camera used to draw the Scene window in the Unity editor, controlled by this quot Scene Gizmo quot widget The default view shows an almost isometric perspective, where all three X Y Z axes are visible. But when I clicked the green Y cone, my view changed to look straight down the Y axis, and I can't seem to return to the 3 axis view. Clicking the other cones on this widget just switchest to look along the X or Z axis instead, and clicking the cube in the middle or the quot Top quot label just toggles between orthographic and perspective projection. How can I get back to the default 3 axis view?
0
How to play sound in WebGL build in Unity? I have a project that works fine when I build for windows, but doesn't work when I switch platform to WebGL. The SerializeField AudioClip variables in the inspector are all 'missing', even after I check 'override for WebGL' convert to AAC. And when I try to link any audio file to an AudioClip within a WebGL build in the inspector, it doesn't seem to work. How do I get sound to play within WebGL? To recreate the problem Switch platform to WebGL. Create a new Script in any recent unity version, then add a SerializeField AudioClip x. Put that script on a new gameobject and try to link an audio asset to it (default import settings, however don't forget to check 'override for WebGL' to AAC, otherwise you will get compiler errors when you switch platform).
0
Creating a Nations Stockpile If I created different XML files for each Nations' Stockpiles and made an XMLmanager to do updates such as resource consumption and trade, wouldn't that be too much resource intensive? I mean, if I had to access each Nations' stockpiles every tick and update them (Quantity, Price, Quality). Is there any other faster way to manage all those updates? From the back and forth in the comments, I've came up with this approach. public class Nation public string NationName public int Population public void NationCreator(string name, int pop) NationName name Population pop public class Stockpile public int food public int water public int wood Then methods to work with that stockpile However, after some thinking and reading, my next approach to this problem will be Arrays but I only know how to make an array of one particular type like double balance 2340.0, 4523.69, 3421.0 How could I do an array like this (Lua style array) in C language? raw material cotton Value 17.50
0
Reading a word list into an array I am making a simple hangman game, I have a small list of words in a .txt file separated by new lines. I put the word list into the assets folder. How can I find the path to the word list so I can use string wordlist System.IO.File.ReadAllLines("pathToFile") Or is there another solution of converting the word list into a string array?
0
Unity 3D Imported Assets Rotated Backwards in game I'm putting together boilerplate for a Unity FPS game, and having an issue with importing an Asset Store model. All of my weapons are asset store prefabs. I'm new to Unity, but this makes me think there's something about the imported prefabs themselves that's setting the axis alignment of the models in game. Anyone know what I'm missing to fix this and rotate that model in the world (without just writing a model script to rotate it programmatically every time) ?
0
How to programmatically disable sprite renderer and mesh renderer in Unity3D? In my game, I have an empty GameObject that has a sprite and a TextMesh as child. I want to access the child (sprite and the text mesh) and turn off the sprite renderer and mesh renderer of the sprite and the text mesh programmatically and be able to then turn it back on, but I don't know how. Some help and or sample code would be much appreciated. Thanks.
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
Which for basic RTS prototype Unity or Torque? I'm wanting to test my hand at writing an RTS (something I've never gotten very far with), and so I'm looking for an indie engine that would give me the most success with a quick setup that I can then tweak and start to get the ins and outs of RTS design development. I've had a bit of familiarity with both Torque and Unity both, but never from that perspective. Which would get me closer to base prototype faster?
0
How to draw grass sprites without using gameobjects? I am making a rimworld like procedurally generated 2D game using Unity's tilemap system. Just like tiles, I also have to procedurally generate grass and trees. Each grass instance should have logic inside that keeps track of it's growth progress and update the grass size appropriately. The downside is, I have to have maps as big as 400x400. That could be THOUSANDS of grass instances and each of them having their own GameObject seems ridiculous and like the game would lag. How can instantiate those grass sprites without creating new gameobjects for each one while still being able to control the growth and similar things? (Come to think of it, the DOTS ECS system in Unity would be perfect for this, however it is nowhere near ready and many things I want to do are just not supported.)
0
error CS1069 The type name 'ZipArchive' could not be found in the namespace 'System.IO.Compression' When I build my project, which references the System.IO.Compression namespace, the build succeeds without issue inside Visual Studio. However, inside the Unity editor, I see the following error error CS1069 The type name 'ZipArchive' could not be found in the namespace 'System.IO.Compression'. This type has been forwarded to assembly 'System.IO.Compression, Version 4.0.0.0, Culture neutral, PublicKeyToken b77a5c561934e089' Consider adding a reference to that assembly. I added a csc.rsp file inside my Assets folder, with the following line r System.IO.Compression.FileSystem.dll Unfortunately, that did not resolve the issue. Here are the properties of the System.IO.Compression DLL that I reference inside Visual Studio How can I fix this error?
0
How can I reduce the size of bundled Unity DLLs on Android? I have created a simple project (I am a Unity beginner) for Android but the apk size is around 18 MB! I checked the documentation. One way to decrease the apk size is to check the editor log. Then I discovered that imported DLLs have a size of 3.9MB. I only used UnityEngine and Collision packages. So how can I avoid to import the other big DLLs?
0
How to program an attack that I control with the arrow keys? I'm making a 2D game prototype in Unity and I want to have the player attack be a sword that hovers around the player with its direction being fixed to the direction you indicate with the arrow keys. So if the sword is in the upward position and you press the left button, you can see the arc it takes and an enemy in the way of that arc takes damage. The game is not a platformer. It's on a flat surface. edit I want to know how to have the sword hover in a radius to the player and point the direction i press the arrow keys. I want to get the action of moving the sword to these positions to do damage to an enemy. But if the sword is in a upwards position and the player presses down, I want it to do an action that attacks the whole radius around the player, on a cooldown. How would I go about programming this? I'm new to programming so I would greatly appreciate some helpful pointers. Edit2 So this is how far I have gotten public class SwordSwing MonoBehaviour public Transform swordHolder Update is called once per frame void Update () if (Input.GetKeyDown(KeyCode.LeftArrow)) swordHolder.transform.Rotate(0, 0, 90) if (Input.GetKeyDown(KeyCode.RightArrow)) swordHolder.transform.Rotate(0, 0, 90) if (Input.GetKeyDown(KeyCode.UpArrow)) swordHolder.transform.Rotate(0, 0, 90) if (Input.GetKeyDown(KeyCode.DownArrow)) swordHolder.transform.Rotate(0, 0, 90) I don't know if this is right, because when I use the arrow keys it just turns the sword 90 degrees and not to the specified position I want it to move to. So Candid Moon said that I have to use Mathf.Lerp() and StartCoroutine() but I have no idea how to use them. I'm not really sure how to animate this either, I have done some animations in Unity but have a hard time implementing them into anything. The hierarchy is now Player SwordHolder Sword Now I also have this script if (GetComponent lt Rigidbody2D gt ().velocity.x gt 0) transform.localScale new Vector3(1f, 1f, 1f) else if (GetComponent lt Rigidbody2D gt ().velocity.x lt 0) transform.localScale new Vector3( 1f,1f,1f) That flips the player sprite when i move left. This also flips the sword, I don't really want this. How do I stop it? Let me know if there is anything I missed, I'm trying to learn.
0
High quality graphics but low apk size How? So I have been playing this app that has so many high quality graphics with some 3d models and tons of levels and it is only 70mb in size.My app that has only 2 pictures is about 20 mb in size lol..Why?
0
How to render a grid of dots being exactly 1x1 pixel wide using a shader? I would like to render a grid with many dots, all equally spaced and being exactly 1 pixel wide. What I was able to achieve so far is this What I would like is (simulated using image editing program) Here is the shader I wrote (which give result of 1st image). This is rendered as a giant quad. Shader quot Custom Grid quot SubShader Pass CGPROGRAM pragma vertex vert pragma fragment frag include quot UnityCG.cginc quot struct vertInput float4 pos POSITION float4 uv TEXCOORD1 struct vertOutput float4 pos SV POSITION float4 uv TEXCOORD0 vertOutput vert (vertInput input) vertOutput o o.pos mul(UNITY MATRIX MVP, input.pos) o.uv input.uv return o fixed4 frag (vertOutput output) SV Target float4 uv output.uv float x step((uv.x 100.0 0.025) 1.0, 0.05) float y step((uv.y 100.0 0.025) 1.0, 0.05) float c min(x, y) return float4(c, c, c, 1.0) ENDCG Is it possible to achieve what I want using a shader ? What is needed from first draft is to control the size of each dot. I have tried to use partial derivatives (ddx and ddy) but was not able to make it work.
0
Why would a property be returning null? I'm working on learning how pass data from one script to the other in Unity and I'm getting a little confused. I have two scripts, PlayerData and CreateCharacter. PlayerData is used to pass persistent data from one scene to another, so it's not going to be attached to any GameObject or Transform. CreateCharacter, however, is attached to a button which gets the information from user input. Here are the two scripts PlayerData public class PlayerData private string playerName public string PlayerName get return playerName set playerName value CreateCharacter public class CreateCharacter MonoBehaviour public InputField playerName public PlayerData playerData new PlayerData() public void AddStats() public void SubtractStats() public void CreateCharacterOnClick() playerData.PlayerName playerName.text Debug.Log(playerData.PlayerName) What's happening is, when I click the button I'm getting a null reference error on playerData.PlayerName but if I just log playerData I actually get the object to return. What I'm trying to see is that the character name(playerName) is logged when the button is clicked. Can anyone explain to me what I'm doing wrong and how to fix it?
0
What are the steps to instantiate a button in Unity? Given a Canvas test canvas containing a Button test button and an empty GameObject that manages instantiation and scripts and the like called test manager, what are the steps to instantiate this button through code as opposed to having it already there? I've tried making the button a prefab and instantiating it as I would any other object but that didn't work. I tried making the canvas a prefab and then trying the button but nothing. I've searched around for quite some time and there's mention of RectTransform and SetParent but steps or specific details would clear up my confusion
0
In Unity, Meta Files are Tracked but Behaviours Fall Off My team is working on a Unity game, and we are using a mercurial repository on BitBucket. Whenever we update, all of the behaviours 'fall off' of state machines, behaviours, etc. When searching for a solution, I discovered that this information was stored in the meta files. I had previously ignored the meta files, but the are now being tracked. However, the files still 'fall off'. I cannot find any other reason this would be happening. Any assistance you can give me would be appriciated. Let me know if you need any additional details.
0
Why do I seem to lose control of my computer when full screen Unity game loses focus? When I press Ctrl Alt Esc or Ctrl Shift Esc the game loses focus, but then the whole PC is unusable and I need to restart the PC to regain control How do I prevent the computer from locking up (let the player control their PC) when a full screen Unity game loses focus?
0
2D physics without "rebound" I'm trying to get my 2D top down shooter to use some physics. I want the player and enemies not be able to exist in the same position, in other words, use collisions. My first attempt was to use a CharacterController, but I could not get my other game objects to collide with my player, even though I had a RigidBody2D and a BoxCollider2D on them. Obviously, due to using a CharacterController, I was not able to add these components on my player. Going one step back, I removed the CharacterController, and rather opted to go the Rigidbody2D route. This worked partially. I now get collisions on my player when he walks into other gameobjects (with RB2D and BC2D on them), but there seems to be a quot rebound quot anomaly occurring my player moves around after collision. I've tried playing around with the settings on the RigidBody2D on the player, but it does not seem to have any effect. This is my PlayerMovement script void Update() HandleRotation() HandleMovement() void HandleRotation() var mousePos Input.mousePosition mousePos.z 5.23f var objectPos Camera.main.WorldToScreenPoint(transform.position) mousePos.x objectPos.x mousePos.y objectPos.y float angle Mathf.Atan2(mousePos.y, mousePos.x) Mathf.Rad2Deg transform.rotation Quaternion.Euler(new Vector3(0, 0, angle)) void HandleMovement() float horizontal Input.GetAxisRaw(Constants.Axis.Horizontal) float vertical Input.GetAxisRaw(Constants.Axis.Vertical) Vector3 direction new Vector3(horizontal, vertical, 0f).normalized if (direction.magnitude gt 0.1f) var speed (Input.GetKey(KeyCode.LeftShift) Input.GetKey(KeyCode.RightShift)) ? mobileController.runningSpeed mobileController.walkingSpeed var moveVector (direction speed) transform.position mobileController.rigidbody2d.MovePosition(moveVector) var camPosition new Vector3(mobileController.transform.position.x, mobileController.transform.position.y, 10) cam.position camPosition The settings on my Player I would like my player to stop dead in his tracks when colliding with another RigidBody2D. Is this possible? And if so, how would I go about doing that?
0
Can a generic class inherit from MonoBehaviour? Expanding upon a previous tutorial, I am adapting a follow script to support multiple variations of a Bezier spline. Each spline variation uses a custom interface called IBezierInterface, and the follow script accesses the method GetPointOnCurve() to determine the correct position. In theory, this all seems very simple. However, I appear to be running in to some trouble. While I intend to pursue the general issues a bit more, myself, I realise that I may be shooting myself in the foot with the generic implementation. While I can find a lot of good examples demonstrating the correct use of generic types, I can not find anything that gives an example of a generic class that inherits from another class. For example, Microsoft documentation includes examples of inheritance as a restriction on the actual type, and an example of inheriting from a generic class but there are no examples of a generic class that inherits from a standard class. Unity documentation has even less examples, but none pertaining to my query. I am not getting errors but that is no guarantee against error. I can not conceive a good prototype model to test my theory, either, given the fact that I am fairly new to the concept of generic types. Given that I am specifically needing my class to be a MonoBehaviour can I make a custom generic class that inherits from MonoBehaviour, such as in my example? public class SplineWalker lt T gt MonoBehaviour where T IBezierInterface ...
0
Maya Single Model with different animation I am newbie in Maya and would like to clarify some implementations in Animation. I know how to create simple animations in Maya. These animations are exported to Unity3D (as .fbx with controllers) to use in my application. I want to know whether it's possible to attach different animations to one model. For example, let's say, I have an arrow mark model and I want to show different animations for the model like moving left, moving right, moving up, moving down, etc. So that, when I export, I'll get one model Arrow.fbx and different controllers LeftAnimController, RightAnimController, etc. Is that achievable? Or I need to create different Arrow mark model with it's own controllers. Any help will be appreciated. Thank you.
0
How to move an object while the animation is going on? I added a jump animation with the character in unity and to move the character I have some code like this if (Input.GetKeyDown(KeyCode.Space)) transform.Translate(Vector3.forward 1 jumpSpeed) Anim.SetTrigger("is jumping") But here the character first moving its position (like a glitch) and then doing the animation. How can I make them happen at the same time?
0
NavMeshAgent in Unity giving jerky performance I am using NavMeshAgent in my Unity project to calculate and move my object to a particular location. When I do navMeshAgent.destination destinationPt the object starts moving, but the motion of the object is very jerky. Is there a way to override the function which is responsible for the jerkiness of the object motion? Or is there a way I can remove the jerkiness of the motion some other way? I also tried setting navMeshAgent.updatePosition false after which I use navMeshAgent.CalculatePath(destinationPt, path) to get the path, but then after this I am not able to figure out how to write my own logic to make the object move. I want a smooth motion with a given acceleration and a max velocity.
0
What is the purpose of the Allocation Callstacks button in Unity's Profile window? I have an idea of what this button does, but I cannot find any specific information in the documentation. What information does this button add to the profiling data? How can I see this extra information?
0
Detecting which side of the collider is hit We are trying to determine which side of the collider is hit in order to let the colliding object pass through or land on the other object. Our previous failed attempts included detecting object velocity and changes on Y axis in our 3D game with locked Z axis (simulated 2D). Currently, the detection is working by calculating the velocity when the "Object in motion" hits the top of the black cube ("trigger collider") by the certain level of velocity (determined by gravity) the "collider" is activated. Otherwise, when the velocity is higher the "object in motion" passes through. This, of course introduced a lot of issues and the solution itself is not elegant. In the other scenario, we have tried adding trigger colliders around the "static object". This also complicates the process when "object in motion" has an arc when landing. Likewise, this solution is hard to maintain and prone to bugs. On top of that, we implemented Raycasting. But we are not getting consistant "Top" and "Bottom" trigger indications when using it. Here is the gist of that code. void OnCollisionEnter(Collision collision) if (collision.gameObject.tag.Equals("my cube")) var hit HitDirection() Debug.Log(hit) bool IsRightOrLeftHit() RaycastHit hit Ray rayUp new Ray(transform.position, Vector3.up) Ray rayDown new Ray(transform.position, Vector3.down) Physics.Raycast(rayUp, out hit) Physics.Raycast(rayDown, out hit) return hit We would appreciate any hint or help, and please ask me any questions if the explanations are not clear enough.
0
Accessing a database with a php script from Unity mobile game So I am attempting to keep track of some user data in my game that I am creating in Unity 3d. I am using Unity's WWW class to do this. I am following this tutorial http wiki.unity3d.com index.php?title Server Side Highscores I am not sure why but I keep getting a 404 error even though the file is on the server. I am using godaddy to host my website and I have the php script that I am trying to access in there so that it can use it to query the database. I am using "http www.mysite myscript.php?" followed by the values that I want to push to the database, as the tutorial shows to do. No matter what I do I end up with a 404 and it doesn't make any sense as I know that it is there in the path I am attempting to connect to. If I type out the path to the php file in a browser it will take me to a page that gives an error about the hash not existing (since I am not passing one unless it is in my game) so I know that the file is there. 3 18 16 Here is my php script to add the values to the database. lt ?php server "MyServersIP" user "MyUser" pass "MyPassword" db "MyDB" conn mysql connect( server, user, pass) mysql select db( db) Username mysql real escape string( GET 'Username' , db) Fuel mysql real escape string( GET 'Fuel' , db) IAPCar1 mysql real escape string( GET 'IAPCar1' , db) IAPCar2 mysql real escape string( GET 'IAPCar2' , db) Score mysql real escape string( GET 'Score' , db) Level mysql real escape string( GET 'Level' , db) Wins mysql real escape string( GET 'Wins' , db) Losses mysql real escape string( GET 'Losses' , db) Ads mysql real escape string( GET 'Ads' , db) LicensePlate mysql real escape string( GET 'LicensePlate' , db) hash GET 'hash' secretKey "mySecretKey" real hash md5( Username . Fuel . IAPCar1 . IAPCar2 . Score . Level . Wins . Losses . Ads . LicensePlate . hash) if ( real hash hash) query "INSERT INTO Player values (NULL, ' Username', ' Fuel', ' IAPCar1', ' IAPCar2', ' Score', ' Level', ' Wins', ' Losses', ' Ads', ' LicensePlate') " result mysql query( query) mysql close( conn) ? gt Here is the code I use to call the php script public string setValues "http www.mysite.com Set Values.php?" private string secretKey "SecretKeyFromThePhpScript" public void SetValues(string username, int fuel, bool iapCar1, bool iapCar2, int score, int level, int wins, int losses, bool ads, string licensePlate, bool firstTime) string hash Md5Sum(string.Format(" 0 1 2 3 4 5 6 7 8 9 ", username, fuel, iapCar1, iapCar2, score, level, wins, losses, ads, licensePlate, secretKey)) string url string.Format(" 0 username 1 amp fuel 2 amp IAPCar1 3 amp IAPCar2 4 amp Score 5 amp Level 6 " " amp Wins 7 amp Losses 8 amp Ads 9 amp LicensePlate 10 amp FirstTime 11 amp hash 12 ", setValues, username, fuel, iapCar1, iapCar2, score, level, wins, losses, ads, licensePlate, firstTime, secretKey) WWW www new WWW(url)
0
Character axis gets messed up when I add the armature into it So basically Ive been working on a walking animation in Blender, but theres a problem when I import it to Unity, the axis get inverted The only thing that is messing it up is the armature that animates the character, if I only import the character itself the axis are normal, if I also import the armature, the axis get inverted...
0
How can i put a skybox on a new layer with a new camera and then move the skybox? I want to create a moving start effect. For example the space station is moving around the star or moving to the star. But instead moving the space station i think it will be better to make effect of the skybox moving. I have in the Hierarchy a RigiBbodyFPSController and a child MainCamera. Now i added a new Camera to the Hierarchy. Now how do i make the rest ? Moving the new camera and the skybox to new layer and move the skybox ? Or it's more logic to say to move the new camera that the skybox is with in it in the new layer. Not sure if my idea is logic or if there are a better ways to do it. The general idea is to make movement effect like the space station is moving around the star or to the star. Star i mean the skybox. The skybox is on the right. I can't see the skybox in the scene view i see it only when running the game in the game view. This is a screenshot when the game is running then i can see the skybox in scene view and game view
0
CharacterController rotation with mouse I'm trying to rotate my characterController around with the mouse movement. I've tried to do so with this rotLeftRight Input.GetAxis("Mouse X") MOUSESENSIVITY Time.deltaTime rotUpDown Input.GetAxis("Mouse Y") MOUSESENSIVITY Time.deltaTime It works fine when I just move the mouse, but Input.getAxis returns 0 if you don't move the mouse, even if it's already on a corner of the screen. Is this normal? What I need is something that returns 0 only when the mouse is in the center of the screen. I don't know if that is posible using Input.GetAxis or I should use another function. Anybody can help me with this?
0
Why can't I rotate anything to be "more than 360 degrees or less than 0 degrees"? I've been trying to make an animation in Unity, but most assets already come bundled with everything facing at 0 degrees, not to say it's a bad thing. However, the problem I'm facing is that the animation keyframes aren't playing out correctly. When this is done with raw measurements (simply dragging the XYZ rotations), negative and greater than 360 degree angles are taken account. But then again Unity could be simply remapping them, whcih is not the case. For example, the prop robotArm prefab, found within Unity's Robot Factory asset pack has a rotator script that simply rotates the whole thing along the Y axis. void OnFixedUpdate() transform.Rotate (new Vector3(0, rotateSpeed Time.deltaTime,0)) Meaning that after slightly more than a full revolution, the Y rotation value should be more than 360 degrees, which it does end up becoming... Eventually. Thinking that was possible, I tried to mimic this behavior by making the arm rotate 720 degrees (twice) in an animation file (this is not using the rotator.cs script attached to the body in the example above). Instead, all I ended up was the arm's body staying still as 720 is the same as... 0 degrees in rotation changes. So, I tried a second experiment trying to rotate from 359 degrees to 1 degree (or 1 to 1 degree). Just like above, it didn't go to plan. When the animation is run, it simply runs from 359, through every angle in between before reaching 1, instead of 359, 360 (0) and 361 (1). If you don't get what I mean, see the diagram below. So, I was wondering, is there a way to allow for such rotation to be defined in an animation curve? Every time I try doing it, any value greater than 360 (or lesser than 0) is replaced by its co terminal counterpart that's between 0 and 359.999999...999.
0
How do I create a Button when I click another Button? I need help. When I click a Button, I want to create a new Button. My code, however, creates four Buttons. What should I do? using UnityEngine using System.Collections using UnityEngine.UI using System.Collections.Generic public class AddButton MonoBehaviour public GameObject prefabButton public RectTransform ParentPanel public Button saveButton void Update() if (Input.GetMouseButton(0)) for (int i 0 i lt 2 i ) GameObject button (GameObject)Instantiate(prefabButton) as GameObject button.transform.SetParent(ParentPanel, false) button.transform.localScale new Vector3(1, 1, 1)
0
Mute Unmute Sound For All Game Scenes by pressing Button My Question is simple i just want to Mute Pause All Sound of the Game having different scenes. From Scene 1 Which is a Main Menu I Have Two Button On Off . When i press On Button it stops or mute full game sound or music like Car sound etc in all Scenes. When i press off button then Sound become active again in all scenes .. I'm new in this field so please give me some help My Game is almost Complete But i can not Control or Mute All scene Sound at the same time..Waiting
0
How to activate Xbox controller vibrations in Unity? Is there any way to toggle the XBOX controller vibrations in Unity ? I came across Handheld.Vibrate() but it seems like it's not meant for controllers.
0
How do I convert a vector into a distance? I'm doing a 2D raycast where i have to pass distance. The scenario is this I'm using rigidbody2d.Moveposition to move my character instantly. However, before a character is moved, i want to do a raycast in that direction. My Movement code is if (Input.GetKeyDown (KeyCode.D)) rigidbody2D.MovePosition(rigidbody2D.position speedx) return where speedx is Vector2 Vector2(1,0) (can be increased as necessary). So when A is down, first i want to do a raycast to see if it hits any collider and then move or not move the character to that position. However, i'm not able to understand how to set the raycast distance so that it corresponds to the exact distance my character intends to move. So, what i'm looking for is a way to corelate Vector2 and float.
0
Is Time.deltaTime framerate dependent? I have a game that calculates your score via Time.deltaTime (the more time the more score). On my PC I get about 1200 points if I just idle the game while on my phone I only get about 400 points. I believe my code must be FPS dependant and that's why my phone is getting a lower score for the same time. Here's the code void Update () time Time.deltaTime score (int)time timerLabel.text score.ToString() Sorry if it's something very obvious. I'm quite new at c . Can't seem to get the solution to work. It just stays at 0 Full Code using UnityEngine using UnityEngine.UI using System.Collections using UnityEngine.SceneManagement public class EndGame MonoBehaviour public Text textWin public Text timerLabel public GameObject retryButton public GameObject points private Vector3 offset private float time private float score void OnTriggerEnter (Collider col) if (col.gameObject.name "Player") setWinText () retryButton.SetActive (true) points.SetActive (false) void setWinText () textWin.text "Final score " score.ToString() void Update () time Time.deltaTime if (time gt 1.0f) score score 1.0f timerLabel.text score.ToString()
0
How to assign game objects to a script without dragging and dropping into inspector? So I have a script for getting into a car which, when mouse down is detected on the given game object it will teleport the player to the car, turn of the player's controller, and switch the player camera to the car camera. The problem is I don't want to have to drag and drop the car game object, the player game object, and both cameras into the inspector for it to work. Instead I would like it to have the script assign all those game objects based on the player who clicked on the car. Those game objects being the car the player, and the two cameras(one parented to the player and the other parented to the car). I have no clue how to go about this so I appreciate any help all the more. Here is a picture of the inspector with the player script Also here is my C code using System.Collections using System.Collections.Generic using UnityEngine public class GetInCar MonoBehaviour public GameObject player public GameObject car public Camera CarCam public Camera PlayerCam void Start () void OnMouseDown () if (Input.GetKey (KeyCode.Mouse0)) player.transform.position car.transform.position print("MovedToCar") GameObject.Find ("Player").GetComponent lt CharacterController gt ().enabled false PlayerCam.enabled false CarCam.enabled true
0
How to align angular velocity wit target rotation in 3D? I'm making a space crew sim (controlling a ship) and have recently posted a question about how to calculate ETA between two rotations. I how now a new question more well defined. Background I have Qtarget and Qcurrent(the ships rotation) and can find Qdelta using Qdelta Qcurrent 1 Qtarget. And I have the angular velocity in rotation speed around the world axis from the Unity. I want to control the ship only using delta angular velocity around ships axis. I want to get the angular velocity aligned with Qdelta so i can just use that angular velocities e.g. x part and the angel to solve for if I should accelerate or decelerate and just decelerate along the y and z axis. After that I want to rotate that data back to ship rotation. I have this test code using UnityEngine using System.Collections public class RoationTest MonoBehaviour public Vector3 startAngularVelocity new Vector3() public Vector3 targetRoation new Vector3() public Vector3 maxShipDeltaAngularVelocity new Vector3() Use this for initialization void Start () rigidbody.angularVelocity startAngularVelocity Mathf.Deg2Rad rigidbody.WakeUp() Update is called once per frame void Update () Vector3 currentAngularVelocity rigidbody.angularVelocity Mathf.Rad2Deg This seams to work Quaternion deltaRoationQuat Quaternion.Inverse(rigidbody.rotation) Quaternion.Euler(targetRoation) This seams to work float deltaAngel Quaternion.Angle(rigidbody.rotation,Quaternion.Euler(targetRoation)) This seams to work Vector3 xAxis new Vector3(1,0,0) Vector3 deltaRotationAxis deltaRoationQuat.eulerAngles Vector3 deltaRotationAxisClampedToShortestDist ClampEulerAngelsToClosest(deltaRotationAxis) Quaternion AlignQuat Quaternion.FromToRotation(deltaRotationAxisClampedToShortestDist, xAxis) Vector3 angularVelocityAligend AlignQuat currentAngularVelocity This should be Quaternion.Inverse(AlignQuat) currentAngularVelocity But that does not work as I think I should but this do. Vector3 maxDeltaAngularVelocityGlobalRotaion rigidbody.rotation maxShipDeltaAngularVelocity Transform max delta angular velocity from ship rotation to global space. The same as maxShipDeltaAngularVelocity Quaternion.Inverse(rigidbody.rotation) but Unity do not suport that. Vector3 maxAlignedDeltaAngularVelocity AlignQuat maxShipDeltaAngularVelocity private Vector3 ClampEulerAngelsToClosest(Vector3 rotation) if(rotation.x gt 180) rotation.x rotation.x 360 if(rotation.y gt 180) rotation.y rotation.y 360 if(rotation.z gt 180) rotation.z rotation.z 360 return rotation Questions Why do this Vector3 angularVelocityAligend AlignQuat currentAngularVelocity align y axis with x axis? It should be Vector3 angularVelocityAligend Quaternion.Inverse(AlignQuat) currentAngularVelocity in my understanding. Also how can Vector3 maxDeltaAngularVelocityGlobalRotaion rigidbody.rotation maxShipDeltaAngularVelocity be right? General thoughts Is this clear enough or am I taking the wrong approach? I general words I want to find the optimal solution in every frame on how to reach target rotation only using delta angular velocity limited by a max value (the ships engines effect) and also receive and ETA. I understand this is an approximation I state above since i assumes no rotation perpendicular to Qdelta but this solution will do for a start.
0
Unity Problems with scene object orientation and rotation after updating my project from 5.0.0 to 5.2.2 Last year I made a large project on Unity 5.0.0, today I re opened it on 5.2.2 to do some work on it. I was given the message that the project needed to be updated, I allowed it to do the update. Now when I open up my scenes, many of my scene objects are misplaced, the rotation is completely wrong and positioned in the wrong place. My scenes are of a refinery and the most commonly broken object is the pipework, something that would take hours to correct manually. My pipework is created this way... All pipes are made in blender and each scene's pipes are saved as a single blender model (with each pipe make from a bezier curve and left as a separate object). Once imported into Unity (as a single .blend file), I've then dragged and dropped coloured materials onto all the individual pipes, so they are all coloured correctly. This has all been fine until updating the project to 5.2.2 now some of the pipes are in the right place, but many are rotated in completely the wrong direction, leaving it looking a mess. If I delete the pipes from Unity and reimport the pipe model back in, this would solve the problem, but then all the materials colours will be gone. Due to the sheer amount of pipes throughout the whole project, to re colour them all again would be an extremely problematic task, especially as it's critical that the pipes are the right colour. I am confused how some of the pipes within the same pipe model are fine and the others are wrong, it would be so much easier to sort if they had all changed rotation together, then I could just switch them all back in 1 go. I have a total of 13 scenes and so far all of them have suffered the same problem. Nothing whatsoever has been changed on any of the scenes, assets or indeed anything in the project folder. In fact I haven't touched a single file within the project since October last year, so it is certainly to do with updating to 5.2.2. Is there anything I can do to fix the problem without having to re import the models back in or manually rotate everything back? I have attached some screenshots to show the issue See how in the blender image, all the pipework is placed correctly and then in the Unity image, half the pipes have flipped and are facing the wrong way. I have removed the ground so this can be seen clearer. Any help would be much appreciated. Many thanks
0
Texture tearing with UV texture atlas mapping The following code maps the texture from a texture atlas to a UV. The problem is I'm having texture tearing issues. Does anyone know how to overcome this problem and have any suggestions? Here is the code I have, all images are point filtered and no mipmapping is used. for (int i 0 i lt mesh.uv.Length i ) UVs.Add(GetUVTextureFromAtlas(mesh.uv i .x, mesh.uv i .y, voxel, 0)) ... Vector2 GetUVTextureFromAtlas(float x, float y, ushort voxel, Facing side) Rect rect GetVoxelTextureRect(voxel, side) float xout UVLerp(rect.x, rect.x rect.width, x) float yout UVLerp(rect.y, rect.y rect.height, y) return new Vector2(xout, yout) float UVLerp(float from, float to, float t) float difference to from return from (difference t)
0
Unity installed version higher than game project version can't open the game project anymore Long story short I had to uninstall Unity and Unity Hub and reinstall them again. I ended up installing Unity version 2020.2.1f1. Some of my game projects were made using version 2020.1.6f1 Now I cannot open them there is a yellow warning triangle next to those games in Unity Hub. I am installing version 2020.1.17f1 as I type these. So my questions Is there no backwards compatibility between newer versions of Unity and older games? How do people deal with this? I've heard people transition their games during development into newer versions of Unity but I wasn't even able to open the games made with older version. How would I go around this if I had spent 2 years or more of development time and was suddenly locked out from my game project how do I prevent situations like these? Here are my Unity versions installed And here are my games (tutorials mostly) I may have answered my own question, but still need your input guys. I just noticed that there is a 'Select Version' dropdown on the right that allows me to open a game project in Unity version I have installed on my system. Is this how you deal with those issues?
0
Unity bounds includes the center of the scene I'm trying to get the bounds of an object and put a box around it. Sounds simple right? I just encapsulate all the bounds together and use its center and size to do so. But the problem is one corner of the box is always at the center of the scene, like a part of the object is there, unless the center of the scene is in the bounds. This is when object is at the center This is when it isn't This is the code i'm using public static Bounds Calculate(Transform TheObject) Renderer renderer TheObject.GetComponent lt Renderer gt () Bounds combinedBounds new Bounds() if (renderer ! null) combinedBounds renderer.bounds var renderers TheObject.GetComponentsInChildren lt Renderer gt () foreach (Renderer render in renderers) if (render ! renderer) combinedBounds.Encapsulate(render.bounds) return combinedBounds
0
How can I load import GIS file (ESRI Shapefile) to Unity3D at runtime? I'm new to Unity3D and I need to implement an open source Markerless Augmented Reality GIS mobile app (Android, IOS) to show the underground utilities (like wastewater pipes, water pipes, electricity lines,...) when the user moves with the mobile camera. I found some SDKs for Unity3d that use location based AR (like Wikitude, Vuforia, ARCore, ... ) but I have not found a way to load a GIS file format (like ESRI Shapefile, CAD, GeoDB, ... ) at runtime and draw (points, lines, polygons) in 3D Unity shapes in its geographic location. Screenshot from (vGIS) software to show what I need to implement .
0
How to make it so my cursor is not behind the UI? My cursor keeps going behind the UI how to make it go above?
0
Have an object rotate on its Y axis towards mouse position I've been looking at some other answers to similar cases but not every one used different methods, and a lot of them were not what i needed, so here's my question What's the best standard way to get the X and Z positions of the mouse onto a plane, so that object can rotate to look at that position? I'm trying to get it in a similar setting to, for example "Angry Bots" where the Player is always facing mouse position. Also, would that be camera independent? i mean, if my camera changes its angle, it would still work because it usually is a projection of the "screen" plane onto the "player" plane, right? I'm sorry, i'm a bit overwhelmed with the many options Camera.main. has, and i'm not really sure which one should i use.
0
How do I create a draggable object which snaps to obstacles in the way? I bring yet another drag with mouse question (I am using Unity with C ), but with a less common particular detail the existence of obstacles in the middle of the way trough which dragging occurs (3D space, not 2D). Let me explain. Suppose I have a plane over which I want to drag a cube called "obj" .That's easy. Here is my simple implementation for that void Update () Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if(Physics.Raycast(ray, out hit, 1000000)) obj.transform.position new Vector3(hit.point.x,0.25F,hit.point.z) It works. However, suppose that I also have a few other cubes over the plane, which are the obstacles. Obviously, when the player moves "obj" over the plane, such movement should be blocked by the obstacles. And then, while colliding with the obstacles, "obj" should move only snipped to the sides of that obstacle. If mouse is moved and "obj" stops colliding with obstacles, free dragging style movement resumes again. To make the challenge harder, I am trying hard to achieve that without the use of RigidBody components at the obstacles (the dragged object can have it). Any ideas on what is the most efficient way of achieving that? Many thanks! EDIT Commentators have brought to my attention that I should mention that objects are allowed to rotate when snapping. EDIT 2 Considering the difficulty of the original formulation, I changed the question allowing the use of Rigidbody components at the dragged objects. The solution just can not use Rigidbody components at the obstacles.
0
Unity 4.6.6 iOS Build Issue I am using unity 4.6.6 to create a Xcode build. When I create a build I am getting following error Cannot initialize return object of type 'Singleton 1 t6738 ' with an rvalue of type 'Singleton 1 t6737 '
0
How to align prefab to a accurate position with the best practice? I'm making a plumber game, I have a pump prefab, and pipe section prefab, which allows the user to connect the pipe during game, the pipe needs to be connected seamlessly during game, which means pipe prefab needs to be aligned in pixel level, please check below User needs to add more and more pipe to connect the with each other, pipe is fixed length prefab.I've got choices, 1.Is the pipe prefab instantiated during game play a good practice? Because it might have many pipe prefabs, if the pipe goes a long way to another position, than there will needs to be so many pipe prefabs, compared to have procedrually generated pipe mesh during runtime, then a long pipe will not have to be cut off to the same small pieces?Which is good way to adpot? 2.If I use the same pipe prefabs to fabricate the piping system, how to accurately connect each other in pixel level, I can make the whole piping system in blender, then cut the system into pieces as my prefabs, then import to Unity as my first choice, this can do pixel level connection, but it seems to have better choice solely solved pixel level connection in Unity? 3.If I do it by generating the mesh during game play, then it could be complex especially it is hard to make elbow pipe mesh during runtime, or could you please advise me of some known library or package can do the work?
0
Correctly get size from Canvas UI element on Unity Normally when anchors are on the same position, we can use .sizeDelta or .rect.width height from RectTransform, but if the anchor are stretched, both of them returns negative values Which in reality is not 5 in size at all There are already SetSizeWithCurrentAnchor but how to get other's RectTransform's absolute size?
0
Unity Render Texture Artifacting I'm having weird black artifacts appear on my render textures when they are transformed while the game is running. I am using a ScrollRect as a scrolling container for buttons (the buttons are just textured quads with the same render texture applied to them). When I translate the quads while the game is running, strange black artifacts will appear on the quads themselves. Is there a way to fix this? Edit Interesting to note, setting every quad inactive except for one fixed the artifacting on the only visible quad http i.imgur.com OInBBWs.png The intensity of the artifacting seems to be related to the number of objects on screen that use the same render texture. 5 quads active with the same render texture has a really pronounced artifacting, 3 is more subtle, 1 is visibly non existent.
0
Question about designing and controlling a forklift's forks I am building a forklift for a game that I am working and I am trying to come up with a valid way of designing it. So far I haven't really liked the way it behaves in game The forklift has three parts to it Wheels Main body Has a rigid body component Forks Has a rigid body component and a configurable joint where the connected body is the main body(2). The movement is perfectly fine but its forks behaviour that is a bit troublesome. I am trying to make it move as a whole with the main body but it appears as if it is trying to detach itself when I hit another rigidbody in the scene(link goes to a screen cast I made of the problem in action). I have adjusted the drag and angular drag parameters of both the main body and the forks, adjusted the linear and rotational configurable joint parameters and yet this problem constantly occurs. According to an answer found on the official unity forums, I shouldn't parent two rigidbodies together. I am thinking about setting the fork as a purely kinematic rigidbody and updating its position every frame. Does anyone else have any other ideas?
0
Cannot select bone influence in Unity In my sprite editor, under the weights menu, the option for bone influence appears kinda faded and I am not able to select it. Unity is also not generating automatic weights around my bones for different sprites in the same image. Is this feature only available in the pro version, or is there some other setting that is causing the problem?
0
Unity2D 5 Flickering sprites on Android So the game had been working fine for a few days on Android phone without any issues. Today, after adding some scripts and tweaking the game a little bit (tweaks which have nothing to do with the sprites and the issue itself), the game assets sprites started on flicker. On PC, they looked fine, but once ported to Android as a developer build, they started to flicker constantly, even after restart. I decided to go in Player Settings and played with some check marks but nothing seemed to help. Following are my current Player Settings Any help would be appreciated. Oh also, I have GUI in my game, can it be the problem?
0
Inventory View Screen Looking to create an inventory screen in Unity, and trying to think of the best way to do it. My current line of thinking is having a few rows of squares for inventory items that are drag and droppable onto a paperdoll, a la Diablo. When dragging and dropping on the items, it would update a 3D model of your current playable object with the items. The menu itself would be easy enough to do with a simple square and a hierarchy of game objects for the items, each responding to mouse hovering over. The problem I am trying to figure out is being able to render the 3D model on the side. Granted, this is a nice to have, and not necessarily a need, but browsing the documentation, the only way I can think of accomplishing this is using a render to texture which requires Unity Pro with a separate camera completely out of bounds of the current space. Anyone have suggestions on how to accomplish this?
0
My runtime mesh is not being created where it's vertices are located, need help I'm trying to create a quad at runtime and I'm encountering an issue where the mesh does not show up in the scene where it's vertices where set. In the following picture you can see the ship, and to the far right the mesh. The 4 white dots around the ship where drawn after the mesh was made using the 4 vertices of the mesh. My Code Handles the method calls for the mesh creation private void BoundingMeshCreation() Quaternion currentRotation ResetPosition(new Quaternion(0, 0, 0, 0)) BoundingPointsType boundingPoints DetermineBounds() Mesh boundingMesh CreateBoundingMesh(boundingPoints) AssignMesh(boundingMesh) ResetPosition(currentRotation) Creates the mesh filter and assigns the mesh private void AssignMesh(Mesh boundingMesh) MeshFilter newMeshFilter gameObject.AddComponent lt MeshFilter gt () newMeshFilter.mesh boundingMesh VectorLine testPoint new VectorPoints("testPoint", boundingMesh.vertices, null, 5) testPoint.Draw3D() Creates a bounding mesh for the unit private Mesh CreateBoundingMesh(BoundingPointsType boundingPoints) Mesh boundingMesh new Mesh() boundingMesh.name "Bounding Quad" Vector3 vertices new Vector3 4 boundingPoints.LowerLeftPoint, boundingPoints.LowerRightPoint, boundingPoints.UpperRightPoint, boundingPoints.UpperLeftPoint int triangles new int 6 0, 2, 1, 0, 3, 2 boundingMesh.vertices vertices boundingMesh.triangles triangles return boundingMesh Resets the units rotation to the specific quaternion and returns the quaterion from before the reset. Bit of a hack for now to make sure that the original box is the proper size. private Quaternion ResetPosition(Quaternion toResetTo) Quaternion currentRotation transformV.rotation transformV.rotation toResetTo return currentRotation Determines and returns the bounding box points private BoundingPointsType DetermineBounds() Vector3 maxBounds childSprite.GetComponent lt Renderer gt ().bounds.max Vector3 minBounds childSprite.GetComponent lt Renderer gt ().bounds.min BoundingPointsType boundingPoints new BoundingPointsType(new Vector3(maxBounds.x, 1, maxBounds.z), new Vector3(minBounds.x, 1, maxBounds.z), new Vector3(maxBounds.x, 1, minBounds.z), new Vector3(minBounds.x, 1, minBounds.z)) return boundingPoints I've even tried manually setting the vertices like the following Vector3 UpRight transformV.position Vector3 UpLeft transformV.position Vector3 LowRight transformV.position Vector3 LowLeft transformV.position UpRight.z 1 UpRight.x 1 UpLeft.z 1 UpLeft.x 1 LowRight.z 1 LowRight.x 1 LowLeft.z 1 LowLeft.x 1 Vector3 vertices new Vector3 4 LowLeft, LowRight, UpRight, UpLeft boundingPoints.LowerLeftPoint, boundingPoints.LowerRightPoint, boundingPoints.UpperRightPoint, boundingPoints.UpperLeftPoint I'm at a loss, and have no idea what I'm doing wrong. My dynamic meshes seem to work perfectly fine for everything else in the game. Thanks.
0
When an animation involves movement, where is the movement better to implement? For context, I am using Blender and Unity. Regarding the question, as an example, in some games, when you get hit, your character tucks a bit and gets knocked back a few distance. The tucking animation I want to implement in Blender but how about the knockback distance? Do you move your model in Blender (tuck and knockback), or do you do the tuck animation only (tuck in place) and then handle the knockback in Unity (basically triggering the tuck animation and then moving the model backwards a bit). My question basically is, what's commonly done and if there's any specific reason, why?
0
What events invalidate the Unity machine identification? I bought a new solid state drive, cloned the old one to the new using CloneDrive, removed the old drive and booted. Everything went well, but when I tried to start Unity I got this popup I am currently just toying around with the free version anyway, so this is no problem to me, but I guess it could be quite troublesome when someone would be in the middle of an actual project with the paid version. It seems like replacing your hard drive invalidates your Unity license. What other changes to the PC hardware can cause this to happen? I do not want to know how Unity detects hardware changes, I want to know which kind of hardware changes need to be avoided to prevent Unity from causing trouble which might lead to disruption of a project schedule.
0
How do I make my rigid body rotate a fixed angle value each time I click the movement keys Ive tried some experiments with the character rotation, but I dont want it to rotate when he touches something, but I also need to unfreeze the Z axis rotation or else the character doesnt rotate when I press a key. My code is this right now, each time I press play (with the Z axis unfreeze) the character just turns like 10 degrees each time I press a key and he is still interacting with objetcs, I dunno what I can do and I might need some help public float speed 2f private Rigidbody rb private float midJump 1 private Rigidbody rB Character Movement void Start() rb GetComponent lt Rigidbody gt () void Update() rb GetComponent lt Rigidbody gt () float moveHorizontal Input.GetAxis("Horizontal") float moveVertical Input.GetAxis("Vertical") Vector3 movement new Vector3(moveHorizontal, 0f, moveVertical) rb.AddForce(movement speed) Character Jump if (midJump 1 amp amp Input.GetKeyDown(KeyCode.Space)) rb.velocity new Vector3(0, 45, 0) midJump 2 Character Rotation else if (rb.velocity.y 0.0) midJump 1 if (Input.GetKeyDown(KeyCode.D)) rb.AddRelativeTorque(new Vector3(0, 0, 90)) rb.angularVelocity Vector3.zero if (Input.GetKeyDown(KeyCode.A)) rb.AddRelativeTorque(new Vector3(0, 0, 90)) rb.angularVelocity Vector3.zero if (Input.GetKeyDown(KeyCode.S)) rb.AddRelativeTorque(new Vector3(0, 0, 180)) rb.angularVelocity Vector3.zero if (Input.GetKeyDown(KeyCode.W)) rb.AddRelativeTorque(new Vector3(0, 0, 0)) rb.angularVelocity Vector3.zero
0
How to change material color (LWRP) I've upgraded my project to LWRP, I've changed my materials to LWRP lit. But in one of the gamemodes i need to change one my materials' color by script. I used to do it simply like wallMat.color Color.red, but at LWRP that code doesn't work, how to fix it? Edit LWRP Light Weight Render Pipeline
0
Why does my shader's Texture become unselected when I run my game? I'd like to add a custom material to a line that I'm drawing in Unity (using Vectrosity). I'm using Unity's built in "Unlit Texture" shader. When I drag a texture from my Resources directory into the "Texture" slot in my shader, everything looks good But when I click play, the texture disappears and my line doesn't show up in my game. However, if I drag the texture to the shader's texture slot after I click play, the texture seems to "stick" and my line renders as expected But once I stop and start the game, the texture again disappears. Why is Unity kicking out my texture when my game starts? Is there something wrong with my texture? I don't see any warnings or errors in the console. I've tried with numerous different textures, and they all do the same thing. I'm using Unity 5.6.1f1.
0
Circle colliders dont work I have a destination and 2 players. I want the players to reach the destination and not overlap in the process. I attached to each player a circle 2D collider and a rigidbody 2D. Also this script using UnityEngine using System.Collections public class Agent MonoBehaviour public Transform destination private Vector2 destPostion private Vector2 playerPosition public float rotation 0 Vector2 velocity Vector2.zero public int maxForce 5 rate of acceleration public int maxSpeed 4 grid squares second private Rigidbody2D rb void Start () rb gameObject.GetComponent lt Rigidbody2D gt () destPostion.x destination.position.x destPostion.y destination.position.y Update is called once per frame void FixedUpdate () Vector3 temp transform.position destPostion.x destination.position.x destPostion.y destination.position.y playerPosition.x transform.position.x playerPosition.y transform.position.y Work out the force for our behaviour var seek steeringBehaviourSeek() Apply the force velocity velocity (seek Time.deltaTime) Cap speed as required var speed velocity.magnitude if (speed gt maxSpeed) velocity velocity (4 speed) Calculate our new movement angle rotation Mathf.Atan2(velocity.x, velocity.y) 180 Mathf.PI transform.rotation Quaternion.Euler(0, 0, rotation) playerPosition playerPosition (velocity (Time.deltaTime)) temp.x playerPosition.x temp.y playerPosition.y transform.position temp rb.MovePosition(temp) private Vector2 steeringBehaviourSeek() Desired change of location Vector2 desired destPostion playerPosition Desired velocity (move there at maximum speed) desired desired (maxSpeed desired.magnitude) The velocity change we want var velocityChange desired velocity Convert to a force return velocityChange (maxForce maxSpeed) The problem is they start moving for a bit and they stop. Also in the scene when I move them with the mouse they overlap. Any ideas?
0
Only do 1 SphereCastAll in Unity3D? I just want to make one SphereCastAll with a center and a radius. I don't want unnecessary sweeping in a desired direction with a desired length. How is this achievable? My solution is pretty unreliable, I think. var hits Physics.SphereCastAll(center, radius, forward, 0.0001f, mask)
0
How to implement a mechanic of entering a town I am planning a game played on a 2 D map, where some spots are "towns". When the player walks into a town, he enters a high resolution map of this town when he exits the town, he returns to the low resolution map of the world (as in e.g. Ultima 4). My question is how to implement this enter exit mechanism in Unity? I thought of two approaches The world map and each of the town maps is a different scene. Entering exiting a town is implemented by loading the appropriate scene using the scene manager. There is a single scene, but the maps are geographically separted. For example, the world map is in coordinates 1...256, town A map is in coordinates 301...364, town B map is in 401...464, etc. Entering exiting a town is implemented by moving the player and the camera to the appropriate map. Is there a better approach? What approach is commonly used to implement this mechanism?
0
how to set multiple materials using array in the submesh of an object I'm trying to insert multiple materials into the object's submesh using the array, but I'm not getting public GameObject obj material mat public void Color(Material mat) for (int x 0 x lt obj.Count x ) obj x .GetComponent lt MeshRenderer gt ().sharedMaterials 1 mat Material mats GetComponent lt Renderer gt ().materials mats 1 mat GetComponent lt Renderer gt ().materials mats print("New Material")
0
Removing unecessary permissions from AndroidManifest that Unity Plugins put in there? My game has a lot of unnecessary permissions added to it, I suspect some are coming from plugins and some from Unity. I've looked at all the AndroidManifest.xml files and couldn't find any that use those permissions so I suspect it's added as a post build process or some other way by the plugins wrapped up in a binary or something. Is there a way to remove those permissions in a post process build step?
0
Detect left and right movement of sprite I have a sprite of ball which moves when a player tap and holds the ball and move finger on the screen. I have a attached animations on it. straight, left, right and when the ball hits something. Here is my code ball.cs public RuntimeAnimatorController straight public RuntimeAnimatorController left public RuntimeAnimatorController right public RuntimeAnimatorController ballHit Animator animator Vector2 prevPos private void Start() animator gameObject.GetComponent lt Animator gt () void Update () Gets the world position of the mouse on the screen Vector2 mousePosition Camera.main.ScreenToWorldPoint(Input.mousePosition) Checks whether the mouse is over the sprite bool overSprite this.GetComponent lt SpriteRenderer gt ().bounds.Contains(mousePosition) if(GameObject.Find("GameController").GetComponent lt brickMovement gt ().gameOver true) animator.applyRootMotion true animator.updateMode AnimatorUpdateMode.UnscaledTime animator.runtimeAnimatorController ballHit If it's over the sprite if (overSprite) If we've pressed down on the mouse (or touched on the iphone) if (Input.GetButton("Fire1") amp amp GameObject.Find("GameController").GetComponent lt brickMovement gt ().gamepaused false amp amp GameObject.Find("GameController").GetComponent lt brickMovement gt ().gameOver false) float x Camera.main.ScreenToWorldPoint(Input.mousePosition).x float y Camera.main.ScreenToWorldPoint(Input.mousePosition).y Set the position to the mouse position prevPos this.transform.position Debug.Log(animator.runtimeAnimatorController) if ((x gt 1.938 amp amp y gt 4.51) amp amp (x lt 1.98 amp amp y lt 4.5)) Debug.Log("Previous Pos " prevPos.x) Debug.Log(IsThisObjectMoving()) if (this.transform.position.x lt 0 amp amp IsThisObjectMoving()) animator.runtimeAnimatorController left else if (this.transform.position.x gt 0 amp amp IsThisObjectMoving()) animator.runtimeAnimatorController right else if (this.transform.position.x prevPos.x) animator.runtimeAnimatorController straight this.transform.position new Vector3(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y, 0.0f) bool IsThisObjectMoving() Vector3 sek0pos Vector3 sek1pos sek0pos gameObject.transform.position StartCoroutine(delay()) sek1pos gameObject.transform.position if ((sek1pos.x sek0pos.x) gt 0f) return true else return false Make function out of the above function that will check if object is moving left or right. IEnumerator delay() yield return new WaitForSeconds(1.0f) I am having issue in detecting if ball is moving left or right. When ball is not moving straight animation should be played. but when it is the respective direction animation should be played. Secondly when I do a hit animation it ends quickly without getting played properly.
0
Shooting at mouse in unity I'm using unity and trying to get my bullet to shoot at a target. I am clicking the mouse and I'm wanting to fire my bullet in that direction. I have gotten the coordinates of the mouse click and tried to compute the vector. Then I've tried instantiate the bullet prefab (which has rigidbody component and is in front of the scene) at my position and then fire it in the direction of the mouse. I can see that my objects being instantiated in my Hierarchy Pane but can't see anything on the screen! Not sure if I'm doing the vector thing right (newb here), but if I click on Yoshi's head, I'm getting ( 2.0, 0.4). Does this sound right? Code void fireBullet(float mousePositionX, float mousePositionY) Vector2 position new Vector2(mousePositionX, mousePositionY) position Camera.main.ScreenToWorldPoint(position) GameObject bullet Instantiate(bulletPrefab, transform.position, Quaternion.identity) as GameObject bullet.transform.LookAt(position) Debug.Log(position) bullet.rigidbody2D.AddForce(bullet.transform.forward 1000)
0
How to Call a function from another script? I just learned in a C tutorial that we can declare var name new ClassNameOfOtherScript() to create a new class object, then use the object to call the function in that class, but it doesn't seem to be working in Unity. Am I understanding it wrong or does it work differently in Unity? I have a class Cube1 this is attached to an object with SpriteRenderer enabled. Then I have another script ClockController which is not attach to any object. When I run it, the color of cube does not change to red? public class Cube1 MonoBehaviour public void Rectangle() GetComponent lt SpriteRenderer gt ().color Color.red public class ClockController MonoBehaviour void Start() var cube1 new Cube1() cube1.Rectangle()
0
Rotate object relative to camera position I am trying to write code that is able to rotate object, based on camera position. So far I ended up with a code posted below. Moving mouse up and down (y input) caused to rotate object in y axis, instead of x. That's why I used cross product. Achieved result is working not exactly as I expected. Rotation is different for every object, dependent on their pivot. I am not exactly sure how it fix it properly. public class DragRotate MonoBehaviour public Camera camera public float rotationSpeed 1 private void Update () float x Input.mousePosition.x rotationSpeed float y Input.mousePosition.y rotationSpeed var rot camera.transform.TransformDirection (new Vector3 (x, y)) rot Vector3.Cross(rot, camera.transform.forward) transform.rotation Quaternion.Euler (rot) This script will be primarily used with one axis rotation, this feature is not implemented in code yet, but it's shown in the use case. According to attachment, I want to rotate selected cube (visible pivot is set to global). It's worth to say, that in this examples padlock has always same position and rotation, the only thing that changes is position and rotation of the camera a) Swipe from bottom to top negative rotation on X axis.b) Top to bottom positive on X axis. c) Other axes should be locked, but for example swipe from right bottom to left top should rotate like example a), but taking into consideration only y (vertical) input. This should behave exactly like example 1, but taking camera rotation into account. So 1a is 1b, 1b is 1a etc. Swipe from left to right should result in 1a rotation, swipe from right to left should result in 1b rotation. Bottom to top or top to bottom should have no effect at all.
0
Unity Light Baking for Best Balance between Performance and Visuals I'm trying to optimize my Unity game. I have static objects, dynamic objects and (only) static lights. I wish to fully pre compute lighting and shadows for the static objects while still maintaining realtime lighting and shadows for dynamic objects, and making them work together seamlessly. From the documentation Realtime "Unity calculates and updates the lighting of Realtime Lights every frame during run time. No Realtime Lights are precomputed." So, If I set it to realtime, I'm not really optimizing anything, am I? Mixed "Unity can calculate some properties of Mixed Lights during run time, but only within strong limitations. Some Mixed Lights are precomputed." It's unclear what "some properties" are and what would the consequences be. Baked "Unity pre calculates the illumination from Baked Lights before run time, and does not include them in any run time lighting calculations. All Baked Lights are precomputed." This will work for static objects. However, dynamic objects will look as if there are no lights in the scene. From what I see, Mixed would be what I need, but I would still have to adjust its sub modes in the Lighting window which is non trivial for me Subtractive Its description suggests it would solve all my problems and still be a nice optimization. However, static objects don't seem to receive dynamic objects' shadows or the other way around either. Baked Indirect, or Shadowmask Does not seem to pre compute direct lighting for static objects, throwing away performance gains. The final question is what method will lead me to the best performance in Unity with these requirements There are static and dynamic objects that both need to be lit by direct lighting Both static and dynamic objects should be able to cast and receive shadows from each other All lights are static Indirect lighting is not important in this case
0
Get the player front position at specific distance The simple way to get player front position at specific distance Vectro3 forward player.transform.forward distance Vector3 newPlayerFronPosition player.transform.position new Vector3(forward.x, forward.y, forward.z) newPlayerFronPosition new Vector3(newPlayerFronPosition.x, newPlayerFronPosition.y 4f, newPlayerFronPosition.z) navigationCanvas.transform.position newPlayerFronPosition navigationCanvas.transform.rotation camRotationToWatch.transform.rotation its actually working fine but the problem is as my player move up or down the navCanvas become appear ver near to my player. How to mainitain spcific distance all the time.?? that no matter player look above or down the navcanvas display at specfic distance.(position) disatnceUICam Vector3.Distance(newPlayerFronPosition, player.transform.position) I also logged the distance and surprisingly it the distance is changing when i am moving up or down. its changing from 6 to 12 as i am looking up to down.
0
When is transform width in code not equal to the transform width in inspector? I've come across a strange case in Unity's UI where the width of a RectTransform isn't the same as what is being reported. I have a transform which is 50 by 50 with no scaling, it is a root object of the canvas yet when I use the information that I get from the transform in code to draw from the bottom left edge of the transform to the top right it doesn't reach all the way! Gizmos.color Color.red Vector2 pos new Vector2(transform.position.x, transform.position.y) Gizmos.DrawLine(pos transform.sizeDelta, pos transform.sizeDelta) Vector3 corners new Vector3 4 transform.GetWorldCorners(corners) Gizmos.color Color.magenta Gizmos.DrawLine(corners 3 , corners 0 ) Gizmos.DrawLine(corners 0 , corners 1 ) Gizmos.DrawLine(corners 1 , corners 2 ) Gizmos.DrawLine(corners 2 , corners 3 ) The first section should draw a line from the bottom left to the top right according to what the transform reports are the width and height however they don't reach across the entire transform. Using GetWorldCorners the actual corners can be found and drawn around, with that data you can extract that the actual width is 60 (150.2 30.2 120 2 60)! Why? Is this a bug or an I missing something obvious here?
0
pause function for x amount of time I've read up on several ways of doing this but can't seem to find one that works for what I need. I have a method that is called and performs some logic, and then I need it to wait for a period of time, then continue with more logic in the same function. I had planned on using a coroutine which is what I did with another part of the game, but I'm running into an issue because the class doesn't directly inherit from Monobehaviour so it can't start a coroutine. I've tried Thread.sleep, but that just makes the game stop, so that isn't what I want. I don't know if there is some way to put a timer in there that will wait and then continue the function or if there is something else that I'm overlooking. Here is the current code public void AssaultRifleShot (GameObject mainBall) if (AmmoRemaining gt 0) if there is ammo remaining, set the main ball to just a normal ball so it can be destroyed on impact and then start coroutine mainBall.GetComponent lt Ball gt ().mainBall false mainBall.GetComponent lt Ball gt ().onBallHitPaddle AssaultRifleShot unsubscribe to event when mainBall is set to false. StartCoroutine(timer, coroutineHost) AmmoRemaining 1 else DestroyPickUp() There are other method calls inside the code for the coroutine, so those would end up going after whatever timer or someting goes in instead of the coroutine.
0
Trigger issues (multiple events, enter exit) not sure if this is a scripting issue or if I've implemented something wrong with the colliders, but here it goes All I want is a simple platform trigger that registers when the player steps on it and when they get leave. I have BoxColliders with IsTrigger on both the platform and the player and in general everything works okay. However there are some strange edge cases where the OnTriggerExit happens immediately after the OnTriggerEnter. Once I've even managed to stand in a place where it constantly went from Enter to Exit to Enter etc. without the player moving at all! So I put position outputs in the debug text and the positions of where the Enter Exit happens is in really strange places, nowhere near the trigger volume! Initially I put a cooldown on the trigger volume, so it could only trigger every second but that doesn't solve the issue of the Exit triggering for some reason when it shouldn't. Here's my code for the platform using System.Collections using System.Collections.Generic using UnityEngine public class TriggerScript MonoBehaviour public Collider player public Material activeMaterial, inactiveMaterial public float TriggerVolumeCooldown 1f private Renderer m Renderer private bool m IsOnCooldown private float m CooldownStartTimestamp void Start() m Renderer GetComponent lt Renderer gt () m Renderer.material inactiveMaterial m IsOnCooldown false void OnTriggerEnter(Collider collider) if (collider player amp amp !m IsOnCooldown) print( quot Player entered quot collider.name quot CD quot m IsOnCooldown quot xyz quot collider.GetComponentInParent lt Transform gt ().position) m Renderer.material activeMaterial m IsOnCooldown true m CooldownStartTimestamp Time.time else print( quot cooldown quot ) void OnTriggerExit(Collider collider) i if (collider player) print( quot Player left quot collider.name quot xyz quot collider.GetComponentInParent lt Transform gt ().position) m Renderer.material inactiveMaterial void Update() if (m IsOnCooldown) if (Time.time m CooldownStartTimestamp gt TriggerVolumeCooldown) m IsOnCooldown false
0
Load uncontrolled 3D asset at runtime in Unity I'm trying to load assets at runtime in Unity. I can load images this way https docs.unity3d.com 455 Documentation ScriptReference Texture2D.LoadImage.html But how can I do the same with 3D assets? From what I read, loading .fbx .obj and alike need importers. But importers are created by users, and support might be bad. I read you can import using https docs.unity3d.com ScriptReference WWW.html But that seems only to work with unity3D files Or do I follow the wrong track? Is there another way to do this?
0
Why my dynamically generated Sprites overlap? I'm trying to dynamically generate scene representing chess board made from sprites. I'm using two textures for these pieces.png (taken from here http opengameart.org sites default files chess 2.png) tiles.png (drawn by hand, consists of two 128x128 squares filled with different colors) The best result I achieved so far is a board with overlapping tiles The sprite mode for these textures is "Single" and pixels per unit are set to "128" (unsure whether I should've done this or not) The textures are being sliced to sprites in my MonoBehavior.Start var tiles new Dictionary lt int, Tile gt () var sprites new Dictionary lt int, Sprite gt () Load all tilesets foreach (var externalTileset in map.tilesets) var tilesetAsset (TextAsset)Resources.Load ("Boards " externalTileset.source) var tileset (Tileset)tilesetSerializer.Deserialize (new StringReader (tilesetAsset.text)) Texture2D texture (Texture2D)Resources.Load ("Boards " tileset.image.source.Replace (".png", ""), typeof(Texture2D)) Debug.Log ("Texture for " tileset.image.source " loaded " texture.width 'x' texture.height) int tilesPerRow tileset.image.width tileset.tilewidth int totalTiles (tileset.image.width tileset.tilewidth) (tileset.image.height tileset.tileheight) for (int tileId 0 tileId lt totalTiles tileId ) float x tileset.tilewidth (tileId tilesPerRow) float y (tileId tilesPerRow 1) tileset.tileheight sprites externalTileset.firstgid tileId Sprite.Create (texture, new Rect (x, texture.height y, tileset.tilewidth, tileset.tileheight), new Vector2 (0.5f, 0.5f)) if (tileset.tiles ! null) foreach (var tile in tileset.tiles) tiles.Add (externalTileset.firstgid tile.id, tile) And when sprites are added to newly created game objects float minX 4 float maxX 4 float minY 4 float maxY 4 for (int i 0 i lt map.height i ) float y minY i (maxY minY) map.height for (int j 0 j lt map.width j ) float x minX j (maxX minX) map.height if (pieces i, j ! null) GameObject piece new GameObject (pieces i, j .properties "Color" ' ' pieces i, j .properties "Type" ) SpriteRenderer renderer piece.AddComponent lt SpriteRenderer gt () renderer.sprite piecesSprites i, j piece.transform.position new Vector2 (x, y) if (tileSprites i, j ! null) GameObject tile new GameObject ("Tile") SpriteRenderer renderer tile.AddComponent lt SpriteRenderer gt () renderer.sprite tileSprites i, j tile.transform.position new Vector2 (x, y) I believe I can hack something to make this work, but I want to know how to do it properly What's wrong with my code or scene resources setup?
0
Workflow to have character look like Tokyo ghoul re Call to exist I am looking into a lot of different software and now that I got my head around most of them, I was asking mysel if someone knew what has been used to create the characters in the game I mentionned. Not specifically software if there is no information about it, but at least as it been modeld sculpted, etc. Thanks
0
Unity warning animations neck and head have scale I always get this warning if I import my model to unity Clip 'soldier idle' has import animation warnings that might lower retargeting quality Note Activate translation DOF on avatar to improve retargeting quality 'neck' has scale animation that will be discared. 'head' has scale animation that will be discared. Even though there are in fact no scale animations on the bones neck and head as you can see in my blender dopesheet. So why is this warning showing?
0
Real Time Physics Based Mesh Deformation I'm working on a game through unity that draws one of is essential elements from traditional tool forging techniques for building tools and such. I want the feel of the game to be able to create a tool that is truly yours and slowly make it better in both design and functionality over time. One major thing I cant't seem to figure out is to be able to take a mesh (in this case a hot piece of meta) and deform it in such a way that you aren't loosing any of the mesh, its just being shifted slightly with each hit of a hammer (or in my testing case click of a mouse). I have looked all over youtube and various forums and I can't seem to find an efficient way of going about it. Any thoughts?
0
Finding next AI move using MinMax algorithm for Checkers I am currently working on a Checkers game using Unity ( human vs computer ) I am done with the base architecture of the game ie defining the rules, moves, jumps etc. I am currently stuck in implementation of MinMax for computer AI. I know how it works but I am confused on two things. Firstly, the heuristics ( I am using simple red checker count black checker count ) but I am not sure if its correct. Secondly, outputting the final path of nodes for my AI to make its next turn. Below is my MinMax implementation so far. int MiniMax(TreeNode node) int depth 2 List lt TreeNode gt pathNodes new List lt TreeNode gt () int final MaxMove(node, depth, pathNodes) return final int MaxMove(TreeNode currNode, int depth, List lt TreeNode gt pathNodes) if (depth 0) return currNode.getPriority() else depth int v 10000 List lt TreeNode gt allPossRedMoveNodes gameBoardScript.createNewRedBoardsFromCurrent(currNode.getCurrentBoard()) foreach (TreeNode RedNode in allPossRedMoveNodes) int v1 MinMove(RedNode, depth,pathNodes) if(v1 gt v) v v1 return v int MinMove(TreeNode currNode, int depth, List lt TreeNode gt pathNodes) if (depth 0) return currNode.getPriority() else depth int v 10000 List lt TreeNode gt allPossBlackMoveNodes gameBoardScript.createNewBlackBoardsFromCurrent(currNode.getCurrentBoard()) foreach (TreeNode BlackNode in allPossBlackMoveNodes) int v1 MaxMove(BlackNode, depth,pathNodes) if (v1 lt v) v v1 return v Max in this case would be Black Checkers ( Computer AI ) and Min is Red Checker, the human player Let me briefly explain what I am trying to do with my code above. I have a TreeNode structure that stores the GameBoard, next possible move and also the Heuristic value In My Max Move, I get all the possible Red Move Nodes from the current board. Logic for finding all possible moves is working absolutely fine. And for my Min Move which would be the human player, I get all its possible black nodes. I am currently testing the code with depths 2 to 3 for my game tree. Please correct me if my current implementation is wrong. And finally how or where do I trace the final path of all my final Tree Nodes based on Min and Max values generated and get the next move for the Black Checker?