_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | Why does adding a value to list makes list not editable in unity inspector I am adding elements from the first list to another similar list, but it makes first not editable in the Unity Inspector. Whenever I try to change values from the inspector it makes them again 0. While If I comment list.Add() I can change values in the inspector. Serializable public class Characterz public string Name public int Age public float Gold public class Actor MonoBehaviour public List lt Characterz gt kings new List lt Characterz gt () public List lt Characterz gt Actors new List lt Characterz gt () void Start() for (int y 0 y lt 30 y ) Actors.Add(new Characterz()) if (y lt 4) I need to comment following line to change Actors list value in editor kings.Add(Actors y ) |
0 | How to communicate to an inventory item which character it's being used on? Currently, I have an Inventory that is a ScriptableObject, which means it's not tied to any specific game object or player character. I just drag it into a MonoBehaviour if I would like expose the data of the inventory. I have created an InventoryUI, which is a MonoBehaviour attached to a GameObject in my scene, and I assign the Inventory SO to it. The InventoryUI contains button GameObjects with an InventorySlot script, to which I assign the item each slot is holding. Everything works fine. When I click on one of the InventorySlot buttons, I'm able to call item methods, such as UseItem. My problem is if the the item is a potion, for example. How can i add health to the player? Of course I could add reference to the player to the slot. But that will reference player repeatedly over 25 slots. |
0 | Unity error "must have a body because it is not marked abstract, extern, or partial" I'm trying to setup a system where I pickup an object drop it into a zone, and then the object is destroyed. So far I have using UnityEngine using System.Collections using UnityEngine.UI public class TriggerZone2 MonoBehaviour public Text MyText private int score public bool CompareTag(string Player) Use this for initialization void Start () MyText.text "" Update is called once per frame void Update () MyText.text " " score void OnTriggerEnter(Collider coll) score score 1 if (other.CompareTag ("Player")) Destroy (other.gameObject) Everything works up until I try to destroy the game object. The console keeps saying Assets Scripts TriggerZone2.cs(11,21) error CS0501 TriggerZone2.CompareTag(string)' must have a body because it is not marked abstract, extern, or partial. I've looked up quite a few threads, but I'm still not sure what it wants me to do with it. How do I fix this? |
0 | Unity Animate Sprite Shape Sprite? Is it possible to animate a sprite shape? I don't see the Sprite Shape Profile in the animator properties, so I was just wondering if there's another way to do that. To clarify Our game is 2D animated by hand, and one level has conveyor belts that span the level. We can animate it normally, but that will end up taking more video memory than if we were able to animate the conveyors as tiled sprite shapes. It may not end up being worth the effort to save the memory, but I figured it was worth a shot. Because the sprites span the level, they end up taking up lots of space in a sprite atlas. |
0 | Long occluding geometries in Resonance Audio for Unity I'm currently looking into using resonance audio (https resonance audio.github.io resonance audio ) for accurately modelling the audio for an environment that approximates to a long corridor with a series of bends. I want to have a sound at the end of this corridor that the user can hear at any point in the corridor based on the sound reflections along the corridor. I have tried a few of the options presented by Resonance Audio Placing reverb probes along the corridor. This seems like the ideal option, however a reverb probe will only apply its baked in reverb profile to sound sources inside the probe. If I try to make the probes larger then they seem to take into account all of the geometry of the corridor at once and things get exceedingly echo ey and consistent regardless of where I am in the corridor. Turning the corridor model into an audio room. This isn't apropriate as it has many of the same issues as a large reverb probe, and also doesn't actually model the space itself. Has anyone had any experience with hearing distant sounds in Resonance Audio environments like this? At this point I have a feeling that Resonance Audio is just not built for this particular situation. |
0 | How can I rearrange layers in Unity 2D? I'm new to using Unity (2019.30a2) and am currently learning by watching Brackey's (youtube) "How to make a 2D Game in Unity" At 6 58 he is able to rearrange his layers easily. On my hand, I can create but am unable to change the order of the layers. Looking at other questions on similar subjects hasn't provided me with a solution yet. I'm currently working around it but feel this will hinder me in the future. The screenshot of the unmovable layers is included below |
0 | Why is my CameraCrop script blurring the screen slightly in Unity? I've been trying to enforce a 4 3 aspect ratio in my Unity game, in order to give a nostalgia feeling to it. But whenever I add this script to my camera and compile my game, it blurs slightly. I am using a 4 3 aspect ratio in the game view and have Fullscreen Window chosen in my Window Option and in Supported Resolutions I have only 4 3 ticked. Also, I am used Pixel Perfect Camera with Pixel Snapping enabled. Here's what my game looks like without the CameraCrop script added And here is what it looks like when the script is added Here's the script I add to my camera using UnityEngine using System.Collections using System.Collections.Generic Requires that the camera component is on the GameObject RequireComponent(typeof(Camera)) public class CameraCrop MonoBehaviour Sets the aspect ratio to whatever you want public Vector2 targetAspect new Vector2(4, 3) Camera camera void Start() camera GetComponent lt Camera gt () UpdateCrop() Call this method if your window size or target aspect change. public void UpdateCrop() Determine ratios of screen window amp target, respectively. float screenRatio Screen.width (float)Screen.height float targetRatio targetAspect.x targetAspect.y if (Mathf.Approximately(screenRatio, targetRatio)) Screen or window is the target aspect ratio use the whole area. camera.rect new Rect(0, 0, 1, 1) else if (screenRatio gt targetRatio) Screen or window is wider than the target pillarbox. float normalizedWidth targetRatio screenRatio float barThickness (1f normalizedWidth) 2f camera.rect new Rect(barThickness, 0, normalizedWidth, 1) else Screen or window is narrower than the target letterbox. float normalizedHeight screenRatio targetRatio float barThickness (1f normalizedHeight) 2f camera.rect new Rect(0, barThickness, 1, normalizedHeight) I am using Unity 2019.4.17f LTS and using Windows 10. |
0 | How to check version of Unity package in project through script I'm writing an asset that will be used by many people, but it depends on TextMeshPro (TMP). I ran into a bug in TMP that can only be fixed by upgrading to a preview version. I want to warn users that install my asset that they need to upgrade their TMP version if they are using a prior version. Surprisingly, I can't find this anywhere online or in the docs. just something like if (TextMeshPro.version lt MyAsset.RequiredTMPVersion) Debug.LogError("Need to upgrade TMP") |
0 | Unity 5 light reflection on the water surface How to adjust reflection in Unity 5 to show up it on the water surface. So I have few light elements in the scene. So I want my water pro to reflect this lights. As example you can see red and yellow lights from the Shanghai's build on the water, that's what I am trying to achieve I've added water pro and setup flare Looks liker here some small reflection on the rect I market as red. But if comparing with real reflection it's more vertical reflection I've marked it as red well If you can see it unity example does not look natural. So if we compare distance from sun to the beach border on real photo, there is a huge sun line over the water surface, but there is not the same line on water pro in unity. Here is a video link with what I did http screencast.com t bq8Ocl24ZAJH |
0 | How can I duplicate a GameObject with the correct number of copies? using System.Collections using System.Collections.Generic using UnityEngine public class FormationsManager MonoBehaviour public GameObject squadMemeberPrefab public int numberOfSquadMembers 20 public int numberOfSquads 1 public int columns 4 public int gaps 10 public Formations formations private int numofmembers private int numofsquads private GameObject squadToClone private List lt GameObject gt SquadMembers new List lt GameObject gt () Use this for initialization void Start() squadToClone GameObject.Find("Squad") numofmembers numberOfSquadMembers numofsquads numberOfSquads formations.Init(numberOfSquadMembers, columns, gaps) GenerateSquad() Update is called once per frame void Update() if (numofmembers ! numberOfSquadMembers) numofmembers numberOfSquadMembers formations.Init(numberOfSquadMembers, columns, gaps) GenerateSquad() if (numofsquads ! numberOfSquads) numofsquads numberOfSquads for (int i 0 i lt numberOfSquads i ) Instantiate(squadToClone) private void GenerateSquad() GameObject go squadMemeberPrefab List lt GameObject gt newSquadMembers new List lt GameObject gt () int i 0 for ( i lt formations.newpositions.Count i ) if (i lt SquadMembers.Count) go SquadMembers i else go Instantiate(squadMemeberPrefab) go.transform.position formations.newpositions i go.tag "Squad Member" go.transform.parent gameObject.transform newSquadMembers.Add(go) for ( i lt SquadMembers.Count i ) Destroy(SquadMembers i ) SquadMembers newSquadMembers In the Update I duplicate the squad if (numofsquads ! numberOfSquads) numofsquads numberOfSquads for (int i 0 i lt numberOfSquads i ) Instantiate(squadToClone) The problem is that if for example when running the game there is 1 squad and then I'm changing the value of numberOfSquads to 3 then instead duplicating more 2 squads it will duplicate more 3. And then if I will change the value of numberOfSquads from 3 to 4 it will add more 4 squads instead only 1. And I also want to make that if I change the value of numberOfSquads to be lower then destroy the last squad s. |
0 | Upper Lower angular limits on Y and Z axes My Task I'm trying to replicate this project. I'm using unity as my physics engine. Currently I'm still learning how to work with the different joints unity has to offer. The type of movement I'm looking for is where a body is connected to only one other body and its relative movement can be limited based on angles on different axes. My Problem I'm using Configurable joints for my movement restrictions. The Low Angular X Limit and High Angular X Limit does exactly what I'm looking for since it can have a different uppper and lower rotation limit. Looking at the documentation, it seems that this can only be done on the X axis. The Y and Z axes only have a Angular Y Limit or Angular Z Limit which set the upper as the opposite of the lower limit. My Question Is it possible for the Y and Z axes to have the same lower upper limit system that the X axis has? Is the use of configurable joint good for this task? Thanks in advance ) |
0 | How to stop rendering a gameObject that has no rendering component in unity I want to stop rendering this gameObject. But the all available renderer.enabled false is not working. Is it because it has no rendering component attached? If so, how can I see it when it is not rendered?! |
0 | Start Broadcast Unity Network Discovery I am using the unity NetworkDiscovery component, and I am wondering how I can auto start broadcasting when the server starts, instead of the client having to click on the gui Initialize Broadcast Start Broadcasting. I would like to be able to put some C in my start host function so that the user does not have to do anything. |
0 | Unity Issue applying Render Texture to object imported from Blender I'm new to Unity and am trying to create a sort of CRT computer monitor terminal with text. To draw the text, I set up a Text Mesh Pro with its own camera, which renders to a Render Texture. I then designed a simple computer monitor model in Blender split into two objects one for the glass part of the screen, and another for the 'rest' of the monitor exterior case. I saved a copy of the .blend file into the Assets folder and imported this into Unity. My blender model (two separate objects, with the separate "screen" piece moved out of the screen) When I try to apply the Render Texture onto the screen object, the texture is rotated 90 degrees anti clockwise and is too zoomed in I can't seem to rotate the texture so that it is the right way up to read the text, and only some of the text is visible. I have tried rotating the object 90 deg. clockwise in Blender and "applying" the transform so unity then thinks the object is oriented correctly. this still caused the texture to be rotated. I also tried exporting as an .obj file, with "Up" set to "Y Up", but this didn't work. I then tried applying the Render Texture to a material, which I then applied to the screen object which didn't work either. If I apply the texture to a standard cube in Unity, it works fine and is rotated and scaled correctly to fit the cube. How can I get the blender object oriented correctly so that the Render Texture applies in the correct orientation and scales so the whole of the Render Texture fits and is not zoomed in? I'm using Unity 2019.3 and Blender 2.82. |
0 | Capture Video without Third Party SDK's I am trying to capture the game play and store it on local memory without using any third party sdk's. I tried This Video Capture Script but i didn't get the recorded file even i don't know whether it's recording or not. anybody please help me to complete the task. Thanks in Advance |
0 | Exposing type definitions to modders in Unity Note that this question is not about modding assets data and not about security, I plan to rely on community trust. I don't know much about DLL's and I was wondering how I can provide interface and attribute definitions for modders. For Kerbal Space Program modders only have to reference the Assembly CSharp.dll, UnityEngine.dll and UnityEngine.CoreModule.dll files of a games build, to create and compile their own DLLs. Are there certain things I have to do, to mimic this behavior, or does this work out of the box? Are there gotchas to this approach? Will a mods DLL, that was compiled using an older version of Assembly CSharp.dll, break if the Assembly CSharp.dll is updated, even though no types relevant to the mod changed? Will modders be able to use Visual Studios debugging features for their DLLs? Is there a better approach to provide type definitions? My question is related to this question. But I would argue that that question is kind of broad, while mine is about one specific aspect. Might not be needed for the question, but here are the two levels of modding that I would like to support for my game 1. Easier modding I want to compile .cs files of modders that implement special interfaces like IAbility, IItem, etc. I will use Roslyn or cs sript to do so. 2. More advanced modding I also want to load .dll's that modders compiled, allowing them to register their own Types in the games DI Framework, mark methods classes with attributes like CallMethodOnLevelLoad and use Harmony. |
0 | Unity 5.3 with C Toggle Sound On Off I'm working with Unity 5.3 with C as code editor These are what I have I have 2 scenes in my project home and options. I have bg object on both scenes. Both bg objects have Audio Source component, which contains same background music that play on awake. I don't use any codes for these background musics, I only click the Add Component button from Unity and add Audio Source. This is what I want Options scene can toggle the background music on off for all scenes. Therefore, there are btnOn and btnOff in Options scene. This is my code in Audio Manager.cs using UnityEngine using UnityEngine.UI using System.Collections public class AudioManager MonoBehaviour public Button btnOn public Button btnOff Use this for initialization void Start () btnOn GetComponent lt Button gt () btnOff GetComponent lt Button gt () btnOn.onClick.AddListener(() gt PlayAudio()) btnOff.onClick.AddListener(() gt StopAudio()) void PlayAudio() AudioSource.volume 0.5f void StopAudio() AudioSource.volume 0f This is the problem I have this error An object reference is required to access non static member UnityEngine.AudioSource.volume. Maybe, this is because I don't write public AudioSource audioSource in my code. But, if I write this, I have to add another audio in Get Component box, and I will have double Audio Source in one scene. What should I do? Thanks |
0 | Unity Import a mesh that only has vertex and edge data but no faces I am working on a game that requires meshes that only have edges and vertices but no faces. In blender, you can make a mesh with only edges and vertices, but if you export it to FBX or OBJ, once it is imported into Unity, the resulting prefab has no mesh data linked to it. The prefab has no MeshFilter. It's as if I imported an mesh with absolutely no mesh data. For example, if I create a plane in Blender and then delete the face but leave the edges and vertices, and then export as OBJ, I can open the OBJ in a file editor. This is a square with no faces Blender v2.78 (sub 0) OBJ File '' www.blender.org mtllib egdes.mtl o Plane v 1.000000 0.000000 1.000000 v 1.000000 0.000000 1.000000 v 1.000000 0.000000 1.000000 v 1.000000 0.000000 1.000000 l 3 1 l 1 2 l 2 4 l 4 3 So it appears that OBJ actually does export with the correct mesh data, however, it seems that Unity does not know how to import an OBJ if there are no faces. Does anyone know if anyone has come up with a solution to this problem yet? If not, I guess I'll just have to write my own parser. If that's the case, does anyone know if there is a way to extend or override Unity's built in OBJ parser? |
0 | Is Update() called on the very first frame in Unity? I'm calling Time.frameCount inside Update() and then immediately Debug.Break() to pause the simulation before Update() is finished. This of course happens (supposedly) on the very first frame, and yet Time.frameCount returns 1, as if one frame had already been rendered by at that point. Also, I'm calling Time.deltaTime the same way, on the first frame inside Update(), and it returns a value too, as if a previous frame had been rendered and took X milliseconds. Considering Time.deltaTime returns the value of the "time it took to complete the last frame", and I'm calling it on the first frame and it's returning a value, is there an "invisible" first frame that Update() doesn't run on? I couldn't find any reference to this specific issue on the Unity docs. |
0 | Is it bad form to use singletons in unity I've heard a lot of people say singletons are bad practice and an 'anti pattern', like here, this answer this article and here. However, a lot of the reasons I've read about seem to be to do with dangers in their creation, them not being thread safe, difficult to destroy safely etc. But in unity where there are functions such as awake() and start() which are (as far as I'm aware) guaranteed to only be called once, are they unsafe to use? |
0 | How To Find Child Object and set is own criteria condition? I am Making 2D Game. I Apply a Two Tag On Multiple Child Game Object.. Crate A Empty Game Object and Put Script Obstacle.cs and Rigidbody2d. Child GameObject Static OnTriggerEnter2D Obstacle.cs void Start() foreach (Transform item in GetComponentsInChildren lt Transform gt ()) if (item.tag "someobstacleslow") 7 child game object find successfully Debug.Log("someobstacleslow " item.tag) if (item.tag "someobstaclefast") 4 child game object find successfully Debug.Log("movefastobstacle " item.tag) Referance https imgur.com a ozcJcO4 I want to some obstacleslow is going slow and someobstaclefast is going fast but nothing happens. Output all obstacle going very fasy?? what i miss my programme?? But Child GameObject not working its own condition? Obstacle.cs float speed 2.5f normal speed float movefastobjectspeed 3f fast spped void Update() goTopToDown() void goTopToDown() foreach (Transform item in GetComponentsInChildren lt Transform gt ()) if (item.tag "someobstacleslow") issue here move top to down object normal speed transform.position Vector3.down speed Time.deltaTime Debug.Log("GameObject obstacle object " item.tag) Debug.Log("inside obstacle object") if (item.tag "someobstaclefast") issue here move top to down object fast speed transform.position Vector3.down movefastobjectspeed Time.deltaTime Debug.Log("GameObject movefast object " item.tag) Debug.Log("inside movefast object") When My Obstacle Touch My Player then Ontrigger2d Is fire Obstacle.cs void OnTriggerEnter2D(Collider2D other) foreach (Transform child in GetComponentsInChildren lt Transform gt ()) if (child.tag "someobstacleslow" child.tag "someobstaclefast") Debug.Log("chiildtag " child.tag) gameovertext.SetActive(true) StartCoroutine(gameover()) Debug.Log("inside triggerfire") But Issue Is all obstacle going very fast(See in referance).I want to some obstacleslow is going slow and someobstaclefast is going fast but nothing happens.??help |
0 | Security of Unity Rpc calls Im just starting to code my game in unity and have been reading up that rpc calls are not validated and can run havoc on the server. For example a modified client can connect to your server and just disconnect everyone by sending networkView.RPC("disconnecteverybody", RPCMode.All) RPC void disconnecteverybody () Network.Disconnect() Is there a way to validate packets? |
0 | Instantiate and launch prefab that's overlapping player? I m very new to Unity and C . I m trying to create my first game and I have now invested about 15 hours trying to find solutions to this issue...I m stumped! My player sprite (blue square) needs to launch a prefab sprite (red circle) of similar size appearing to originate from itself. Here is a GIF of what I have so far...I don t want the blue cube to collide and go flying. After clicking and dragging on Player (drag to aim) via OnMouseDrag to set the target vector, I m trying to Instantiate a prefab sprite (Dynamic RigidBody2D, CircleCollider2D) using the Player sprite s position (a Dynamic RigidBody2D, BoxCollider2D) and have it APPEAR to be originating from inside the Player object. Launch is triggered via function called in OnMouseUp. Both objects should immediately come under control of Physics to collide with the environment which will include other moving RigidBody2D objects later. Targeting should allow 360 degrees to include straight into an obstacle allowing rebound effect. Here is some excerpts of my code using System.Collections using UnityEngine public class Teleportation Grenade MonoBehaviour This script is attached to Player and requires projectile prefab. tested with thrust set between 100 and 200. public float thrust public Transform prefab public LineRenderer playerShotLine private Vector2 playerToMouse private Vector2 targetVector ... void OnMouseDrag() Vector3 mouseWorldPoint Camera.main.ScreenToWorldPoint (Input.mousePosition) Vector2 playerToMouse mouseWorldPoint transform.position mouseWorldPoint.z 0f playerShotLine.SetPosition (0, transform.position) playerShotLine.SetPosition (1, mouseWorldPoint) playerShotLine.sortingOrder 3 opposite direction of line renderer targetVector playerToMouse void OnMouseUp() SpawnPrefab () void SpawnPrefab() Instantiate(prefab, new Vector3(transform.position.x, transform.position.y, 0), Quaternion.identity) prefab.GetComponent lt Rigidbody2D gt ().AddForce (targetVector thrust, ForceMode2D.Impulse) This is only one of many, many iterations. It's the gist of it though. I appreciate any insight from the community. |
0 | How do I show a camera's field of view area through another camera? I have a side camera that can be set on run time with changeable field of view with GUI. I am searching for a way to show the field of view of the side camera using my main camera. I am thinking about custom mesh creation through code so that it can be generated alongside the camera rectangle, but it seems too complex. Should I proceed with this method or are there any other solutions? ! |
0 | Help deciding data structure for spatial partitioning, using only value types in c I simply want to implement some sort of grid where I can sort units in an RTS into cells, and then for each unit check to avoid other units and attack other units, in 2d. My map grid is currently 10 000 x 10 000 cells, with 20 thousand units. To be specific, my grid is sparse but the units move together in very dense groups of about 300 each (like an ancient army type of formation). So cells will either be extremely dense, or completely empty, no in between really. My issue in deciding is that I am using Unity job's system and burst compiler. If you do not know, jobs is a multithreading system, and burst is an LLVM based compiler outputting very fast assembly. The limitations of these systems is you can only use value types. So no classes. I have looked at using a MultiHashmap, but from what I read this can be very slow because I need to run a hash function for every unit. Then when I want to iterate al units in a cell, this is much slower than iterating an array. Especially, because I will also be checking the 8 neighbour cells for each unit as well. That's a lot of hashing being done. Finally, I have to clear the map every frame. The advantage here is Unity provides a container NativeMultiHashMap which is thread safe, so I can build and query it in parallel. I have looked into quad trees. But quad tree does not seem suited to multithreading, especially without using references. So if I did this, it would most likely be single threaded. My question is, are my above statements correct in thought? Is there a faster way to organize my data? If I go with a hashmap, how can I query it most efficiently? |
0 | Unity3d zooming with orthogonal camera like in Google maps I am implementing 2d orthogonal zoom. As far as I know in Unity3d there are no translations like in OpenGL. Taking this into consideration, I work with camera size camera position (center) real world mouse position I have no issues implementing simple zoom in zoom out operations, combined with camera position changes ( drag'n'drop ) But I have some issues calculating camera zoom shift in this case camera size (4,4) camera position (0,0) real world mouse position (1,0) A double zoom in (2x) is applied, as a result camera size (2,2) camera position (0.5,0) real world mouse position (1,0) User shifts real mouse position to (1.5,0) and applies a double zoom out ( 0.5 ). In this case camera size is again (4,4) camera position ??????? real world mouse position (1.5,0) What should be the camera shift so the mouse doesn't visually move ? What is the formula for calculation in this case ? Thank you in advance. P.S. Any suggestion regarding current method of handling zoom are welcome Update So I resolved this issue with Blue's help. The basic idea about shifting is right. The main reason it didn't work was incorrect zoom factor. Example Initial camera size is 5. User zooms in by 1, camera size is now 4 ( it displays less content on the same 'screen'). User changes mouse position and zooms out by 1. Camera size is 5 again, but the amount of zoom is actually different initially the change was 20 ( 1 5 ) in the second time, the change was 25 ( 1 4 ) My fault was that, when zooming out, I tried to restore position by 20 , not 25 . |
0 | Unity SphereCast HitInfo Give me an interpolation of the normal surface? I'm doing a SphereCast for a GroundCheck of a player. I have my Raycast hitInfo, and here in the picture at the left, I Debug.drawRay in black the direction of the hitInfo.normal every frame It seems like hitInfo.normal give me an interpolation of the normal, not the real normal of the surface... I only want the real normal of the surface... (red normals I have draw on the right), and may be the green one (the perfect normal between 2 surface), but if I can have only the red one, it would be great How can I do it ? Thanks ! |
0 | Unity animations not transitioning properly I am currently trying to animate transitions between four different directions. I have four total animations for walking, and another four for the idle state. I cannot seem to figure out why when I try to transition from a walking state to another walking state in a different direction (not the direction I am idling in) it must wait for the walking animation to finish, and then play the walking animation in the new direction. You can see my sprite begin to walk forward, and then when I attempt to turn south the animation it continually plays the north animation until the animation is finished. What I am trying to achieve is a smooth transition that switches immediately. I know very little about animating and much more about programming. My list of attempted solutions is very short, and limited to only changing the length of each animation. |
0 | How to Steer a Moving Object Away From Another Object(s) I'm working with C in Unity, and I'm making a top down space shooter game in which there are many different AI controlled ships flying around. The problem is that these ships often fly on top of one another in passing, and sometimes even will fly the same route on top of one another if given the same waypoint. I want to add a system to steer my AI ships away from each other as well as other obstacles so that instead of overlapping one another when flying the same path they will fly side by side, and will also try to avoid things that pass in front of them. My current system essentially works like this The AI looks at all of the current objectives, points of interests, etc, and decides where it wants to be on the map (a coordinate). The AI then sends an input direction to the ship, which then applies acceleration in that direction and changes the velocity. Therefore, any solution to alter my ship's pathing would need to alter this input direction somehow. So my first idea was to check if there are any obstacles (ships, asteroids, structures, etc) within a radius of the ship, increasing this radius based on the ship's velocity (higher velocity larger "view" radius) Collider2D hits Physics2D.OverlapCircleAll(transform.position, ship.velocity.magnitude) If there is something nearby, calculate the direction to that collision, then calculate the opposite direction and scale it to the reciprocal, which also has the added effect of making the aversion stronger the shorter the distance to the collision is foreach (Collider2D hit in hits) if (hit.gameObject gameObject) continue exclude self from the search Vector2 v hit.ClosestPoint(transform.position) (Vector2)transform.position v (1 v.magnitude) v.normalized I would perform this for every nearby obstacle and add all of these together to get the avoidance vector avoidanceVector v continue Then I add the total avoidance vector to the AI's input direction and normalize the result inputDirection avoidanceVector inputDirection.Normalize() However, when i add this avoidance vector to my input direction, my ships exhibit a strange behavior where sometimes they will simply stop moving completely. commenting out the line where i add them together stops this behavior. I'm really not sure what could be going wrong here, but I think it has to do with my approach altogether. Can anyone help me figure out a clean, simple way to make my ships steer away from other objects? |
0 | Where's Anti Aliasing in LWRP? In Unity 2019.2 LWRP (lightweight render pipeline project) the default Game Output(Quality High) is rendering with jaggies. Inorder to get a clear render ,while looking for the Anti Aliasing option it doesn't seem to be under the default location (Edit Project settings Quality )for LWRP projects. Where is the Anti Aliasing option in LWRP and is there any other way to get a clear game render? |
0 | Why does Unity think my RectTransform has changed? I am working with UI. I want to know when my RectTransform changes its position. I am using transform.hasChanged void Update() if (transform.hasChanged) Debug.Log("Updated Position") transform.hasChanged false However, it thinks it has always changed. "Updated Position" is constantly printing out. If I remove and then readd the component while in play mode, the issue resolves itself. However, I don't want to have to do this, as it is very hacky. I could just throw a bunch of if statements in there to check, but I'd prefer to make use of the build in transform.hasChanged property. How can I check to see if my RectTransform has changed its position efficiently and elegantly? |
0 | Change Unity 3d viewport shortcuts to match Blender? The shortcuts in Unity are more similar to Maya (Alt Middle for 3d orientation, LeftClick select, etc). I've looked into Edit gt Shortcuts but couldnt find them. Is there any way to do this? |
0 | Programmatically generated mesh vertex colors not showing up in Unity? I'm sorry if this is an obvious thing to solve but I just can't figure it out...did I miss something...I've generated a mesh and during vertices generation I've also set its colors (and colors32 just in case) by reading those values from a ply file, and afterwards I've added a number of vertex color shaders but none of them will show the vertex point colors in play mode, it's either solid black or just like I added no material to the mesh (which I've tried doing manually in play mode too). Did I miss something please? |
0 | Google Play Game Services (Unity Plugin) Turn Based Multiplayer List of Open Matches I took a closer look at Google Play games services Turn based multiplayer, and I cannot find out if I am somehow able to just get a list of all open matches, so that I can implement my own GUI. It seems really weird to me that they would not let you do such a simple task. Is this just a problem with the Unity implementation or is it a general problem? Using the Google UI would make a clunky feel which I would like to avoid. |
0 | Android black screen with Unity app in subview I've exported an Unity app game I have made to Android Studio. In Android Studio I made a layout and within it I have a framelayout. However, when I run the app the framelayout is completely black, why? Here is my Java code public class UnityPlayerActivity extends Activity protected UnityPlayer mUnityPlayer don't change the name of this variable referenced from native code FrameLayout fl forUnity Button bt groen, bt gul, bt sort Override protected void onCreate(Bundle savedInstanceState) requestWindowFeature(Window.FEATURE NO TITLE) super.onCreate(savedInstanceState) getWindow().setFormat(PixelFormat.RGBX 8888) mUnityPlayer new UnityPlayer(this) if (mUnityPlayer.getSettings().getBoolean("hide status bar", true)) setTheme(android.R.style.Theme NoTitleBar Fullscreen) getWindow().setFlags(WindowManager.LayoutParams.FLAG FULLSCREEN, WindowManager.LayoutParams.FLAG FULLSCREEN) setContentView(R.layout.main) this.fl forUnity (FrameLayout) findViewById(R.id.fl forUnity) this.fl forUnity.addView(mUnityPlayer.getView(), FrameLayout.LayoutParams.MATCH PARENT, FrameLayout.LayoutParams.MATCH PARENT) this.bt groen (Button) findViewById(R.id.bt groen) this.bt gul (Button) findViewById(R.id.bt gul) this.bt sort (Button) findViewById(R.id.bt sort) this.bt groen.setOnClickListener(new View.OnClickListener() Override public void onClick(View v) UnityPlayer.UnitySendMessage("Main Camera", "ReceiveRotDir", "G") ) this.bt gul.setOnClickListener(new View.OnClickListener() Override public void onClick(View v) UnityPlayer.UnitySendMessage("Main Camera", "ReceiveRotDir", "Y") ) this.bt sort.setOnClickListener(new View.OnClickListener() Override public void onClick(View v) UnityPlayer.UnitySendMessage("Main Camera", "ReceiveRotDir", "B") ) mUnityPlayer.requestFocus() Here is my XML lt ?xml version "1.0" encoding "utf 8"? gt lt RelativeLayout xmlns android "http schemas.android.com apk res android" android layout width "match parent" android layout height "match parent" android rowCount "3" android columnCount "10" gt lt FrameLayout android layout width "match parent" android layout height "400dip" android id " id fl forUnity" android background " 00FFFF" android layout centerHorizontal "true" gt lt FrameLayout gt lt Button android layout width "wrap content" android layout height "wrap content" android text "Gr n" android id " id bt groen" android layout column "4" android layout row "2" android layout alignTop " id bt sort" android layout toRightOf " id bt sort" android layout toEndOf " id bt sort" android layout marginLeft "30dp" gt lt Button android layout width "wrap content" android layout height "wrap content" android text "Gul" android id " id bt gul" android layout column "9" android layout row "2" android layout alignTop " id bt sort" android layout toLeftOf " id bt sort" android layout toStartOf " id bt sort" android layout marginRight "30dp" gt lt Button android layout width "wrap content" android layout height "wrap content" android text "Sort" android id " id bt sort" android layout below " id fl forUnity" android layout centerHorizontal "true" android layout margin "10dip" gt lt RelativeLayout gt |
0 | Having trouble with foreach loop affecting anything past the first object found I have been trying to disable isTrigger in unity c script on all GameObjects containing a certain tag. Currently my code works and disables the isTrigger part of the box collider, but it only does this for the first object with the tag I am looking for do this for all objects. Here is the code using System.Collections using System.Collections.Generic using UnityEngine public class DefenseCollisionTrigger MonoBehaviour public static Rigidbody rb public bool CanBePlaced public GameObject defenseTriggers void Start () CanBePlaced true defenseTriggers GameObject.FindGameObjectsWithTag("Defense") public void OnTriggerEnter (Collider other) if (other.tag "Defense") CanBePlaced false public void OnTriggerExit(Collider other) if (other.tag "Defense") CanBePlaced true public void IsTriggerFalse() foreach (Object dt in defenseTriggers) Debug.Log("working on it") GetComponent lt Collider gt ().isTrigger false That is what is currently looks like. The public void IsTriggerFalse() is called on each time I go to instantiate an object with my mouse button. The Debug.Log is working and printing to the console. This is the closest I have came to making it work, but it only works for the first object. I have searched for hours and watched videos looked at unity docs on foreach statements with no luck to my issue. I have also tried using foreach (GameObject dt in defenseTriggers) instead of just Object. Anyone know how to solve my issue? |
0 | Procedurally generate with different sized cubes I am trying to procedurally generate my world like in Minecraft with tons of blocks. I have watched lots of videos about this but they all use a single fixed size cube. I would like to achieve the same as in Minecraft but with different sized cubed for example. How could this be done? I am using Perlin Noise for generation. |
0 | Why does Avatar Mask not work as expected? I have 2 layers The base layer, and an upper body layer. On the upper body layer, I have an avatar mask because I only want to affect the upper body. However, this mask doesn't work as expected. Here is what it looks like This is what is looks like when the upper body layer has a weight of 0 And this is with the upper body layer with a weight of 1 and with the Avatar Mask As one can see, the lower body is affected. The avatar mask doesn't seem to have an effect. Is that a bug in Unity, or is there anything I could still check? Thank you! |
0 | Improving Rigidbody collision between real time movable object and other Rigidbodies I have a cube that has been scaled to be rectangular (controlled by a remote Raspberry Pi gyro accelerometer magnetometer) and am translating its orientation into Unity via calls to transform.localEulerAngles new Vector3(...). This works wonderfully (the cube object modeled to be a Pi rotates perfectly), however now I'm running into issues with the actual physics. GIF of successful roll Initially the ball will land on and roll around the Pi object, however when I start to increase the speed of my movements the ball will sometimes fall through the Pi. The cube has a Rigidbody (no gravity, is kinematic) and Box collider (not triggered), and the sphere has a Rigidbody (has gravity, not kinematic) and Sphere collider (not triggered) attached. I've tried varying the collision detection from discrete to continuous on both objects and have noticed similar behaviors. The intent is to turn this into a marble maze type game, and the issue that I have is similar. If I roll the ball into the joint between a wall and the floor (both stretched cubes), rotate it down, and then rotate it up, the ball will fall through the joint. I have the same movement code attached to the GameArea object below. Again, same issue with various types of collision detection applied. My assumption is that this is a quickness of movement thing, as the cubes overlap each other (there's not a space for the ball to sneak through). For reference, in the physics colliders section of the project preferences, all relevant layers are supposed to collide with each other. I don't mind getting into code based collision detection, but this seemed fairly trivial for Unity to take care of so I was wondering if I was missing something obvious. |
0 | How can I improve my touch slide mechanic to be more smooth and fluid? I have the following C code, but it leaves me with two problems void FixedUpdate() if (Input.touchCount 1) this.transform.Translate(Input.touches 0 .deltaPosition.x 0.009f, 0, 0) Firstly, the gameobject (which is a sphere in my case), has a tendency to leave the ground and fly into the air. Additionally, it is not as smooth and snappy but fluid as I would like it to be. If you look at some of the following gameplay videos, you will see the kind of movement I am looking for. "Splashy!" Gameplay "Sky Ball" Gameplay "Balls Race" Gameplay More specifically, from actually playing each of the above games, there is a certain "ratio" that seems to be operating in regards to each swipe gesture and the actual movement of the ball. That is, the ball does not go exactly where the finger goes, for it is slightly ahead, if that makes sense. What I mean is, the device is only so wide, yet for that width, the ball can always reach it's required destination on either end of the horizontal axis. This must mean that for every pixel the finger moves, the ball moves a little bit more to fit that pixel density of the screen. In other words, in the case of "Splashy!", it's clear that even if the finger moves the entire distance across the screen, the ball moves more than double that distance. By "smooth", "fluid", and "snappy", I mean that the swiping gesture is very responsive. It moves where you want it to and does not over or undershoot. Additionally, the "snappy" effect is present when you stop swiping. The ball seems to "snap" into it's end position. My question, then, is what is the best way to improve my script as to achieve the polished mechanic I am looking for, as is depicted in the above videos? Also, how can I keep the sphere on the ground without constraining any axes on the rigidbody? I am using Unity3D with C . I would appreciate any help you could provide. Thank you. |
0 | All GameObjects and Models are Transparent Whenever I create a new game object its completely transparent, with the Mesh Renderer selected. This is really frustrating as I am new to Unity and Google offers no solutions. |
0 | Typedef redefinition error when running Unity iOS project in Xcode 9 simulator I was able to run my Unity 2017.1.0b10 iOS project successfully on my iPhone 6S (Using Xcode 9). I changed the Target SDK to Simulator SDK to try it out on other device simulators then I got the following errors in the UnityMetalSupport.h file. Below are screenshots of my player settings |
0 | Setting SteamVR Camera Target Eye before SteamVR installed in Unity I'm writing a plugin that can be used in both VR and non VR projects. I have a Camera that is used to display UI containing some game info on a secondary monitor. My problem is that when the end user adds my plugin and then imports steam vr, this UI camera's Target Eye is set to "Both" by default. I can't have any SteamVR code in my plugin. But I can't adjust Target eye property of the camera without it. I just want it so that the camera doesn't change when a user imports SteamVR. I want it to always render to the main display (target eye none) So just to clarify, I have my plugin, written in a non vr project with a standard Unity camera. There is no Target Eye setting for this standard camera. User wants to use it in VR project, imports plugin into SteamVR Project Camera used to render UI gets automatically converted (wrongly) into SteamVR camera Defaults to Target Eye Both Need it to be Target Eye None At the moment to avoid users submitting countless bug reports, I have to provide warnings in like 6 places telling users to dig way into my built in prefabs to adjust this setting manually if they use SteamVR. It's not easy for new Unity users, and I want to make adoption as easy as possible. |
0 | 18.5 9 Android ratio force to 16 9 problem in Unity I want to my game build in devices with 18.5 9 ratio like Samsung S8 forced to be displayed as 16 9 ratio. I already set Aspect ratio mode to Custom and set it to 1.86 in Player Settings. I also overrided Android Manifest like this lt ?xml version "1.0" encoding "utf 8"? gt lt manifest xmlns android "http schemas.android.com apk res android" package "com.unity3d.player" xmlns tools "http schemas.android.com tools" android installLocation "preferExternal" gt lt supports screens android smallScreens "true" android normalScreens "true" android largeScreens "true" android xlargeScreens "true" android anyDensity "true" gt lt application android theme " style UnityThemeSelector" android icon " drawable app icon" android label " string app name" android isGame "true" android banner " drawable app banner" gt lt activity android name "com.unity3d.player.UnityPlayerActivity" android label " string app name" android screenOrientation "sensorLandscape" android launchMode "singleTask" android maxAspectRatio "1.86" android resizeableActivity "false" android configChanges "mcc mnc locale touchscreen keyboard keyboardHidden navigation orientation screenLayout uiMode screenSize smallestScreenSize fontScale layoutDirection density" android hardwareAccelerated "false" gt lt intent filter gt lt action android name "android.intent.action.MAIN" gt lt category android name "android.intent.category.LAUNCHER" gt lt category android name "android.intent.category.LEANBACK LAUNCHER" gt lt intent filter gt lt meta data android name "unityplayer.UnityActivity" android value "true" gt lt activity gt lt meta data android name "unity.build id" android value "633a700a 7389 4a19 972c ac1f177788f8" gt lt meta data android name "unity.splash mode" android value "0" gt lt meta data android name "unity.splash enable" android value "True" gt lt meta data android name "android.max aspect" android value "1.86" gt lt application gt lt uses feature android glEsVersion "0x00020000" gt lt uses permission android name "android.permission.INTERNET" gt lt uses feature android name "android.hardware.touchscreen" android required "false" gt lt uses feature android name "android.hardware.touchscreen.multitouch" android required "false" gt lt uses feature android name "android.hardware.touchscreen.multitouch.distinct" android required "false" gt lt manifest gt And as you see add attributes like android maxAspectRatio amp android resizeableActivity to AndroidManifest manually. But by installing the app on devices with that specific ratio, the game still running full screen and out of the bounds. I am using Unity 2018.1.4f1 (64bit). |
0 | Unity 5.1 audio issues (no sound in back channels) I've trying to bring in surround sound audio into my project. I've set my computer up to run in 5.1 and when I play a 6 channel audio through windows media player (it's a test audio that does left speaker, right speaker etc) it works fine. However, when I run it through Unity, all I get is the front 3 channels. I've set it in the Edit project settings audio to be 5.1 in there. I even set it in code with following void Start() AudioSettings.speakerMode AudioSpeakerMode.Mode5point1 How ever, when I run a debug line of print ( AudioSettings.driverCaps) It tells me that Unity is only playing in stereo. Is there something I'm still not doing? I should also add I've ran 10 different tests using the 3D audio pan and spread options. I've set both to either being fully off, half way on and full. Still the same results. |
0 | How to check strings from multiple lines in one input field? I need help with input fields. I already set the line type to 'Multi Line NewLine' in inspector, but I have problem with submitting the string. Here's the code using UnityEngine using System.Collections using UnityEngine.UI public class GameController MonoBehaviour public string code public string code1 SerializeField public InputField input public void Check(string guess) if (string.Equals (guess,code)) Debug.Log ("correct") else Debug.Log ("wrong") public void GetInput(string guess) Check (guess) input.text "" I want to have both 'code' and 'code1' strings to be inserted in different lines inside the same input field but I don't know how to check both 'code' and 'code1' string value inside the Check(). Any help would be appreciated. |
0 | Worker threads are not being utilized in Time rewind system, is this job system really multi threaded? I am trying to make a simple time rewind mechanic. It's working but it becomes slower as number of game objects increases. I decided to give Job System a shot. My idea is to interpolate between positions and rotations for N game objects in parallel. It is certainly running faster than single thread execution. However, when I see the profiler, the worker threads are sitting idle. Here's the screenshot And here's the IJob code using System using System.Collections.Generic BurstCompile struct RewindJob IJob public int RewindableIndex ReadOnly public NativeArray lt Vector3 gt positions public NativeArray lt Vector3 gt finalPositions public float currentTime public void Execute() rewind code for interpolating b w positions and this is how I schedule RewindJob for each entity like this in main thread NativeArray lt Vector3 gt finalPositions new NativeArray lt Vector3 gt (m Objects.Count, Allocator.TempJob) for (int i 0 i lt m Objects.Count i ) NativeArray lt Vector3 gt positions new NativeArray lt Vector3 gt (count, Allocator.TempJob) TimeRewindable rewindable m Objects i for(int yo 0 yo lt count yo ) positions yo rewindable.m Transforms yo .position RewindJob rewindJob new RewindJob() rewindJob.finalPositions finalPositions rewindJob.positions positions rewindJob.RewindableIndex i JobHandle handle rewindJob.Schedule() handle.Complete() positions.Dispose() for(int i 0 i lt m Objects.Count i ) m Objects i .transform.position finalPositions i m Objects i .transform.rotation finalRotations i finalPositions.Dispose() finalRotations.Dispose() What I can understand is it's not real multi threading but context switching. Can anyone just explain a little bit what's happening? Thanks. |
0 | How to create an Editor class for a generic class For all my MonoBehaviour scripts, instead of them inheriting from MonoBehaviour they inherit from a generic class like so public abstract class MonoBase lt T gt MonoBehaviour where T MonoBase lt T gt public class Example MonoBase lt Example gt Now, I would like to make an editor script for all those MonoBase classes, and the closest I have gotten to a solution that will compile is CustomEditor(typeof(MonoBase lt gt )) public class MonoBaseEditor lt T gt Editor where T MonoBase lt T gt public override void OnInspectorGUI() this.DrawDefaultInspector() MonoBase lt T gt myScript (MonoBase lt T gt )this.target if (GUILayout.Button("Build Object")) But of course it doesn't really work. Am I missing something or is there really no way to make a generic editor class like it's mentioned in an answer here. |
0 | How do I slice a 3D object at runtime in Unity? I'm specifically looking for some sort of algorithm or way that can "cut" a 3 dimensional mesh with some other game object. How would I implement this? |
0 | Collision with supposedly aligned box colliders I am quite new to game development, and I am trying to create a top down game with 2D sprites, but with a 3D feel to it. I managed to do so with the 2D engine by setting Transparency Sort Mode to Custom Axis with the axis values set to (X 0,Y 1,Z 0). I then moved the pivot of GameObjects to bottom center and used the pivot as sorting point for the sprites. I am now trying to create the environment, but my character 'clips' against the Box Colliders, even though I did all I could think of to align them (same pivot coordinates, same collider offset and size). See the attached GIF for an example I think that the cause is mentioned here, but there are no solutions mentioned there. My two solutions Remove the colliders, group the objects in a parent object, and add the collider there. But then I would get the same issue if I place two of those instances next to each other. I am still pondering to drop this approach altogether and try the same in the 3D engine, but with a fixed camera angle. I lack experience to estimate if that would be a better approach, so if someone thinks that approach would be better suited to this game style, I am happy to hear it. Can anyone give me advice on this issue, or point me towards resources that might be useful? Thanks in advance, Florian Some pictures of the settings I used |
0 | Access Single Pass RenderTexture I'm trying to achieve a mirror effect where a second camera renders to a render texture, which is then passed into a shader using SetGlobalTexture. Everything works fine outside of VR, but in Steam VR it seems like the render texture only stores the texture for one eye (left), even with single pass stereo enabled in player settings. How can I access the texture for the second eye? Or rather, how can I access the texture where both eyes have been drawn, one on each half of the screen? What I'm doing at the moment void Awake() mirrorCameraRenderTexture new RenderTexture(vrCam.pixelWidth, vrCam.pixelHeight, 24) mirrorCamera.targetTexture mirrorCameraRenderTexture Shader.SetGlobalTexture(" MirrorCameraRenderTexture", mirrorCameraRenderTexture) |
0 | Physics.IgnoreCollision not working right after invoked When invoking Physics.IgnoreCollision in Unity, it seems work but it still have collision detection right after creation. I have this issue with ejecting empty case after gun fire, it's spawning position located inside of character controller(collider), so when ejecting case created, it immediately hit to my character controller and makes my character slows. First I thought that it's coming from something else, but it's not, because when I just not spawning the empty case, it never happens. This is the code GameObject ejectedCase Instantiate(emptyCasePrefab, caseSpawnPoint.position, caseSpawnPoint.rotation) Collider caseCollider ejectedCase.GetComponent lt Collider gt () Physics.IgnoreCollision(caseCollider, playerCollider) Note that playerCollider is Collider. I also tried with CharacterController(because it's extended from Collider class) but result was same. Why I said something like "it's not working right after invoked" because it's actually working after passed some time. If it's not work, character controller step on the empty case and makes camera jittering issue on vertical axis. This is totally gone after ignoring collision detection with above code, however it still works right after creation and makes my character really slow. How do I avoid this weird glitch, makes IgnoreCollision works right after it invokes? In addition I don't want to fix this issue with using Layer Collision Matrix. I didn't tried but it will work sure, however I don't want to spend Layer for this purpose only, because it's number is limited and already using lots of layers in other logics so it makes game logic more complicated if I use Layer to avoid collision detection. I want to know why "Physics.IgnoreCollision" not works because literally it saids "ignore collision" but it wasn't. |
0 | Sending a shot left right up down based on directional key press I am trying to make a top down shooter game with similar combat to the Binding of Isaac when I press the up key the shot goes up when I press the right key the shot goes to the right I have all the rest of the code such as the point where the projectile is instantiating and the if statement to check for the button press I just want to know where I should put the vector 2 to allow me to set the direction and what to write into the vector 2 private void Update() if (Input.GetKeyDown("up")) if (Time.time gt shotTime) Instantiate(projectile, shotPoint) shotTime Time.time timeBetweenShots This is my Projectile script (at least the parts that I think would be useful) void Update() transform.Translate(Vector2.up speed Time.deltaTime) I realized that if I change the Vector2.up to make it say Vector2.down it would now shoot down But I need that to be able to change depending on which direction I am shooting. |
0 | gazing and lip syncing in Unity 5.2 Is it possible to achieve gazing or lip syncing in Unity 5.2 at all, similar to Locomotion done through MecAnim? |
0 | Why am I getting a down arrow in my Unity scene when using Oculus Rift and how do I get rid of it? In Unity, I have set up a scene to try out in Oculus Rift. When I hit play in Unity, everything works fine until about 5 seconds later when I get an arrow (Assets OVR Textures out.png) that appears in the center of my screen and won't go away. What does this arrow mean and how can I get rid of it? It is obstructing my view of the level that I am trying to view. |
0 | Touch to continue (coroutine) in unity When the object gets destroyed in my game, I want a touch to continue function after a delay. This is what I tried. this is the SceneManager class which is attached to the Main Camera public bool ttc public void NextLevel() StartCoroutine(Delay()) IEnumerator Delay() yield return new WaitForSeconds(2) print("touch to continue") ttc true My Object class void OnDestroy() Camera.main.GetComponent lt SceneManager gt ().NextLevel() if (Camera.main.GetComponent lt SceneManager gt ().ttc true) if (Input.GetKeyDown(KeyCode.V)) Application.LoadLevel("TheGame2") I also tried this IEnumerator Delay() yield return new WaitForSeconds(2) print("touch to continue") if (Input.GetKeyDown(KeyCode.V)) Application.LoadLevel("TheGame2") side note I will change the 'KeyCode.V' to a mouse button later |
0 | Changes to one Unity trail renderer causes all of them to flicker I'm using Unity. So I have a prefab, and this prefab has a trail renderer component attached to it. However, for some of the game objects I want to stop the trailer renderer at certain points in time. But doing so seems to make all of the trail renderers blink flash off and on. I've tried changing time, disabling the component, and using Clear() while hiding the trail renderer behind the background before needing to be used. All of these makes all trail renderers flicker on the frame the change happens. I believe providing the code won't be helpful, it's just if(x) disable action, if(y) enable action. What can I do? |
0 | Technique to find a mesh intersecting with a primitive solid without using colliders? For what it's worth I'm using Unity3d, but I believe the problem is more general. There are hundreds if not thousands of meshes with hundreds of vertices each. There is one sphere that can be intersecting any of those meshes and is constantly moving. Are AABB colliders approximating the mesh's volume the best way to go about this? Or is there a more specific technique that can be used here? (A limitation I have is that my colliders need to be rotated, so they're each stored in a game object, so the number of game objects becomes absurdly large for my meshes(tens of thousands) which is slowing down my game.) I have a couple of properties unique to my situation I believe might allow me to ditch colliders I don't care about the meshes colliding with each other. Just the one sphere. I only need to know that the intersection exists, I don't care about the point of the intersection or any other metadata. Just a boolean of the intersection occuring and what mesh it happened with. I don't need to know the exact moment frame when the intersection occurs. If I can find out an intersection occurred within 100 200ms 20 30 frames of it happening it'll be fine. |
0 | Third Person Highlight "Usable" Objects I'm trying to figure out a good solution in a third person RPG to determine if the character is facing and close enough to an object for it to highlight and be shown as a usable item a door, or a chest, or any other usable object in the scene. I imagine the best approach is ray casting, but I've yet to figure out how this would actually work. I plan to have a usable script on all usable objects that defines what happens during use (a door or chest opens, a coin goes into your inventory, etc), but I need to know whether the player can use the item, highlight it, and also determine which object is the "best choice" based on facing direction and distance if multiple items are in range. |
0 | (unity) move the world or the character I'm making a game like this https www.youtube.com watch?v hO7573lphqI wherein a 3D ship is flying around on a 2D plane. From the player's perspective, the ship will stay stationary in the center of the screen. The question I have is whether it's better to have to ship stay stationary and the world move around the ship? Or should I have the camera follow the ship as it moves around? Notes assume the ship can go infinitely in any direction this is in Unity, though I'm curious if that differs from other tools like Unreal I will be culling items that are offscreen either way Obviously, having the camera follow the ship is easier from the programming side of things, but I'm wondering if there's a good reason not to do that (if the player moves far enough in one direction does it hit an internal limit that would break the game)? Thanks! |
0 | Handling rotation interpolation at 180 degrees I currently have a scene where 3d a gents move throughout a grid, each time they move that can pick a random cardinal direction up,down,left or right. They then rotate to face that direction using Quaternion.Slerp. However I noticed there were some edge cases where the agents didn't move at all, and found out the problem was being caused during rotations at 180 degrees. Doing some reading on this I found that Slerp and Lerp dont handle rotations at this degree very well if at all and now I'm at a loss on how to proceed. I tried using transform.rotateAround() to rotate the character around the Y axis to the direction, but again at 180 degrees the agents start to just spin in circles forever. Here's my current rotate code IEnumerator rotate() while(Quaternion.Angle(transform.rotation,direction) gt 0.3) var tempRotation Quaternion.Slerp(transform.rotation, direction, Time.deltaTime rotateSpeed) this.transform.rotation tempRotation yield return null this.transform.rotation direction Heres the code that handles picking where to go int choice Random.Range(0,4) prevPos pos if((choice 0) amp amp pos.x lt gs.maxX) pos.x 1 direction Quaternion.AngleAxis( 90,Vector3.up) else if((choice 1) amp amp pos.x gt 0) pos.x 1 direction Quaternion.AngleAxis(90,Vector3.up) else if((choice 2) amp amp pos.y lt gs.maxY) pos.y 1 direction Quaternion.AngleAxis(180,Vector3.up) else if((choice 3) amp amp pos.y gt 0) pos.y 1 direction Quaternion.AngleAxis(0,Vector3.up) If someone could point me in the right direction on how to handle this gracefully I'd really appreciate it! |
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 | How can I represent collection of distant but visit able stars while using minimal resources? I have recently started to plan a project in Unity that will be for Android. I have a database that consists of over 150,000 stars (may trim this down if I O cripples the overhead). The game will hopefully consist of a free to explore universe creating the illusion that the user is flying in a realistic representation of the stars. My biggest concern at the moment is how do I create a realistic environment with these starts, while keeping the resource impact on the phone to a minimum? Some people mentioned using octrees, would this be wise? This is my first game that I am looking to create so any help would be much appreciated to this novice! |
0 | 1 Texture For Multiple Models, Or 1 Model Using Different Textures For Each I'm creating some voxel flowers that are exactly the same, just different colours. Is it better to create 5 models and use 1 texture that has the 5 different colours, or create 1 model and use 5 different textures for each colour? Am curious as to which is more efficient in regards to performance, as there could be quite a few flowers on screen. I'm playing around with MagicaVoxel and Unity. |
0 | Not able to find the constraints option in the Rigidbody component I am working on a game tutorial right now and I need to freeze constraints for a model prefab. I add a Rigidbody component and I want to freeze rotations on the x and z axes. However, I am not able to find the option in the component. Is there another way to access rotation constraints (I do not want to code the constraints at the moment)? Or is there something I am missing in the new version. Please do let me know. Thanks I am using Unity 5.6.7f1 Personal |
0 | Client projectile ignores camera Y axis in multiplayer shooter I'm able to spawn the bullet and make it move. But the problem is, only the host can shoot the bullet in the way the camera is facing(takes both X axis and Y axis correctly). The client takes only the X axis of the camera and keeps the Y axis at zero. Here's the code for spawning and applying velocity Command void CmdFire() GameObject fb Instantiate(fireBall, spawnPoint.position, spawnPoint.rotation) fb.GetComponent lt Rigidbody gt ().velocity gameObject.GetComponentInChildren lt Camera gt ().transform.forward fireSpeed NetworkServer.Spawn(fb) And the code for the camera attached to the player void Update() mouseX Input.GetAxis("Mouse X") mouseSensitivity Time.deltaTime mouseY Input.GetAxis("Mouse Y") mouseSensitivity Time.deltaTime Horizontal Looking playerBody.Rotate(Vector3.up mouseX) Vertical Looking xRotation xRotation mouseY xRotation Mathf.Clamp(xRotation, 90f, 90f) transform.localRotation Quaternion.Euler(xRotation, 0f, 0f) |
0 | Unity Changing color of 2D sprite distorts sprite shape In my 2D game, my circle shape for example, appears round, but when I change the color then it turns into a low poly circle with 8 16 points, more like a potato. Is there any way around this? myColor new Color32 ((byte)colorR1, (byte)colorG2, (byte)colorB3, visibility) Color32 negativecolor new Color32 ((byte)colorR1, (byte)colorG2, (byte)colorB3, (byte)(255 visibility)) MaterialPropertyBlock props new MaterialPropertyBlock () props.SetColor (" Color", myColor) rend.SetPropertyBlock (props) props.SetColor (" Color", negativecolor) backchildrend.SetPropertyBlock (props) |
0 | How do I size my map in blender so it will be the right size in unity? I am working on a fps game but I cant get the size right of my map in blender, every time I export it to a .fbx file (unity won't work if it is a .blend file) it is a super small plane floor in unity the player controller is 10 as big as the map. I don't know what to do. |
0 | Speech recognition in Unity 5 for Android I've been working on a game in which the player have to say particular words to perform various tasks. For example, if the player says "boat", a boat pops up in the game. The game I'm building is specifically for offline play, on an Android device. Just for reference, there is a game titled "Pah!" which implemented this offline speech recognition for one specific word. In this game, when you say "pah", the GameObject moves jumps. I've tried everything from speech to text to forums, and even tried Google and used using Windows.Speech, but nothing works. From what I've learned, I need to use the Google speech API for Android speech recognition. I am a bit new, when it comes to Java. I gave it a try and created a basic script, which I thought might take at least one input in speech from the player, but Unity disagrees and says it couldn't recognize the script. I created another script in C , by taking help from tutorials, but when I switch the platform from Windows to Android it doesn't work, because Unity.Windows.Speech is a Windows namespace I am blank, and hence, this question. I have googled, visited forums, and even looked at YouTube videos for an answer. I came across a few Unity assets which I paid for, and they are all garbage. If anyone could help me, how do I implement speech recognition in Android, using Unity 5? |
0 | Line of sight shader Strategy games (such as Door Kickers) use a player's unit's line of sight as a major game feature. To provide feedback to the player regarding which areas are in view and which are not, different colours are used to display areas that are currently visible by a unit and areas which are not. Can anyone recommend an approach for creating this effect in a shader? |
0 | Unity NavMesh pathfinding using Job System I'm trying to write a system where I can run each enemy's NavMesh pathfinding in parallel, using Job System. The problem I'm having is that I can't pass the NavMesh agent argument as it's a reference type. InvalidOperationException PathfindJob.agent is not a value type. Job structs may not contain any reference types. I'm probably approaching this problem in a completely wrong way, but this is all I've come up with. Here's the current Enemy code using System.ComponentModel using Managers using Unity.Collections using Unity.Jobs using UnityEngine using UnityEngine.AI using UnityEngine.Jobs namespace Characters RequireComponent(typeof(Rigidbody)) public class Enemy MonoBehaviour Header("Stats"), SerializeField private int health 100 SerializeField private int damage 20 SerializeField private float aggroRadius 10f private Rigidbody body private NavMeshAgent agent private Transform target private void Awake() body GetComponent lt Rigidbody gt () agent GetComponent lt NavMeshAgent gt () target PlayerManager.GetInstance().GetPlayer() private void OnDrawGizmosSelected() Gizmos.color Color.blue Gizmos.DrawWireSphere(transform.position, aggroRadius) public struct PathfindJob IJobParallelForTransform public Vector3 TargetPosition public NavMeshAgent Agent public float AggroRadius public void Execute(int index, TransformAccess transform) var distance Vector3.Distance(TargetPosition, transform.position) if (distance lt AggroRadius) Agent.SetDestination(TargetPosition) I'm scheduling the job from the GameManager class. |
0 | How to code simple Goomba like AI for 3D Platformer? I'm making a 3D Platformer and have an enemy similar to a Goomba in terms of AI. How do I get the enemy to walk around and then follow the player when they're in range? |
0 | Why RaycastAll misses some objects? Update 2 (see below) I'm writing a turn based game. During setup phase time scale modifier equals to 0, what prevents running of any physics based code and FixedUpdates. User have freezed action and may make decisions. The problem is that sometimes I cannot select objects during the setup mode. I'm doing selection in the following way I obtain mouse position ray I run RaycastAll against this ray without limitations I check for hit objects, which has Selectable script on them. Then rest of the logic happens. Mouse handling looks like following Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) (...) RaycastHit hits Physics.RaycastAll(ray) DEBUG string debug quot Raycast all gave quot hits.Length quot hits quot for (int i 0 i lt hits.Length i ) debug hits i .collider.gameObject.name quot quot Debug.Log(debug) END DEBUG Sometimes though I'm not getting valid results from RaycastAll. Take a look at the following example I clicked top left blue ship. You may see a small sphere on it I wrote a debug code, which generates a series of spheres along the ray to make sure, that it is valid. Since you see only one sphere here, it seems like everything's OK (note that I added this code to diagnose the problem. Spheres surely aren't causing it) The scene view looks like following It should be clear on this image, that ray hits the ship's box collider. In this specific case, a couple of units next to ship is an explosion, which has bigger sphere collider. You can also see debug log from the session, which clearly says, that RaycastAll only hit explosion and it missed the ship, which is just next to it. Now the question is why RaycastAll doesn't return the ship along with the explosion? Note, that this problem happens more often and without near objects with colliders, sometimes I just cannot select a ship and all I have to do is to move camera, such that object is closer to center of the screen. Edit Now this gets interesting! I added some debugging. After the RaycastAll, I manually go over all colliders in the scene and verify the raycast. The code now looks like following RaycastHit hits Physics.RaycastAll(ray) DEBUG string debug quot Raycast all gave quot hits.Length quot hits quot for (int i 0 i lt hits.Length i ) debug hits i .collider.gameObject.name quot quot Debug.Log(debug) var colliders GameObject.FindObjectsOfType lt Collider gt () foreach (var collider in colliders) RaycastHit temp if (collider.Raycast(ray, out temp, float.PositiveInfinity)) Debug.Log( quot Manually verified, that ray hits quot collider.gameObject.name) END DEBUG And when I try to click the quot un raycastable quot object, I get Raycast all gave 1 hits MissileExplosion(Clone) Manually verified, that ray hits MissileExplosion(Clone) Manually verified, that ray hits Falcon(Clone) A bug in Unity engine? Edit Yup, a bug in Unity engine. Hey, We have been able to reproduce this bug and have sent it for resolution with our developers. Regards, Unity QA |
0 | What's the best for doing ground check? What's the best for ground check? I have a capsule player and I'm using the raycast technique but it's not accurate when it comes to slopes. So what's better? Overlapping, Raycasting, CheckCapsule, or CapsuleCasting? |
0 | Why are the inputs not changing the animation on keypress? I have been following this tutorial. You can watch 16 00 18 20 to see what I am trying to do. What should be happening is I press a key, my animation plays and the parameters or Inputs get updated depending on which key I press. There are no errors in my script, but the parameters or Inputs are not updating. I have checked that I am using floats and that all my names match up. I've watched this part of the video and checked that my code was exactly like his multiple times. When using the model that he used in the video, the inputs the inputs are working fine. So would this mean there is something wrong with my animation, or is this an issue in my script? using UnityEngine using System.Collections public class Player MonoBehaviour public Animator anim private float inputH private float inputV Use this for initialization void Start() anim GetComponent lt Animator gt () Update is called once per frame void Update() if (Input.GetKeyDown("1")) anim.Play("Armature Walking", 1, 0f) if (Input.GetKeyDown("2")) anim.Play("Armature TurnRight", 1, 0f) if (Input.GetKeyDown("3")) anim.Play("Armature TurnLeft", 1, 0f) if (Input.GetMouseButtonDown(0)) int n Random.Range(0, 2) if (n 0) anim.Play("Armature Walking", 1, 0f) else anim.Play("Armature TurnRight", 1, 0f) inputH Input.GetAxis("Horizontal") inputV Input.GetAxis("Vertical") anim.SetFloat("inputH", inputH) anim.SetFloat("inputV", inputV) Anyone got any ideas? |
0 | Unity3d Do I need to destroy gameobject AND script? From proper leak protection do I need to delete both of these or will getting rid of one take care of both? Currently I am destroying the script AND the gameobject private void OnDestroy() Destroy(this.gameObject) Destroy(this) |
0 | Problem with coroutines unity 3d I cannot understand why the coroutines are not waiting the designated number of seconds before executing the code below it. At the moment, the animation bleeds into the next state. I could get around this by using .time and if statements but I thought the whole point of coroutines is that you can avoid that sort of mess. public IEnumerator LoadBow() this.gameObject.GetComponent lt Animation gt ().CrossFade("Load Bow") yield return new WaitForSeconds(this.gameObject.GetComponent lt Animation gt () "Load Bow" .length) aimStates AimStates.Draw public IEnumerator DrawBow() this.gameObject.GetComponent lt Animation gt ().CrossFade("Draw Bow") yield return new WaitForSeconds(this.gameObject.GetComponent lt Animation gt () "Draw Bow" .length) aimStates AimStates.Aim public void Aiming() moveTarget.SetActive(false) switch(aimStates) case AimStates.Load StartCoroutine(LoadBow()) break case AimStates.Draw StartCoroutine(DrawBow()) break |
0 | How to make AI detect a target behind a wall, who is only partially exposed? I'm making an FPS game where, even when a target's whole body is behind a wall or box, but its finger or foot exposed, the AI should be able to detect it and shoot its finger. So far the way I've thought of to implement this it so traverse all the targets, find who is near a wall, and compare their position with the corner of wall. But I don't know how to check whether its finger is exposed. I could use a raycast forward from the AI's gun, but would I need to add a collider to every small body part of every target? |
0 | Memory game texture on cards I'm new with Unity and I'm working on recreating memory game. I found this sample http xtasestudios.com unity samples (select "Memory"). I decided for C . I've created my own card in Blender, added 3 different materials (without textures), also I created flip flop animations. After importing .blend file in Unity and assigning scripts, textures, animations, positioning camera etc.. Everything works fine, except textures on cards. I can change color on cards, but when I want to see any texture on my card, I see only color, not whole texture. I really have no idea why is this happening and how to fix it. Any help will be appreciated! |
0 | What is the standard practice for animating motion move character or not move character? I've downloaded a bunch of (free) 3d warriors with animations. I've noticed for about 25 of them, the 'run' animation physically moves the character forward in the z direction. For the other 75 , the animation just loops with the characters feet moving etc., but does so in place, without changing the character's physical location. I could fix this by 1.) Manually updating the transform in code for this 75 , to physically move the character 2.) Alter the animation by re recording it, with a positive z value at the end (when I did this it caused the character to shift really far away the rest of the units, probably something to do with local space vs world space I haven't figured out yet). But before I go too far down this rabbit hole, I wonder if there is any kind of standard? In the general case, are 'run' 'walk' animations supposed to move the character themselves, or is it up to the coder to manually update the transform while the legs move and arms swing in place? Is one approach objectively better than the other, or maybe it depends on the use case? If so, what are the drawbacks of each? I know nothing about animation, so I don't want to break convention (if there is one). |
0 | Reverse Movie in Unity 5 guys! Is it possible to reverse video or apply a rewind in Unity 5? I searched in the web but could not find the solution. |
0 | Prevent showing movie files after packaging unreal game I developed a game which has some videos inside it. I added videos into my project folder so that I can access them. After packaging, on the folder all videos will be shown as its original format which everyone can play it. How is it possible on release version no one can go to game folder and play it? Maybe some kind of encryption or change format of file which only its game can play it would help it. For example when you have a game on your computer, the only way to see the video is that you play the game and you will see relevant videos in the right time. However, after packaging, all videos will be on a folder any everyone can go to the folder and play it and see videos even without playing game. In Unity after releasing the game, you can't access assets, it will be shown in a file with .resource extension so no one can access it. However, in Unreal Engine, it will show the real file. |
0 | ArgumentException The Object you want to instantiate is null I am trying to copy data over from a binary file but when trying to instantiate a gameobject, it comes out as "null". static void LoadBuildings(SaveBuilding buildings) if (buildings.Length 0) return foreach(SaveBuilding b in buildings) if(b.type.ToString() "Farm") Farm build Instantiate(Resources.Load("Farm")) as Farm Debug.Log("Build " build) build.position.x b.positionX build.position.y b.positionY build.level b.level build.levelText build.GetComponentInChildren lt Text gt () The debug line shows there is no object and when the next line tries to execute I get an error ArgumentException The Object you want to instantiate is null. I initially had it as Farm build Instantiate(build.prefab) as Farm as I get an error "Use of unassigned local variable". I tried adding a prorperty above the if statement "GameObject build", I tried doing Farm build new Farm() above the if statement also but still get the initial error. I have a folder titled "Resources" and confirmed a prefab labelled "Farm" is there also. Could it have anything to do with the "static" prefix for the method? |
0 | How to detect which car T boned the other in a collision? Setup The game has cars and collisions, and I'm trying to create the following system When a car T bones another, the one getting T boned is destroyed When the cars collide laterally (usually just bump into each other), a normal physics collision happens (and nothing is destroyed) When the cars collide head on, the lighter one is destroyed. The cars are all instantiated from 1 prefab. This can't be changed. Car Setup The main body sans the bumper has a normal, non trigger collider and the dynamic Rigidbody. It has the tag quot Destructible quot . A child object (which also houses the bumper model, but that shouldn't matter) has a normal, non trigger collider for the bumper. It has no Rigidbody and reports to the parent's Rigidbody. It has the tag quot Destroyer quot . Attempted Solutions 1) The transform.forward solution Get the transform.forwards of both cars and compute their dot product. If the 2 vectors are opposite each other (or close to it), destroy the lighter car. If the vectors are facing away from each other (or are close to parallel), let a normal collision happen. If the vectors are perpendicular (or somewhere in that ballpark)... then I'm lost. How do I know which car T boned which? That brings us to the solution 2. 2) The 'multiple colliders' solution Assign another collider to the bumper of the car and give it a separate tag (e.g. quot Destroyer). As a consequence, give the other main collider a tag, too (e.g. quot Destructible quot ). If a Destroyer collider hits a Destructible, the latter is destroyed. If a Destructible hits a Destructible, a normal physics collision happens. If a Destroyer hits a Destroyer, destroy the lighter one. But here, I run into an issue. You can't have multiple colliders on the same game object. Ergo, create an empty child and attach it there. I won't set it to Trigger, or otherwise it won't detect collisions with another of its type (i.e. Destroyer). In order to destroy colliding objects, I need a script and an OnCollisionEnter() inside it. OnCollisionEnter() won't run if neither of the game objects has a non kinematic Rigidbody. This means I need to give the bumper colliders a non kinematic Rigidbody. But if I give them dynamic Rigidbodies, they'll just... float away from the car. In other words, I need a way to create a 2nd collider but keep it firmly attached to the car. Furthermore, if the main collider covers it, then I need to exempt it from collisions with the 2nd collider (let's call it the sub collider), and I can't use layers to do that or otherwise the sub collider won't detect main colliders on other cars. If I don't cover it, then I need the sub collider to act as a normal physics collider, too, when it hits, for example, a wall, and not have the bumper sink into it. That means it needs a non kinematic Rigidbody. How can I solve this issue? |
0 | Unity RigidBody not rebounding as expected on low impact collisions I have a Rigidbody2D with a CircleCollider2D, on which I display a sprite of a circle. This Rigidbody can be "shot" in my game. I also have 4 rectangular BoxCollider2Ds on the edges of the game screen. When I shoot the circle, it rebounds fine from the rectangular colliders, except for cases when the impact velocity normal to the rectangular collider's surface is very small. In that case, the rebound velocity in that direction is somehow zero. Here is the circle's RigidBody2D and CircleCollider2D setup Here is the BoxCollider2D of the rectangular collider The material "New Physics Material 2D" attached to the ball and the BoxColliders has Friction set to 0 and bounciness set to 1 Here are two gifs, the first one demonstrating how it works (correctly) in most cases, and the second one demonstrating what happens on a low velocity impact. The "choppiness" of these gifs is due their "giffy" nature. In my game, the movement is smooth. I'm wondering why, on the low velocity impacts, the ball doesn't rebound in the same way as on the high velocity impacts (i.e, by the outbound angle inbound angle rule)? Edit I stepped into the circle's void OnCollisionEnter2D(Collision2D collision) method, and, sure enough, on the very slow collisions, the collision.otherRigidbody.velocity had a zero component for the slow velocity of the incoming collision (so depending on whether the impact's x or y velocity was slow, the respective component of the resulting velocity was, for whatever reason, set to 0). Oddly enough (at least for me I am still not completely familiar with all of Unity's in's and out's), the collision.relativeVelocity had been updated to hold the correct resulting velocity of the impact. Thus, by adding following code to the OnCollisionEnter2D method, I am able to handle the collision correctly, even on low impact collisions if (collision.otherRigidbody.velocity.x 0) collision.otherRigidbody.velocity new Vector2(collision.relativeVelocity.x, collision.otherRigidbody.velocity.y) if (collision.otherRigidbody.velocity.y 0) collision.otherRigidbody.velocity new Vector2(collision.otherRigidbody.velocity.x, collision.relativeVelocity.y) While this seems to solve the issue I am experiencing, it doesn't seem to me that I should need to be doing this... |
0 | Weird "jiggly" "warping" effect on my tiles I need help with a problem I'm having in Unity regarding a quot jiggly quot quot warping quot effect. It is a strange effect which occurs when I move my sprite character and makes the tiles have additional pixels which aren't on the sprite and disappear when you move more. I've also linked a video of my issue you can see it more clearly on the tree. To note My tiles are 16x16, my fox sprite is 64x64 and the enemy sprite is 48x48. I'm using Cinemachine. |
0 | Select a button without calling click i have a grid layout group containing buttons. My game must be playable with a joystick and so I have to navigate the buttons using horizontal vertical input. My problem right now is when the layout group first becomes visible. Once I click on a button (with my mouse), it becomes "selected" and I can navigate through the layout group with my keyboard and 'click' with spacebar. This functionality is all fine, except for the need to click the button with a mouse to set the first selection. I've tried both of the following void buttonClicked() Debug.Log("clicked") void Start () this button is actually instantiated from a prefab, not shown here Button btn inventorySlot.button btn.onClick.AddListener(buttonClicked) attempt 1 btn.Select() attempt 2 eventSystem.SetSelectedGameObject( btn.gameObject, new BaseEventData(eventSystem) ) both these commands do select the button, but they also inadvertently call the onClick, and the button is clearly being clicked because it changes color (I have configured this through button opts in the inspector). My question is how can I "select" the button without clicking it? I perhaps should also note, I am populating the layout group with buttons at runtime. Each button is intantiated from a prefab in Start() (not showing that here). I only add the event listeners and try to select the button after it's already added to actual game objects in my scene. |
0 | Waitforseconds is skipping over I have a function for a timer using waitforseconds but instead of waiting for how long I want to, it just skips it. A ui text should become "foo" then 5 seconds later become "bar" but it turns to bar as soon as it starts. Code void Update () text1.text "foo" wait (5) text1.text "bar" IEnumerator wait(int time) yield return new WaitForSeconds(time) |
0 | Unity3D Tag as a public variable in editor How do you incorporate Tag strings into a scripts editor found in the inspector? What it is I'm babbling about When you create a public GameObject fooObject in a script, it shows up as a box that can have Game Objects dragged onto in its editor. It also has a small clickable dot that shows every Game Object that could be selected. Now, say I have a public string fooString that would specifically be used for referencing the Tag strings of Game Objects (such as if (fooObject.tag fooTag) or another use). Is there a way to define that string so that in the script's editor it strictly allows tag names to be used with it? I'm assuming with a similar clickable dot or a drop down menu of every selectable tag. Although I could just manually type my string, a solution like the one above would have big object orientated advantages. For example, if I was to change the name of this tag, it would change the string variable accordingly, as if the variable was a reference to such tag. Note to the moderators I looked for an answer to this question for nearly 2 hours now to no avail. I understand that I may be missing some specific wrong word choice, in which case this question easily could have already been answered here. If this is closed as a duplicate, then, a quick comment explaining my mistake would be greatly appreciated. |
0 | Unable to save player data in a binary file within Update() method I'm trying to save player life within a binary file in Application.persistenceDataPath. I've written a method to store the player life public void SaveLife() BinaryFormatter bf new BinaryFormatter () FileStream file File.Open (Application.persistentDataPath " playerInfo.dat", FileMode.Open) PlayerData data new PlayerData () data.savedLife life bf.Serialize (file, data) file.Close () The problem is that when the SaveLife() is called OnApplicationQuit it works. Instead, if I call it within an Update() method of a class, it doesn't work. The Update() method is called when a certain event is triggered void Update() if (life lt 20) if ( certain event is triggered) SaveLife() lifeTimer Time.deltaTime if (lifeTimer lt 0) ResetLife () The container class for the data is Serializable class PlayerData public int savedLife What could be the problem? |
0 | How can I separate gameview from UI most efficiently in Unity? Let me provide an image to illustrate what I mean. It is from a game called Runescape. |
0 | How to generate a "loop room" in a platformer game (by Unity)? I want to build a level with a room whose left edge is linked to right edge in a 2D platformer game in Unity. My goal is let all objects disappear in one side will appear in other side of the room. Just like this Both sides should have collision with other objects. Right now I'm doing this by cloning objects on the other side, but it is too complicated. Is there any other good way to solve this? |
0 | Make the texture array node work with cubemaps? I am working on a procedural interior mapping shader in Unity's Shader Graph. Ideally, I'd like to feed it a set of cubemaps it can pick from semi randomly. However, it seems that by default the texture array asset one can provide to a graph does not support reading cubemaps. Does anyone have a way to use this, or perhaps a clever custom node or alternate texture mapping, so that I can read a number of cubemaps into the shader semi randomly? Preferably an arbitrary number, but even a fixed number would be somewhat of an improvement. |
0 | Unity5 UI How to trigger button click event while preventing menu item deselect event? So I've got a load menu using Unity's new UI system, basically just a list of save games you can select with a mouse click along with a couple of buttons at the bottom to delete or load the selected game file. I've been disabling the Load Game and Delete Game buttons using the interactable attribute whenever a saved game item in the list is deselected deleteButton LoadPanel.GetComponent lt Button gt ().interactable false loadButton LoadPanel.GetComponent lt Button gt ().interactable false This disables the buttons fine, but when I click on a saved game and then click a button, the deselect event for each save file is triggered BEFORE the onclick event for each button. This is no good. If I have no deselection event for each individual save file I can click on each save file and then click the load or delete buttons and every thing works fine, but the buttons never get disabled which is not ideal. My question is How can I disable the buttons when an item is deselected, but still trigger the onclick event when they are selected? Are there any workarounds to this? |
0 | Large Mesh at a far distance So I am trying to do something like KSP, where I have a ground to orbit Level of Detail with the planets. And from theirBuilding a new Universe Video I know they are using scaled space, and local space, where (as i assume) The whole planet is divided in smaller quads. This is all fine but from my understanding They are all still in the same unity scene and rendered( if they re not invisible( isn t that automatically decided by the cpu gpu?)). But now to my question. Even if such a Quad just has 16x16 Vertices, it s still up thousand if not millions of units away from the scene origin and you and the camera(I know there are two cameras for near and far) Wouldn t this quad produce a lot of lag and be really inefficient? Or is this not a problem for unity. Generally how far can I put things in unity? Please also note that I know about the the trick where they move everything back to the origin if the ship passes 6000 units, to reduce the jittering. |
0 | How to increase drag sensitivity while dragging distance is less than a certain value I built a inventory hotbar wheel for mobile controls. The wheel can be accessed if I put my finger on a specific quot hitbox quot on the right side of the screen and drag left. The result looks like this. I haven't added in item icons and such, but the black stain things are going to be the outlines of the items, and there will be item icons in the middle of them. As you can see, the larger, darker outline is the active item (the one that will be used equipped from the inventory). I have coded the script for the inventory so that the active item will be 3 slots away from the right side of the screen. This is the script public class Quick Acces Slider MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler public Image quickAccessSlider public Canvas canvas public float slotDistance public float slotPosition public float trueOffset public float offset public float canvasWidth public Vector2 originalPosition public Vector2 position public float slideDistance public float slideCap public float scrollSpeed Start is called before the first frame update void Start() canvasWidth canvas.GetComponent lt RectTransform gt ().rect.width public void OnPointerDown(PointerEventData drag) originalPosition drag.position slotPosition new float quickAccessSlider.transform.childCount slotDistance 1f (slotPosition.Length) offset trueOffset slotDistance for (int i 0 i lt slotPosition.Length i ) slotPosition i ((i slotDistance) (slotDistance 2)) offset if (quickAccessSlider.transform.GetChild(i).gameObject.activeInHierarchy) slideCap slotPosition i OnDrag(drag) public void OnDrag(PointerEventData drag) position originalPosition drag.position slideDistance Mathf.Clamp(((position.x canvasWidth) 2f), 0f, slideCap) for (int i 0 i lt slotPosition.Length i ) Scale active objects, change color, etc quickAccessSlider.rectTransform.anchoredPosition new Vector2(slideDistance quickAccessSlider.rectTransform.rect.width, quickAccessSlider.rectTransform.anchoredPosition.y) public void OnPointerUp(PointerEventData release) Array.Clear(slotPosition, 0, slotPosition.Length) originalPosition Vector2.zero position Vector2.zero slideDistance 0 The inventory slider is set up so that there is a rectangular panel, with the item slots as its children, and the pivot point of the panel is the right side of the screen, as such Essentially, right now, because I have the offset value which makes the active object the one that is 3 slots from the right side, I actually have to swipe a certain amount before I can get to the first active item. I want to make it so that the slider is more sensitive to drag while the slide distance is less than the offset value, so that I don't have to drag as mush to get to the active item. I also want the effect to work in the reverse scenario, where I am trying to stow the slider (dragging toward the right of the screen). I've tried a few methods such as where I tweak the slideDistance while it is less than the offset, or where I try to Lerp the slideDistance value to the offset value, but none of them seem to work due to a few reasons. The main reasons my solutions didn't work was because the slideDistance value needs to be equal to the offset value once I'm done tweaking the value it is not longer less than the offset value to prevent jittery movement, and because I need the increased sensitivity to work both ways, when dragging left and also dragging right. |
0 | Unity sprite rig affecting performance I created a simple sprite rig using the skinning editor provided by the new 2D Animation V2 package. But it causes a huge FPS drop when added to the scene. Methods such as SpriteSkin.LateUpdate generates significant amount of garbage as shown in the picture See the spike shown on the CPU profiler when the rig is being enabled The rig is not even animated. I also checked the other sample rigs provided by Unity and they also performed in a similar fashion. Is this normal? I'm targeting mobile, so anything that can be done to avoid or improve the situation will be helpful. I'm using 2d animation v2 2.0.0 preview.2 in Unity 2018.3.8f |
0 | unity Tilt Android Device player Freeze When Die I attached tilt script to my Player to move player x and y Axis. Player have Rigidbody2D and also IsKinematic true. but the problem when the player can Die i want to stop tilting and player goes down to ground. here is my tilt Code public float Speed 20f void Update () if (PlayerControll.instance.isAlive) transform.Translate (Input.acceleration.x Speed Time.deltaTime, Input.acceleration.y Speed Time.deltaTime, 0) else PlayerControll.instance.PlayerRigidbody.isKinematic false I try to do that using disable tilt script when Player die and Iskinematic false but the problem is player can freeze to his position not goes down to the ground. I do that so many way but not done so what i do don't know then i post the Question. thanks in advance. |
0 | Game states passing data between scenes I'm not entirely sure if I'm doing this right, but I always considered the scene system in Unity as some sort of state management (rather than e.g. a level system) which allows to group the contents (entities, components) into the usual main states of the game (menu, ingame), which can then be invoked or replaced together. Now I have a very specific concern and I have no clue how to deal with that in Unity, mostly because of it's abstractions from code and other restrictions My game features a procedurally generate terrain where as I'd like to tweak the generator before actually launching it. The tweaking is done in some sort of 'pre game' state (as part of the main menu) where the values are stored in e.g. TerrainData model class. Usually in other engines, I'd to it like this Providing an UI within the menu state to tweak the parameters of the game Storing the parameters in a view model (and data model) Instantiate the ingame state (which requires said data model in the .ctor Pass the data model to a generator and start the generation Now, here are the main problems Most types in unity (scenes, monobehaviors) do not allow constructors because they use it for themselves It doesn't seem possible to instantiate scenes manually (there's only e.g. Application.LoadLevel("") which only takes the name of the scene, not a instance reference etc. it doesn't seem possible to pass data between scenes, without reverting to awkward workarounds such as singletons, playerprefs, DontDestroy etc. which are all not really suitable for this case. So, how can I properly solve this? Is there a better way to manage states rather than scenes? Prefabs maybe? Backlink to UntityAnswers question http answers.unity3d.com questions 1149480 game state management and passing data between sce.html |
0 | Prevent Unity from crashing your computer? Recently, I made a very dumb mistake that caused Unity to crash my computer. I could move the mouse sometimes, but everything else became completely unresponsive, leading to me having to shut off my PC. What happened I had an object, let's say an arrow, that could collide with another object, let's call it spawner. When the arrow collides with the spawner, it's supposed to destroy the arrow that activated the spawner. The spawner would then, as the name might imply, spawn more arrows. The problem was that I forgot to temporarily disable to collision on the newly spawned arrows, meaning that as soon as they would spawn inside the spawner's collision box, they'd spawn more arrows, and those arrows would spawn more arrows, and those arrows would... you get the idea. It was a very stupid mistake I realized the moment I hit play, but it was too late. Now, I know that was entirely my fault, but I was wondering if you could prevent Unity from sending your PC into a coma like that? (Besides not making a dumb mistake like that, of course...) I'll be honest, I kind of expected Unity would have some sort of fail safe for this kind of error. Is there a way to limit the object count for example? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.