_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | 2D Animation based on Time.deltaTime has problems when the game performs long operations I animate my 2D sprite using the Update() method float timer 0.0f float delayPerFrame 0.04f void Update() timer Time.deltaTime if (timer gt delayPerFrame) timer 0 Logic to display the next frame As you can see, it is pretty simple every 0.04 seconds the next frame will be set. But sometimes, my game needs to do some exhausting processing (like loading large scenes and whatnot), which causes a tiny little lag in the game. When this happens, my sprite begins with a wild, fast animation. Then eventually it resumes at a normal pace. I imagine this is because the lag caused the Time.deltaTime value to skyrocket for a period of time. I am also under the impression that Update() is called too often during such period (although that shouldn't matter). I don't want to use existing animation features of Unity. My game is already built under this particular piece of logic, so I'd like to fix it. Using FixedUpdate() doesn't help. I can also confirm that Time.deltaTime does indeed peak at the beginning. Note that this occurs only after doing an exhaustive operation. If you spawn a sprite of these in the middle of the game, everything will go smoothly. But if you spawn them immediately after doing something like loading a large scene, then they will have some sort of boost at the beginning. |
0 | How can I resize a game object using single drag handle? Really need your help. I'm trying to create a custom controller for my app to allow users to resize and rotate game objects using a single drag object. I was able to create the code to create the visuals and to rotate it but I'm stuck on how to resize the game object. To position the drag handle at the start, I'm getting the bounds of the target object and taking the bounds.extents.magnitude to determine the y position. So I was hoping the behavior would be such that when you drag the handle closer to the center of the target object it shrinks the bounds.extents.magnitude based on the new handle position and then becomes bigger if you go further away from the center of the target object. Here is where I am now using System.Collections using System.Collections.Generic using UnityEngine public class CircleMaker MonoBehaviour public float lineWidth .1f private int segments 360 private LineRenderer line private float radius private Renderer boundsSource private Bounds bounds public GameObject dragHandle public GameObject target private int pointCount private Vector3 points public int angle 0 public float zPosition 8.0f public bool isDraggingHandle false void Start() line GetComponent lt LineRenderer gt () boundsSource target.GetComponent lt Renderer gt () bounds boundsSource.bounds line.useWorldSpace true line.startWidth lineWidth line.endWidth lineWidth line.positionCount segments 1 line.receiveShadows false line.shadowCastingMode UnityEngine.Rendering.ShadowCastingMode.Off pointCount segments 1 points new Vector3 pointCount float r bounds.extents.magnitude float d2r Mathf.Deg2Rad (target.transform.localEulerAngles.x 360f segments) dragHandle.transform.position new Vector3(Mathf.Sin(d2r) r, Mathf.Cos(d2r) r, zPosition) target.transform.position DrawCircle() void Update() if (isDraggingHandle) rotate object based on drag handle location Vector3 direction target.transform.position dragHandle.transform.position int sign (direction.x gt 0) ? 1 1 float offset (sign gt 0) ? 0 360 float angle Vector2.Angle(Vector2.down, direction) sign offset target.transform.rotation Quaternion.Euler(0, 0, angle) if (target.GetComponent lt DragAndDrop gt ().isDragging true) dragHandle.transform.parent target.transform else dragHandle.transform.parent null DrawCircle() draw circle around target gameobject based on bounds.extents void DrawCircle() radius bounds.extents.magnitude target.transform.localScale.x for (int i 0 i lt pointCount i ) float rad Mathf.Deg2Rad (i 360f segments) points i new Vector3(Mathf.Sin(rad) radius, Mathf.Cos(rad) radius, zPosition) target.transform.position line.SetPositions(points) |
0 | How to Stop TextMeshPro Truncate from Removing Next Line? Unity 2020.3.1f1 In updating from Unity 2019 to 2020, it appears the TextMeshPro (TMP Text) is behaving differently. The code for TMP stayed the same upon updating Unity, so I presume Unity itself must be doing something differently. Nevertheless, I also updated the TMP package and it did not resolve the issue. The Issue I have two lines of text in one text box. I want the overflow to be truncated, but to keep the second line in existence. Example Input This is the really long text on the first line that I want cut but still have this line show. In short, I want it to read as follows when using the quot truncate quot option like it used to work before This is the really long text still have this line show. Instead, the second line disappears and it acts as if I have only that first line (centered vertically). This is the really long text So how do I get this functionality back? Is it possible? |
0 | Text Based Tutorials for Unity3d I hope this is the right place to ask this. I'm very new to Unity but not to programming. I also have some basic game programming experience. I'm searching for text based versions of the videos from unity3d.com learn tutorials. These tutorials are very good, but I end up forwarding videos a lot to get key screenshots and code snippets. Is there any text pdf html .doc .rtf (i'm very open) version or similar resource to learn unity? Again, those tutorials are amazing and I'd hope to find something of similar quality, but I know that if I have to skim through tens of hours of video I'll end up frustrated. I get that the long hard way is probably the most robust one for deeper understanding, but I was hoping to hack a quick project. EDIT If this can make it a relevant question, then I am currently looking at the "Roll a Ball Tutorial". Really, any other text tutorial would be very welcome |
0 | How to stop my particle systems from being frustum culled Please could somebody advise on whether it is possible to control the culling of particle systems in Unity? I am referring to the entire system, not individual particles. In my use case, I am modifying the vertex transformation to get the quot distant object effect quot . When the camera thinks it is not viewing something it will cull it (frustum culling). For most game objects you can get around this by inflating the size of the bounds to make the camera think it is within its frustum and therefore not get culled. However, particle systems are not a single object, they are many particles and I can t see a way of manipulating the total bounds of the system. Any ideas? |
0 | Render object with different shader depending on the camera I have an object with a custom shader. When it is being rendered by cameraA, then I want it to render a particular way (ex red). When it is rendered by another cameraB, I want it to render a different way (ex green). Is there some way I can tell what is the current camera rendering in the shader? Or perhaps I can toggle a boolean value in my shader between rendering of each camera? Where would I do this (OnPostRender() maybe?). |
0 | Should larger Unity Projects use Visual Studio I've worked with several engines and I'm most comfortable with a mature engine, world editor and C codebase. I'm now looking at Unity as a side project and have mostly been working in Javascript. Has anyone done a large scale project with Unity and does it require Visual Studio or is sticking to the Javascript approach best? Are there any big pitfalls with large scale Unity projects or with working with Visual Studio? Most the stuff I've seen has been focused at smaller Indies or people with little experience. I should have phrased this as an external IDE, Visual Studio is just my IDE of choice |
0 | Global fog does not work with deferred rendering in Unity When I set deferred rendering the global fog from the Unity Standard Assets does not work, there is no fog at all. With forward rendering the global fog works. How do I add fog with deferred rendering? |
0 | Raycast implementation in order to optimizate collision detection I want to know if a gameobject (a plane) is facing another one to prevent collisions. Right now I have an array that contains all planes in the scene and, for each one, compare position in order to detect if is facing it or not. The number of planes is small, but I want to increase it and this method is a little... Mean. I was thinking to implement a raycast to detect if the gameobject has another one in front of it. Is it worth? Will it be less expensive? I think that raycast it's very expensive. In addition, I think that I will have to run three raycasts for every plane. Obviously this is not executed every frame, but every two seconds. |
0 | Mirror problems after building game in unity Hi I am facing a weird problem in unity when I build a particular scene. Here is the screenshot of how the mirror looks when I play the game from inside the unity editor And here is how it looks once I build this scene and then play it The quality settings at Edit Project Settings Quality are these And the player settings at File Build Settings Player Settings are these So how do I fix this? What do I need to change or is there any other entity? |
0 | how to put elements around circle with equal distance? I know circle formula and know how to draw it. but I want put 4 points on it with equal distance from each other. how can I do that? I work with unity. |
0 | Why is transform.up behaving differently for different functions? Can anyone please explain to me what i'm doing wrong here? As I see it the raycast is the only one using transform.up correctly, though why not Debug.DrawLine() and lineRenderer.SetPosition(1, transform.up maximumBeamLength) using UnityEngine RequireComponent(typeof(LineRenderer)) public class LaserBeam MonoBehaviour SerializeField private float maximumBeamLength 5f private LineRenderer lineRenderer private void Start() lineRenderer GetComponent lt LineRenderer gt () void Update() lineRenderer.SetPosition(0, transform.position) RaycastHit2D hit Physics2D.Raycast(transform.position, transform.up) Debug.DrawLine(transform.position, transform.up maximumBeamLength, Color.blue) Debug.DrawLine(transform.position, transform.up , Color.red) if (hit.collider) lineRenderer.SetPosition(1, new Vector3(hit.point.x, hit.point.y, transform.position.z)) else lineRenderer.SetPosition(1, transform.up maximumBeamLength) |
0 | Refresh UI after changing source code I was trying following things. GameManager bool gameHasEnded false public GameObject completeLevelUI public void CompleteLevel() completeLevelUI.SetActive(true) public void EndGame() if(gameHasEnded false) gameHasEnded true Invoke( quot Restart quot ,2f) void Restart() SceneManager.LoadScene(SceneManager.GetActiveScene().name) EndTrigger public GameManager gameManager void OnTriggerEnter() gameManager.CompleteLevel() I get a log in the console quot END quot . Earlier I was using Console.Log( quot END quot ) on CompleteLevel(), but I changed that source code. The old code seems to be working and not the new one. It's like Unity couldn't refresh that source code. (And I am sure that I have successfully saved the C file.) using System.Collections using System.Collections.Generic using UnityEngine public class PlayerCollision MonoBehaviour public PlayerMovement movement void OnCollisionEnter(Collision collisionInfo) Debug.Log(collisionInfo.collider.name) if (collisionInfo.collider.tag quot obstacle quot ) movement.enabled false FindObjectOfType lt GameManager gt ().EndGame() |
0 | Animated textures for models How to write a shader? Was watching some Rocket League and notice there was animated decals and wheels. . I would like to implement something similar to the effects in the image above. How would I go about writing a Unity Shader to do the wheel effect? I don't know much about Shaders, but can I edit the standard Unity Shader to do the animation effect? |
0 | Not able to change Rigidbody 2d gravity scale I have been trying to change the gravity scale of my Rigidbody2d when I click on it. By default it is by 0 and when I click on it, it should change to 1, so that it falls down. I have a square with a boxcollider2d and a Rigidbody2d and a square with just a box collider. public bool gravity false public bool m isRunning false public SpriteRenderer m spriteRenderer private Rigidbody2D rb private void Update() if (gravity) rb.gravityScale 1 private void Start() m spriteRenderer this.GetComponent lt SpriteRenderer gt () rb GetComponent lt Rigidbody2D gt () private IEnumerator Changecolor() yield return new WaitForSeconds(1) int random Random.Range(1, 4) if (random 1) m spriteRenderer.color Color.blue else if (random 2) m spriteRenderer.color Color.red else if (random 3) m spriteRenderer.color Color.green else m spriteRenderer.color Color.yellow this.StartCoroutine("Changecolor", 3f) private void OnMouseDown() gravity true m isRunning !m isRunning if (m isRunning) StartCoroutine("Changecolor", 3f) else StopCoroutine("Changecolor") |
0 | Get all images from peristent data path and save them to a Texture2D array So i managed to make a working script that downloads images from firebase in this situation and saves them to Application.persistentDataPath. Now what i would like help in doing is getting all those images quot jpg quot and assigning them to a Texture2D array for later use. So far i have mananged to open one of those images by name and assign it to a single texture. public Texture2D image private void Awake() string dirname quot levelNature quot string path Application.persistentDataPath quot quot dirname quot quot quot nameofImage.jpg quot LoadSprite(fileName) private void LoadSprite(string path) if (string.IsNullOrEmpty(path)) Debug.Log( quot null or empty quot ) if (File.Exists(path)) byte bytes File.ReadAllBytes(path) Texture2D texture new Texture2D(1024, 1024, TextureFormat.RGB24, false) texture.LoadImage(bytes) image texture Debug.Log( quot success quot ) With just one image i can assign it to a texture but since later on in the gameplay i'm using a texture2d array to assign those images to the gameplay , which now are set through the inspector , i would like to load all images in a particular folder to a Texture2D array which later on i will be using to show each image index in a specific level. I did try it out like this but it isn't successful. public Texture2D source var fileNames Directory.GetFiles(Application.persistentDataPath quot quot dirname quot quot quot .jpg quot ) source new Texture2D fileNames.Length int index 0 foreach (var fileName in fileNames) source index LoadSprite(fileName) i get the error here that it cant convert void to texture2D index Hopefully once all images are loaded i could see in that array in the inspector all the images and then use that for the rest of the game. Thank you! |
0 | How to restrict movement of Leap Motion hand object I have a quot Hand quot GameObject controlled by a Leap Motion Controller. The Hand despite having RigidBody and Box Collider just seemingly moves with no regards to physics (transform translate movement I suppose). So it clips through other Rigidbody objects. I'm trying to pseudo introduce physics to it. I created a second GameObject quot HandClone quot (with Rigidbody and Box Collider) that copies the first Hand position but moves with actual physics. HandClone script private void FixedUpdate() rb.MovePosition(targetTransform.position) rb.MoveRotation(targetTransform.rotation) Now HandClone goes where Hand goes, and HandClone is successfully bumping into other objects. However, when HandClone gets stopped by something, Hand still keeps moving past HandClone and clips into the other objects, like before. Now I am thinking that the way to solve this is to constrict Hand's movements to the bounds of HandClone so that finally Hand will stop clipping through objects. But how can this be achieved, would that even work, and is there a better way? Will movement streamed from Leap Motion Controller even respond to scripts like that? Edit I've now decided to hide Hand and place HandClone where Hand was. But my script for HandClone to copy Hand's movements is making HandClone fly all over the place. Here's the script using System.Collections using System.Collections.Generic using UnityEngine public class clone1 MonoBehaviour private Rigidbody rb public GameObject target void Start() rb this.GetComponent lt Rigidbody gt () Update is called once per frame void Update() private void FixedUpdate() Vector3 newRotation new Vector3(target.transform.eulerAngles.x 8.5f, target.transform.eulerAngles.y 172.78f, target.transform.eulerAngles.z 94.02f) rb.MoveRotation(Quaternion.Euler(newRotation)) The reason why I am adding those float numbers is because when the game isn't playing, those numbers are what make HandClone sit in the correct position, so I thought it would help with alignment in playmode. But HandClone is just flying everywhere regardless. Any advice with making the HandClone stay attached to the avatar's wrist would help. |
0 | Unity SOAP wsdl problem i'm trying to using a SOAP service from my game but the problem is that after using wsdl.exe for generete the connector Unity inform me that System.Web namespace doesn't exist. How can I use the wsdl? There is some workaround without writing a lot of code? Many thanks |
0 | Sprite with transparency Create box collider (ignoring transparent area) I have a sprite which has a transparent area in it. The non transparent area is a free form graphic (red). I would like to create a box collider around it (yellow), but ignoring the transparent area. Some notes to the image above Left This is what happens, if I apply a PolygonCollider2D. The yellow line represents the area covered by the PolygonCollider2D. This is not what I want. Middle This is what happens, if I apply a BoxCollider2D. The yellow line represents the area covered by the BoxCollider2D. This is also not what I want, as it includes the transparent area of the sprite. Right This is what I want Have a BoxCollider2D outside my free form graphic. Here's how I currently load my sprite data into the game during runtime My sprites are located in the Assets Resources SceneData ... folder structure of my project. The graphics are stored as .png files. When loading a level, I load the required graphics as sprites like this var sprite Resources.Load lt Sprite gt ("SceneData AfternoonAtTheBeach DragAndDrop Graphics Level1 ElephantWithIceCream") "ElephantWithIceCream" is the .png file (Resource.Load wants me to refer to this file without file extension) After that, I create a new game object and attach a SpriteRenderer component to it. The sprite is assigned to the SpriteRenderer by setting the sprite attribute of the SpriteRenderer component. My first thought on how to solve my problem was to do something like this Create a PolygonCollider2D and try to convert it into a BoxCollider2D. But I was not able to find code examples on how to do this. After that, I thought of trying it to do like this Create a PolygonCollider2D and try to extract some useful information out of it (such as bounds, center, extents, etc...). Delete the PolygonCollider2D and create a BoxCollider2D. Use the previously extracted info to create the BoxCollider2D. But I fail doing so. I am also a bit confused as sometimes they refer to world space or local space. Does anyone have a working recipe for doing something like this? I do not really understand how to work with center, bounds and extents. If there is any better way of doing this, I am highly interested. Thanks a lot for your help! |
0 | Stop 2D platformer character from sliding down slope I'm making a 2D platformer game with the default Unity 2D physics. I am implementing slopes, but my player slips down the slope because of the physics. Here is the code I use for the player movement MoveInput Input.GetAxisRaw( quot Horizontal quot ) rbd2.velocity new Vector2(MoveInput speed, rbd2.velocity.y) rotacion de personaje if (MoveInput gt 0) transform.localScale new Vector3(1f, transform.localScale.y, transform.localScale.z) if (MoveInput lt 0) transform.localScale new Vector3( 1f, transform.localScale.y, transform.localScale.z) |
0 | When importing Mixamo animated characters into Unity, they come without avatar? I'm using Unity 2019.3.3f1. I create the character in Adobe Fuse. I uploaded it to Mixamo and choose an animation. I then downloaded the fbx for unity file. When imported into Unity, it is visible that the file has no avatar or animator component. How can I fix this? Is it a Unity version issue? |
0 | Are the prefabs stored in RAM or in the Hard disk? (Unity3D) I have many prefabs objects (65 MB) in an Unity3D project. My game use 100 different levels with combinations of the prefab objects. What is better create 100 scenes or create only one scene where the prefab objects are placed with data from a XML?. Each Scene load your own prefab objects? Are the prefab objects loaded in the RAM when the scene is loaded or are stored in the hard disk and then loaded in the RAM when come in the scene? |
0 | Possible to yield a coroutine when it is taking too long to run? Suppose I have a function that raycasts from (0,0,0) to every object in the scene. Sometimes the scene contains just a couple objects and sometimes it contains several hundred. Is it possible to setup the raycasting function in a way that ensures a good framerate? For example, within the "for" loop that shoots the rays could I somehow evaluate how much time has passed since the loop started and "yield return null" if the time in seconds is greater than the target time of each frame? |
0 | stop previous audio from playing when starting a new one I created a dialogue system with audio it works perfectly fine unless you start skipping the voice lines so then it all becomes a mess with all of the voice lines overlapping is there a way to make it so when you go to the next audio line the previous one stops playing? Example of what is happening as you can see in the video you can switch the text just fine and it doesn't show the previous one but for the audio, it just transforms into a jumbled mess, is there a way to fix this or to at least make it so people cant go to the next line until they finish hearing the current one? DialogueManager Script public class DialogueManager MonoBehaviour public Door1Animation doorAnimation public Text nameText public Text dialogueText public Text changeText public AudioManager Sound public Animator textBoxAnimation public Queue lt string gt sentences public Queue lt string gt voiceLines void Start() sentences new Queue lt string gt () voiceLines new Queue lt string gt () public void StartDialogue (Dialogue dialogue) textBoxAnimation.SetBool( quot Open quot , true) changeText.text ( quot Aperte R para continuar quot ) nameText.text dialogue.name sentences.Clear() voiceLines.Clear() foreach (string sentence in dialogue.sentences) sentences.Enqueue(sentence) DisplayNextSentence() foreach (string voiceLine in dialogue.voiceLines) voiceLines.Enqueue(voiceLine) PlayNextLine() public void DisplayNextSentence() if (sentences.Count 1) changeText.text ( quot Aperte R para fechar quot ) if (sentences.Count 0) EndDialogue() return string sentence sentences.Dequeue() dialogueText.text sentence public void PlayNextLine() if (voiceLines.Count 0) return string voiceLine voiceLines.Dequeue() Sound.Play(voiceLine) public void EndDialogue() Debug.Log( quot End of conversation quot ) doorAnimation.openDoor true textBoxAnimation.SetBool( quot Open quot , false) AudioManager Script using UnityEngine.Audio using System using UnityEngine public class AudioManager MonoBehaviour public Sound sounds void Awake() foreach (Sound s in sounds) s.source gameObject.AddComponent lt AudioSource gt () s.source.clip s.clip s.source.volume s.volume s.source.pitch s.pitch s.source.loop s.loop private void Start() Play( quot BackgroundMusic quot ) public void Play (string name) Sound s Array.Find(sounds, sound gt sound.name name) s.source.Play() Just the part of the interaction code so you can go to the next line audio public void Update() if (Input.GetKeyDown(KeyCode.E)) PersonInteract() buttonInteract() if (Input.GetKeyDown(KeyCode.R)) FindObjectOfType lt DialogueManager gt ().DisplayNextSentence() FindObjectOfType lt DialogueManager gt ().PlayNextLine() Inspector view of the dialogue manager |
0 | How to express and verify euler rotation limits in Unity I need to find a way to set min and max angles for each Euler component and check whether transform.localEulerAngles falls within those limits. My current code looks like this class JointLimit MonoBehaviour SerializeField Range( 180f, 180f) private float minX 180f SerializeField Range( 180f, 180f) private float maxX 180f SerializeField Range( 180f, 180f) private float minY 180f SerializeField Range( 180f, 180f) private float maxY 180f SerializeField Range( 180f, 180f) private float minZ 180f SerializeField Range( 180f, 180f) private float maxZ 180f public float Error get Vector3 localEuler transform.localEulerAngles Vector3 signedLocalEuler new Vector3(Mathf.DeltaAngle(localEuler.x, 0), Mathf.DeltaAngle(localEuler.y, 0), Mathf.DeltaAngle(localEuler.z, 0)) float error 0 error Mathf.Max(0, minX signedLocalEuler.x) error Mathf.Max(0, signedLocalEuler.x maxX) error Mathf.Max(0, minY signedLocalEuler.y) error Mathf.Max(0, signedLocalEuler.y maxY) error Mathf.Max(0, minZ signedLocalEuler.z) error Mathf.Max(0, signedLocalEuler.z maxZ) return error This basically checks whether the Euler components fall within the specified range and sums the exceeding angles up to an error. The problem is that Unity internally stores rotations as Quaternions and that there can be several euler representations for a single Quaternion, like Euler 123f, 17f, 235f and Euler 57f, 197f, 55f are the same thing. Is there any way I can bring an Euler representation into some kind of normalized form that allows me to reliably check it against my limits? |
0 | Unity profiler spikes with vsync vs smooth no vsync I'm trying to profile my game, this is a webgl game, and the browser forces vsync. My problem is, when I disable vsync in unity I get a pretty smooth profiler, while with vsync I get huge spikes. I cant tell if this is an editor issue or this spikes exist in the webgl version as well (I do have stuttering when playing in the browser, but cant tell if these spikes are the same ones) I don't display the WaitForTargetFPS in profiler as it is not interesing. no vsync with vsync Any ideas friends? |
0 | How to Make Organic Fade to Black in Unity I'm working a retro old style video game, and I was wondering whether or not there is a way to create an organic fade to black, similar to what is found in the original NES console. I am aware of how to create a traditional fade to black screen, but it doesn't really fit the theme of my game. I'm using Unity 2019.4 LTS. Here s a example of a character about to exit the area and cause a fade to black Here s what the organic fade looks like at 75 completion And here s what a traditional fade looks like at 75 completion |
0 | Limit mouse movement within 2 points I have a circle sprite that i only want to move between 2 empty game objects (points). Using Vector3.Lerp() I'm able to move the circle between those points void FixedUpdate() float speed 10 Time.deltaTime float current Mathf.PingPong(Time.time speed, 1.0f) transform.position Vector3.Lerp(startPoint.position, endPoint.position, current) The output The problem I want to move that circle using a mouse drag (basically like a UI slider from point a to point b) and as soon as the mouse leaves the circle to stop moving it I can currently move the circle anywhere on the screen using the mouse. I've set a circleCollider2D around the circle sprite and I have this code that moves the circle bool Selected false void Update() if (Selected) Vector2 cursorPos Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.position cursorPos if (Input.GetMouseButtonUp(0)) Selected false void OnMouseOver() if (Input.GetMouseButton(0)) Selected true What I've tried I have tried adding a gameobject with a box collider between the two points and using triggers to detect when the circle exits the trigger (OnTriggerExit2D), but this solution only works when the circle fully leaves the collider (which i don't want). I want a way for the circle to move just like its moving currently with Vector3.Lerp but with mouse control I tried locking the circle to only one axis and moving it. While this worked, it failed when i rotated the whole slider as its only locked on one axis and rotation doesn't change that I have also tried to implement the mouse position into the Vector3.Lerp function with no luck Vector3.Lerp(startPoint.position, endPoint.position, mousePosition.x) I tried with y and z, all of it failed. And this way wouldn't work when i go to rotate the slider |
0 | Rotate bone on 1 axis to look at another object Unity 3D I'm new to game development and I'm trying to create a basic 3D Tower Defence game as my first project. I've created a basic turret in Blender and I'm now trying to rotate 2 different bones to make the turret follow the enemy. The first bone (which I have working) rotates the turret to face the direction of the enemy. The second which I can't get right needs to rotate the gun at the top of the turret to look down at the enemy. I need it to keep facing the same direction as the rest of the turret and don't want it to tilt to either side. So it needs to move on 1 axis only. I have tried various things, including examples from the Internet but I can't figure it out. So far I've managed to get it to look down at its base, up at the sky and spin like a wheel. Basically everything except where it's supposed to be looking. Here is the code I have at the moment if (enemiesInRange.Count gt 0) Rotate Platform This section works fine Transform platform transform.root.Find("Armature BaseBone PlatformBone") Quaternion targetRotation Final rotation (I.e. facing the enemy) Vector3 turretPosition platform.position Store the turrets current position turretPosition.y 0 0 the Y axis to stop the turret tilting up or down Vector3 targetPosition enemyManager.activeEnemies enemiesInRange 0 .transform.position targetRotation Quaternion.LookRotation(targetPosition turretPosition) float rotateSpeed 2.0f Time.deltaTime platform.transform.rotation Quaternion.Lerp(platform.transform.rotation, targetRotation, rotateSpeed) Rotate GunBox TO DO This part is not working Transform gunBox transform.root.FindChild("Armature BaseBone PlatformBone LowerArmBone UpperArmBone GunBoxBone") Vector3 gunBoxPosition gunBox.position float angle Vector3.Angle(gunBoxPosition, targetPosition) gunBox.RotateAround(gunBox.position, Vector3.left, angle) Debug.Log(angle) Here's a picture of the turret to give you an idea what I'm working with. You can see in the screenshot that the bone's default X rotation is roughly 50. Enemies walk through the trench around the turret. The PlatformBone rotates everything from the silver platform upwards. I also don't understand why the line below makes the turret rotate instead of tilting it. I would expect to rotate the turret around the Y axis to keep it flat on the floor and face another direction. Yet I seem to have to do the opposite (If I select the PlatformBone its Y axis is facing up as expected) turretPosition.y 0 0 the Y axis to stop the turret tilting up or down |
0 | Projector making the scene objects grey in Unity Everytime I enable my projector, it makes all the overlapping elements look entirely grey. The shadows also disapear. I tryed a couple of other shaders found on the internet but the issue still persists. |
0 | Show hide soft keyboard on demand I'm writing simple chat app using Unity. The problem with Unity's default implementation of soft keyboard visibility is that it hides itself when i'm clicking outside of keyboard panel. What i want is that keyboard stays always shown until i explicitly tells otherwise. For a couple of days i tried to find similar questions but none of them helped me. I have very little experience in "native" android development (i.e. Java). So far i managed to create simple native plugin for Unity. I tried to manually open keyboard with this code imm (InputMethodManager)context.getSystemService(Context.INPUT METHOD SERVICE) imm.toggleSoftInput(InputMethodManager.SHOW FORCED, InputMethodManager.HIDE IMPLICIT ONLY) The result was fine, except the keyboard had InputType set to TYPE CLASS NUMBER. For my app i needed TYPE CLASS TEXT. So i tried to research how to set InputType and stumbled on fact that this property can only be changed inside EditText object. As i'm writing my app in Unity, i had no way of finding my InputField's inside native code. So i tried to create EditText inside my native plugin. I followed the logic that if i create custom EditText, place it inside main layout and set visibility to NONE or make background transparent, then i can set focus to that element and be fine FrameLayout myLayout activity.findViewById(android.R.id.content) focusedText new EditText(context) focusedText.setFocusable(true) focusedText.setInputType(InputType.TYPE CLASS TEXT InputType.TYPE TEXT VARIATION NORMAL) myLayout.addView(focusedText) focusedText.setFocusableInTouchMode(true) focusedText.requestFocus() focusedText.setBackgroundColor(activity.getResources().getColor(android.R.color.transparent)) imm.showSoftInput(focusedText, InputMethodManager.SHOW FORCED) The end result was a mess. Soft keyboard behaviour became undesirable. In order for keyboard to show, i first needed to select InputField, then i would see transparent EditText be created in the middle of my layout with all input characters visible. Even if all worked fine, it still looks like a wacky hack. Does anyone stumbled across similar issues? |
0 | Unity Graphics.DrawMesh lags behind rotation? I have a setup in unity using Graphics.DrawMesh() to draw a mesh on my players camera location in the update loop, Graphics.DrawMesh(viewModel, matrix, material, layer, null, 0) matrix Matrix4x4.TRS(cam.transform.position, cam.transform.rotation, scaleFps) when I use my mouse to move around the camera, it lags behind where the camera is, as can be seen in the video. I have no idea how to fix this. I've tried not using the matrix, and it doesn't change anything. https youtu.be eWFFYcOX 4Q Here's the script I use for moving the camera Get the current mouse input. yaw Input.GetAxis("Mouse X") mouseSensitivity pitch Input.GetAxis("Mouse Y") mouseSensitivity Clamp the camera rotation. pitch Mathf.Clamp(pitch, maxLookAngle, maxLookAngle) Calculate and rotate the camera. currentRotation Vector3.SmoothDamp(currentRotation, new Vector3(pitch, yaw), ref rotationSmoothVelocity, mouseSmoothScale) Rotating the player. Vector3 bodyRotation new Vector3(0, currentRotation.y, 0) transform.localEulerAngles bodyRotation Rotating the camera. Vector3 cameraRotation new Vector3(currentRotation.x, 0, currentRotation.z) playerCamera.transform.localEulerAngles cameraRotation ' |
0 | Can we measure the distance between and AR marker and camera? I'm in the middle of developing a game in Augmented Reality using Unity and ARToolkit plugin. I wanted to measure the approximate distance between the AR marker and the position of camera. Can anyone help me with a solution to this problem? Thanks in advance. |
0 | How can I display a 3d object and my player on a canvas? The main goal is to animate my player with animator on a canvas. The problem is that any 3d object (my player, a cube) I drag over the canvas is transparent not seen. The main camera is set to Clear Flags Depth Only and Culling Mask to Everything. The Main Menu Canvas is set render mode to Screen Space Camera and I selected the main camera. The Main Menu Background Material is set to New Material I created and on the new material I added a shader I created that make this image to be blur. The main camera settings screenshot And the Canvas settings And the Main Menu Background settings You can see in all the screenshots in the scene view top left that my player and the cube both are transparent on the canvas. Now if I change the Main Camera Clear Flags to SkyBox then I see my player and the cube but also they are not looking like they should be with the texture materials and also I don't want the Main Camera to be the clear flags on SkyBox I want the objects to be over the blur image so the Main Camera should be clear flags depth only. The main goal again is to put my player on the canvas with the blur image and animate my player. This is for my main menu. The canvas that will display the player if the player will be on his own canvas should be transparent and only display the player so the canvas will not overlap the other cnavas with the blur image. I want to animate using animator the player not only to display it as static object. This is a screenshot of what I mean I used paint to cut my player and put it on but the player canvas should be transparent or without a canvas the player should be on like the ui button on the left Another screenshot. On the top it's the scene view window the player the ui button and the blur image. On the bottom the game view window the ui button is on the blur image. I want the player to be the same as the ui button on the blur image and then to animate the player. Not like in my other screenshot the player should not have a skybox background or something it should be like the ui button on the blur image |
0 | How can I get a raycast to hit navmesh only? In Unity, I'm trying to get the raycast to hit the navmesh only, but I cannot find an option to place navmesh on a specific layer. Is there a way to raycast to the navmesh itself? |
0 | Instantiate player prefab using player data When my scene loads, I want to add my prefab to it along with its components. Here is what I mean scene loads player gender is determined via playerprefs or playfab sdk player prefab is loaded and displayed using said gender The prefab would have a script components attached for the current data etc. I might be approaching this wrong, but I want this to work with multiplayer in the future, so that's why I didn't just add the prefab directly to the hierarchy. What is the correct way of doing this? |
0 | How can I prevent a latitude longitude based chunk system from Mercator projection stretching? I'm working on an little mapbox based game and I'm currently working on an latitude longitude based chunk system. The distance between each of them should be the same. As you can see in the example the width and height of each chunk are equal. The little grey square is just the chunk middle. Those chunks were created near latitude longitude zero, where they aren't effected by the Mercator projection. But due to the Mercator projection the distances between the chunks are increasing as more as they move away from the middle (they look kinda stretched). As you can see the distances between each one aren't equal anymore. The height of each of those chunks did increase. Here's another picture of the Mercator projection to visualize what I mean The chunks of the first picture were created near the middle of the word map (where the big black upper arrow points towards). The chunks from the second pictures were created near the bottom of the world map, where the other arrow points towards. The type of game I'm developing requires equal chunk sizes and also it doesn't look that good when at some point the chunks look different due to the stretching. I want to achieve a chunk system like this on the mercator projection I calculate the chunks as follows First we need the player latitude longitude coordinates 3.0146683, 5.3046076 One latitude is about 110.57 km gt 110570 meters. One longitude is about 111.32 km gt 111320 meters. One chunk should be about 750 meters on the map. Because latitude and longitude got different ranges we need to adjust the chunk size. One latitude factor 110570 750 147,43. One longitude factor 111320 750 148,42. One latitude chunk size 110570 147 750 meters. One longitude chunk size 111320 148,42 750 meters. (Maybe this step is unnecessary) Now we convert the Lat Lng to meters. Latitude in Meter 3.0146683 110570 meters 333 331.873931 Meters. Longitude in Meter 5.3046076 111320 meters 590 508.918032 Meters. Now we need to calculate the meters till the last chunk by using modulo. Latitude Modulo gt 333 331.873931 modulo 750 331 meter. Longitude Modulo gt 590 508.918032 modulo 750 258 meter. After that we are able to calculate the Latitude and Longitude chunks. Latitude chunk position 333 331.873931 331 333 000.873931. Longitude chunk position 590 508.918032 258 590 250.918032. When we didive that now through the chunk size we get the actual chunk position. Chunk X 333 000.873931 750 444,0011. Chunk Y 590 250.918032 750 787,001. Rounded Chunk X 444 Chunk Y 787. Now we know that the player stands right in this chunk 444 787 . In the next step I just calculate the Chunk X and Y back to latitude and longitude and convert them via transform.AsUnityPosition to 3D coordinates, where I place those grey objects then. So basically I need a way to have the same visual distance between each of those chunks. Or either a way to change the projection from Mercator to a square projection, where nothing is stretched. I never worked with mapbox Google Maps before... so I'm a newbie. Or is there maybe a formula I can use to prevent my chunks from being stretched by the projection? Thanks for your time and attention! ) |
0 | Unity inconsistent memory profiling when running same scene I'm in the making of a 2D silhouette style game where I'm trying basically 2 setups One where it consists only of sprites, One where it consists of a mix of sprites and meshes with NO texture. Now, I'm experimenting with the two as I wish to want the scenes to take up the least memory. I have these weird outcomes SPRITE SETUP Total 280 MB, Textures 155.5 MB, Meshes 1.7 MB Total 249 MB, Textures 151 MB, Meshes 4.1 MB Total 279 MB, Textures 151.0 MB, Meshes 10.8 MB SPRITE amp MESH SETUP Total 334.4 MB, Textures 188.2 MB, Meshes 1.8 MB Total 241 MB, Textures 148,0 MB, Meshes 2,3 MB Total 253.1 MB, Textures 157.7 MB, Meshes 4.2 MB Total 301.8 MB, Textures 157.7 MB, Meshes 8.4 MB Total 234.8 MB, Textures 145.3 MB, Meshes 1.9 MB Now, I find these result strange because It was checked on the exact same scene (the mesh setup had same amount of objects, just swapped the sprites for meshes) and the data is inconsistent, meaning there is about 100MB difference between the same mesh scene A scene of mostly mesh with zero textures uses more, or at least not less, textures than a sprite only scene?? By taking a look at the data above, I would require someone skilled to guide me through this. Shall I keep using those meshes or just go for sprites? What is really goind on here with this data? |
0 | Importing audiofile into Unity3d gets shown after ending playmode I am working on a game where the user has the possibility to import custom audio tracks that can be listened to during the game. For this I am making use of System.IO.File.Copy method. This works, there are no issues or flaws here. When I inspect the target and destination folder the file(s) get copied properly and show up in the folder. The issue however is that the Unity Editor doesn't show the file despite it actually being there. During play mode in the Unity editor the new file isn't shown in the resources folder (which I use as destination for now). When I use windows file explorer I can clearly see the file in the corresponding folder. Using debugs (in Unity) also state that the folder is empty, however when I use debugs outside of Unity it shows that the folder contains the copied item. Keep in mind that these both debugs are called roughly at the same time. I have tested this in many ways to be 100 certain that Unity doesn't see the file, while it is there. So once I stop playmode it starts loading importing processing the new file and then it shows up in the folder in unity as well. When I launch playmode after this the file is indeed loaded and included in the game as well. I however need this to happen without having to stop playmode. So there is probably some type of processing that I haven't called for Unity to process the addition of the new file and for it to be visible. So in a nutshell basically copying a file from folder to folder isn't enough for Unity to directly utilized in the same play session (and all after). How can I make the audio file directly showable and accessable? There aren't any errors or warnings. The file plays correctly after it has been processed. I am at a loss with this issue bug. |
0 | Using a Wii remote as main controller? I would like to use a Wii remote to control my player in my 3D game. So far I have the arrow keys and mouse to move and look but I want the Wii d pad to move and accelerometer data to look around. I have downloaded Unity Wiimote 1.1 and the demo works fine. In my game I have imported the Unity package for the Wii remote but I'm not sure what script goes where, attached to what, how to call particular functions. They are mostly C scripts. There is no documentation with the Unity Wiimote 1.1 and as I'm a newbie, I'm clueless on what to do. Or is there a simpler method to getting the Wii remote to be the main controller? |
0 | object reference not set to an instance of an object hello i have a error "object reference not set to an instance of an object" when my ball collide with the spikes.its supose to remove one heart but it doesnt. health code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class Health MonoBehaviour public int health public int numOfHearts public Image hearts public Sprite fullHeart Use this for initialization void Start () Update is called once per frame void Update () if (health gt numOfHearts) health numOfHearts for (int i 0 i lt hearts.Length i ) if (i lt health) hearts i .sprite fullHeart if (i lt numOfHearts) hearts i .enabled true else hearts i .enabled false public void Damage(int dmg) numOfHearts dmg spikes code using System.Collections using System.Collections.Generic using UnityEngine public class Spikes MonoBehaviour private Health Player Use this for initialization void Start () Player GameObject.FindGameObjectWithTag("Player").GetComponent lt Health gt () Update is called once per frame void Update () void OnTriggerEnter2D(Collider2D col) if (col.CompareTag("Player")) Player.Damage(1) here i have the error. |
0 | Unity LWRP Sprite Renderer Sorting incorrectly after upgrading I'm making a project where every tile is a sprite renderer, this would work fine in the old unity system (from the fact that it used it until recently), but upgrading to the LWRP broke the sorting of the sprite renderers. Previously, I didn't have to change the order at all, but now they phase in and out of each other based on the position of the camera, like the picture shown below. They all use LWRP 2d Sprite Lit Default, as any other of the LWRP materials do not use the texture from the sprite renderer and instead make it all black. I do not want to use sorting layers because I have meshes sprinkled in, and what i have seen there is no way to control if the mesh is on anything but order 0, besides some hacky way. Even using a box mesh it gets cut off when the floor is closer to the camera. Here is what it looks like far away, the floor should be there the entire time and not have the darkness of the walls seeping down into them. I don't think I can use mesh renderers either, as I want a way to control the texture from each individual object, and share a material through all of them. I think if I used a mesh renderer I would have to use a material for each different tile, and I would not be able to tile them like I am doing now. |
0 | How can I reduce Unity's package size? I've been experimenting with Unity3D 4.3's 2D features. I've created a simple prototype game to learn how Unity works, how to create sprite animations, collisions and all the basic things. My project compiled for PC was approximately 23MB. The game includes one larger bitmap for a background (originally 1MB JPEG). The player spritesheet was black and white with almost no details. So all the assets had (in their original, compressed form) no more than 2 3 MB. I ended up with one large executable file (about 10MB) and a folder with .dll files and assets (5 6MB). Can that be reduced? My experience with C WinForms code makes me believe that executables and DLLs grow that big only when binary data was involved (images, sound, etc). Is that the case with Unity? I am interested in developing 2D applications for Android and iOS, where low total app size is a priority. |
0 | Referencing a Text in Unity Error I am working on trying to add a coin system to my game. I have it setup right now so that when the player hits a coin the score text goes up by 1. I have setup a reference in the script, which is attached to the coin, to the score text in my scene. In the game the player can click a button that will switch between two lanes to avoid enemies. These lanes are infinte and in these lanes is where I put the coins. And when a new lane is created the reference to the text disappears from the coin and teh tect does not change. I am not sure why the reference is disappearing. Here is the coin script that is on the coin public int scoreToGive 1 public Text coinText void OnTriggerEnter2D(Collider2D other) if(other.gameObject.tag "Player") AddScore() public void AddScore() TheScore.theScore if(coinText ! null) coinText.text TheScore.theScore.ToString() Destroy(gameObject) void Update() coinText.text GameObject.FindGameObjectWithTag("Ui").ToString() Thanks to anyone who can help! |
0 | Client not executing commands in Unet Edit Okay, so I partially solved the problem by adding a rigid body component to the capsule. I read somewhere that apparently you have to have one in order to move on the server. Problem 2 The next problem I have is that I can now move a capsule that is spawned by the client fine and the host can move it as well as many times as they like. The problem I am getting now is that when the host spawns a capsule the client cannot move it at all and I get a sort of glitch effect on the client side and the capsule still doesn't move on the host side. Is there a reason why it would only work one way and not the other way around? I thought at first it might have to do with Spawn vs SpawnWithClientAuthority but that doesn't seem to make a difference. Project Summary I have a pretty simple multiplayer project, all I want to do is have one player host and the other join as a client. Once they are joined together the two players can spawn a capsule and then when the user clicks on a capsule. They should be able to pick it up and move it around the scene and the other player should be able to see this action. I can get both players to connect to the server and spawn their own capsule and both players can see this. The movement script is done as well. However, it is only transmitted on the host side. When the client picks up the object it does not update on the server. Problem I have done a bit of debugging and have found that when I call the command on the client it is not being executed at all through line breaks and simple debug statements. Code public void OnInputClicked(InputClickedEventData eventData) Debug.Log("clicked") if (isLocalPlayer) if (Physics.Raycast(transform.position, direction transform.forward, hitInfo out hit, maxDistance range)) Debug.Log("Hit capsule") objectID GameObject.Find(hit.transform.name) objNetId objectID.GetComponent lt NetworkIdentity gt () playerIDThatClicked player.GetComponent lt NetworkIdentity gt () CmdAssignAuthority(objNetId, playerIDThatClicked) Debug.Log("grabbed") else if we are releasing the object we want to unassign our authority if (objNetId ! null) CmdAssignAuthority(objNetId, playerIDThatClicked) objNetId null Debug.Log("released") Command void CmdAssignAuthority(NetworkIdentity target, NetworkIdentity player) Debug.Log("inside cmd") current target.clientAuthorityOwner playerconn player.connectionToClient if (current ! null amp amp current ! playerconn) Debug.Log("Had authority now removing and replacing") target.RemoveClientAuthority(current) target.AssignClientAuthority(playerconn) else if (current ! null) Debug.Log("removing authority") target.RemoveClientAuthority(current) else if (current null) Debug.Log("No authority, adding one now") target.AssignClientAuthority(playerconn) else Debug.Log("CmdAuthority error") target.RemoveClientAuthority(playerconn) Question Am I calling this command correctly? The script is attached to a player prefab and the capsule prefab contains a network id and a network transform. I am pretty new to Unet and this feels like a noob mistake. |
0 | Unity Proximity Warning System Trigger issues I'm trying to set up a proximity warning system but I'm having some trouble. To simplify things as much as possible I have two game objects in a scene (Object1 and Object2). Object1 has a large child object (twice as large as Object1 or Object2) which has no mesh renderer, but has a box collider (with the Is Trigger box ticked). Object 2 has a rigidbody component. When Object1 gets close enough that it's child's Box Collider overlaps with Object2's rigidbody, a script on Object1 should Debug.Log the name of the object it's close to once a frame until Object1 moves away. My code is as follows public Collider objectCollidedWith void OnTriggerStay(Collider other) objectCollidedWith other.transform.GetComponent lt Collider gt () void Update() Debug.Log(objectCollidedWith) Unfortunately, something about my setup isn't working. The console just shows "null" once a frame and the objects getting close doesn't change this. Can you tell me what I'm doing wrong? Many thanks for your time. |
0 | Why does duplicating my object cause its vertex animation shader to distort it? I used a vertex shader (based on this example) to animate a flag waving. When I have a single flag in my scene, it works correctly. When I duplicate the flag, all of the copies become wildly distorted after I hit play. Here is the shader code I'm using Shader "Custom Flag" Properties MainTex ("Albedo (RGB)", 2D) "white" Speed ("Speed", Range(0, 5.0)) 1 Frequency ("Frequency", Range(0, 1.3)) 1 Amplitude ("Amplitude", Range(0, 5.0)) 1 SubShader Tags "RenderType" "Opaque" Cull off Pass CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" sampler2D MainTex float4 MainTex ST struct v2f float4 pos SV POSITION float2 uv TEXCOORD0 float Speed float Frequency float Amplitude v2f vert(appdata base v) v2f o v.vertex.y cos((v.vertex.x Time.y Speed) Frequency) Amplitude (v.vertex.x 5) o.pos mul(UNITY MATRIX MVP, v.vertex) o.uv TRANSFORM TEX(v.texcoord, MainTex) return o fixed4 frag(v2f i) SV Target return tex2D( MainTex, i.uv) ENDCG FallBack "Diffuse" How can I make this work with multiple flags using the same material? Should I use a new material instance for each object like this? It doesn't seem optimal material new Material (Shader) Create new material material.SetFloat (" Speed", Speed) material.SetFloat (" Frequency", Frequency) material.SetFloat (" Amplitude", Amplitude) material.SetTexture (" MainTex", MainTex) flagObj.GetComponent lt MeshRenderer gt ().sharedMaterial material Set values |
0 | Camera relative movement is pushing into off the ground instead of parallel I'm building upon roll a ball tutorial in unity, and I have managed to rotate the camera around the ball just fine with the code below. But there's one problem. In this code, when I add force to the ball, with W for example, the force will be added in the exact direction the camera is looking at the ball, meaning pushing the ball onto the ground, increasing friction and lowering speed. And if I press S the force will push the ball to the air, lowering friction and making the ball move fast. So my question is, how can I achieve rotation without this issue? Code for Camera (CameraController) public GameObject Player private Vector3 offset public float cameraSpeed private Vector3 point static public Vector3 finalMovement void Start () offset transform.position Player.transform.position point Player.transform.position transform.LookAt(point) void LateUpdate() point Player.transform.position offset Quaternion.AngleAxis(Input.GetAxis("Mouse X") cameraSpeed, Vector3.up) offset transform.position point offset transform.LookAt(point) Vector3 movement void FixedUpdate() movement new Vector3() float moveHorizontal Input.GetAxis("Horizontal") float moveVertical Input.GetAxis("Vertical") movement new Vector3(moveHorizontal, 0f, moveVertical) finalMovement GetComponent lt Camera gt ().transform.TransformDirection(movement) Code for ball public float speed void FixedUpdate() rb.AddForce((CameraController.finalMovement) speed) |
0 | 1 kb swf file created when building to flash in unity I am trying to build a project in flash that I have made. It goes through its building process, but when it is done the swf file that it creates is 1 kb in size. I am not sure what I am doing wrong or what is going on. I have built to flash before and never ran into this problem until recently. |
0 | Particle system on sphere surface I would like that particle system travels only on sphere surface. I have set sphere and particle system as it's child. How to constraint particle system ? How to make trails follow along sphere surface? On sphere it would look something like this with trails without trails |
0 | Issues with 3dsmax and Unity3d scale I changed the units in Blender so they are identical to Unity 3d. If I make a 1m 3 box in Blender, it will import into unity as exactly the same size as the standard cube. With 3ds max, I changed the unit setup to metric and made sure it was centimeters in the system unit setup tab. However, when I import an obj file made in Blender and used in Unity, it is absolutely tiny. I have to convert the model to meters on import and then, when exporting, I have to set the model scale to .01 otherwise it is enormous in the unity scene. I've tried changing the max units to meters and nothing changed. How do you change the max unit grid setup so one grid unit is 1m 2 and exactly equivalent to unity's grid? |
0 | How to share Unity High Scores on social media (Facebook , Google and Twitter)? This may be a common question but as a n00b I have some confusion on achieving this . I am on a small game project and I want the user to share his her scores on social media after completing the game . When they post , it should be something like "Hurrayyyy ! I Scored 12345 on My Game App Name , Can you beat my score ? Try it ." where ' My Game App Name ' and 'Try it' should be a link directing to Google Play Windows Store etc . My Idea is like this Here Share This on Facebook , Share This on Google and Share This on Twitter are 3 UI Images with Button component attached to them . So when the player clicks on those buttons , they should post on social media . So how to achieve this ? I got something here , but I don't know how to use that . I will prefer not to use Facebook Unity Plugin . So can I achieve this ? I need code in c , not in JavaScript ) I hope you will help me to figure this out . Regards , NB ) |
0 | Raycasting against my plane does not detect collisions in Unity I'm trying to keep the camera above a plane which acts as the ground, so I wrote this bit of code RaycastHit hit if (!Physics.Raycast (transform.position, new Vector3 (0, 50, 0), out hit, 5)) transform.position new Vector3 (0, 20, 0) Debug.Log ("No ground found when raycasting down!") Debug.DrawRay (transform.position, new Vector3 (0, 50, 0), Color.red, 0, true) else if (hit.distance lt 1) transform.position new Vector3 (transform.position.x, 1, transform.position.z) The camera is clearly over the plane on position 0, 20, 0 while the plane is at 1, 1, 1, with scale 50, 1, 50, but it never detects a hit. The ray drawn by DrawRay() does intersect the plane. The plane is oriented upwards, but just to be sure I tried raycasting from below as well, without success. I have also tried replacing the mesh collider with a box collider using size 10, 1, 10 (I'm not sure why, this seems to be the same size as my scaled plane) and 10, 10, 10. Neither worked. What Am I missing? |
0 | Enemy shake vibrate when following character I am using the arongranberg A path finding project to create way points for one enemy to follow the player. However, the enemy vibrates back and forward by about 0.1 0.2 unit distance when moving. I have done a lot of research regarding this problem in the past few days but to no avail I could not find a solution that solves it. This is link to a gif to show what I mean. I have tried, changing Application.targetFrameRate 30 changing fixed update to update and vice versa using rigidbody2d and turn interpolate on plus using velocity to move turning iskinematic on and off using translate to move. none of the above solution works. Below is the script I have for my enemy. Any advice would be appreciated. using UnityEngine using System.Collections Note this line, if it is left out, the script won't know that the class 'Path' exists and it will throw compiler errors This line should always be present at the top of scripts which use pathfinding using Pathfinding public class AstarAI MonoBehaviour The point to move to public Transform target private Seeker seeker The calculated path public Path path The AI's speed per second public float speed 200 The max distance from the AI to a waypoint for it to continue to the next waypoint public float nextWaypointDistance 0.02f The waypoint we are currently moving towards private int currentWaypoint 0 Rigidbody2D rb public void Start () rb this.GetComponent lt Rigidbody2D gt () seeker GetComponent lt Seeker gt () Start a new path to the targetPosition, return the result to the OnPathComplete function seeker.StartPath( transform.position, target.position, OnPathComplete ) public void GoToNewTarget(Transform newTarget) path null currentWaypoint 0 nextWaypointDistance 0.02f target newTarget seeker GetComponent lt Seeker gt () seeker.StartPath( transform.position, target.position, OnPathComplete ) public void OnPathComplete ( Path p ) Debug.Log( "Yay, we got a path back. Did it have an error? " p.error ) if (!p.error) path p Reset the waypoint counter currentWaypoint 0 public void Update () if (path null) We have no path to move after yet return if (currentWaypoint gt path.vectorPath.Count) Debug.Log( "End Of Path Reached" ) return this.GetComponent lt Rigidbody2D gt ().MovePosition (path.vectorPath currentWaypoint ) Debug.Log (path.vectorPath currentWaypoint ) Direction to the next waypoint Vector3 dir ( path.vectorPath currentWaypoint transform.position ).normalized GetComponent lt Rigidbody2D gt ().velocity new Vector2 (dir.x 3, dir.y 3) Vector3.MoveTowards(transform.position, path.vectorPath currentWaypoint , 2 Time.fixedDeltaTime) dir speed Time.deltaTime rb.velocity dir this.gameObject.transform.Translate( dir ) Check if we are close enough to the next waypoint If we are, proceed to follow the next waypoint if (Vector3.Distance (transform.position, path.vectorPath currentWaypoint ) lt nextWaypointDistance) currentWaypoint return |
0 | How can I add velocity to the standard CharacterController? I have FPS controller from standard asset. After a long trial and error I figured that CharacterController doesn't respond to AddForce. So, I have this trigger in the scene which I would like to throw FPS controller upwards. Now, I know that I need to replace AddForce with adding velocity to the player. How to do that? I need to use FPS controller component for velocity and add Vector3.up. So, every game object other which will enter the trigger, will get upwards velocity. void OnTriggerEnter(Collider other) other.attachedRigidbody.AddForce(Vector3.up 100, ForceMode.Impulse) |
0 | How to avoid movement speed stacking when multiple keys are pressed? I've started a new game which requires no mouse, thus leaving the movement up to the keyboard. I have tried to incorporate 8 directions up, left, right, up right and so on. However when I press more than one arrow key, the movement speed stacks (http gfycat.com CircularBewitchedBarebirdbat). How could I counteract this? Here is relevant part of my code var speed int 5 function Update () if (Input.GetKey(KeyCode.UpArrow)) transform.Translate(Vector3.forward speed Time.deltaTime) else if (Input.GetKey(KeyCode.UpArrow) amp amp Input.GetKey(KeyCode.RightArrow)) transform.Translate(Vector3.forward speed Time.deltaTime) else if (Input.GetKey(KeyCode.UpArrow) amp amp Input.GetKey(KeyCode.LeftArrow)) transform.rotation Quaternion.AngleAxis(315, Vector3.up) if (Input.GetKey(KeyCode.DownArrow)) transform.Translate(Vector3.forward speed Time.deltaTime) |
0 | Camera to the right from the character I'm trying to create a camera like in Fortnite or Gears of War. It's focus must be to the right side from the character But when I rotate the camera, the character slightly shivers. Lerping and multiplying by Time.deltatTime doesn't help. This is my code using UnityEngine RequireComponent(typeof(Camera)) public class ThirdPersonCamera MonoBehaviour Header("Sensitivity") SerializeField private float xSensitivity SerializeField private float ySensitivity Header("Limit angles") SerializeField private float upLimit SerializeField private float downLimit Header("Positioning") SerializeField private Vector3 offset SerializeField private float maxDistanceFromPlayer SerializeField private Transform player private float rotationAboutX private float rotationAboutY Start is called before the first frame update void Start() rotationAboutX transform.localEulerAngles.x rotationAboutY transform.localEulerAngles.y void Update() rotationAboutX Input.GetAxis("Mouse Y") ySensitivity rotationAboutY Input.GetAxis("Mouse X") xSensitivity rotationAboutX Mathf.Clamp(rotationAboutX, downLimit, upLimit) Adjust camera position. void LateUpdate() Vector3 direction new Vector3(0.0f, 0.0f, maxDistanceFromPlayer) Quaternion rotation Quaternion.Euler(rotationAboutX, rotationAboutY, 0) Point to look at in the runitme. Vector3 focus player.position transform.TransformDirection(offset) Rotate vector according to mouse inputs. transform.position focus rotation direction transform.LookAt(focus) It shivers only if offset is not zero. Otherwise it's ok. |
0 | Problems with gravity and box colliders in Unity 3D I have a game character that can jump or roll in order to avoid obstacles. He is able to roll while on the ground and he can also roll while he is in the air after jumping. Everything was working fine when I made him roll. I want to make it so that when he rolls while he's in the air after jumping, he would fall at a faster pace than if he was just falling normally. So I did this in my c script IEnumerator IncGravAcc() Physics.gravity new Vector3(0, 50f, 0) yield return new WaitForSeconds(2f) Physics.gravity new Vector3(0, 9.8f, 0) I call this coroutine in the function that runs when the down arrow is clicked. Everything is working fine. When he rolls while in the air, he falls at a faster than normal rate. However he doesn't land properly and he just falls right through the platform like it's not even there. Here's a video to show what I mean https youtu.be sirc4L3MnqM I have a box collider, not set to isTrigger, on the player (you can see it, the green box, right underneath him in the video) and the player's also a rigidbody. The platforms don't have rigidbodies on them but they do have box colliders set to trigger. You can see the platform's box collider in the relation to player's box collider in the picture provided (the platform's box collider is the larger one of course) How do I get it so that the character doesn't fall through? Please let me know if there's anything else you need to know about the project. Thank you for helping me! |
0 | Is it possible to load asset bundle dependencies manually in Unity 5.0? Is it possible to tell Unity to not load asset bundle dependencies automatically so they can be loaded manually. If so, how can this be done? |
0 | Creating an object in javascript with unity (unityscript) So I have a ton of experience with JavaScript (its what I do for a living) but I am new to unity. I have built a game engine in javascript but now want to move it over to unity. I have been trying to implement my player class but am running into this error. I have a getter function for my level up stats. and inside of my level up function I call that getter function and store it now I know this would work in normal javascript but its not in unity and I have having a heck of a time googling any information on objects in unityscript. Here is the relevant code function level getter() return base level exp float , lvl exp modifier float , current level int function level up() var level object new Object() level object level getter() level object.current level 1 level object.base level exp level object.base level exp level object.lvl exp modifier level setter(level object.base level exp, level object.lvl exp modifier, level object.current level) I guess my first question is, is it even valid to return an object like that in unityscript?(in the level getter() function). If its not valid what do people suggest I do instead. Set a getter function for each var? My second is how do I declare level object so that it can accept the return if it is valid, and so that I can access the members of the object. I have been looking around at tutorials and google for several hours now and have found nothing to clear up my confusion over objects in unityscript. So any help would be appreciated. |
0 | pre load new scene in unity async but don't show it I have a top down dungeon crawler in 3D where I show one room at a time. Each room is it's own unity scene. Each room has an exit point that when clicked I fade the screen, load a new scene and then fade in the screen. What I'd like to do, but not sure how, is to pre load the next possible scenes (note the S, there will be 2 but could be more. 2 because it's the next room or the previous if the player decides to go back) while in one scene. I know the scenes that are possible to get to, but how can I pre load but not show them and because there is more than 2, I assume if they go in one direction, there is a pre loaded one that I need to unload. Overall I want to do this to make a faster smoother transition between rooms, but I want the one room at a time for artistic style. |
0 | Unity build does not launch and leaves no logs errors I have released my first title Audio Infection ( https store.steampowered.com app 911580 Audio Infection ) for a bit over a year ago. Recently 1 user has so far encountered an issue where the game does not launch. He is the only user that encounters this problem. He has this issue on both Win 7 and Win 10. His system specs are fine and his drivers are up to date. The game does not leave a log file, rather it looks like it is unable to boot. There are no Windows error reports on it either. I watched it through Discord screenshare because I could not properly understand his issue. I had asked a few other random people to test my game and demo (he has the issue with both, the demo and full version) however no one else (including me) is able to reproduce this behavior. At this point I have tried updating Unity from 2018 to 2019 (no change in behavior) added manual logging (with no results) updating drivers (on his system) installing Visual C (on his system) empty project with Unity sample scene (he was able to load the sample scene!) deleting crashhandler.exe (used to fix similar issue in the past based on older threads) modifying files deleting and downloading the files What else can I try in order to figure out what is causing the issue? I am honestly clueless. Since the sample project was able to boot on his system there is definitely something wrong with the build on my end. However he is the first person with this issue. It doesn't even get to the point of launching on his system and it can't be found in the memory either. It is almost as if Windows is blocking it from launching, however that is not the case. But the result is very similar to that. There is a free demo on the store page available in case you want to see if it boots on your system. It works for both VR and non VR systems. When no VR devices are detected all VR related contents are disabled. This has been thoroughly tested and worked on loads of different Windows systems with different specs, with VR and no VR. Once again, there are no errors, no logs, the build doesn't even make it to that point, yet that exact same build works for literally everyone else on various systems. I am absolutely clueless about what to do in order to resolve this issue. Any help advice or pointers towards the right direction are greatly appreciated! PS he is not a troll, I have known this guy for a long time now and he genuinely wants to support me. |
0 | FindObjectsOfType returns null array I am making the game in this tutorial https www.youtube.com watch?v OR0e 1UBEOU and at 2 53 23 he is coding a LevelController script. I noticed that mine wasn't working the way his was and so I went to try and debug the error. I found that the error was in the function FindObjectsOfType() You can find my code below. using System.Collections using System.Collections.Generic using UnityEngine public class LevelController MonoBehaviour private Enemy enemies private void onEnable() enemies FindObjectsOfType lt Enemy gt () Update is called once per frame void Update() Debug.Log( enemies) When I run this my debug log returns null values which is confusing because I have 3 objects (Monster, Monster (1) and Monster (2)) which have the Enemy script assigned to them. What could be going wrong? |
0 | How can I roll up a plane with a vertex shader? I have plane that I want to roll up using a vertex shader, like this I found a math demo that shows the kind of curve I want my mesh to follow. I tried implementing this in my shader code, but the results don't form a roll as expected Shader " Custom Rolling " Properties MainTex ("Base (RGB)", 2D) "white" Bend("Bend",Float) 1 Strength("Strength",Float) 1 SubShader Tags "Queue" "Geometry" "IgnoreProjector" "true" "RenderType" "Opaque" Cull Off Pass CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" struct v2f half2 texcoord TEXCOORD0 float4 vertex SV POSITION sampler2D MainTex float Bend float Strength v2f vert(appdata full v) v2f o I don't know what should I write here for rolling ,please help me. v.vertex.y ??? v.vertex.y exp( Bend (v.vertex.x Strength)) something like this but this hasn't twist effect o.vertex UnityObjectToClipPos(v.vertex) o.texcoord v.texcoord return o float4 frag (v2f i) COLOR float2 uv i.texcoord.xy float4 tex tex2D( MainTex, uv) return tex ENDCG Fallback Off Instead of a neat roll, the end of my plane shoots up into the sky! |
0 | objects are keep falling I added some screenshots above. When I run the game obstacle are falling rapidly through y axis. So, there's no more obstacle in that ground. If there's ground than those obstacle should stopped. I tried by freezing them. But, when another object hit them they are froze. So, I want ground to stop them. I have another question also. I have player movement. When I will run the program. The Player should be go through z axis. But, The object(player) don't move. PlayerMovement.cs using UnityEngine public class PlayerMovement MonoBehaviour public Rigidbody rb public float forwardForce 2000f void FixedUpdate() rb.AddForce(0,0,forwardForce Time.deltaTime) if(Input.GetKey( quot d quot )) rb.AddForce(30 Time.deltaTime,0,0, ForceMode.VelocityChange) else if(Input.GetKey( quot a quot )) rb.AddForce( 30 Time.deltaTime,0,0, ForceMode.VelocityChange) if(!Input.touchSupported) Still support PC keys if(Input.GetKey(KeyCode.D)) rb.AddForce(30 Time.deltaTime,0,0, ForceMode.VelocityChange) else if(Input.GetKey(KeyCode.A)) rb.AddForce( 30 Time.deltaTime,0,0, ForceMode.VelocityChange) else For touch devices if(Input.touchCount 1) var touch Input.GetTouch(0) var touchPos touch.position var isRight touchPos.x gt Screen.width 2f if(isRight) rb.AddForce(30 Time.deltaTime,0,0, ForceMode.VelocityChange) else rb.AddForce( 30 Time.deltaTime,0,0, ForceMode.VelocityChange) if(Physics.Raycast(transform.position,Vector3.down,0.5f) false) rb.velocity new Vector3(0, rb.velocity.y, 0) rb.constraints RigidbodyConstraints.FreezePositionZ else rb.constraints RigidbodyConstraints.None if(rb.position.y lt 1f) FindObjectOfType lt GameManager gt ().EndGame() PlayerCollision.cs using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class PlayerCollision MonoBehaviour public PlayerMovement movement void OnCollisionEnter(Collision collisionInfo) Debug.Log(collisionInfo.collider.name) if (collisionInfo.collider.tag quot obstacle quot ) movement.enabled false FindObjectOfType lt GameManager gt ().EndGame() else if(collisionInfo.collider.name quot END quot ) FindObjectOfType lt GameManager gt ().CompleteLevel() void Restart() SceneManager.LoadScene(SceneManager.GetActiveScene().name) If you look at above source code clearly. So, you might see that I have a Debug.Log right there. But, when I run the game. I don't get any message to console. As a new game developer(learning) I don't know what's happening, what's wrong with this. |
0 | Playing an animation all the way through with one quick keypress with Mechanim Unity I have an if statement inside of the Update function that is only called if three other conditions are met. The problem is that right now the function sets a boolean to true which causes the animation to play inside of unity Mechanim. This boolean is only true when I hold down the button, but I would like it to play the whole animation or keep this boolean true for a certain amount of time, thanks and here is my Code. Running and jumping animation if (Input.GetKey (KeyCode.W) amp amp (Input.GetKey (KeyCode.Space)) amp amp otherAnimation false) anim.SetBool ("isRunningAndJumping", true) else anim.SetBool ("isRunningAndJumping", false) |
0 | Unity frame rate drops stall I have an issue where my game suddenly stops for a second and then continues. And I think it has something to do with my performance so I took at look at the profiler I tried to take a screenshot as soon as the crack happened However, since I am a bit new to optimization could anyone give me a helping hand on what might be the problem here? |
0 | In Unity, is there a difference between Vector3.down and Vector3.up? I've noticed numerous tutorials and examples using something like "transform.up 1" or " Vector3.up" instead of simply saying "transform.down" and "Vector3.down". Is there a good reason for this, or is it simply a style difference? I'm specifically thinking about downward raycasts, if that matters at all. |
0 | When I shoot from a gun while walking, the bullet is off the center, but when stand still it's fine. (Video Included) I am making a small project in Unity, and whenever I walk with the gun and shoot at the same time, the bullets seem to curve and shoot off 2 3 CMs from the center. When I stand still this doesn't happen. This is my main Javascript code script RequireComponent(AudioSource) var projectile Rigidbody var speed 500 var ammo 30 var fireRate 0.1 private var nextFire 0.0 function Update() if(Input.GetButton ( quot Fire1 quot ) amp amp Time.time gt nextFire) if(ammo ! 0) nextFire Time.time fireRate var clone Instantiate(projectile, transform.position, transform.root.rotation) clone.velocity transform.TransformDirection(Vector3 (0, 0, speed)) ammo ammo 1 audio.Play() else I assume that these two lines need to be tweaked var clone Instantiate(projectile, transform.position, transform.root.rotation) clone.velocity transform.TransformDirection(Vector3 (0, 0, speed)) I just started Unity, and I might have a difficult time understanding some things. EDIT Here is a video http www.screenr.com 2pxH (If there are any more mistakes in my code, feel free to edit it.) |
0 | Creating multiple levels in Unity without duplicating scripts I'm trying to create a falling word typing game like z type. I have used the code provided here I want to create multiple levels in the game, and it seems like I need to make some changes in the code for each level. For example, in the word display file, I want the active word to be changed to red for level 1 and blue for level 2. So I created a copy of my level 1 scene, created a duplicate WordDisplay script file, changed the code for active word to blue.... public class WordDisplay MonoBehaviour public Text text public float fallSpeed 1f public void SetWord (string word) text.text word public void RemoveLetter () text.text text.text.Remove(0, 1) text.color Color.red ... Here's the duplicate script I made public class WordDisplay1 MonoBehaviour public Text text public float fallSpeed 1f public void SetWord (string word) text.text word public void RemoveLetter () text.text text.text.Remove(0, 1) text.color Color.blue ... Then I made a copy of the WordSpawner as well because I was getting an error I had to change the method's return type to to WordDisplay1 and then got one more error which was in the Word file, leading to more changes... public class WordSpawner MonoBehaviour public GameObject wordPrefab public Transform wordCanvas public WordDisplay SpawnWord() ... public class WordSpawner1 MonoBehaviour public GameObject wordPrefab public Transform wordCanvas public WordDisplay1 SpawnWord1() ... Then I created a duplicate of the word prefab and selected the appropriate word spawner file... All of this seems like too many changes for a simple colour. Is there a better way to have multiple levels without having to create a duplicate of all these files and the word prefab? |
0 | How do I properly change the value of a prefab'd instance variable? I am currently following a tutorial on how to make a 2D platformer in Unity. The tutorial explains how to make an enemy wave spawner, but it doesn't explain how to make enemies stronger after I have completed a certain amount of waves. So, to explain I have an Enemy class, which has an EnemyStats class in it public class Enemy MonoBehaviour System.Serializable public class EnemyStats public int damage 20 public int maxHealth 100 public int CurrentHealth get return currentHealth set currentHealth Mathf.Clamp(value, 0, maxHealth) private int currentHealth public void Init() CurrentHealth maxHealth public EnemyStats stats new EnemyStats() private StatusIndicator statusIndicator void Awake() stats.Init() statusIndicator transform.Find("StatusIndicator").GetComponent lt StatusIndicator gt () if (statusIndicator ! null) statusIndicator.SetHealth(stats.CurrentHealth, stats.maxHealth) And in the WaveSpawner class I have the method to spawn the enemy private void SpawnEnemy(Enemy enemy) Transform sp spawnPoints UnityEngine.Random.Range(0, spawnPoints.Length) if (CurrentWave 5 0) enemy.stats.maxHealth 20 Instantiate(enemy.transform, sp.position, sp.rotation) In the WaveSpawner you can set a certain number of waves (let's say 5), and after you complete all of the waves I've set them to repeat. So after I beat the 5 waves, I want the 5 waves to repeat and the enemies to be stronger (for example to have their max hp increased by 20). I do that with the line enemy.stats.maxHealth 20 But the problem here is that after this line is executed and I Instantiate the enemy prefab, the prefab changes its value in the inspector. So let's say that the initial value of the prefab was 120, after I beat the 5 enemy waves, the value of the prefab is set to 140. Then, after I reset the game, the initial value of the prefab is 140 and the max health of the first enemies is 140 and not 120. I have tried to not change the maxHealth variable of the EnemyStats class, but instead to have another variable tempMaxHealth and do the changes on it. This doesn't resolve my problem, as other problems arise and I don't know what to do anymore. I hope that you have an answer for me, I would be grateful if that's the case. |
0 | Unity how do I make an input only available to the code? I have a simple function attached to a button. I then decided to change it by adding an input. The problem is that the function won t run unless I specify the input in Unity via the inspector. I don t want to do that because it will affect the function and I have already changed it inside. I already set the input when I run the function so there s no need to set it again in Unity this is a problem because the input is going to be different depending on different scenarios. How can I overcome this? public void Eruption(string biome) if (biome sea ) do something |
0 | Framerate drop from 160 to 56 59 when upgrading Unity to 2020 I just updated to Unity 2020.2 from Unity 2019.4. I use Ubuntu 2020.10. Everything is super fast but the framerate is less than 60 FPS, precisely between 56 and 59 FPS, for all my Android project. With Unity 2019.4, it was more than 160 FPS. Even Unity Sample scene has this framerate. Is this bug on my laptop or a configuration set by Unity? How can I edit it to get my previous framerate? |
0 | How do I stop gyroscope controlled camera from jittering when holding phone still? I have here a simplified version of my gyro controlled camera with a sensitivity modification (a side effect of increasing sensitivity is that the jitteriness is exacerbated). public class GyroControl MonoBehaviour private Transform rawGyroRotation Vector3 gyroAdjust SerializeField private float smoothing 0.1f void Start() Input.gyro.enabled true Application.targetFrameRate 60 rawGyroRotation new GameObject( quot GyroRaw quot ).transform rawGyroRotation.position transform.position rawGyroRotation.rotation transform.rotation private void Update() rawGyroRotation.rotation Input.gyro.attitude gyroAdjust rawGyroRotation.rotation.eulerAngles 2 increase rotation sensitivity transform.rotation Quaternion.Euler(gyroAdjust) transform.rotation Quaternion.Slerp(transform.rotation, rawGyroRotation.rotation, smoothing) When in motion, the jittering isn't noticeable. But when you hold the phone still, there's what I assume to be just analogue noise that causes jittering. I would really appreciate any help or advice on how to add a filter or something to reduce the jittering for this kind of controller. Thanks. |
0 | Unity Build Failed Duplicate Class I'm here struggling for hours to build my game (android) and 'Execution failed for task checkReleaseDuplicateClasses' Duplicate class androidx.annotation.AnimatorRes found in modules androidx.annotation.annotation 1.0.0.jar (androidx.annotation.annotation 1.0.0.jar) and androidx.annotation.annotation 1.1.0.jar (androidx.annotation.annotation 1.1.0.jar) Duplicate class com.google.android.gms.auth.api.signin.zaa found in modules classes.jar ( com.google.android.gms.play services base 17.0.0 ) and classes.jar ( com.google.android.gms.play services base 17.1.0 ) ... are just two examples of the 486 warnings I'm getting. Can anyone help a noob out? Thanks so much for your time! |
0 | Instantiated object not tracking collision I have an issue, and I'm not sure why it's happening. I have a prefab that I've built in a colour changing game. It has the following Four 2D objects that if they collide with the player (2D collider attached to all), they cause the player to die. One 2D object that if the player strikes, it generates a duplicate of itself with the Instantiate function. All 2D objects are created The four objects that cause the player to die are being created as normal and continue to cause the player to die. However, the object that instantiates the prefab and increments the score can no longer be collided with. The player appears to pass behind it. I'm pasting my code below. I would really appreciate if anyone can offer advice on this void Update () if (Input.GetButtonDown("Jump") Input.GetMouseButtonDown(0)) thing.velocity Vector2.up bounciness scoreText.text score.ToString() private void OnTriggerEnter2D(Collider2D collision) if (collision.tag "plusScore") score Destroy(collision.gameObject) Instantiate(barrier, new Vector2(transform.position.x, transform.position.y 7f), transform.rotation) return if(collision.tag ! currentColour) Debug.Log("You DIED!") SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex) score 0 |
0 | How to properly create a handle for setting moving platform's target position in Unity? As the title suggests, I am trying to set up a handle for setting target position of a moving platform. I have an empty GameObject(targetPos) and this is what I want to use for setting target position of the moving platform. Here is the code I have for it so far but it does not seem to work correctly and I am not sure what is wrong. The problem is, the empty gameobject's transform is not using correct position for moving platform to go to. Not that I put the empty gameobject as the child of the moving platform. using System.Collections using System.Collections.Generic using UnityEngine public class MovePlatform MonoBehaviour public Transform targetPos private Vector3 initialPosition, targetPosition, targetPosDebug public float speed 3 public bool loop void Start() initialPosition transform.position SetTargetPosition(targetPos.position) void Update() transform.position Vector3.MoveTowards(transform.position, targetPosition, speed Time.deltaTime) if (transform.position targetPosition) if (loop) SwitchDirection() public void SwitchDirection() if (transform.position initialPosition) SetTargetPosition(targetPos.position) else targetPosition initialPosition private void SetTargetPosition(Vector3 localPosition) targetPosition initialPosition localPosition targetPosDebug targetPosition void OnDrawGizmos() if (Application.isPlaying) Debug.DrawLine(initialPosition, targetPosDebug, Color.red) else Debug.DrawRay(transform.position, targetPos.position, Color.red) Gizmos.DrawSphere(targetPos.position, 1.0f) |
0 | Storing stats for multiple tiers of upgrades on an item I have one script for all my weapons (I have 3 weapons in total) and each of these 3 weapons has 3 different tiers. I'm currently using a method to set the values, like this public void SetTier1Value() if (weapon1IsActive true) damage 6 fireRate 18 etc... if (weapon2IsActive true) damage 5 fireRate 20 etc... and like this for the rest of the weapons and tiers All the weapons and all the tiers will have the same variables, the only difference between them are the values of their stats. I know that the way that I'm doing stuff is over complicating a lot. I want to fix so in the future it's easier to add new weapons and the code in general isn't that bad to change. What I want from this script is to be able to change the values of the weapon easily by code. What ways can I do this? |
0 | Batch Combine multiple Graphics.DrawProcedural Calls in Unity I have multiple calls to Graphics.DrawProcedural in my Unity project. E.g. I'm drawing 1000 procedural geometries that share the same material and get their positions meshes from a ComputeBuffer. At some place in my code I'm doing something like this foreach(ProceduralGeometry pG in proceduralGeometries) pG.Draw() Where draw sets the Materials buffer accordingly and calls Graphics.DrawProcedural. Is there anything I can do to batch all these geometries together? Currently I perform over 1000 DrawCalls (seen in the frame inspector) which happen to be very expensive performancewise. Thanks in advance! |
0 | is mvc design pattern good for developing video games? how mvc design structure works in game development and specially in unity game development. I know what mvc is and how it works but in coding structure for game development specially in unity I don't know how it really works. as you may know is it a good structure for developing video games? if its a yes, why and how it should be used? thank you for helping |
0 | Unity how to put a target under a character's feet that follows ground model contours? In my current projects, one of the power ups needs to place a target marker centered on the position of the player triggering it the actual design for this is TBC, but will be a circle with a radius of 10 units. The ground for the playing arena is a model, and not flat. Assuming that I use a texture to show this target area, how can I have this texture render following the contours of the ground? Alternatively, any other approach to solving this would be appreciated. Thank! |
0 | unity3d AI terrain detection My goal is to have my animals walk around within a certain range. Everything works except for when it comes to the y axis. I can choose a position for it to walk and it will go there but I have no way of telling the height of the terrain at the selected point, or at the points all along the way. Im wondering how I can have my npc's always walk on the ground rather than walking through the ground. My code is here if it helps, but my problem is pretty straight forward. if(timer 0) Look at target myTransform.rotation Quaternion.Slerp (myTransform.rotation, Quaternion.LookRotation (walkToPosition myTransform.position), rotationSpeed Time.deltaTime) if(Vector3.Distance (walkToPosition, myTransform.position) gt 1) Move towards target myTransform.position myTransform.forward walkSpeed Time.deltaTime anim.CrossFade("walk") else walkToPosition.x Random.Range(initialSpawn.x walkDistance, initialSpawn.x walkDistance) walkToPosition.z Random.Range(initialSpawn.z walkDistance, initialSpawn.z walkDistance) timer walkCooldown anim.CrossFade("idle") Debug.Log (walkToPosition) EDIT I am doing this project in Unity3d. I do not need to know how to render this, all I am looking for is some kind of function or something that I can use to tell the character to walk along the ground rather than walking through it. At the moment when I set a new walk to position, the Y coord is 0, which means the character is going to forcibly go to the 0 axis without even considering the terrain. |
0 | 3D Collisions Walking below a slope pushes me through the floor Here's a really short video (less than 30s) of this issue https www.youtube.com watch?v JrKbpTY8cMU When I move the player towards a slope (the player is below it), it pushes the player inside the floor Collider instead of blocking it. I've searched the Internet for a while but haven't found anything about it Do you have something in mind ?Thanks for your time Info I move the player using rigidbody.MovePosition() The collision of the player is a Capsule. |
0 | How do I draw a context menu next to my object? I want to show a menu next to an item in an inventory. This is what I try to rebuild I do this by placing a canvas in 3D world space next to the inventory As I don't want the menu to be rotated, I rotated the menu the opposite X value as the camera. The camera has an X rotation of 11, so I rotate the menu by 11 to make it look straight Since I don't want the menu to get stuck in the case, I move it closer to the camera One can see that the menu is now offset to the left and to the top because of the camera perspective. How could I offset the menu in such a way that it still aligns with the right top corner of the item? Thank you! |
0 | Unity Nav mesh lading data each frame Hey all I had a question, I was looking into my game's performance and noticed this in the profiler Is there any way to optimize this such as pre generating tiles so it doesn't have to do it each update ) ? |
0 | How can I flip a coin? I am working in unity and have flattened out a cylinder object to make a coin for a 3d coin flipping game, but I am not sure how to get the coin to flip when the player swipes across it and allow for a double flip if the player swipes over it a second time while in mid air. here is what I have tried using System.Collections using System.Collections.Generic using UnityEngine public class CoinFlip MonoBehaviour private Vector3 start private void Start() start gameObject.transform.position void Update() transform.position transform.right Mathf.Sin(Time.time 0.45f) 0.025f void OnEnable() gameObject.transform.position start |
0 | Unity 2109.3.4 apk fails to install on to quest Hello's I was able to successfully sideload APK's on to the quest for a while now however when I updated to unity 2019.3.4 side quest is now unable to successfully load a built APK onto the oculus quest. Here is the error I receive, INSTALL FAILED NO MATCHING ABIS Failed to extract native libraries, res 113 I have tried numerous things and am a bit stuck. Any help is appreciated List of attempts Tried with SDK included in unity Tried custom android studio location Tried switching from MONO backend and enabling Arm 64 Tried lowering min to the lowest API level Tried updating all SDK tools in android studio Tried custom ndk, unable to get one unity is happy with Tried clearing cache and uninstalling prev install |
0 | Unity Facebook WebGL build... Does this work or not?!?! Getting conflicting answers So here is the facebook documentation.. It seems to be saying you can output a Facebook WebGL build from Unity and upload it. It does not work for me, I get this message when I upload. "Games must reference one of our supported SDKs via our CDN." Theres also this thread, with people saying it is not supported. https forum.unity.com threads facebook instant games support html5.499198 Yet the latest version of Unity has a WebGL option when building to Facebook platform. What is going on? Does or doesn't this work? |
0 | Effects of collisons broken glass, damaged cars, how are they created? My question is related in particular to achieving the effects of collision in game engine, how is this done? I have searched a bit, read from the internet and went through a few tutorials, and saw that one way to create one of the effects, explosion, or something breaking is to create the model in pieces, and apply force (in a game engine such as Unity 3D) to make the pieces fly off. It seems to be a solution, but it doesn't address the problem of items that are vaporized in a big explosion, with so many pieces. How is this done? Basic methods and tricks etc would be helpful. Secondly, the problem of things bending and getting damaged on impact, such as a car's front end destroyed when it hits a wall? How is this done? One thing that comes into my mind is to create each component of a car in a different state as an animation in 3Ds Max or Maya, and then in the engine, according to the collision, switch the model state in the time bar. Is this how it is done? Finally, what about materials, such as net of a basketball net, or a soccer goal net for example? Effects of ball hitting it can be calculated and applied in a script, but how to make the net bend and stretch with it? Is it done through models or materials? Also what about a flag fluttering in the wind? My questions are specific to game engines, particularly Unity3D. Some good links on the subject would also be helpful. |
0 | Building a game project in C for Unity in VS? Say that a project needs to be created from scratch for later use in Unity, for scripts. What is the ideal way to setup this without using a template in Visual Studio? Can this be created in C with some simple classes and one or two game loops? |
0 | LeanTween How to check if gameObject is destroyed? I am trying to animate a gameObject using LeanTween which has got destroyed already. The MissingReferenceException occurs in LeanTween.setOnUpdate() The null check doesn't work either (gameObject ! null) I have used LeanTween.cancel(gameObject,false) but it still throws an exception. |
0 | The type or namespace name OpenCVForUnity' could not be found I am working on face traching in unity3D I have downloaded and imported the sample project on "FaceTracker Sample using OpenCV for Unity". But when I tried to runned the project,its showing me the error.Below is the screen shot of the error What will be the issue?can anybody help out please? I am using unity(5.0.0f4(64 bit)) |
0 | Why does Unity not follow the z value when drawing text? I'm currently working on the credits of our game. For this I'm using multiple elements in a canvas I want the order that these elements are drawn in to be as follows, I gave them a z value based on this Z Object Object type 0 Text (The actual credits) Text 1 Hider (Green for demonstration) Sprite 2 Divider (The grey line) Sprite 2 Gametitle Text The camera has a z value of 10. The canvas is in "Screen Space Camera" render mode. But for some reason Unity is not drawing these items based on these Z values As you can see, the Divider is drawn over Text, but Text is above Hider and Gametitle. Why is this happening and what can I do so the credits get properly drawn? |
0 | Unity Photon Networking Cant understand OnPhotonSerializeView In all tutorials I see that an object sends data over the network and receives the data. For sync in the same method Code void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) if (stream.isWriting) stream.SendNext (transform.position) stream.SendNext (transform.rotation) else Debug.Log("never gets called ") never gets called... transform.position (Vector3)stream.ReceiveNext () transform.rotation (Quaternion)stream.ReceiveNext () But when I test my code, the lower part, where the data gets received, is never executed! I never see the logs. But the object is SYNCHED because it is set in the inspector But the problem is that the object is not interpolated so it looks kind of funny. So, I need to know how can I make the upper method to work so I can do some interpolation stuff. |
0 | How to move the player while also allowing forces to affect it For now, that's how I move the player rb.velocity Vector2.right input.x And I affect him a force while he is damaged by an entity rb.AddForce(Vector2.right force) It works fine, until I try to move while I'm damaged by an entity. Since my velocity input.x while I move, I can't affect any forces to it. I've tried to summarize velocity rb.velocity Vector2.right input.x But then I need to clamp the speed and if I clamp it, my force which is affected to player is also clamped. How can I resolve this problem? |
0 | How to share some elements of array with different players on Photon in the same Room? Unity3d I want to assign cards to different players in the room. I've a Class "Cards" that contains an array of 52 cards like this "2 of spades","3 of spades"....... and so on. All i want is to assign random indexes or values to different players on the basis of which I'll instantiate Cards Sprites. How can I do that? I've heard that there are RPC calls but how do I manage to make a "Middle Man" script that would deal with different players? |
0 | How can I implement a revealing light beam? In SEARCHLIGHT, you control a ray of light that illuminates incoming enemies that are otherwise invisible in the night sky. Here is an illustration How would I go about doing this, preferably in Unity? I imagine this is less about lighting and more about shaders, but I'm not sure on details. The fact that I know very little about coding shaders makes it worse. If it is about shaders, what are the specifics? Is there a stretched quad that moves with said shader applied to it, or perhaps is using the Line Renderer a better option? As a beginner, may I try to achieve a similar effect, or should I leave it for when I'm better? (P.S. The game was made in Unity. Here is its itch.io page.) |
0 | Unity mailchimp Klaviyo subscription form Hey everyone so i want to add a subscription form on my game. so far i can send data to a database and display them on a leaderboard, i found a similar question here but its a bit outdated. Ideally i would like to use klaviyo but since this is the only lead i have i might want to get familiar with how it works! using System using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Networking using UnityEngine.UI public class MailingScript MonoBehaviour public InputField emailField public InputField nameField public void onClick() StartCoroutine(SendToMailChimp()) private IEnumerator SendToMailChimp() WWWForm form new WWWForm() form.AddField( quot EMAIL quot , emailField.text) form.AddField( quot b 0f079b7af1cef143021ff4236 6cd74c0a6a quot , nameField.text) form.AddField( quot subscribe quot , quot Subscribe quot ) UnityWebRequest www UnityWebRequest.Post( quot https slaga games.us1.list manage.com subscribe post?u 0f079b7af1cef143021ff4236 amp amp id 6cd74c0a6a quot , form) yield return www.SendWebRequest() if (www.isNetworkError www.isHttpError) Debug.Log(www.error) else Debug.Log( quot Registered quot ) this is my code so far but it wont do anything. i have a same code for the database which works! |
0 | Unable to move GameObject? This simulates a GameObject swinging between two positions. I am unable to manually move a GameObject on the Y axis using the Unity editor (in scene view) when the following script is attached and running, it's like a solid animation Vector3 min, max void Update() min wall1.position new Vector3(4,0,0) max wall2.position new Vector3(4,0,0) transform.position Vector3.Lerp (min, max, (Mathf.Sin(2 Time.time) 1.0f) 2.0f) |
0 | Limit rotation angles for Quaternion I have a short snippet that's rotating the meshes of the wheels as I'm driving forward, but it's also rotating wheels to match the direction I'm turning, and I wish to turn this off completely. Quaternion quat Vector3 position m WheelColliders i .GetWorldPose(out position, out quat) m WheelMeshes i .transform.position position m WheelMeshes i .transform.rotation quat How would I lock what angles I don't want the wheel meshes rotating? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.