_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 |
Character rotation according to camera causes rapid flipping when game starts When I load my scene, my character rotates 90 and 90 on the X axis very fast about 4 or 5 times, and then he stops at 90 on X axis (lays back down). When I move the character, the rotations are just the way I want them, but I need to fix that weird bug at the beginning of the game. Here's my character's movement logic. It's based on the rotation of the camera, which is a child of my character object. void Update() Vector2 vec new Vector2(horizontal, vertical) vec Vector2.ClampMagnitude(vec, 1) Vector3 camF cam.transform.forward Vector3 camR cam.transform.right camF.y 0 camR.y 0 camF camF.normalized camR camR.normalized transform.position (camF vec.y camR vec.x) Time.deltaTime MoveSpeed Vector3 deltaPosition transform.position prevPosition if (deltaPosition ! Vector3.zero) transform.forward deltaPosition prevPosition transform.position
|
0 |
How to restrict the players movement win relation to screen bounds in Unity? (Without colliders) I am really enjoying making the switch to Unity. But here I have found one of those rare moments where it appears to make things more difficult (at least it is for me as I am crap at understanding the actual manual) Basically my 'player' is a space ship. It starts life at 0,0,0 world coordinates and I have been doing all the movement based off of that. (ie. Add force X to move left or right, and there is a constant Z speed which is done via rb.transform.Translate().) I want to restrict the movement on the X Axis, so in Libgdx id use something like if (player.position.x lt 0) player.position.x 0 if (player.position.x gt viewport.getX()) player.position.x viewport.getX() The thing is that wont work for me in Unity for several reasons (1. I dont know much about the viewport as I didnt create it. 2. the player.position is being affected by the rigidbody forces. AND i am working in world coordinates with the players position). As I said, the player is constantly moving forward on Z axis, so making colliders doesnt seem like the right choice for me. I'm pretty sure Unity devs would of put this in Unity v0.001 but I just cannot for the life of me find how to actually do it. (Any info I can find seems from like 2011 and also is pretty badly written code making this simple matter takes dozens of lines of code and some methods I'm hoping there is a Unity method already made, like player.transform.ScreenPosition or something but yeah I cannot find it!? Any help would be massively appreciated as always.
|
0 |
Unity Quaternion Rotate Unrotate Error I'm trying to un rotate a quaternion, aligning it with the axis, and then rotate it back to where it was originally. But with every iteration it seems to lose precision and just after 20 iterations the rotation disappears. Here is an example, which is a simplification of my code Quaternion rotation Quaternion.Euler (0f, 90f, 0f) Debug.Log ("Before " rotation.ToString ("F7") " Euler " rotation.eulerAngles.ToString()) int iterations 1 for (int i 0 i lt iterations i ) var currentRotation rotation rotation Quaternion.Inverse (currentRotation) rotation rotation currentRotation rotation Debug.Log ("After " rotation.ToString ("F7") " Euler " rotation.eulerAngles.ToString()) With 1 iteration the output is Before (0.0000000, 0.7071068, 0.0000000, 0.7071068) Euler (0.0, 90.0, 0.0) After (0.0000000, 0.7071067, 0.0000000, 0.7071067) Euler (0.0, 90.0, 0.0) With 5 iterations Before (0.0000000, 0.7071068, 0.0000000, 0.7071068) Euler (0.0, 90.0, 0.0) After (0.0000000, 0.7071019, 0.0000000, 0.7071019) Euler (0.0, 90.0, 0.0) With 10 iterations Before (0.0000000, 0.7071068, 0.0000000, 0.7071068) Euler (0.0, 90.0, 0.0) After (0.0000000, 0.7059279, 0.0000000, 0.7059279) Euler (0.0, 90.0, 0.0) With 15 iterations Before (0.0000000, 0.7071068, 0.0000000, 0.7071068) Euler (0.0, 90.0, 0.0) After (0.0000000, 0.4714038, 0.0000000, 0.4714038) Euler (0.0, 90.0, 0.0) And finally with 19 iterations Before (0.0000000, 0.7071068, 0.0000000, 0.7071068) Euler (0.0, 90.0, 0.0) After (0.0000000, 0.0000000, 0.0000000, 0.0000000) Euler (0.0, 0.0, 0.0) At the 19th iteration the euler angles becomes zero, and at previous iterations altough the euler angles are still correct, if I rotate a vector with the quaternion its magnitude is changed. I hope you can help me and sorry for my bad english!
|
0 |
How can I check if the text string is not equal and then to do something? using UnityEngine public class DrawLines MonoBehaviour public LineRenderer lineRenderer public string text private Vector3 positions private string oldText private void Start() if (lineRenderer null) lineRenderer GetComponent lt LineRenderer gt () lineRenderer.startWidth 0.3f lineRenderer.endWidth 0.3f 0, 0, 0 5, 0, 0 5, 5, 0 0, 5, 0 positions new Vector3 5 new Vector3(0, 0, 0), new Vector3(5, 0, 0), new Vector3(5, 5, 0), new Vector3(0, 5, 0), new Vector3(0, 0, 0) DrawLine(positions, Color.red, 0.2f) void DrawLine(Vector3 positions, Color color, float duration 0.2f) GameObject myLine new GameObject() myLine.transform.position positions 0 myLine.AddComponent lt LineRenderer gt () LineRenderer lr myLine.GetComponent lt LineRenderer gt () lr.positionCount positions.Length lr.startColor color lr.endColor color lr.startWidth 0.1f lr.endWidth 0.1f lr.useWorldSpace false lr.SetPositions(positions) void DrawText() for (int i 0 i lt positions.Length i ) if (oldText ! text) var pos Camera.main.WorldToScreenPoint(positions i ) text positions i .ToString() var textSize GUI.skin.label.CalcSize(new GUIContent(text)) GUI.contentColor Color.red GUI.Label(new Rect(pos.x, Screen.height pos.y, textSize.x, textSize.y), text) GUI.contentColor Color.green GUI.Label(new Rect(pos.x, Screen.height pos.y 20, textSize.x, textSize.y), i.ToString()) private void OnGUI() if (positions ! null) if (positions.Length gt 0) DrawText() I added oldText variable but not sure how use it more then I did so far. I want that if the text is the same in the loop then don't show this text not in red not in green. Each time show the text once if it's not equal. When the square is closed
|
0 |
How do I properly light characters in a Unity scene? I made a game prototype and want to improve some of rendering the visuals through light baking (which I'm new to). While I was mostly able to do this in my environiments, I'm having issues doing this for my characters in Unity. Previously, they came out with odd ish dark shadows in places as they were affected by light and dull colors. After I begin light baking though and adding Light probes in areas that my characters would be extremely light, especailly on the skin areas. It doesn't look good at all. Alternatively, without using light probes, it looks like this. I'm genuinely confused on how to properly light these characters if I can't get a middle ground of proper lighting. Can anyone help me try to understand this and solve this problem?
|
0 |
Support multiple gamepad layouts (Unity 2017.3) My game supports touchscreen, keyboard mouse and the Xbox One controller and the input so far works properly. Now I also want to add a second layout for the gamepad the player can then pick in the settings, e.g. Layout 1 Fly up with "A", fly down with "B" (so two buttons) Layout 2 Fly up with "LB", fly down with "LT" (LT uses an axis, not a button!) With keyboard touchscreen and gamepad input I was able to create two different inputs in Unity's InputManager for the same thing and they would then trigger depending on which input device you're using. I thought about adding a bool for the layouts and checking it every time a button is pressed but that sounds more like a quick and dirty solution. Descriptions of InputManagers I've found so far make it sound like they're used for rebinding keys or to support different gamepads (e.g. Xbox One and PS4), which I don't want need (plus, these InputManagers are usually pretty expensive). How do you handle actual different layouts that use the same buttons axis for different things, especially with something using a button in the first layout and an axis in the second?
|
0 |
Unity How to add bones to procedural mesh Basically this is the set up An N amount of prefabs are bundled together into a new GameObject. This is then merged into a single main mesh composited of M amount of material submeshes. The shape is standing upwards on the Y axis and is a bunch of arms. The goal is to move these by adding bones. I wasn't able to find many examples on how to properly assign bones to a procedural mesh which isn't a simple cube. The problem is assignment of vertices to the boneweights. I'd like for the transform Y 0 vertices to have no weight and the Y furthest vertices have full weight. I am not sure how the assignment should be done.. Any pointers? ) So far the Lower and Upper bone transforms are in the right place, but when moving them the mesh isn't bending as I hoped it would in a nice curve, half of the vertices are simply moved uniformly with a thin mesh line connecting the two halves. private void AddBones() if(m SkinnedRenderer ! null) Make bone weight for vertices BoneWeight weights new BoneWeight m MainMesh.vertexCount int halfway (weights.Length 2) for (int i 0 i lt weights.Length i ) if(i lt halfway) weights i .boneIndex0 0 weights i .weight0 1 else weights i .boneIndex0 1 weights i .weight0 1 m MainMesh.boneWeights weights Make bones and bind poses Transform bones new Transform 2 Matrix4x4 bindPoses new Matrix4x4 2 bones 0 new GameObject("Lower Bone").transform bones 0 .parent m MergedRoot.transform bones 0 .localRotation Quaternion.identity bones 0 .localPosition Vector3.zero bindPoses 0 bones 0 .worldToLocalMatrix m MergedRoot.transform.localToWorldMatrix bones 1 new GameObject("Upper Bone").transform bones 1 .parent m MergedRoot.transform bones 1 .localRotation Quaternion.identity bones 1 .localPosition new Vector3(0, 1.5f, 0) bindPoses 1 bones 1 .worldToLocalMatrix m MergedRoot.transform.localToWorldMatrix m MainMesh.bindposes bindPoses m SkinnedRenderer.bones bones m SkinnedRenderer.sharedMesh m MainMesh m SkinnedRenderer.rootBone bones 0
|
0 |
Lightmapping runtime combine children Is it possible to have lightmapping on runtime generated combine children in Unity? It is possible to bake combined meshes when they are done in the editor, but the .apk .ipa size increases too much.
|
0 |
How to animate material change to get a status bard effect, in unity Imagine a long cube, like a bar, that has a dark material, and you want to animate changing its material to a light material, but do it gradually from one end to the other, like filling up a tube, or like a progress bar that fills from one end to the other. Is there a way to achieve this in Unity? Or do you need to generate the animations in Blender or similar and control them in unity?
|
0 |
how to make turret only shoot when pressing in specific location? im using this code to shoot bullets from turrets, it is working perfectly but what i want to do is that, if i ll click mouse at the bottom of it it will still shoot i want it to only shoot if i will click on those positions i ll attach image to explain what i want to do here is my code using System.Collections using System.Collections.Generic using UnityEngine public class shoot MonoBehaviour public Rigidbody2D projectile public Transform fireTransform public GameObject missilePrefab public float fireForce 90000 public Transform projectileSpawnPoint public float projectileVelocity public float timeBetweenShots private float timeBetweenShotsCounter private bool canShoot protected Animation Animation void Awake() Animation GetComponent lt Animation gt () void Start () canShoot false timeBetweenShotsCounter timeBetweenShots void Update () if (Input.GetMouseButton(0) amp amp canShoot) GameObject missile Instantiate(missilePrefab, fireTransform.position, transform.rotation) Animation.Play () Rigidbody2D missileBody missile.GetComponent lt Rigidbody2D gt () AudioSource audio gameObject.AddComponent lt AudioSource gt () audio.PlayOneShot ((AudioClip)Resources.Load ("sh")) missileBody.AddForce(transform.forward fireForce) canShoot false if (!canShoot) timeBetweenShotsCounter Time.deltaTime if(timeBetweenShotsCounter lt 0) Animation.Stop () canShoot true timeBetweenShotsCounter timeBetweenShots
|
0 |
Placing units on isometric map (2D) I'm making a map editor for further RTS game (2D), something like the first StarCraft Editor. Terrain tiles will be a rhombuses. So I'll probably just make an 2D array with intigers, that corresponds proper tiles. Then, after creating the terrain, you'd probably like to add some units and structures to map (especially if you're making a scenario). I'm not sure how do I check if the unit can be placed somewhere. I decided to make units almost independent from terrain tiles like in StarCraft (1), so the units are not placed in any grid. I'll give a simple image As you can see, those green tiles represent a passable area (grass, let's say), and a blue one impassable (for example water). That stickman in a box is our unit. You can place it only in green area. That means the box can't go outside the green rhombuses. I have some ideas how to achieve this, but I'm not sure which one would be the most optimal. 1) Since I work in Unity, I could add a collider to every tile. That will be very simple to do and will probably have terrible optimalisation in maps 256x256. 2) Math. I can calculate if any of those boxes crosses tile's borders. If so, I'll have to check if all those tiles are passable. It won't be that easy to programme (well, for me at least) and... yeah, here comes my dillema. Am I right that it would have much better optimalisation? Is it worth the effort? What about saving this map? I can easily save the array with tiles, but how can I do it with units? Just save their positions or is there a better way to do it? EDIT I've tested the first idea (I've written script to create 256x256 map that will be probably the biggest, and to move a camera). The map generates quite long (comparing to tiles without collider), but after that there isn't much difference in performance (it doesn't mean it won't cause problems when I add more features than moving a camera )). I can also attach colliders only to impassable tiles, not all. This should improve the performance even more. Still not sure if that's a good idea. EDIT 2 I've just realised how bad my idea was. Let me visualise this So if you consider not the whole rectangle, but only a circle, it's not only easier to implement, but also more reasonable. You can now convert rhombus' vertices' position from isometric to cartesian like B lint said CartX ( 2 IsoY IsoX) 2 CartY ( 2 IsoY IsoX) 2 You can also do it with circle's center point. Radius is equal to half of square (rhombus) side length OR sqrt(2) square side length (when square is inscribed in circle). So now I have a square grid and a circle. How can I check if all squares that this circle lays on are passable? What's the most optimal way to do it?
|
0 |
objects disappear before time I created a little pool in order to better manage my enemies, to which, an enemySpawner object calls to retrieve a clone and show it on screen public class ObjectPool MonoBehaviour public static ObjectPool current public GameObject objectForPool public int poolAmmount 20 public bool growth true List lt GameObject gt objectsForPool void Awake() current this Use this for initialization void Start () objectsForPool new List lt GameObject gt () for (int i 0 i lt poolAmmount i ) GameObject obj Instantiate(objectForPool) obj.SetActive(false) objectsForPool.Add(obj) public GameObject GetPooledObject() for (int i 0 i lt objectsForPool.Count i ) if (!objectsForPool i .activeInHierarchy) return objectsForPool i if (growth) GameObject obj Instantiate(objectForPool) objectsForPool.Add(obj) return obj return null Update is called once per frame void Update () The call(EnemySpawner update) void Update () transform.position new Vector3(transform.position.x (speed Time.deltaTime), 0, transform.position.z) if (transform.position.x lt boundary.xMin transform.position.x gt boundary.xMax) speed 1 if (Time.time gt nextSpawn) nextSpawn Time.time spawnRate GameObject clone GetComponent lt ObjectPool gt ().GetPooledObject() if (clone null clone.activeInHierarchy) return clone.GetComponent lt EnemyMovement gt ().SetPlayerShip(playerShip) clone.transform.position transform.position clone.transform.rotation transform.rotation clone.GetComponent lt Health gt ().RestoreHealth() clone.SetActive(true) The problem here is, that my enemies are being deactivated on mid trajectory https youtu.be ZGHC6wwGX1E I know my issue is in my pooling, but I can't figure out what I'm doing wrong
|
0 |
Set Layer of UI Object being Dragged In my game, I have an inventory system with slots and images in those slots. The images are by default disabled, but when an item is added to the slot, the image component becomes enabled. I have implemented a very simple drag and drop system for moving objects around in the inventory using IBeginDragHandler, IDragHandler, and IEndDragHandler. As I am dragging an item from one slot to another, I want the item image to be rendered in front of the slots and the rest of the inventory. Currently, when dragging an item image, it renders behind the empty slots. I don't want to use hierarchy order to organize the layers of these slots because moving items around is very dynamic and the hierarchy order of the slots changes seemingly randomly when I press play. Is there another way to ensure that the item image being dragged is "closer to the camera" or in front of the rest of the inventory? Thanks.
|
0 |
Making Scene at editor mode On Button click at editor mode I am trying to make a scene of selected Hierarchy game object but the problem is as i click the button new scene become upon and I lost the scene where i were selected the Game object. My code given below if (GUILayout.Button("Generate Scene")) Scene newScene EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects) SceneManager.MoveGameObjectToScene(Selection.activeGameObject, newScene) EditorApplication.SaveScene("Assets RegionScene " gameObjectSelected gameObjectSelected.Count 1 .name ".unity") newScene
|
0 |
How to create a Spawn Area that can be visualized in the Unity Scene Editor? Consider a Spawn Area for GameObjects. We define a Spawn Area to be a boundary consisting of 3 or more points such that an object can spawn at any coordinate that is within the boundary of the Spawn Area. Contrast this with a Spawn Point, where objects can only be spawned at that specific coordinate. In Unity, one method of creating such a Spawn Area is to place an Empty Game Object at a point, and then use Random.Range around that point. Vector3 emptyGameObjectCoordinate emptyGameObject.transform.position Vector3 randomSpawn emptyGameObjectCoordinate new Vector3(Random.Range( 1, 2), 0, 0) My issue with this approach is that it is very difficult to visualize this area through the scene editor. It would look like a simple cube no matter what the area actually is. I have considered possibly using a box collider as the area. This is can easily be visualized. However, Unity Lacks a method to select points within a collider. It would be ideal if we had a method such as Random.insideCollider. BoxCollider collider GetComponent lt BoxCollider gt () Ideally. But sadly, does not exist. Vector3 randomSpawn Random.insideCollider(collider) So my question is, what is the Unity way of creating a Spawn Area such that it can be visualized through the scene editor? As a bonus, how can we create areas that consists of arbitrary points, as opposed to just being rectangles or cubes? It would still need to be possible to visualize it, and it should be easy to select random points within it.
|
0 |
My array loads in the wrong order I have a load all chapters script which loads up all the Chapter items in an array and instantiates the buttons in the Viewport so you can select which chapter you would like to play. The problem is the chapters load up in the wrong order, they load up as Chapter 4, Chapter 0, Chapter 1, Chapter 2, Chapter 3. Below is the code I am using. void Start() menuManager GetComponentInParent lt MainMenuManager gt () levelManager GetComponentInParent lt LevelManager gt () chapterArray Resources.LoadAll lt GameObject gt ("Chapters").OrderBy(go gt go.name).ToArray() txtStatus.text "" if (chapterArray null) txtStatus.text "Could not find Chapters" return else txtStatus.text "Loading..." FillChapterList() txtStatus.enabled false void FillChapterList() foreach (GameObject chapter in chapterArray) GameObject listChapter Instantiate(chapterListItemPrefab) listChapter.transform.SetParent(chapterListParent, false) ChapterListItem chapterListItem chapterListItemPrefab.GetComponent lt ChapterListItem gt () chapDetails chapter.GetComponentInChildren lt ChapterDetails gt () chapterListItem.Setup(chapDetails.chapterNumber,chapDetails.chapterName) This is not only happening with the Chapter Select, it has been happening with all the arrays I load up in this fashion. Below is the visual side of the problem where you can see it loads the last object First. I have been struggling with this for a while and I think its stopping me from progressing forward. Thank you for reading this and taking the time out of your day to help.
|
0 |
Stop 2D platformer character from sliding down slope I'm making a 2D platformer game with the default Unity 2D physics. I am implementing slopes, but my player slips down the slope because of the physics. Here is the code I use for the player movement MoveInput Input.GetAxisRaw( quot Horizontal quot ) rbd2.velocity new Vector2(MoveInput speed, rbd2.velocity.y) rotacion de personaje if (MoveInput gt 0) transform.localScale new Vector3(1f, transform.localScale.y, transform.localScale.z) if (MoveInput lt 0) transform.localScale new Vector3( 1f, transform.localScale.y, transform.localScale.z)
|
0 |
How can I access a method via a string in Unity? I myself am new to unity and I would like to know how it is possible to access a method via a string, something like this public string PlayerPrefsName public GameObject Button public string GadgetForSkin private void Start() GadgetChanged PlayerPrefs.GetInt(PlayerPrefsName) if (GadgetChanged 0) Button.SetActive(false) GadgetForSkin quot GadgetForSkin quot GadgetChanged public void GadgetChecker() GadgetForSkin() public void GadgetForSkin1() If it's not possible, how can I achieve something similar?
|
0 |
Issue with dark .PNG files in Unity I made sprite assets in Krita and I exported them as .PNG files. When I import the files into Unity assets, however, they become a lot darker than the original colors. So far, I haven't found the issue, and I was wondering what's going on?
|
0 |
GTA style camera Unity I am wanting to make a 3d RPG with unity, and I'm in the planning phase. For the camera I decided to make it GTA style. I want the camera to be rotated around the player without effecting the movement of the player. If anyone can give any pointers on this, I would be very grateful.
|
0 |
How can the fluid stream be stuck to the top of flask? I created a flask and added a fluid stream to the top of the flask. When I translate the flask, the fluid stream goes along with the top of the flask. How do I achieve this when rotation occurs. void Start () aa.transform.position new Vector3(bb.transform.position.x, bb.transform.position.y 4, bb.transform.position.z) aa.SetActive(false) aa.SetActive(true) void Update () aa.transform.position new Vector3(bb.transform.position.x, bb.transform.position.y 4, bb.transform.position.z) aa is the fluid stream and bb is the flask cc.transform.position new Vector3(bb.transform.position.x, bb.transform.position.y 4, bb.transform.position.z) The traslation works. But you can see the gap between top of flask and rotation here. How do I close that gap?
|
0 |
How to see the surface arc in Unity? How to see the surface arc in Unity? There is the tutorial and in this tutorial we can see the arc in editor While I can not see it. I checked that all my gizmos are enabled. How can I enable the arc?
|
0 |
How can I rotate an object with random speed with some delays? using System.Collections using System.Collections.Generic using UnityEngine public class Turn Move MonoBehaviour public int TurnX public int TurnY public int TurnZ public int MoveX public int MoveY public int MoveZ public bool World Use this for initialization void Start () Update is called once per frame void Update () if (World true) transform.Rotate(TurnX Time.deltaTime,TurnY Time.deltaTime,TurnZ Time.deltaTime, Space.World) transform.Translate(MoveX Time.deltaTime, MoveY Time.deltaTime, MoveZ Time.deltaTime, Space.World) else transform.Rotate(TurnX Time.deltaTime,Random.Range(3,300) Time.deltaTime,TurnZ Time.deltaTime, Space.Self) transform.Translate(MoveX Time.deltaTime, MoveY Time.deltaTime, MoveZ Time.deltaTime, Space.Self) This is the random part Random.Range(3,300) but sine it's changing the random numbers too quick the changes are almost not visible. I want somehow to make that if for example the next random will stay for example 5 seconds at this speed number then move to the next random number and again stay at this number 5 seconds and so on. Tried this using System.Collections using System.Collections.Generic using UnityEngine public class Turn Move MonoBehaviour public int TurnX public int TurnY public int TurnZ public int MoveX public int MoveY public int MoveZ public bool World private bool IsGameRunning false Use this for initialization void Start () IsGameRunning true StartCoroutine(SpeedWaitForSeconds()) Update is called once per frame void Update () IEnumerator SpeedWaitForSeconds() var delay new WaitForSeconds(3) define ONCE to avoid memory leak while (IsGameRunning) if (World true) transform.Rotate(TurnX Time.deltaTime, TurnY Time.deltaTime, TurnZ Time.deltaTime, Space.World) transform.Translate(MoveX Time.deltaTime, MoveY Time.deltaTime, MoveZ Time.deltaTime, Space.World) else transform.Rotate(TurnX Time.deltaTime, Random.Range(3, 300) Time.deltaTime, TurnZ Time.deltaTime, Space.Self) transform.Translate(MoveX Time.deltaTime, MoveY Time.deltaTime, MoveZ Time.deltaTime, Space.Self) yield return delay wait but that just rotate the object once each 3 seconds. and not rotating it all the time with speed changing every 3 seconds. but now it's not rotating for 3 seconds it rotating every 3 seconds. better to describe what I want is like intervals. The object should spin all the time nonstop like i Update but then each 3 seconds to change for a random speed. for example spin at speed 5 ....after 3 seconds spin at speed 77 ....after 3 second spin at speed 199
|
0 |
Managing data for large number of levels in Unity? I am making a Unity game vaguely in the vein of Candy Crush Saga for a client and am moving in circles trying to decide how to manage the data for all of their levels. In brief, they want to divide the game into multiple regions that each have 100 levels. For example, you might go to the world map, select Teddy Bear Islands, and then go to the winding path style level select screen similar to King's "Saga" games. My goal is to have the levels be procedurally generated, so the data for each level will consist of dozen or so parameters instead of hundreds of variables. There will only be one scene, and the levels will be built by running the parameters through an algorithm. The game isn't a match 3, but for comparison, imagine if your level data for a match 3 was just basic parameters like the number of each type of piece and the target score, and each time you started a level it would randomly arrange pieces based on the input parameters (instead of you manually declaring the position of each piece). The data for a level will look something like int targetScore int levelType float difficultyModifier int numPieceA int numPieceB int numPieceC int numPieceD I haven't worked with such a large data set (in terms of the number of levels) in Unity before and am unsure how to structure it. In a less editor driven engine, I would probably just store all of the levels in XML files. However, since this is a Unity project I feel like I should be making an editor based solution that will be easier for the client to work with in the future. With an XML driven approach, I imagine that I would have an XML for each region containing all of the 100 levels in that region, and each location on the world map would be linked to one of the XML files. When the user selected a region, it would read the levels into an array, and link each of the 100 level buttons to an array index. For a more editor driven approach, I might create custom editor windows where the regions and levels can be defined, and then link the region and level buttons to the data from the editor window (I haven't done much with editor windows yet and am not entirely sure how to tackle this approach). Or I could create a serializable LevelData type and a simple MonoBehavior with a public array of LevelData so that the levels could be defined on GameObjects in the inspector. Each solution has pros and cons, and I'm stuck on what to do. Is there a conventional approach for managing such a large number of levels in Unity? Should I try one of the above approaches, or is there a better solution?
|
0 |
C JSONs not formatting array of objects stored inside another object. I know the title is a bit confusing because I don't really know how to phrase this. This is what I have System.Serializable public class Sector public string name public Vector3 sectorPosition public float sectorRadius public buildingComponent components System.Serializable public class buildingComponent ScriptableObject public string componentType public Vector3 componentPosition public Vector3 compenentRotation When I try converting this into a json string like this Sector ssector new Sector() ssector.name "sTom" ssector.sectorPosition Vector3.up ssector.sectorRadius 2 ssector.components new buildingComponent 3 print("component length " ssector.components.Length) ssector.components 1 new buildingComponent() ssector.components 1 .componentPosition new Vector3 (1, 2, 3) string sdata JsonUtility.ToJson(ssector) I end up with the following "name" "sTom","sectorPosition" "x" 0.0,"y" 1.0,"z" 0.0 ,"sectorRadius" 2.0,"components" "instanceID" 0 , "instanceID" 341752 , "instanceID" 0 The components array is not actually being formatted, it's only saved with an instanceId or whatever this does. Is there any solution to this or will I have to go with an alternative formatting. I just want to save this data on a server but I only get one string to do so, so I have to format everything into one string. Thanks in advance!
|
0 |
Enable and disable different component on a Gameobject So far I am not clear how do you actually access the various components on a game object, to enable and disable them. I have a component that has various scripts and elements, like a camera, transform, audio listener and few other custom scripts. It is in the scene, so I try to access to it via script private GameObject player player GameObject.Find("the player") So far so good if I want to access for example to the camera, and enable or disable it, I can do it player.GetComponent lt Camera gt ().enabled true This disable correctly the camera, or eanble it, depending from the paramenter that I pass. Now, if I want to access my script, called "playerscript" I can't do the same thing, since I get an error player.GetComponent lt playerscript gt ().enabled true Not sure why I get an error I have a class that is called "playerscript", that is attached to that player object, but instead, VS complain. This is the error message Error CS0246 The type or namespace name 'playerscript' could not be found (are you missing a using directive or an assembly reference?) I did try to use also GetComponentInChildren, but the result is the same. If I have the object player, which hold a reference to the original game object instantiated in the scene, why I can't simply access all the elements attached to it, via GetComponent and dot notation? I believe this used to work time ago, but in Unity5 I can't get this to work. EDIT This is the content of the playerscript class using UnityEngine using System.Collections public class playerscript MonoBehaviour Use this for initialization void Start() get the instance of the button from UI manager void OnTriggerEnter(Collider world item) enable item animation void OnTriggerExit(Collider world item) disable item animation
|
0 |
Game Object will NOT stretch across entire content area I'm loading prefabs into a content area using a content size fitter and vertical layout group. I've tried multiple things to get the loaded prefabs to stretch across the entire content size (including the Unity Manual for this issue), but I'm at an impass. I'll post a screenshot below to show what I'm working with Here's how I'm loading in the prefabs in case this is where i'm screwing up void CreateRaceSelect() for (int i 0 i lt races.races.Count i ) raceButton (GameObject)Instantiate(raceButtonPrefab) raceText raceButton.transform.FindChild("Text").GetComponent lt Text gt () raceButton.name i.ToString() raceButton.transform.SetParent(content.transform) raceButton.GetComponent lt RectTransform gt ().localPosition new Vector3(xPos, yPos, 0) raceText.text races.races i .ToString() yPos (int)raceButton.GetComponent lt RectTransform gt ().rect.height I'm sure this is a minor screw up but at this point I have no other ideas.
|
0 |
Serialize classes in unity c Is there some best practices to serialize objects to file on mobile devices in Unity using C . I've tried to search it myself, but found only this link. However, it looks like here they are trying to cache AssetBundles. I'm new to Unity, but I have some experience in iOS (swift) development. Here we have opportunity to cache some objects(variables) in local storage, to avoid overusing network. So I wanted to create some static class (for example Storage), which caches variables to file permanently and return them by some key.
|
0 |
Unity Hub 2.3.0 Buggy Setup? I recently downloaded the new Unity Hub 2.3.0 setup and since I hadn't used (or downloaded Unity Core) using the previous version of the Hub, I simply deleted the folder containing Unity Hub instead of uninstalling it like any normal person would. Now, every time I open the Unity Hub Setup and try and install it, it always shows the same "Installation Aborted, could not install successfully," error. I can't even uninstall the previous version from Windows Settings! I've tried changing the destination folder, but still doesn't work. Any help is appreciated! P.S. This error occurs when installing UnityHub, not the Unity Core Platform! I've also looked at all other similar posts. Thanks.
|
0 |
Unity yield WaitForSeconds() not working I am new to Unity development. I started learning Unity by reading tutorials, demos, examples, and watching videos. And I am having some trouble with using this timer. Here is my code void OnCollisionEnter(Collision colli) if (colli.collider.name "Car") Debug.Log("On Collision naz . ") Destroy(Car) Destroy(this.gameObject) GameObject clone (GameObject) Instantiate(Bum, transform.position, Quaternion.identity) StartCoroutine(deleteObject(clone)) Just want to delete "clone" object after 1 second IEnumerator deleteObject(GameObject bum) Debug.Log("chuan bi destroy naz . ") lt run normally yield return new WaitForSeconds(1.0F) Debug.Log("Destroy rui naz , '") lt not display Destroy (bum) Why won't this object be destroyed after 1 second?
|
0 |
how to duplicate a button via script? I have the following code public GameObject characterButtonPrefab public GameObject characterButtonContainer public GameObject optionsContainer public GameObject charButtons private int charButtonsIndex 0 private Text cBT private string buttonTexts new string "Strength 5", "Agility 5", "Intelligence 5", "Charisma 5", "Diplomacy 5" private void Start() LevelIsOver false IsNextWave false Time.timeScale 1 for (int i 0 i lt charButtons.Length i ) int size charButtons.Length cBT new Text size GameObject container (GameObject)Instantiate(characterButtonPrefab) container.transform.SetParent(characterButtonContainer.transform, false) cBT i characterButtonPrefab.transform.FindChild("Text").GetComponent lt Text gt () cBT i .text buttonTexts Random.Range(0, buttonTexts.Length) charButtonsIndex if (charButtons.Length gt 0) GameObject currentChar (GameObject)Instantiate(characterButtonPrefab) currentChar.transform.SetParent(optionsContainer.transform, false) currentChar.transform.SetSiblingIndex(0) currentChar.GetComponent lt Button gt ().onClick.AddListener(() gt CharacterSelection()) I declared the size of array to 20 in the inspector and everything work fine. The buttons are created and text changed. The question is how do I duplicate the first button in that array to another panel ? I have searched the internet but nothing found about this. I have tried this GameObject currentChar (GameObject)Instantiate(charButtons 0 ) currentChar.transform.SetParent(optionsContainer.transform, false) currentChar.transform.SetSiblingIndex(0) currentChar.GetComponent lt Button gt ().onClick.AddListener(() gt CharacterSelection()) But I get ArgumentException The Object you want to instantiate is null.
|
0 |
game button animation lag with Photon Friends, I am making games using photon. But I could not do the delay animation as described in this link. The action appears to be late on the player according to the ping. Can you give an ideas about this?
|
0 |
How to handle data for a competitive multiplayer games I am kinda new to Multiplayer Games and I am really wondering how I should handle my data Should each player send and update their data to the database (server) everytime one of their essential variables changes (like health or ingame currencies), or should they save the data as long as the game is running and then update the data all at once at the end of, lets say, each round? I was thinking about using Firebase and Unity and here's a scenario Let's say 2 players connect to a game. Then one of them gets damage and the other one gets gold. Does the data change get sent to the FireBase Database immediatly or should I just update everything when the round ends they disconnect?
|
0 |
Layers in Unity won't drag I'm trying to rearrange my layers in Unity but I can't seem to drag them. When I try to do this I'm in edit layers under the heading sorting layers and I click on the symbol and try to drag it but it won't move. I also tried restarting Unity twice but it won't resolve the problem. Could someone help me with this?
|
0 |
How to implement the swipe up and down number select Unity3d I want to implement the UI like in the image. I want the users to select the number by swiping up and down. I found the tutorial on the YouTube which is similar to the what i wanted (https www.youtube.com watch?v mL FLsV3WRs) But it shows only the numbers from 0 to 9. I want to show from 1 to N (n can be any number). Any idea to help me to get this would be great.
|
0 |
How to reach IK Pass and weight by script? I need to reach IK Pass box, and control the weight by time from 1 to 0. I tried GetLayerIndex and did not give me any of those options.
|
0 |
If statements seem to act as though the condition is always true I have other scripts in the same project using boolean if statements that work fine, but I've tried multiple methods of testing if the if statements below are working and none of them worked! I don't really know what to ask because I don't know whats going on. I've tried placing theae statements in Update and Start, and in both instances the if statement completely ignored the check and just executed the contents of the block as though the check evaluated to true. void OnTriggerEnter(Collider other) if(other.gameObject.CompareTag("Player")) working true Extremity false if(Extremity) Instantiate(Cannon, transform.position, transform.rotation) Extremity !true The false statement is only in there to show that even when the bool is set to false immediately before the check, it still runs the Instantiate method inside as though it were true.
|
0 |
How can I make an instantiation random? I'm trying to do it so when I have an instantiated an item upon the game starting, it is random as to whether it actually instantiates or not. Here's the code I have so far public GameObject anyItem void Start() Instantiate(anyItem, new Vector3(0, 0, 0), Quaternion.identity) Instantiate(anyItem, new Vector3(11, 0, 0), Quaternion.identity) How can I do it so these items (individually, not both together) are decided randomly as to whether they will actually be instantiated or not?
|
0 |
Why does setting a static member value in MonoBehaviour child class constructor have no effect? I am following a tutorial for Unity. I don't know C but I know other similar languages. I got the tutorial to work. Here is the script I used. using System.Collections using System.Collections.Generic using UnityEngine public class PlayerMove MonoBehaviour private Rigidbody rb public float speed Use this for initialization void Start () speed 3.5f rb GetComponent lt Rigidbody gt () Update is called once per frame void Update () float fx Input.GetAxis ("Horizontal") float fz Input.GetAxis ("Vertical") rb.AddForce (new Vector3 (fx, 0, fz) speed) This goes slightly against my C instincts, which are to put initialization values in a constructor. public PlayerMove () speed 3.5f void Start () rb GetComponent lt Rigidbody gt () This doesn't work. In Unity, the speed field has an initial value of 0. Why does setting the initial value in a constructor not work?
|
0 |
Getting distance between point of an object and another object in Unity First, I'd like to apologize because this is a very basic and repetitive question, but I am completely new to game development. I understand that I can find a distance between two objects using float dist Vector3.Distance(other.position, transform.position) However, how can I find the distance between a point of one object to other object? For instance let's say my object is this sphere Now, how can I return an array that says that there are no objects to the left (null), in the front there is an object at 1, and to the right there is an object at 0.5? Thank you for your patience and understanding
|
0 |
Food Game using Online Searchs I am thinking of making a simple game with Unity. The aim would be to keep a person healthy by feeding it well balanced food and drinks. Rather than hard codding every single type of food or drink I can think of I was thinking of letting the player choose any type of food he wants and then screen the internet for it's calorific value, saturated fat, sugars etc ... This would make the game much more enjoyable than being limited by the foods I can think of. I was wondering how you would go about doing that ? Could I use an API to extract data from google or wikipedia. I noticed that when you type " food calories" in Google you get a return from the Wikipedia page like this Obviously, there is a way of extracting the data from Wikipedia and I could automate the searchs by taking the player's entry as a string and running a search with it. How would one recommend going about this ? Also, is it safe ? Thanks
|
0 |
Unity Raycasting only hitting mesh colliders from particular directions I have a game which involves clicking to select some objects. Each of the objects has a mesh collider attached to it so that objects can be clicked, handled by the following if (Input.GetMouseButtonDown(0)) if left button pressed... Find hit object Ray ray task scene.main camera.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit)) execute some function() Now this works fine when I run the game in the editor. However, when I build and run in the browser some objects are not being selected when clicked, and it seems to be objects that are created from particular meshes. I have tried changing the mesh import settings to generate colliders but this doesn't seem to do anything changing Prebake Collision Meshes in build settings, which again doesn't solve the problem Changing mesh collider cooking option to both 'everything' and 'none' Setting 'Queries Hit Backfaces' to true in physicsmanager settings making setting the meshes to convex, which does then work in the build but is not ideal. EDIT I've noticed that the raycasting is actually working for the problem objects but only from particular directions. Is this because, according to the manual 'Faces in collision meshes are one sided. This means objects can pass through them from one direction, but collide with them from the other.' Any thoughts on what might be causing this?
|
0 |
Unity Blurry on new Windows 4k Computer I just got a Razer 14 Inch 4k with a GTX 1060 and am having some blurry rendering in unity. Also the cursor is tiny... Here is a screen shot As you can see, the rendering is really blurry. I came from a mac and did not expect unity to look worse after switching to a computer with a great screen res and graphics card... Please help! EDIT I am still getting jagged shadows but now I seem to be able to fix it with changing shadow distance in Quality Project Settings But then the shadow disappears really quick if i have low shadow distance...
|
0 |
How to generate objects at specific intervals and make them move with same speed? I'm creating an infinite runner where character has to jump on randomly generated pillars. The pillars are positioned with a gap between each of them. The gaps are dmin and dmax. In addition to this, i want the pillars to move to the left of screen with increasing velocity. But they all need to move with same velocity so that the gap in between them is maintained. I have the script as follows pillar is a prefab.go is an empty gameobject which will later be used to Instantiate pillars. first is the first pillar, manually positioned in the scene. using UnityEngine using System.Collections public class GM MonoBehaviour float tempx,dmin 1.3f,dmax 3.5f GameObject bins Vector2 speed,pos,tempvel public GameObject pillar,go public Transform first Use this for initialization void Start () speed new Vector2 ( 0.005f,0) tempx first.transform.position.x tempvel new Vector2 (0, 0) void Update () if ((Vector3.Distance (go.transform.position,transform.position) lt 40f)) tempx Random.Range(dmin,dmax) pos new Vector2(tempx, 2.22f) go Instantiate(pillar,pos,Quaternion.identity) as GameObject bins GameObject.FindGameObjectsWithTag("trash") tempvel new Vector2 ( 0.0005f, 0) foreach (GameObject bin in bins) bin.GetComponent lt Rigidbody2D gt ().velocity new Vector2(Random.Range( 0.005f, 0.05f),0) bin.GetComponent lt Rigidbody2D gt ().velocity tempvel Problem is, the speed of pillars increases way too fast. They move to the left at nearly invisible speeds. Also, after a certain speed, the gap between the pillars increases. They become so far apart, one is in camera view, another is somewhere far away. Is there a way to accomplish this?
|
0 |
Why does applying force to a game object apply force to children, as well? I have a script on my player to move. I do not have root motion applied because, root motion does not work perfectly so I'm manually adding velocity to the player. The player is holding a ball and the ball is a child of the player. However, when I apply force to the player it seems to apply force to the ball so he stops holding it and it is just floating around instead. My player and my ball both have rigidBodies and I'm applying force like this. var velocityX horizontal HorizontalSpeed Time.deltaTime var velocityZ vertical VerticalSpeed Time.deltaTime rigidBody.velocity new Vector3(velocityX, 0f, velocityZ) I know as a hack I can apply a late update to the ball, but I'd rather understand what is going on. Can anyone help me figure this out?
|
0 |
3D visual effects on videos I'm trying to get some hands on experience with 3D visual effects on videos. Similar to those AR apps, I want to add a 3D model with effects, say a dragon, to a video. Something like this famous demo https youtu.be u5hQpRbHERg But I don't really want to make it this fancy with camera tracking. I like to start with the simplest approach probably just placing a dragon on the field (like its last scenes) with fixed camera. What's the best way to do it? Some tutorials would be very helpful.
|
0 |
Unity not opening in Ubuntu I installed the latest version version of Unity for Linux from the official website, but when I try to launch Unity, it displays a blank dialog box. I waited for a long time, but nothing happens. These are my system specifications. I was running Unity on the same computer, several months ago, using Windows. Model Thinkpad R500 Processor Intel Core 2 Duo CPU P8600 2.40GHz 2 RAM 2Gb DDR3 RAM Storage 155Gb HDD Graphics Card ATI Mobility Radeon HD 3400 Series 128mb dedicated GFX Why is it doing this? Is there a problem with the latest build? What should I do to fix it?
|
0 |
Remove delay when changing axis input in the Unity Input Manager I had a problem playing with the Input Manager, where for example When Horizontal ( ) is pressed, it increase its value but, when Horizontal ( ) is pressed, the horizontal value stays positive for a little, but keeps decreasing. This causes the character to continue playing "right" animations and still moving to right for a few seconds, instead of instantly playing 'left" animations and moving to left. The problem also makes the character movie a little after the player releases the key. I have also used Input.GetKey(), but that means the player cannot change the setting from the game launcher, and I don't want to create player setting in game, for now. What I am trying to achieve is when Horizontal ( ) is pressed, then the player presses Horizontal ( ), it should instantly turn left without delay. When the player is not pressing any Horizontal key, it should stop moving horizontally, instantly. This problem also appears along the Vertical axis. How do I make it so input snaps to 1 or 1, with out slowly moving back and forth?
|
0 |
How to create a "border" effect in Unity? Okay let me start off by saying I have searched for several days on this topic, and it seems that either nobody posted anything about it, or it is on the internet, but too far buried under piles of useless information for me to find. I have created a custom terrain algorithm in Unity and have built a parser to read provinces onto the map. The short version description of the parser is that it goes into the assets folder, finds "map provinces.png", reads the borders of the provinces as vertices, reads "map height.png" to determine the height of the visual terrain, and reads "map terrain.png" to determine how much of each province is of each terrain (for example, Paris can be 95 urban, and 5 forest in my setup). I want to make each and every one of the 500 european provinces start with a player. The idea is that the players will fight small scale wars for 30 40 turns, by which point most or all small players will be absorbed into the most successful players country. These will then fight for 60 80 turns for dominance, with alliances being forged and broken and countries being destroyed. The problem is described below Each player has his own unique color. Many of the players will obviously have similar colors, and I do not want 2 dark red countries bordering eachother without some easy way to see the border. I want to basically draw a line in between any two provinces that belong to different players and border each other. I am having trouble finding a way to easily do this, as my current solution tests all provinces if they border foreign provinces, and runs a rather expensive test on each of the bordering provinces vertices to see if they border eachother, then stores those vertices as vectors and draws a line from each vertex to its others. I have considered using a shader to accomplish this, but was unsure if that was the right approach and whether or not that would (or could?) be more efficient.
|
0 |
Black screen when building apk Unity Alright, I have a bit of a confession to make I accidentally posted this question in the wrong place Stack Overflow. Whoops. Anyway, here's my problem. Sorry if you've seen this before. Here's the original post. I've been struggling with this issue for a few days now. Windows builds for my game work fine, but when I build it to Android, it loads, shows the "made with Unity" screen, then fades to black. Now, I know the next scene (an animated logo) is running because it is playing the audio in real time. However, nothing in the scene is visible. Then, the UI for the in game loading screen appears. Normally, the game would then load, and it does, but again, the camera thinks there are no sprites in the scene. I can still play the game, and the audio sounds just normal, but I can't see. Then, when I die, the game over UI appears, and I can use it as normal. The shop menu works absolutely fine, but the game itself does not. It's as if Unity decided that all SpriteRenderers in the game just didn't exist, and that the camera background color was now black. There are no scripts or animations causing this directly, as it does work in editor and on a PC build. The game also works fine using Unity remote, but the build has the issue. I also made sure that none of the textures were too large for Android (to the point where not one of them is larger than 256x256, which looks terrible but proves a point). Now, before anyone asks, yes, I have seen the other question on this topic, and no, sadly, it did not help. My camera is set to "solid color", not "don't clear." I tried "skybox" too, just to be safe. I have also tried disabling post processing, hoping that Android was just unable to handle it. It did nothing. I have even tried entirely disabling all of the sprites in the scene, but even then, the background is still black, indicating that the camera is still not playing nice. Also, here is a screenshot showing the quality settings for the Android build.
|
0 |
Prefabs scaling change also the original prefab I want to work with a prefab as local and global variable? something like that. So my question is how to change a prefab scale without affecting the original prefab.
|
0 |
Unity Ragdoll moves away from parent So this is a weird one. I've looked it up but can't find anyone with similar issues. Basically I have a simple combat system and after the enemy health is zero I go through each rigidbody component in the enemy object and add a force to make it go flying on death. For some reason, the parent object isn't affected and stays still while the Skeleton goes flying. Does anybody know how to make the parent object follow the skeleton, or make the skeleton follow the parent because as of now they act as separate entities? I've tried just adding force to the parent but that only moves the parent object and none of the children. Would appreciate any advice! Thanks.
|
0 |
Texture2D GetPixels Finding pixels that are not transparent. Problem as finding more than expected I am trying to make a level design system where I use a low resolution png file with certain pixels filled. My code will turn this location of the pixel in the image into placement of platforms in my game. But I test the following code with a png i made with only 1 pixel in it (the rest are transparent). But the result is it finds 4 every time. Is it possible there is a discrepancy between the Gimp png and the texture that Unity sees. (In GIMP I used pencil 100 hardness 1px width. There are also settings for 'resolution' of the image, which i left at defaults) public class LevelBuilder MonoBehaviour public Texture2D sourceTex Color32 pixels int pixelsFound 0 private void Start() pixels sourceTex.GetPixels32() for (int i 0 i lt pixels.Length i ) if (pixels i .a ! 0) Debug.Log("found colored pixel. total " pixelsFound)
|
0 |
How do you get the world position from the screen position in a URP shader graph used in a ScriptableRenderPass? I'm using a shader graph in the Universal Shader Pipeline (URP) to do some post processing in a ScriptableRenderPass. How do I get the world coordinates of the screen position? I have tried using the View Direction node, set to World And I have tried the Screen Position node, with either a Transform node or Transformation Matrix node Neither seems to be working because the colors change as I move the camera around, but I would expect the color to stay the same since the world position of the GameObject in the view is not changing. Any suggestions?
|
0 |
Best data types for DNA, edibles and creatures So I am making a sort of continuous evolutionary system in the Unity3D engine. Currently I have a DNA class that has values that gets applied to a Creature object on initializing e.g. public class DNA public float maxSpeed public float foodWeight public DNA(float maxSpeed) this.maxSpeed maxSpeed this.foodWeight foodWeight Where every Creature has a public DNA variable that gets set when instantiating a population of Creatures via a GameManager class. In this "ecosystem" I want to have the creatures crave for food and try to avoid the poison. My question isn't about the reproducing or natural selection part, but more about what the best kind of data type for each object is. Since I want the project to have expandable amount of Creatures, sorts of food etc. Is the best way to handle all data via one GameManager, or should I seperate it in for example CreatureManager, FoodManager etc.? Maybe a PopulationManager of some sorts? Is the current setup for the DNA data optimal? Also, currently I have food and poison just as two prefabs and detect collision (and add or substract health whether it's food or poison via tag), wouldn't it be smarter to create a struct for food and poison so I can later on expand on this? Sorry if any of the given information is unclear or a bit vague, please say so if this is the case! I would be glad to clarify and add any needed information. Thank you for reading through the entirety of my question, thanks for your time! )
|
0 |
Getting the angle between three points? I have three points, A, B and C (stored as Vector2 in Unity). I am trying to find the angle at point B if there were a line AB and and a line BC. I know, this should be a simple google search, and I have found several methods but for some reason, they ALL return totally unexpected results with my data set! I checked to make sure that the three points I pass to compute the angles are indeed the correct (x,y) coordinates, and that same data is used elsewhere in my code without any problems. Considering that all functions return strange results, it must be that I am not understanding something here... here is one formula Vector2 A some vector2.normalized Vector2 B some vector2.normalized Vector2 C some vector2.normalized float Angle Mathf.Atan2(B.y A.y, B.x A.x) Mathf.Atan2(B.y C.y, B.x C.x) Here's another that I tried where p0,p1,and p2 and just vector2's function findAngle(p0, p1, p2) var a Math.pow(p1.x p0.x, 2) Math.pow(p1.y p0.y, 2), b Math.pow(p1.x p2.x, 2) Math.pow(p1.y p2.y, 2), c Math.pow(p2.x p0.x, 2) Math.pow(p2.y p0.y, 2) return Math.acos((a b c) Math.sqrt(4 a b)) The data is a List of Vector2 control points for creating Bezier curves. I want to calculate the angle between index 0,1,2 then 2,3,4 then 4,5,6 etc. with the middle index as the angle needed. I understand that both formulas return radians, but converting to degrees returns sometimes 180 for all points even though the points are all different and the angles vary greatly, sometimes 0 (if I switch the points around), and in the case of the atan2 function above, it gives numbers that "look" like angles, but plotting the points, one can see that the angles do not correspond to the visual plots... I must be doing something very dumb here and I'm not great with math so any hand holding is much appreciated. Here's an image of the output
|
0 |
How can I make a character Blink effect in Unity? I am making a game where I am making a health script where I have made a blueprint of what needs to be done. I'm trying a blinking effect after the character is hurt. Can someone help me make a blink effect in Unity for JS?
|
0 |
How do i create a random planet generator and use it on Unity? For example https managore.itch.io planetarium Something like this, create random sprite circles who at least are realistic looking, as far as realism can be pixel, I don't think this can be done on Unity alone so i think i might need to implement it after i coded it in another language or another engine, so my how do i do it? can i do it on unity? and how would i implement if i decided that unity isn't fit for this thing? The usage of the planets will be throughout the game and will be used as the main planet so it is of great value to the game
|
0 |
Large Scale Case Handling for 2D Procedural Environment I am creating a procedurally generated side scroller and I have a question regarding proper code structure Architecture when it comes to connecting different platforms and large scale cases. There are various platform types I need to connect (e.g. a hill which leads into a tunnel which then leads into a cave, etc). I can successfully generate and connect the meshes using a bezier curve. My problem is that the way I am handling each platform connection case seems very clunky inelegant the more I expand. Currently I am using switch statements to handle each scenario like the above mentioned. Below is a small snippet of how I am handling each case. public void SetTransition(int PrevPlatform, int CurrPlatform , Vector3 LastPosition) switch (PrevPlatform) case 0 GroundTransition (CurrPlatform,LastPosition) break case 1 CaveTransition (CurrPlatform,LastPosition) break case 2 WaterTransition (CurrPlatform,LastPosition) break case 3 TunnelTransition (CurrPlatform,LastPosition) break case 4 WallJumpTransition (CurrPlatform,LastPosition) break From here I have separate functions that handle the cases using more switch statements. The problem now is that I am starting to have a large number of branching functions that are relying each case. My code structure is becoming this large tree of switch statements. For the most part it works but I wanted to reach out to other developers before I continued this route. Is there a more effective, organized methodology to handling large scale cases?
|
0 |
Point to using vSyncCount higher than 1? Is there a point to using QualitySettings.vSyncCount higher than 1? From my understanding it sets the framerate to fractions of the screen refreshrate (i.e FPS refreshrate vSyncCount). So 1 is standard VSync and 2 to 4 make no difference compared to 1 for eliminating tearing and only artificially limit framerate. The only use for this that I can think of is for reducing power draw for battery driven devices like phones. Am I missing something?
|
0 |
SVG textures for 3D game objects in Unity? Is there a way to make textures using vector graphics and use it for 3d models so that textures would be object size independent and won't get blurry?
|
0 |
How do I fix this "java.lang.ClassNotFoundException" error? I received my first crash report via the Google Developer Console, yesterday, and I'm completely lost. This is my error message java.lang.ClassNotFoundException Didn't find class "com.unity3d.player.UnityPlayerNativeActivity" on path DexPathList zip file " mnt asec com.JamaludineDolley.NinjaBallDash 1 pkg.apk" ,nativeLibraryDirectories vendor lib, system lib, vendor lib How do I fix this java.lang.ClassNotFoundException error?
|
0 |
Is ArrayLists so slow that it is doomed to kill performance in Unity? I was reading Which Kind Of Array Or Collection Should I Use? The document states to use list for the most performance. "...They are the fastest array in unity. For this reason, built in arrays are the best choice if you need the fastest performance possible from your code (for example, if you're targeting iPhone)...performs significantly faster than ArrayList." I am inclined to use list besides performance issues as well because... If you're using List you won't have to cast objects since it's generic and use a T backing storage (at least .net does this). ArrayList have to cast everything to object and cause boxing with value types. faster for value types as it avoids boxing., strongly typed elements. But it got me to wonder, since everyone seems to favor to make a degrading statement about ArrayLists, is ArrayLists that horrible? If so why does it even exist? Is it more of trace of supposedly deprecated codes?
|
0 |
Camera follow rotating ball ortogonal direction I have a ball, that has been moved via addForce. It colides in the scene with objects, leading to rotation in all axes. I want a camera to follow this ball but from the side (direction ortogonal to the move vector and UP vector). No matter what I do, I cannot get this working. The closest I get is almost correct, but camera "bumps" during frames. I have used this in camera script to attach camera to the ball and move it with it this.transform.LookAt(this.cannonBall.transform.position, Vector3.up) this.transform.position ball.transform.position No I need to rotate camera 90 degree aroun up axis and move it a little backward to track ball from the side. How can I achive this? If I use this.transform.Rotate(Vector3.up, 90, Space.World) It mess up lookAt
|
0 |
Large Scale Case Handling for 2D Procedural Environment I am creating a procedurally generated side scroller and I have a question regarding proper code structure Architecture when it comes to connecting different platforms and large scale cases. There are various platform types I need to connect (e.g. a hill which leads into a tunnel which then leads into a cave, etc). I can successfully generate and connect the meshes using a bezier curve. My problem is that the way I am handling each platform connection case seems very clunky inelegant the more I expand. Currently I am using switch statements to handle each scenario like the above mentioned. Below is a small snippet of how I am handling each case. public void SetTransition(int PrevPlatform, int CurrPlatform , Vector3 LastPosition) switch (PrevPlatform) case 0 GroundTransition (CurrPlatform,LastPosition) break case 1 CaveTransition (CurrPlatform,LastPosition) break case 2 WaterTransition (CurrPlatform,LastPosition) break case 3 TunnelTransition (CurrPlatform,LastPosition) break case 4 WallJumpTransition (CurrPlatform,LastPosition) break From here I have separate functions that handle the cases using more switch statements. The problem now is that I am starting to have a large number of branching functions that are relying each case. My code structure is becoming this large tree of switch statements. For the most part it works but I wanted to reach out to other developers before I continued this route. Is there a more effective, organized methodology to handling large scale cases?
|
0 |
main camera not covering whole screen in unity3d I have been using unity and i got a problem where my main camera is covering only the first half of the floor i made. camera position is left and the floor is rotated ,i m posting an image please help . I have shown a player white coloured and an enemy pink coloured .player is not shown as you can see.
|
0 |
UNET start game with friend by finding their name, Android There is a game at the google play store called Fun Run 2 Multiplayer Race. I loved its feature to find friends by writing their names, and then to play with them. Is it possible to achieve that with UNET? How? Another one is called Virtual Table Tennis. There I have a lobby full of people from whom I can choose. Can I achieve that with UNET? How?
|
0 |
Unity How do I fix the players model rotation in a NetworkManager to spawn properly? How do I fix the players model rotation in a NetworkManager to spawn properly? I created a game with the NetworkManager code. Player Model is a cone I made and imported. all works fine but when the NetworkManager spawns the player model it is sideways. I have tried turning it in 3ds but the player remains sideways when it is spawned by NetworkManager on run, Ohterwise the model is fine in unity, and no matter how I rotate it, in or out of unity , The NetworkManager Rotates it. All other objects attached to the main object remain with proper orientation all, All other objects including instantiated ones appear properly.
|
0 |
How to simulate an elastic force, using Hinge Joint ? I've a bucket connected to a rope. I would like that when a ball fall in my bucket , my bucket "bounce"down and up .. like it is connected to an elastic rope. How can i do that ? Thanks
|
0 |
how to create a curve movement of slider in unity I am trying to create a curved (not circular) movement of slider. Here is my demo images for reference I have watched some tutorial but those are for circle images. I want to make this movement along the arrow images below car. Also if this can be done with just images without using slider that will be ok too. I just this done the simpler and easy way.
|
0 |
Add picture in the Hierarchy view in Unity How can I add a picture in the Hierarchy view in Unity? For example, Dragon bones does it automatically. Here it is As you can see there is a picture on the right of the gameObject name.
|
0 |
Unable to add AR session I am new to unity and i am trying to make a AR app. I have installed AR foundation, Arcore Xr plugin, Arkit XR plugin via package manager. Then if i go to the Hierarchy panel to add a AR session and right click, I am not seeing any XR option to add a AR session. What should i do now? Anyone please help me.
|
0 |
Make enemy follow player intelligently I was trying to make a script to make my enemy follow my player intelligently (but not too much) and I want to know if there was a better way to do it (of course there is but I wanted to find a way myself) Here is what I did I wanted my enemy to detect the player when he approach a certain distance from him. I have a varibale to determine what distance the nemy have to back up (when player is too close) and when it has to follow the player (player too far). Now, I didn't wanted the enemy to just forgot there is an intruder when the player goes around a corner and they can't see him. When the enemy sees the player directly (raycast), they rotate toward him and start following him directly by normalizing the difference of their 2 position. Now is the tricky part i'm not sure about. My player has a list that keeps the 1000 last positions of my player and that update every 0.01 second to add the lastest position and remove the oldest. If the enemy can't see the player directly (!raycast) he goes through all the positions in the list by checking for every Vector3 1 is there something between the enemy and this position ? 2 is there something between this position and the player ? Then it add up the distance between the enemy and the point and the distance between the point and the player and checks 3 is the lenght of the path by going at this point shorter than the last shortest path ? if it's smaller, it's assigne to the best point. If it detected a point that matches these conditions, it goes at it and if it doesn't see the player, it continues checking for new points. If no point matches the condition, he just stop following the player (the enemy lost him). All this works with raycasting to check positions, presence of objects between enemy, player and points and path to go.
|
0 |
addressables unity unknown async error public AssetLabelReference imgs List lt IResourceLocation gt myImgs new List lt IResourceLocation gt () SerializeField List lt Texture2D gt loadedImages new List lt Texture2D gt () private void Start() Addressables.LoadResourceLocationsAsync(imgs.labelString).Completed imgReady void imgReady(AsyncOperationHandle lt IList lt IResourceLocation gt gt op) myImgs new List lt IResourceLocation gt (op.Result) insta() void insta() Addressables.LoadAssetsAsync lt Texture2D gt (myImgs, cb) void cb(Texture2D s) loadedImages.Add(s) I get the locations of the images but not the asset themselves I get an error of Exception encountered in operation Resource(Man.png) Unknown error in AsyncOperation UnityEngine.ResourceManagement.Util.DelayedActionManager LateUpdate() (at
|
0 |
Animation works, but Unity doesn't realize it I have an animation which plays once, and it played once just fine. I want to Invoke a method as soon as the animation finishes. I have been researching and experimenting for over an hour now, but without the result I want. I try to get the animation from the Animator, but Unity says my animation is not attached. The thing is, I don't care if it's attached...I just want to know how long it is, not actually do anything with it. How can I achieve this? Here is the code which results in the error CODE using UnityEngine using System.Collections RequireComponent(typeof(PolygonCollider2D)) RequireComponent(typeof(Animator)) public class Construction MonoBehaviour Use this for initialization void Start() Invoke("EnableObstacleState", GetComponent lt Animator gt ().animation.clip.length) private void EnableObstacleState() GetComponent lt PolygonCollider2D gt ().enabled true ERROR MissingComponentException There is no 'Animation' attached to the "Barricade(Clone)" game object, but a script is trying to access it. You probably need to add a Animation to the game object "Barricade(Clone)". Or your script needs to check if the component is attached before using it. Construction.Start () (at Assets Scripts Construction.cs 11)
|
0 |
How to solve the ground check problem? I noticed a problem in Unity's third person controller's ground check. The ground check should detect whether or not the player is standing on the ground. It does so by sending out a ray beneath the player. However, if the player stands on top and in middle of two boxes and there is a space between these boxes, then the ray shoots into the gap and the player thinks he is not in contact with the ground, which looks like this I am unable to move. You can clearly see that the ray is in the gap and thus the player animator airborne blend tree is active. What is the best way to solve this problem? I was thinking of shooting multiple rays, from the same origin but with different angles. And OnGround should only be true, if X of these rays hit the "ground". Or is there a better way?
|
0 |
FPS horizontal smooth camera rotation I have a problem, my camera is parented to the FPS Controller prefab, then there is a script I wrote for the rotation of the player horizontally by mouse movement, it all works but the rotation is very choppy and not smooth. How can I have the camera rotating smoothly or should I not parent my camera to the FPS Controller at all and make the rotation through scripting if so then how? here's the script of character rotation void Update () float rotationY Input.GetAxis ("Mouse X") 50f transform.Rotate (0, rotationY, 0)
|
0 |
Changing color for each element in linerenderer not working I want to change color for each line (element) just like in color switch. But my code is not working. What I wanted is that the right line should turn blue then the down line should turn color red. What is wrong with my code? void Start() lineGeneratorPrefab new GameObject() DrawLine() private void DrawLine() GameObject myLine new GameObject() myLine.transform.position start myLine.AddComponent lt LineRenderer gt () LineRenderer lr myLine.GetComponent lt LineRenderer gt () lr.positionCount 4 lr.SetPosition(0, new Vector3( 2, 0, 0)) lr.SetPosition(1, new Vector3(2, 0, 0)) lr.SetPosition(2, new Vector3(2, 2, 0)) lr.SetPosition(3, new Vector3( 2, 2, 0)) lr.materials 2 .color Color.blue lr.materials 3 .color Color.red
|
0 |
Real Time Physics Based Mesh Deformation I'm working on a game through unity that draws one of is essential elements from traditional tool forging techniques for building tools and such. I want the feel of the game to be able to create a tool that is truly yours and slowly make it better in both design and functionality over time. One major thing I cant't seem to figure out is to be able to take a mesh (in this case a hot piece of meta) and deform it in such a way that you aren't loosing any of the mesh, its just being shifted slightly with each hit of a hammer (or in my testing case click of a mouse). I have looked all over youtube and various forums and I can't seem to find an efficient way of going about it. Any thoughts?
|
0 |
is unity DOTS mature enough to build a whole project on it? maybe you assume this question opinion based but its not. please read the whole question. the question has 2 aspects. are all features implemented? just better say, can i do everything or any gameplay i did on monobehaviours, on the DOTS? all are needed features implemented? including Ai, navigation, physics, animations and... the bigger problem about DOTS and ECS is software engineering. DOTS gives us much better performance in memory and performance and parallel processing but it takes all good OOP practices from us. as you may know, DOTS is not OO and uses its own architectures. most of references values are gone in dots to make data more compact. so there is no solid principles. dependency injections and all those OO design patterns. instead we have a hardly coupled code and entities. the question is does DOTS and ECS really lacks software engineering or its just we dont know enough about it and there are standards about it? many people say that you should make all project on old monobehaviours and you can migrate section that are expensive to DOTS. im not really sure what is the right approach for using with new technology.
|
0 |
Left Hand and Right Hand Coordinate Systems In Blender and other 3D modeling tools, the coordinate system is right handed, while in Unity 3D and Orbiter Space Flight Simulator, they are left handed, why this could happen? Why they don't simply use the right hand coordinate system all the time to make things easier? Why don't all programs that deal with 3D graphics use Z as up? Y Z ZX YX RIGHT HAND LEFT HAND TOP VIEW TOP VIEW (fortunately, Unity3D converts from Blender coordinate system to Unity3D coordinate system)
|
0 |
Gyroscope Parallax Effect In Unity I want to make a parallax effect in Unity 3D with gyroscope like the one on this site http matthew.wagerfield.com parallax I found an asset, but it is too expensive. So I need a script which I can set to the GameObject, so it would move depending phone's gyroscope.
|
0 |
Rotate arrow without using Unity3d physics engine I have this code that simulates the movement of a projectile without using the unity physics engine IEnumerator LaunchProjectile(int angle, float speed) Move projectile to the position of throwing object add some offset if needed. Projectile.position transform.position new Vector3(0, 0f, 0) Projectile.rotation transform.root.rotation Debug.Log(transform.root.eulerAngles) Calculate distance to target float target Distance speed (Mathf.Sin(2 firingAngle Mathf.Deg2Rad) gravity) Extract the X Y componenent of the velocity float Vx Mathf.Sqrt(speed) Mathf.Cos(firingAngle Mathf.Deg2Rad) float Vy Mathf.Sqrt(speed) Mathf.Sin(firingAngle Mathf.Deg2Rad) Calculate flight time. float flightDuration target Distance Vx this.arrowSimulationScript Projectile.gameObject.GetComponentInChildren lt ArrowSimulation gt () float elapse time 0 while (!arrowSimulationScript.Collided()) Projectile.Translate(0, (Vy (gravity elapse time)) Time.deltaTime, Vx Time.deltaTime) Projectile.LookAt(Projectile.position new Vector3(0, (Vy (gravity elapse time)) Time.deltaTime, Vx Time.deltaTime)) arrowSimulationScript.Velocity new Vector3(0, (Vy (gravity elapse time)) Time.deltaTime, Vx Time.deltaTime).magnitude elapse time Time.deltaTime yield return null The arrow is fired in the direction of the object which has this script attached. To make the arrow rotate I use this line of code Projectile.LookAt(Projectile.position new Vector3(0, (Vy (gravity elapse time)) Time.deltaTime, Vx Time.deltaTime)) The arrow moves towards the right direction but with the tip facing the z axis direction, instead of the direction of the bow. Here is a video of the problem https www.youtube.com watch?v cyK6DXxTw E If I comment out that line of code the arrow fly with the tip facing the direction of the bow, but it doesn't rotate.
|
0 |
uNet Client cant see server spawned objects I'm facing a problem where when I connect with the host, all the towers spawn. After I connect with a client only to find out there are no towers visible and I can walk through them when looking at the host screen. My tower spawn script ( GameManager.cs ) public int numberOfDestroyedTopTowers 0 public int numberOfDestroyedMidTowers 0 public int numberOfDestroyedBotTowers 0 public GameObject topTowerSpawns public GameObject midTowerSpawns public GameObject botTowerSpawns public GameObject towerPrefab void Start() CmdSpawnTowers() Command void CmdSpawnTowers() for (int i 0 i lt midTowerSpawns.Length i ) GameObject currTower (GameObject)Instantiate(towerPrefab) currTower.transform.position midTowerSpawns i .transform.position currTower.name "Tower MID " i NetworkServer.Spawn(currTower) for (int i 0 i lt topTowerSpawns.Length i ) GameObject currTower (GameObject)Instantiate(towerPrefab) currTower.transform.position topTowerSpawns i .transform.position currTower.name "Tower TOP " i NetworkServer.Spawn(currTower) for (int i 0 i lt botTowerSpawns.Length i ) GameObject currTower (GameObject)Instantiate(towerPrefab) currTower.transform.position botTowerSpawns i .transform.position currTower.name "Tower BOT " i NetworkServer.Spawn(currTower) The script is derived from NetworkBehaviour and it does have a Network Identity on it (Server Only checked). Also on my towerPrefab I also have a network identity with server only checked. I have added my tower prefab under the network manager "Registered Spawnable Prefabs".
|
0 |
How can non CG shader code in Unity be included? In Unity shaders, include, define, and other preprocessor commands seem to not be able to be used outside the CGPROGRAM section of the shader. Since these are required for compiling multiple shader variants, and a large portion of the shader is non CG, this would be incredibly useful to reduce shader duplication. Do these commands exist outside CG?
|
0 |
Unity Rendering Pass Before Refraction not showing In the documentation it states Before Refraction Draws the GameObject before the refraction pass. This means that HDRP includes this Material when it processes refraction. To expose this option, select Transparent from the Surface Type drop down. I have selected the Transparent option for surface type but the Before refraction rendering pass is not in the drop down list for rendering pass. How can I get it to be there? Are there some other option that might be disabling it?
|
0 |
How can I make item interactable for action? In this script when there is a detection I'm setting the flag detect to true and using in with other scripts. And using the clickForDescription flag and OnGui to display text description for each interactable item if there is a text for it. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class DetectInteractable MonoBehaviour public Camera cam public float distanceToSee public string objectHit public bool interactableObject false public Transform parentToSearch public static bool detected false private RaycastHit whatObjectHit private bool clickForDescription false private bool clickForAction false private int layerMask 1 lt lt 8 private void Start() private void Update() if (Input.GetMouseButtonDown(0)) clickForDescription true clickForAction true Debug.DrawRay(cam.transform.position, cam.transform.forward distanceToSee, Color.magenta) if (Physics.Raycast(cam.transform.position, cam.transform.forward, out whatObjectHit, distanceToSee, layerMask)) detected true objectHit whatObjectHit.collider.gameObject.name interactableObject true print("Hit ! " whatObjectHit.collider.gameObject.name) else detected false clickForDescription false print("Not Hit !") private void OnGUI() if (clickForDescription true) ProcessOnGUI(parentToSearch) void ProcessOnGUI(Transform parent, int level 0) foreach (Transform child in parent) if (child.GetComponent lt ItemInformation gt () ! null) ItemInformation iteminformation child.GetComponent lt ItemInformation gt () if (child.name objectHit) var centeredStyle GUI.skin.GetStyle("Label") centeredStyle.alignment TextAnchor.UpperCenter GUI.Box(new Rect( Screen.width 2 50 20 level, lt INDENTATION Screen.height 2 25, 100, 50), iteminformation.description, centeredStyle) Process next deeper level ProcessOnGUI(child, level 1) public class ViewableObject MonoBehaviour public string displayText public bool isInteractable This is the ItemInformation using System.Collections using System.Collections.Generic using UnityEngine public class ItemInformation MonoBehaviour TextArea public string description Once object is tagged for Interactable and the ItemInformation is attached to it it will display some description for the item. Now I want to do something for action. For example if the item is Interactable and a script name ItemAction is attached to it do some action, For example move the object from side to side or rotate the object. The logic should be like the Information. It's just with the Action there might be many options then just displaying text. I'm not sure how to make some logic and how to work with the ItemAction. using System.Collections using System.Collections.Generic using UnityEngine public class ItemAction MonoBehaviour
|
0 |
How to apply a force to a wheeled veichle and make wheel rotate ? I've a veichle with 4 wheel and 4 wheel collider. My veichle is a toy.. so i would like to apply an impulse force (veichle rigidbody.addforce) to that veichle, move it and make wheel rotate... How can i do ? Thanks
|
0 |
Unity3d vector and matrix operations I have the following three vectors posA (1,2,3) normal (0,1,0) offset (2,3,1) I want to get the vector representing the position which is offset in the direction of the normal from posA. I know how to do this by cheating (not using matrix operations) Vector3 result new Vector3(posA.x normal.x offset.x posA.y normal.y offset.y, posA.z normal.z offset.z) I know how to do this mathematically Note indicates a column vector, indicates a row vector result 1,2,3 2,3,1 0,0,0 , 0,1,0 , 0,0,0 What I don't know is which is better to use and if it's the latter how do I do this in unity? I only know of 4x4 matrices in unity. I don't like the first option because you are instantiating a new vector instead of just modifying the original. Suggestions? Note by asking which is better, I am asking for a quantifiable reason, not just a preference.
|
0 |
Unity using Animation and Ragdoll The question is simple, but I can't resolve it for a couple of days. I have an enemy model with ragdoll attached and also a couple of animations(e.g. idle, walk, run). It seems that ragdoll work only when animator is stopped and vice versa. What I want is when the animation is playing all the forces are applied too, e.g. when I shoot enemy he still walking by animation and and ragdoll corresponds with AddForce(). I tried to find appropriate tutorial for that, watched ton of youtube videos and read a lot of unity forums, but no success. Any help is appreciated. Thanks in advance.
|
0 |
Issue picking the closest vector in a unique circumstance I have a list of targets that can be picked depending on the magnitude from the vector created using for(int i 0 i lt targetQueue.Count i ) 2 loops to cycle through targets for(int j 0 j lt targetQueue.Count j ) if two targets are the same, then skip them if(targetQueue i ! targetQueue j ) getting the direction using the source and destination vectors Vector3 iDir targetQueue i .transform.position transform.position Vector3 jDir targetQueue j .transform.position transform.position comparing i with j, if i is less than target at j then match found if(iDir.magnitude lt jDir.magnitude) LockedTarget is a gameobject to show what target the turret is locked on to LockedTarget targetQueue i if match found then set locked target to target at i break This code compares every target to each other, however it does this twice, once on each side( target i becomes target j ). When the magnitude is compared, if the target i is smaller, then this is now the locked target as this target is closer to the turret. This works every time except for one instance and I can't figure out why its happening here When both targets are inside the collider, the target on the right should still be highlighted, yet I get the target that is farther away being selected, this also occurs with more than two targets, with even stranger results. These being that the original target chosen for 'DEADLOCK' what i'm calling it, stays locked. Even when I move the other targets above, below, left and to the right of it. This only occurs with this target, i've tried with 2 other targets (south of the turret) and it works as intended by properly switching based on size of magnitude of the direction vector between the target and the source. I have ruled out the possibility being that it is an issue to do with adding target's to the gameobject list as it works everywhere else. When measuring the lengths of the magnitudes, the wrong target is chosen as the locked target. It does show that the closest target on the images does actually have the smallest vector magnitude. UPDATE the magnitudes of the vectors are increasing and decreasing by tiny amounts, 1 to 2 for a major movement. this makes sense as its worldPos. What doesn't make sense is the target on the right having a magnitude of 49 and the target above having a magnitude of 82, when according to world space they are pretty close to eachother. Can anyone help me with this issue? its been driving me nuts for days. It must be to do with the magnitudes of the direction vectors not being calculated properly.
|
0 |
How to create pixel perfect text in TextMeshPro with a shadow? Problem Making the font asset of type Raster creates a pixel perfect font, but it doesn't have the underlay option inside its material to give it a shadow. Making it of type SDF (or one of the variants) does, but it's blurred in game view. See the image for a visual example. The top text uses the SDF variant, whereas the bottom is of Raster type. This is Game View, zoomed in. Attempted Solution I considered using Unity's own Text component, which, strangely enough, doesn't blur in Game View (but does in Scene View). However, to give it a shadow, I need to create a 2nd, black Text object to place behind it with a small offset. This is fine, but then I need to match its value to the main Text's, and I can't seem to do that without checking every frame inside Update(), which is wasteful.
|
0 |
Virtual World Plaforms and Unity3d I'm moving in the direction metaverse developing. A few years back I wandered around in Second Life and found it entertaining for a New York minute. Now, I'm set to plunge into the Virtual World MMO enviroment. ReactionGrid's Jibe seems to be wonderfully paired with Unity3d. I've been a Unity developer for 5 6 years now. Is there a open source Virtual World Platform that integrates with Unity like Jibe? I've read an article on platforms like OGRE, Open Colbalt, OpenSimulator, Project Wonderland and Sirikata but none seem to mention working with Unity3d.
|
0 |
Moving camera vertically only after player is too high or too low In my 2D platformer game, I find it very exhausting for the player if the camera follows the player all the time. So, I looked up for some tricks to make camera movement feel more natural. The first trick is from James Doyle, where the camera follows a target instead of the player itself. Thus, I can safely use Mathf.Lerp for the target, and avoid having jitters. The second thing I want to do is to limit the vertical movement of the camera. That is, I don't want the camera to move up and down whenever the player jumps. It is dizzying. Instead, I want camera to follow the player only if player is vertically too high or too low. Here is roughly what I do PlayerController.cs public Transform cameraTarget private void FixedUpdate() if(Mathf.Abs(transform.position.y cameraTarget.position.y) gt verticalLimit ) cameraTarget.position new Vector3(cameraTarget.position.x, Mathf.Lerp(cameraTarget.position.y, transform.position.y, Time.fixedDeltaTime), cameraTarget.position.z) if (Input.GetAxisRaw("Horizontal") ! 0) cameraTarget.localPosition new Vector3(Mathf.Lerp(cameraTarget.localPosition.x, Input.GetAxisRaw("Horizontal") cameraAheadAmount, 0.8f Time.fixedDeltaTime), cameraTarget.localPosition.y, cameraTarget.localPosition.z) The problem for this approach is that whenever the vertical distance between the player and the camera target is less than the limit, the camera does not follow the player anymore. So, what I get is basically a camera following the player from down below, again, all the times. I thought of using a boolean flag to tell the camera follow the player when vertical limit is exceeded, but then when do I set and unset the flag? I am new to Unity's Update() and FixedUpdate() logic, so I cannot somehow design a workaround. Is there a simple way to do this?
|
0 |
Game is darker on build I've been recently doing test builds of my game. In Unity, I worked on baking the lighting to ensure everything looked fine. However, upon building, the game level becomes far darker and much of the lighting and baking is ineffective. Here is how the scene looks in the editor And here is how it looks in the built game It's much darker than intended. Here are my lighting settings which I've baked in Unity's Editor. These settings and lightmap parameters were designed to, at least in the editor, provide decent quality while making light bake times relatively quick. However, I've noticed that newer Unity's Lighting settings are way different now, so perhaps something is amiss here? I've been at my wits end trying to figure this out for the past while, but I can't figure out why this is happening or how to fix it. Any ideas?
|
0 |
Why the Render texture is not working when trying to preview a camera on a object? In the editor in Assets right click Create Render Texture Then changed the Render Texture name to SecurityCameraTexture Dimension 2D size 480 x 256 Then created a new material Assets right click Create Material Then changed the material name to SecurityFootage Then changed the material shader from Standard to Mobile Diffuse Then dragged the render texture(SecurityCameraTexture) to the top right image place of the SecurityFootage(material) Next I have a tv object in the scene. In the tv screen I dragged the new material The SecurityCamera. On the SecurityCamera I attached the script that rotate the camera from side to side And the script using UnityEngine using System.Collections public class scr camera MonoBehaviour public float rotate amount Use this for initialization void Start () Update is called once per frame void Update () transform.rotation Quaternion.Euler(transform.eulerAngles.x, (Mathf.Sin(Time.realtimeSinceStartup) rotate amount) transform.eulerAngles.y, transform.eulerAngles.z) Last step I did was to drag the render texture(SecurityCameraTexture) to the camera Target Texture. When running the game and watching the tv I don't see the camera preview in the tv. It should the show the camera preview the camera moving from side to side and what the camera is showing. The camera preview was working fine before I started working with the render texture. But it's not showing the preview in the tv.
|
0 |
Unity General Prefab I have 2 questions about how i should approach this. I want to make a 2D game, with alot of different creatures. Question one If i have alot of monsters and i'm using ScriptableObjects, since they have very similar variables. How can i make one Enemy prefab which will load the right ScriptableObject information? For example i have an Enemy Prefab, then it will load random monster between Dragon, Frog, Wolf. How can i achive this without creating 3 new Prefabs for each one and instead load just the right ScriptableObject. Question two Should i create new prefab for each monster? Or is approach 1 the right way to do it, if you plan to expand over 100 creatures. Thanks
|
0 |
Formatting Unity data for communication with a REST API I am pretty new to unity but I am not new to programming. I am building a Hololens application in Unity 2017.2 and it communicates with a REST api that I built. I am using Unity as a front end more or less and it manages my state. Coming from the web developement world, I have my server converting my models into JSON and I am sending that as a response. For the most part, it works well but since Unity works on an older version of C , I am having issues working with the JSON data, mainly if the data type is not a string, int, float, or double. For example, if my model contains a date data type I am having issues converting it back into a c model or even arrays are proving to be a pain. I don t want to rely on unity packages too much as most I have tried don t do what I need but I am open to any good ones if you know of any. My question is, what is the best way to send data from my API to Unity? Should I send xml or a csv instead? Or even a more C native approach? (If that makes sense)
|
0 |
Continous repeatable object image moving horizontally unity3d I want to move objects on the screen horizontally. And the user has to pop the object by touching it. When user touch it, it gets destroyed and new object comes randomly. For experimenting, I used Unity's Scroll Rect to move them. What can be the best solution for this.
|
0 |
Loading texture from Resources folder not working C So I want to load different textures for my game object when different conditions are met. There are no errors when I compile this code. The colours change according to the condition, that part does work. The textures do not load though. The textures are stores in a Resources folder in Unity. The first code works but the second does not. Why is this the case? Below is my code using System.Collections using System.Collections.Generic using UnityEngine public class Level4 MonoBehaviour Material mat GameObject Sphere Use this for initialization void Start() Sphere GameObject.FindWithTag("Player") Material mat GameObject.FindWithTag("Player").GetComponent lt Renderer gt ().material Update is called once per frame void Update() try if (Input.GetKeyDown(KeyCode.UpArrow)) Renderer rend GetComponent lt Renderer gt () Material mat rend.material rend.material.mainTexture Resources.Load("face1") as Texture mat.color Color.red catch (System.Exception) this is the second code that does not work using System.Collections using System.Collections.Generic using UnityEngine using System.IO.Ports public class arduino MonoBehaviour SerialPort sp new SerialPort(" . COM6", 9600) Com port and the baud rate of the arduino Material m Material GameObject Sphere void Awake() Sphere GameObject.FindWithTag("Player") m Material GameObject.FindWithTag("Player").GetComponent lt Renderer gt ().material void Start() if (!sp.IsOpen) If the erial port is not open sp.Open() Open sp.ReadTimeout 250 Timeout for reading Update is called once per frame void Update() if (sp.IsOpen) Check to see if the serial port is open try string portreading sp.ReadLine() get the string output of the serial port float amount int.Parse(portreading) if ((amount gt 251f)) Renderer rend GetComponent lt Renderer gt () m Material rend.material rend.material.mainTexture Resources.Load("face1") as Texture m Material.color Color.red catch (System.Exception)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.