_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | Keeping 2 objects within cameras view I have two object to control and I wanted to keep them at cameras view without adjusting the cameras size but the camera can move only in positive y axis meaning ones it goes up it shouldn't move down but it's okay if one object gets out of bounds. Since its 2D the camera is Orthographic view. |
0 | Idle Clicker games, supporting numbers many factors bigger than trillions in C using Unity Apologies for sloppy work and probably a poor grasp of fundamentals. I have a (likely primitive) way to convert the ever increasing number values of my enemy hp into a string format to display in game. (K for thousands, M for millions, B for billions etc) if (target healthmax gt 1000) if (target healthmax gt 1000000000) enemy hp text.text "Health " (target healthcur 0.000000001f).ToString(" .00") " " (target healthmax 0.000000001f).ToString(" .00") "B" else if (target healthmax gt 1000000) enemy hp text.text "Health " (target healthcur 0.000001f).ToString(" .00") " " (target healthmax 0.000001f).ToString(" .00") "M" else enemy hp text.text "Health " (target healthcur 0.001f).ToString(" .00") " " (target healthmax 0.001f).ToString(" .00") "K" else enemy hp text.text "Health " target healthcur " " target healthmax but I stopped here after I noticed that although I could convert long numbers I would eventually hit a number too large to handle such as " 2.147484e 09" in my editor, and it would stop working. I am using floats currently, is there a different type of variable that handles this easily? if not, what is an efficient way of solving this? Would it be efficient to convert every new factor of 100 to a new variable and only handle the highest valued variable? eg if num gt 1000, k 1, num 0 if k gt 1000, m 1, k 0 ... (Please feel free to let me know anything about my post I may need to amend, I am new here) |
0 | Tile map creation, problem with position of tiles I am trying to create a basic tile map script to learn Unity and I am unable to understand why my tiles are spaced far apart and I can't seem to control their spacing. Moreover, there seems to be a difference between tile map size and Unity sizes, how do I convert tile map size to Unity size? My understanding of tile maps are limited but here is what I want to do. I want to be able to set tile size, amount of tiles displayed and the spacing between each tiles. Image http puu.sh in6XW 416f8971bc.png public static int TILE WIDTH 32 public static int TILE HEIGHT 32 public float tileSize 0.1f private Transform , tiles void Start () var w 18 width var h 15 height tilePrefab.gameObject.GetComponent lt SpriteRenderer gt () tiles new Transform w,h for (int y 0 y lt h y ) for (int x 0 x lt w x ) Transform tile Instantiate(tilePrefab, new Vector3(x tileSize,y tileSize,0),Quaternion.identity)as Transform tile.parent transform tiles x,y tile |
0 | Simple Water surface simulation problems (GDC2008 Matthias Muller Hello World) Im attempting to implement a simple height field water surface simulation outlined in Matthias Muller's GDC 2008 talk. "http www.matthiasmueller.info talks gdc2008.pdf" I can't seem to see why it my implementation doesnt work. Could anyone help? Any advice or help would be much appreciated. The main processing loop is below The obstruction array is initialized as 1. And the source just adds 0.1f to a point. void wave() for( int i 0 i lt size i ) height i source i height i obstruction i for (int i 1 i lt iwidth 1 i ) for(int j 1 j lt iheight 1 j ) velocityField indexFind(i,j) (height indexFind(i 1,j) height indexFind(i 1,j) height indexFind(i,j 1) height indexFind(i,j 1) ) 4 height indexFind(i,j) velocityField indexFind(i,j) dampening height indexFind(i,j) velocityField indexFind(i,j) int indexFind(int x, int y) return (x iwidth y) This is what happens (height field rendered as a texture on a plane) This is the page from the link that outlines the algorithm |
0 | Best way make static GameObject clickable 2D I've built a turn based battle combat game (like pokemon) but i'm stuck between a rock and a hard place. Asfar as i understod UI elements should be inside Canvas, while Players, Enemies, Items and etc... Should not be inside a canvas. Correct me if i'm wrong. I've tried different ways how to handle this situation. Such as make Enemy as a button, but seems not to fire. Since i think it has to be inside a canvas. Also make enemy which have animations as button, may not be a good idea? Update event, to check if the mouse is down and mouse position is converted with screentoworldpoint and see if the positions matches with the enemy position. Update event, to check if the mouse is down and rayCast see if we colide with something. But i dont feel like this is neccesary since the enemy does not move. So the position is always the same. Also if it's possible to take into consideration that every enemy is different size. But this is a minor detail, i would like firstly tackle the best way handle onClick event without the extra overhead. I would appericate any feedback on my dilemma. |
0 | Camera position and angle different when running inside Unity and when running on Android On Windows, running Unity 4.6.1p5, my simple game with only a cube, camera and light looks like this but under Android (Gingerbread on a 5 inch Galaxy Player) the cube appears lower down, slightly different angle and smaller (relative to the screen size). Sorry couldn't get a screenshot with my screenshot app... Any ideas why please? |
0 | Starting Couroutine in newly activated gameObject I'm working on a UI system that animates an element's properties using coroutines. Every element that should be animated has a component called AnimatedUIElement which provides the function Enter(). The function Enter() is basically starting coroutines depending on the chosen animation settings, but only after calling Enable(), which sets the gameObject active with gameObject.SetActive(true) , updates its component references and makes the element interactable. AnimatedUIElement also defines an Exit() function acting similar, but disabling the element after the animation. public class AnimatedUIElement MonoBehaviour private CanvasGroup canvasGroup ... public void Enter() ... TriggerEntry() private void TriggerEntry() PlayChildrenEntry() Calls Enter() on all animated Children Enable() StartCoroutine(SomeAnimation(...)) private void Enable() gameObject.SetActive(true) Init() canvasGroup.interactable true canvasGroup.blocksRaycasts true private void Init() canvasGroup GetComponent lt CanvasGroup gt () ... private IEnumerator SomeAnimation(...) ... public void Exit() Similar to Enter, but disabling the element Now I want to open the options panel by clicking a button in the game's UI. The panel is inactive (unticked) in the beginning, while the AnimatedUIElement component is enabled. UI Hierarchy Options Button calls Enter() on Options Panel. The desired setup in the Button Component calling OptionsPanel.Enter() and MainPanel.Exit() But clicking the button throws the following exception Coroutine couldn't be started because the the game object 'Main Menu Button' is inactive! UnityEngine.MonoBehaviour StartCoroutine(IEnumerator) AnimatedUIElement AnimatePosition(Vector2, Vector2, Single, AnimationCurve) (at Assets Animated UI Elements AnimatedUIElement.cs 265) AnimatedUIElement TriggerEntry() (at Assets Animated UI Elements AnimatedUIElement.cs 93) AnimatedUIElement Enter() (at Assets Animated UI Elements AnimatedUIElement.cs 73) AnimatedUIElement PlayChildrenEntry(Transform) (at Assets Animated UI Elements AnimatedUIElement.cs 219) AnimatedUIElement TriggerEntry() (at Assets Animated UI Elements AnimatedUIElement.cs 79) AnimatedUIElement Enter() (at Assets Animated UI Elements AnimatedUIElement.cs 73) UnityEngine.EventSystems.EventSystem Update() In this stack trace you can see that the Options Panel did not start coroutines as no animation was defined in its component, but called Enter() on its children, which are animated. Using debug logs I found out that, while Init() is called immediately after Enter(), Awake() is called after the coroutines (which happen later in the program flow) throw errors. This makes it seem like the object is not available instantly after calling setActive(true). Is there an explanation and possibly a fix for this behavior? |
0 | Transform.Rotate micro stutter? Hey all I have a quick question. I am new and obviously still learning the basics of programming scripting. However I am confused by the result of a simple script. The goal is to have a Start Menu with a 3d background.The camera is attached to an Empty Object, which has a script that is meant to constantly rotate. My confusion, is whether I am live testing in Unity, or a built executable. When the empty object is rotating, it will have a pause or a few milliseconds, and then continue with its rotation. Almost like a planned micro stutter. Regardless of where it is in its cycle. How can I make the rotation as perfectly smooth as possible? Below is the script for rotating the empty object that the camera is attached to. public class cameraAnchor MonoBehaviour public float speed 5f Update is called once per frame void Update () rotate camera anchor around y axis transform.Rotate(Vector3.down, speed Time.deltaTime) |
0 | Accessing DualShock 4 motion sensor in Windows (ideally Unity) I'm trying to use a DualShock 4's IMU as a motion controller in Unity, under Windows 7. So far I've tried DS4Windows (1.5.11) reads motion sensor data, but does not expose them to Unity as axes unless I map them to the left amp right sticks. This is not enough since I lose use of the sticks, I can only fit 4 of the 6 channels of data, and the values coming through are clipped into a narrow range. Motioninjoy (0.7.1001) does not appear to detect the DS4 as a controller (latest docs refer only to DS3 and prior) GlovePIE (0.43) after following instructions for using the DualShock 3 with LibUSB Win32 (a long shot), SixAxis properties are all blank. In the past I've used external programs like GlovePIE to capture Wii remote motion sensor data and pass it to Unity via OSC messages, so I'd be open to an approach like this if I can't get Unity to read the controller's sensors directly through its Input system. Anyone had luck with this? |
0 | Testing Unity 2D Physics I am looking to push the 2D physics in Unity to the extent where when so much is going on that there becomes noticeable lag in a game. This is for testing purposes, so that when so much is going on that a button can be pressed to reduce the amount of physics objects on screen then see what affect that has. So in my small 2D demo I have placed alot of barrels on the map, all of which have physics on them, player bumps into them and they move. I have went to the extent of placing alot of them on the map (864 to be exact), bumping into them I still don't see any effect on the gameplay. Other things I have tried, besides adding alot in, is increasing the mass of the barrels, changing their linear and angluar drag and making them bouncy. Is there anything I can do besides adding alot more in? Thanks! |
0 | Why does OnControllerColliderHit not work while Physics.CheckSphere() does? Using the following code below, when my character hits a crate and goes over it, it ends up floating in the air, while jumping is no issue. That successfully lands on the ground. using UnityEngine public class Testing MonoBehaviour public CharacterController Controller speed of the character public float Speed 12f earth gravitational value public float Gravity 9.81f Vector3 velocity hit point of character float hp 90 bool Grounded true public void OnControllerColliderHit(ControllerColliderHit hit) Grounded true hp velocity.magnitude velocity.y 0 Debug.Log(hp) public void OnControllerColliderExit(ControllerColliderHit hit) Grounded false public void Checkstatus() if (Grounded false) velocity.y 0.5f Gravity Time.deltaTime void Update() float x Input.GetAxis( quot Horizontal quot ) float z Input.GetAxis( quot Vertical quot ) Vector3 move transform.right x transform.forward z Controller.Move(move Speed Time.deltaTime) if (Input.GetKeyDown(KeyCode.Space) amp amp velocity.y 0) velocity.y 12 Grounded false check if it grounded Checkstatus() Controller.Move(velocity Time.deltaTime) Here's an image showing the floating player And why does the code below (using Physics.CheckSphere()) have no issue? Feels like the above code is better (if working correctly), as it doesn't need to waste resource on checking the condition of Grounded (like in checkstate1()) every frame. using UnityEngine public class NewPlayerMovement MonoBehaviour public CharacterController Controller public float Speed 12f public float Gravity 9.81f Vector3 velocity public LayerMask groundmask float hp 90 bool Grounded true Update is called once per frame void checkstate1() Grounded Physics.CheckSphere(this.transform.position, 0.85f,groundmask) if (Grounded true) hp velocity.magnitude Debug.Log(hp) velocity.y 0 public void Checkstatus() if(Grounded false) velocity.y Gravity Time.deltaTime void Update() checkstate1() float x Input.GetAxis( quot Horizontal quot ) float z Input.GetAxis( quot Vertical quot ) Vector3 move transform.right x transform.forward z Controller.Move(move Speed Time.deltaTime) if (Input.GetKeyDown(KeyCode.Space) amp amp Grounded true) velocity.y 12 Grounded false Checkstatus() Controller.Move( velocity Time.deltaTime) |
0 | What is the difference between body transform and root transform I am learning about Root animation and here come two terms, one is root transform and Body transform. As name suggests that body transform is the character body but what is root transform? and what is the Root transform rotation based upon body orientation, Feet, center of mass or original. |
0 | How to make a cell shader like BOTW in Unity? It seems most cell shader tutorials focus on individual shaders for materials, but the effect used in BOTW seems to be more like a filter, that is applied to everything. I've researched multiple examples that have been done in UE4 like here and here but nothing in Unity. How would I apply something like this in Unity? |
0 | Setting up a singleton class in Unity I have spent a long time (4 5 hours) digging around as to why my version of the Breakout Unity Tutorial was not working. There where repeated errors of NullReferenceException Object reference not set to an instance of an object xxxxxxx when running the game and calling Game Manager scripts from other scripts in the game. After much reading up on vaguely useful questions and answers on here I know well enough what the error text means, but the answers on here that describe the error in detail do not reference how to solve this issue on an instance of a singleton. Elsewhere I found a solution, and want to show this solution as I figure that can help a lot of other people searching for why this issue occurs Qualifier There is an inconsistency with the Breakout Tutorial see the instantiation of the Game Manager class using UnityEngine using System.Collections using UnityEngine.UI public class GM MonoBehaviour public int lives 3 public int bricks 20 public float resetDelay 1f public Text livesText public GameObject gameOver public GameObject youWon public GameObject bricksPrefab public GameObject paddle public GameObject deathParticles The below sets the Game Manager Class (GManager) as an instance so is a static variable. This means its accessed via the class rather than via an instance of the class. This means Game Manager can be reached from other scripts with code GManager.instance.xxx whatever So only one GManager instance will be running. This is a singleton pattern. public static GM instance null private GameObject clonePaddle Use this for initialization void Awake () if (instance null) instance this else if (instance ! this) Destroy (gameObject) Setup() public void Setup() ... Please read my solution below |
0 | Instead of using yield wait for seconds can I use a UI button for async? the code below is the code I use to load my game scene ater the intro animation plays. The way it works is that it preloads the game scene because it is big enough it takes time to load and activates it after 15 seconds. I want to use this code in a similar manner for my main menu, but instead of preloading and waiting for seconds I want it to preload and wait for UI button. public class IntroToForest MonoBehaviour public float WaitToLoad 14.0f void Start() StartCoroutine(LoadScene(WaitToLoad)) IEnumerator LoadScene(float WaitToLoad) yield return null AsyncOperation asyncOperation SceneManager.LoadSceneAsync("Forest Map") asyncOperation.allowSceneActivation false while (!asyncOperation.isDone) if (asyncOperation.progress gt 0.9f) yield return new WaitForSeconds(WaitToLoad) asyncOperation.allowSceneActivation true yield return null Side note I incorporated DmGregory's answer into my menu controller script and got this public class MenuController MonoBehaviour public string SceneName AsyncOperation preload void Start() preload SceneManager.LoadSceneAsync(SceneName) preload.allowSceneActivation false public void Go to game() if (preload.progress lt 0.9f) if (PlayerPrefs.HasKey("HasSeenIntro")) preload.allowSceneActivation true else PlayerPrefs.SetInt("HasSeenIntro", 1) SceneManager.LoadScene("Intro") The problem is that the UI button will not work. |
0 | 2D collision of thrown objects in Unity I am currently working on a game inspired by traditional 2D Zelda games ("Link To The Past", etc.) in Unity using the 2D settings. I am looking for the best way to handle objects that the character throws and how to handle the collisions correctly given the perspective of the camera. A thrown object is rendered further up the screen to create the illusion it is in the air however due to this it will collide with enemies and objects that are not on it's current plane. Below is a screenshot of "Link To A Past" for those who aren't familiar with the perspective of the game. I have thought about two ways to potentially implement this system but both don't feel like good the solutions. Turn off collision during the throw until near the end of the throw. I feel for this solution that different colliders would be required to ensure the correct object is experiences the collision. The issue I see with this solution is that it doesn't account for taller objects. If I throw an object directly at a wall the object should detect that. A system where using Unity's physics layers I turn layers off during the flight and based off the location of the thrown object. For example turning off the physics layers of objects that are above the object but shouldn't be hit due to the perspective. This method seems like a lot of work but could be a solution to the problem. Any thoughts for better solutions or refinements would be much appreciated. |
0 | Getting a CineMachine FreeLook Camera to work with a GamePad(joystick) I have no idea how to get the FreeLook cam to work with the second stick on a gamepad. The docs seem to have nothing on the topic. Has anyone done this before ? |
0 | Can Unity support use textures that are not square? I have been told by another highly skilled Unity artist that Unity cannot efficiently handle non square images. Since that doesn't sound right to me, I wanted to get a second or third confirmation to that claim. Having worked in the game development industry for almost 15 years, I have always understood that best practice was keeping in powers of two, but that if the UV map called for it, a 1024x512 map was acceptable, rather than using a 1024x1024 map with 1024x512 pixels of wasted UV space. Granted, that was best practice on game engines other than Unity. Can anyone confirm that in Unity's case, it is better (best practice) to have a 1024x1024 image containing UV islands occupying 1024x512 pixels, rather than using a 1024x512 image map to exactly accommodate the UVs? Which platforms can use non square images and which ones cannot with the Unity engine? I am particularly interested in whether or not this limitation affects PC builds. |
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 can I unregister an event from another scene or another script? This is where and how I register the event void Update() if (Input.GetKeyDown(KeyCode.Escape)) if (Time.timeScale 0) DisableEnableUiTexts(true) SceneManager.UnloadSceneAsync(0) if (fadeImage ! null) fadeImage.SetActive(true) GetGameMusicVolume() Cursor.visible false Time.timeScale 1 else Time.timeScale 0 MenuController.LoadSceneForSavedGame false SceneManager.LoadScene(0, LoadSceneMode.Additive) SceneManager.sceneLoaded SceneManager sceneLoaded Cursor.visible true And the event private void SceneManager sceneLoaded(Scene arg0, LoadSceneMode arg1) I need to be able to unregister the event either from another scene or another script. |
0 | Model a chain with different elements in Unity 3D I have to model, in unity 3D, a chain that is composed of various elements. some flexible, some rigid. The idea is to realize a human chain where each person is linked to the other by their hands. I've not tried to implement it yet as i've no idea on what could be a good way to do it. In the game i've to manage a lot of chains of people... maybe also 100 chains composed of 11 15 people. The chain will be pretty simple and there won't be much interaction... Probabily some animation of the people one at time for each chain and some physic reaction (for example pushing a people in a chain should slightle flex the chain) the very problem of this work is that in the chain each object is composed by flexible parts (arms) and rigid parts (the body) and that the connection should remain firm... just like when people handshake... hands are firm and are the wrists to move. i can use C4D to model the meshes. i know this number may cause performance problems, but it's also true i will use low poly versions of human. (for the real it won't be human, but very simple toonish characters that have harms and legs). So actually i'm trying to find a way to manage this in a way it can work, the performance will be a later problem that i can solve. If there is not a fast 'best practiced' solution and you have any link guide doc that could help me in finding a way to realize this is, it would be very appreciated anyway if you post it. thanks |
0 | Unity onEditEnd and onSubmit only firing from Return key I have an InputField in my UI, but currently I can only submit its contents via the Return key. I tried mapping other buttons to the Submit action (e.g. the tab key on keyboard and the X button on my joystick), but neither worked. I tested both onEndEdit and onSubmit (via the Event Trigger component). That said, onClick is being called correctly when I remap my Submit button. I can navigate the menu with my joystick and alternate keyboard controls, but I can't submit the InputField without pressing Return. Why is this? |
0 | 2d raycast collision problem I am currently making a 2d top down game in unity and have stumbled upon a problem with my raycast collision. I want my green player to stop moving when colliding with a wall, therefore i made my player object cast a ray in the direction it is moving. Its velocity is nullified when the distance to the collision point is equal to zero, or below. What seems to be the case is that the player object stops moving way to late and ends up overlapping the wall object. I tried to make an offset such that the player stopped a bit earlier, but it seems that the offset needs to differ depending on the side of the wall block. It even feels like the point at where the player stops is arbitrary and differs from time to time. I would really like to know why this happens and what i can do to fix it. BTW, I would also really like to be able to change the players speed and still have it work. Here are some pictures of my problem The code i use for the player using UnityEngine using System.Collections public class Player MonoBehaviour SerializeField private float speed Rigidbody2D body bool justChangedDir Vector2 moveDir void Start() body GetComponent lt Rigidbody2D gt () void MoveDirection() Vector2 input new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")) if ((input.x ! 0 amp amp input.y 0) (input.x 0 amp amp input.y ! 0)) justChangedDir false if (moveDir.x ! 0) moveDir new Vector2(input.x, 0) if (input.y ! 0 amp amp !justChangedDir) moveDir new Vector2(0, input.y) justChangedDir true else if (moveDir.y ! 0) moveDir new Vector2(0, input.y) if (input.x ! 0 amp amp !justChangedDir) moveDir new Vector2(input.x, 0) justChangedDir true else moveDir input void CheckCollision() RaycastHit2D hit new RaycastHit2D() if (moveDir.x ! 0) hit Physics2D.Raycast(body.position, Vector2.right moveDir.x, 1) Debug.DrawRay(body.position, Vector2.right moveDir.x, Color.yellow) else if (moveDir.y ! 0) hit Physics2D.Raycast(body.position, Vector2.up moveDir.y, 1) Debug.DrawRay(body.position, Vector2.up moveDir.y, Color.yellow) if (hit.collider ! null amp amp hit.distance lt 0.5 ) body.velocity Vector2.zero else body.velocity moveDir speed Update is called once per frame void Update() MoveDirection() if (moveDir ! Vector2.zero) CheckCollision() else body.velocity Vector2.zero Any help will be really appreciated ) Many thanks in advance! Gusgus |
0 | jumping and movement with rigidbody2d.velocity, gravity problem i'm making a 2d platformer and i move my character with rigidbody2d.velocity swiping up to jump and moving while holding the left or right side of the screen. the problem is that when i jump and i try to move left or right in the air, my character falls very slowly. i've read that the reason why that happens is because rb.velocity overrides gravity at every frame, is there a way to move left or right in the air with normal gravity? my full code is Rigidbody2D rb public float speed 1f public float jumpforce 3.5f private Vector3 mouseDownPos private float startTime 0f public float holdTime 0.15f void Start() rb GetComponent lt Rigidbody2D gt () void Update() if (Input.GetMouseButtonDown(0)) mouseDownPos Input.mousePosition startTime Time.time if (Input.GetMouseButtonUp(0)) if ( startTime holdTime gt Time.time amp Input.mousePosition mouseDownPos) tap Debug.Log("T A P") if (Input.mousePosition.y gt mouseDownPos.y 100 ) jump rb.velocity new Vector2(rb.velocity.x, jumpforce) if (Input.GetMouseButton(0) amp startTime holdTime lt Time.time) move while grounded if (Input.mousePosition.x lt Screen.width 2) Debug.Log("Left click") rb.velocity transform.right speed else if (Input.mousePosition.x gt Screen.width 2) Debug.Log("Right click") rb.velocity transform.right speed if (Input.mousePosition.x lt Screen.width 2) move while in the air Debug.Log("Left click") rb.velocity new Vector2( speed, rb.velocity.y) else if (Input.mousePosition.x gt Screen.width 2) Debug.Log("Right click") rb.velocity new Vector2(speed, rb.velocity.y) the rigidbody2d of my character is |
0 | Gameobject not destroyed OnCollisionEnter I have this GameObject with the tag coin I am trying to destroy when the player collides with it using this code located in a player script attached to the player public void OnCollisionEnter(Collision col) var hit col.gameObject if(hit.tag "Coin") Destroy(hit.gameObject) However upon collision nothing is happening |
0 | UnityIAP Subscription Purchase Basically I want to setup UnityIAP for implementation of weekly or monthly subscription for apple store game. I completely read following article given by Unity Integrating Unity IAP In Your Game After this I become aware with actual implementation but i have following questions arise how we can get information about subscription already purchased by this user? how we track time for auto renewable subscription purchase? Please give me some information about this. |
0 | How to add a bolt into my unity project In my game, one of the character you pick as a special ability called the dash. It allows the player to quickly move forward. Included below is the code. It just throws up a bunch of errors. This is a 3d scene using System.Collections using System.Collections.Generic using UnityEngine public class PlayerJump MonoBehaviour Start is called before the first frame update void Start() Update is called once per frame void Update() if (Input.GetKeyDown("q")) transform.Translate(Vector3.KeyDirection 260 Time.deltaTime, Space.World) |
0 | Obstacle avoidance with 2.5D game I'm struggling to make the sprites avoid each other and other obstacles in the field. To achieve something like this To do so I decided to have a 3D environment with an Orthographic camera. It all looks as I wanted. I have set up a plane. My sprites have a 3dCollider and a rigidbody as I want them to be affected by physics. I move the sprites using RigidBody.MovePosition. I checked the collisions, how far they where from their target position, etc... I've tried also a few scripts that intend to do something like this, but I think they are not suitable from what I am doing as after adapting them they don't work. Can somebody give me some guidance on a simple way to do this? I don't want to use a A pathfinding system as I think it's too complex to what I want to do, but if I have to use one I will... I just need some guidance on this... |
0 | Questions about texture compression So when I choose the texture in the Inspector window I see three tabs Default, Standalones amp Android. I can choose some variants of how to compress this texture, but My texture is a png (so it's RGBA). When I click the Default Format I can see stuff like Alpha 8, R 8, RGB 24 bit. So if I choose R8, for example, does that mean that my GBA channels will be thrown away? What is the Max Size? My texture is 600x375. If I choose 512 will it clip my texture to 512x375 or what? And why it is called Max Size if I am working with a single texture right now? If I choose Default Format to Automatic and does not do any override on any specific platform will Unity choose default texture compression formats for a specific platform using this table? |
0 | Playing a simple camera animation with Animator I haven't worked with the animation system in Unity before and am getting overwhelmed trying to figure out how to start playback of a simple animation. Yes, this is a "stupid question", but I've spent more than an hour researching this and can't find an answer on how to do something this simple I've created an animation called CameraZoom for the scene's camera. The CameraZoom animation is supposed to play when a specific event occurs, so I want to trigger it from script. I've created the animation on the camera, it has the Animator component attached to it, and by default the animation plays as soon as the scene starts. I can stop the animation from code, but when I try to start it, nothing happens. Here's my code private Animator myAnimation void Start () myAnimation gameObject.GetComponent lt Animator gt () myAnimation.Stop() public void ZoomOut() Debug.Log("Zoom out!") myAnimation.Play("CameraZoom") This script successfully stops the animation when the scene starts, but when I call ZoomOut, the animation doesn't play. Here are the states It may be I'm not understanding how to utilize the state machine and I'm trying to play the animation incorrectly. Tutorials I can find on the Animator are either too vague or discuss other features such as triggers and parameters that I don't know how to apply to such a simple task. I know I could whip up a Coroutine to zoom the camera out in about 30 seconds, but I'm trying to learn how to utilize the Animator for basic keyframe animations. |
0 | Unity how to apply programmatical changes to the Terrain SplatPrototype? I have a script to which I add a Terrain object (I drag and drop the terrain in the public Terrain field). The Terrain is already setup in Unity to have 2 PaintTextures 1 is a Square (set up with a tile size so that it forms a checkered pattern) and the 2nd one is a grass image Also the Target Strength of the first PaintTexture is lowered so that the checkered pattern also reveals some of the grass underneath. Now I want, at run time, to change the Tile Size of the first PaintTexture, i.e. have more or less checkers depending on various run time conditions. I've looked through Unity's documentation and I've seen you have the Terrain.terrainData.SplatPrototype array which allows you to change this. Also there's a RefreshPrototypes() method on the terrainData object and a Flush() method on the Terrain object. So I made a script like this public class AStarTerrain MonoBehaviour public int aStarCellColumns, aStarCellRows public GameObject aStarCellHighlightPrefab public GameObject aStarPathMarkerPrefab public GameObject utilityRobotPrefab public Terrain aStarTerrain void Start () I've also tried NOT drag and dropping the Terrain on the public field and instead just using the commented line below, but I get the same results aStarTerrain this.GetComponents lt Terrain gt () 0 Debug.Log ("Got terrain " aStarTerrain.name) SplatPrototype splatPrototypes aStarTerrain.terrainData.splatPrototypes Debug.Log("Terrain has " splatPrototypes.Length " splat prototypes") SplatPrototype aStarCellSplat splatPrototypes 0 Debug.Log("Re tyling splat prototype " aStarCellSplat.texture.name) aStarCellSplat.tileSize new Vector2(2000,2000) Debug.Log("Tyling is now " aStarCellSplat.tileSize.x " " aStarCellSplat.tileSize.y) aStarTerrain.terrainData.RefreshPrototypes() aStarTerrain.Flush() ... Problem is, nothing gets changed, the checker map is not re tiled. The console outputs correctly tell me that I've got the Terrain object with the right name, that it has the right number of splat prototypes and that I'm modifying the tileSize on the SplatPrototype object corresponding to the right texture. It also tells me the value has changed. But nothing gets updated in the actual graphical view. So please, what am I missing? |
0 | Unity2D Save everything in a scene before loading another and come back to it? So I have am into this endless runner thing where everything is generated randomly from prefabs. Okay cool! But I am currently working on a bonus collectible which takes the player to another scene. After certain time, the player must reach at exactly the same position it left from. But that's not the problem. I have figured out a way to save and load player's and camera's position using temporary prefabs. My problem is When the player collects the bonus thing in main scene and goes to the bonus scene and comes back, there's a sort of gltichiness or distortion in the game view. As if, the bonus scene is frozen and other scene is overlapping and everything is being stretched. But in inspector, everything including camera is in place. In game view, on returning, the camera seems to be starting from beginning while in inspector its exactly where its supposed to be. Not only that, there's a lot of distortion, which I am 70 sure is because the level had to load all over again and there's no possible way of game knowing which prefabs were instantiated as they all are random. Compiling up, my question is, how can I save everything in a scene before leaving and load it all again at once so it doesn't have to go through all of it again. Is there any less complex way? I hope I have made my ques clear. Thank you. |
0 | How to make proper billboarding trees ? (Unity3D C ) I make a 2.5D first person game like Doom, Duke Nukem 3D, and Daggerfall used to be. I'm new to Unity and game development in general, so I'm sorry if this seems obvious to some people. What I want is to have the 2D sprites of the trees to billboard smoothly in the same way they did in the old games. Take a look at this video to understand what I mean https www.youtube.com watch?v xPwGXf8y6XA amp t 277s I've already tried the proposed solution at http wiki.unity3d.com index.php?title CameraFacingBillboard and it doesn't work the way I want, it's uncanny and off putting the way it works. Please help me. |
0 | Move enemies over the network without sending their positions I am trying to move enemies on two clients without sharing their positions. I use this startingPosition GetRandomDir() Random.Range(1f, 10f) To have the same movement on clients and server, I set the same seed to get the same directions with Unity Random. I set it with the system datetime now ticks on server and clients Random.InitState(newTicks) I am getting the same movements on the server and on the clients until a enemy starts looking for a player and chasing that player. When this happens, the enemy on one client is not at the same position on the other client. One enemy is targeting a player on one client, but on the other client he hasn't targeted that player yet. The enemy keeps wandering creating a different position on one client than on the server or other clients for example. Is there a better way to synchronize the enemy movement ? My idea was not to send the positions of the enemies from the server to the clients but rather have the clients move their enemies themselves. I would also like to know what to search for on Google to get help with this problem networking ai movement doesn't help, synchronize movement over the network without sending position does not return the results I would like either. What I think is strange and I don't understand is that the same code is executed on both the client and the server. The players and the enemies are at the same positions. Yet the enemy will choose to chase a player on the server and not to chase a player on the client. Resulting on the client to view the enemy at a different position than the position of the enemy on the server. |
0 | How to change transform.position.x after a state is changed? When I press attack button, player will change to Normal Attack state to perform Normal Attack animation and you will notice the player seem like step back a little bit as the width of sprite for Normal Attack animation is longer than Idle animation. http youtu.be hnPXt kprqQ To solve this issue. I need to change the transform.position.x 0.5 to move a bit further to match the position of Idle animation stands and transform.position.x 0.5 when Normal Attack state done its animation and back to Idle state. How can I perform transform.position.x 0.5 when when Normal Attack state done its animation and back to Idle state? |
0 | Base64 Decoding In Unity I am trying to decode a map file for Unity which I believe was compressed using Base64 encoding. The actual data looks like this H4sIAHah5VgA z2PvQ7CMAyEXyXyjASsXStGeAHEkBRTivJTOQlKW XdSYKc7dOd7 Tb4CrnmzQIHQzRB2eExi9qOAiQMbwdZeOFdiyCUx o7mKD6ZnVc5EIfca JnPTRaNBG459VFjslM1TgYVhZfCJO zSaG29LUktSi1LfDYyKAbJEDCFSGVXbR5omkP51UZd19n 6PrpLh77D92WFGkKAQAAAA And I am expecting an output that looks like custom,cuboid,default,1,1,1,0,1,1,1,1.0,1.0,0,0,0,0,0,0,0 While Base64 decoding should be an easy feat, this particular case is giving me trouble. I've tried decoding it into several different formats, but all my attempts resulted in garbled messes. I am fairly certain that the file is in a Base64 format, but it shouldn't be this difficult to decode. Does anyone have an idea of how the file was encoded and how I might go about decoding it? |
0 | Approximately circular range of motion on a square tile grid I've been working on a grid based tactics style game to learn the ropes of Unity. I have an issue with movement range for a player unit. Let's say the units move range is 3 spaces.. If I set up each grid tile with 4 neighbours (up down left right), I get this movement range If I give each tile diagonal neighbours too 8 in total, I get this What I'm actually looking for is what you'd see in these type of games traditionally, like this Here is the code that finds the unit move range list, starting at tile (5, 5). It adds the initial tile node and its neighbours to the movelist, then works outward looping through all their neighbours. It's based off a youtube tutorial. public HashSet lt Node gt getUnitMovementOptions() float , cost new float mapSizeX, mapSizeY HashSet lt Node gt moveList new HashSet lt Node gt () HashSet lt Node gt tempMoveList new HashSet lt Node gt () HashSet lt Node gt finalMoveList new HashSet lt Node gt () int moveSpeed 3 Node unitStartNode graph 5, 5 finalMoveList.Add(unitStartNode) Initial costs for the neighbouring nodes foreach (Node n in unitStartNode.neighbours) cost n.x, n.y costToEnterTile(n.x, n.y, unitStartNode.x, unitStartNode.y) if (moveSpeed cost n.x, n.y gt 0) moveList.Add(n) finalMoveList.UnionWith(moveList) while (moveList.Count ! 0) foreach (Node n in moveList) foreach (Node neighbour in n.neighbours) if (!finalMoveList.Contains(neighbour)) cost neighbour.x, neighbour.y costToEnterTile(neighbour.x, neighbour.y, n.x, n.y) cost n.x, n.y if (moveSpeed cost neighbour.x, neighbour.y gt 0) tempMoveList.Add(neighbour) moveList tempMoveList finalMoveList.UnionWith(moveList) tempMoveList new HashSet lt Node gt () Debug.Log( quot Total move spaces for this unit is quot finalMoveList.Count) return finalMoveList Here is the costToEnterTile function public float costToEnterTile(int targetX, int targetY, int sourceX, int sourceY) Tile t tileTypes tiles targetX, targetY get current tile type float cost t.movementCost diagonal if (sourceX ! targetX amp amp sourceY ! targetY) cost 0.3f return cost If I tamper with the cost value in here, I can get different results in the movement range overall shape, but it's a bit hit and miss depending on the movement range. Can anyone offer insights in to what path I need to head down to solve this? |
0 | Sprite doesn't change material or picture I am quite new to unity and currenty I'm practicing with a 2D topdown game. I created a tile map with "tiled", imported it in Unity with "TiledToUnity" and changed some things like player movement, camera and so on. Now I wanted to create collectible coins. So I created a new 2D Sprite and added the picture of the coin I had to it. But the picture of the coin did not change. I tried the same with adding a material with the coin as picture but it did not work out either. To check if the object is even there I added a collide box to the coin and my player body did indeed collide. What did I do wrong while adding a picture to the sprite? Thanks in advance! (Sorry fotgot the pictures. ) Edit |
0 | How to connect a 3D head to a body? I am new to Unity, game making, etc. I have downloaded the trial version of Avatar Maker and a similar Unity plugin called Didimo Editor, with the hope of using their features to make game characters that look like real people, using photographs. They both do more or less what I want. However, both tools output only heads, and do not connect them to 3D bodies. Avatar Maker has another plugin that allows for this, but it is only for male bodies and most of its features are not to my liking. So my question is how can I put these heads on working 3D bodies? The trailer for Didimo Editor seems to confirm that it can, at least, and Avatar Maker is able to export its heads to OBJ, FBX and Prefab, so I'm assuming maybe there is a way to do that too. |
0 | Problem with texture's quality in Unity . After setting a texture to GameObject, it looks bad. Some pixels can be seen and colors are distorted. The image itself is in good quality but after importing it to Unity, it looks ugly. Screenshot explanations left, image attached to the GUITexture GameObject middle, image before importing to Unity right, after importing (shown in inspector) |
0 | In Unity, what's a better solution than having a bunch of singleton static managers? (SceneManager, UIManager, SfxManager, PfxManager) I always hand a bunch of public static manager classes in my game GameManager (singleton) for reading and writing persistent data and gamestate across scenes SceneManager for holding scene data (coins picked up, score, are we in a cutscene) UIManager for dealing with HUD stuff SfxManager for sound effects PfxManager for particle effects On the gameobject that holds these manager classes, there are also subordinate classes (e.g. HUDManager, a smaller class that managers tasks specific to HUD, and then delegate those tasks into other smaller scripts) in order to avoid monolithic manager classes. Is this method frowned upon in Unity game development and if so, what are some better solutions than this approach? |
0 | how to clamp the look at function? how can i look at a target on 2 axis but clamp the the object's rotation ,to only rotate from 45 to 45 on x and from 60 to 60 on y axis. i used this script to look at target and clamp the rotation, but it's not working right ) there is no problem with maximum value but whenever the rotation is about to become zero or a negative value the wired problem will show up. i made a gif here (http www.mediafire.com view 55phgr5qrhy8fk1 record.gif) public Transform target public float speed public float minimumX public float maximumX public float minimumY public float maximumY Start is called before the first frame update void Start() Update is called once per frame void Update() Quaternion OriginalRot transform.rotation transform.LookAt(target) Quaternion NewRot transform.rotation transform.rotation OriginalRot transform.rotation Quaternion.Lerp(transform.rotation, NewRot, speed Time.deltaTime) transform.eulerAngles new Vector3(Mathf.Clamp(transform.eulerAngles.x, minimumX, maximumX), Mathf.Clamp(transform.eulerAngles.y, minimumY, maximumY), 0) |
0 | Fixing text on the screen for Oculus Rift I would like to fix text to the screen for an Oculus Rift in Unity. The text should say something like "get comfortable and then press any key". It seems like OVRGUI.StereoBox should work for this and I've tried to copy an example I found on Github, like so public class TargetScript MonoBehaviour void OnGUI() Debug.Log("Drawing Recenter dialog.") string loading "LOADING..." OVRGUI guiHelper new OVRGUI() guiHelper.StereoBox(300, 300, 300, 300, ref loading, Color.white) Debug.Log("Stereo Box should be visible.") Debug.Log (guiHelper) The log messages indicate that this code block is definitely being hit, but no text is visible on screen. What am I doing wrong? |
0 | Unity 2019.2.5 Convert Mouse Rotate Pan Zoom camera to touch I have a Unity C script that uses the mouse to rotate pan zoom a camera around a scene with a main focal point (PC Build). It works very well for me, but I need to convert it for a kiosk touch screen (windows Surface Pro) and have had no luck modifying the script or finding answers. Would some kind soul please save me from this hell! My current working mouse script is below. Any assistance is GREATLY appreciated! using System.Collections using System.Collections.Generic public class MouseOrbit MonoBehaviour public Transform target public float maxOffsetDistance 2000f public float orbitSpeed 15f public float panSpeed .5f public float zoomSpeed 10f private Vector3 targetOffset Vector3.zero private Vector3 targetPosition Use this for initialization void Start() if (target ! null) transform.LookAt(target) void Update() targetPosition target.position targetOffset if (target ! null) targetPosition target.position targetOffset Left Mouse to Orbit if (Input.GetMouseButton(0)) transform.RotateAround(targetPosition, Vector3.up, Input.GetAxis("Mouse X") orbitSpeed) float pitchAngle Vector3.Angle(Vector3.up, transform.forward) float pitchDelta Input.GetAxis("Mouse Y") orbitSpeed float newAngle Mathf.Clamp(pitchAngle pitchDelta, 0f, 180f) pitchDelta newAngle pitchAngle transform.RotateAround(targetPosition, transform.right, pitchDelta) Right Mouse To Pan if (Input.GetMouseButton(1)) Vector3 offset transform.right Input.GetAxis("Mouse X") panSpeed transform.up Input.GetAxis("Mouse Y") panSpeed Vector3 newTargetOffset Vector3.ClampMagnitude(targetOffset offset, maxOffsetDistance) transform.position newTargetOffset targetOffset targetOffset newTargetOffset Scroll to Zoom transform.position transform.forward Input.GetAxis("Mouse ScrollWheel") zoomSpeed CLASS |
0 | Unity inspector not showing variables of custom component that inherits from a built in class I made a class AdvancedButton that inherits from the built in class Button public class AdvancedButton Button public bool advancedTest false The Unity inspector only shows the variables of Button, but not the variable advancedTest. Is this normal or am I missing something? |
0 | Can I make the project files source code of my comerical Unity game avalible as a DLC or with the game? Is it legal and or a good idea to let the players download the source code project files of a comerical Unity game with the game or as a DLC? |
0 | How to prevent OnCollisionEnter2D calling a function again and again? My current code makes a ball keep jumping whenever it hits the ground. But when it hits a vertical ground it keeps calling the jump function again and again. That is because OnCollisionEnter2D makes the isGrounded bool true as long as it is in touch with a vertical collider. I tried several ways for example this didn't work for me void FixedUpdate() if(isGrounded true) Verticaljump() isGrounded false void OnCollisionEnter2D(Collision2D collision) if(collision.gameObject.CompareTag("H Ground")) isGrounded true As shown in the picture the OncollisionEnter2D starts and keep adding force on y axis.Is there any way I can call a function only once even if the gameObject keeps colliding with a surface. OnCollisionExit2D also does not work. So how can I call a function only once as it collides with ground and even if it keeps colliding with the ground? |
0 | Coding style about collisions with geometry Let's say I'm writing 3D Pacman. I have "Dot" objects throughout my maze, that are structured as follows in the Inspector Dot (GameObject) Sphere w Collider When I run into the sphere trigger, I can trivially say "Get me your parent and check if it's a Dot" However, I hate baking in the knowledge that some spheres have parents that are Dot objects. If the trigger were on the Dot itself that problem would solve itself, as I could just call GetComponent(). What's a good programmatic style approach to finding out what logical Game Object actually owns the geometry you've collided with? I could add a Tag of "Dot" to the sphere but that's just a level of confirmation, I still would have to walk up to it's parent and check. |
0 | Make gameObject stick to another gameObject after it has collided with it? Currently, I am using the following code to make objects stick to other gameObjects. rb GetComponent lt Rigidbody gt () rb.isKinematic true gameObject.transform.SetParent (col.gameObject.transform) It works perfectly, but it causes many other problems... For example, after colliding, it can no longer detect collisions... Is there an alternative to this code (which makes a gameObject stick to another one after collision)? |
0 | Cardboard VR Mode rendering black in Unity I've searched around and seen this problem is quite common, but none of the fixes I've read have resolved the issue If VR Mode is enabled in the GvrViewerMain prefab, the scene will render as just a black screen. I've set the Graphics API to OpenGLES2, I've disabled Multithreaded Rendering, I've disabled direct render, yet this continues to be an issue. This happens both within unity itself and if it is built and run to my phone. Has anybody encountered this problem do you know of any further steps to take to resolve the issue? |
0 | Can ARToolKit be used for color detection? I'm trying to make an app that will show an object from different sides, but the target will be too small for any real marker detection. Think of a cube with one or two centimeter sides. The camera distance is not a problem but it has to be at least ten centimeters out or what I'm trying to do won't work. I was wondering whether it was possible to color one side of the cube differently than others and make ARToolKit recognize the color to know which side it's looking at. Is this possible or just not in the range of things ARToolKit can do? If so, is there any kind of AR that can do this. |
0 | Blender to Unreal or Unity will combining animations into one clip for a parent object to store effect workflow? Hey so I have a gun and a set of rigged hands in blender, and I was wondering if I made a parent object for the gun, hands and everything, took all the animations respectively (such as right hand reload, left hand reload, gun reload, etc) and combined them all into one animation called reload, would there be problems in the future when working in Unreal or Unity? Would I be able to apply the same animation to all the objects that are a part of the action and have them work respectively? |
0 | Parent and child with different Animators I'm animating my 2D game (Unity 5.4). Is it a good bad practice to have parent and child gameobjects with different Animators? Example a 2D bug, that has sprites for every body part. On the "body container" parent object I add an Animator and animate all parts except the head. For the head, that is a child gameobject to the body (in scene's hierarchy) I want to add a separate Animator and animate only the head. Also is that influencing performance in any way? |
0 | Unity ECS Issues with rotation Posting this here because I spent several days trying to figure out why I couldn't rotate my entities the way I wanted to in Unity. For a little bit of background, I'm creating a flight dynamics model using Unity's Entities package. Part of this project involves providing keyboard input to a system in order to manipulate the motion of an aircraft a very basic simulator. I encountered an issue when I tried rotating my aircraft entity using the Rotation.Euler() method. In fact, just about every approach I saw on every forum I visited could not provide the answer I was looking for. My keyboard input logic manipulated the bank angle (roll), alpha (pitch), and yaw, and I was trying to set an absolute angle for my entity based on those values. It seemed that I was unable to set the rotation values the way I would in the inspector panel, since rotating the entity one direction would make rotating it along another axis unpredictable. Such is the nature of quaternions. Thus, I found a solution to my issue, involving a simple helper function that converts a float3 array of rotation values (one for each axis) to a quaternion. I'll be posting the code and explanation in the answer below. EDIT In the previous iteration of my code, this is what I had tried in order to update my entity's rotation Vector3 temp transform.rotation.eulerAngles temp.x 90.0f state.bank temp.y 0.0f temp.z state.alpha Entities.ForEach((ref Translation translation, ref Rotation rotation, ref AircraftData aircraftData) gt translation.Value position rotation.Value Quaternion.Euler(temp) ).Schedule() All other code within the answer below was the same (minus the new quaternion calculations). |
0 | Extending control remapping script to work with mouse buttons I have created a default key map for my game, however I have also included an option in the settings where the player can change the key bindings. My issue is if the player clicks on the button for shooting, which is defaults to mouse0, or aim on mouse1, then click on another key, they can never go back to mouse0 or mouse1. I am unsure of how to include all the mouse buttons scroll wheel into the viable buttons the player can choose from. Here is the part of my code that deals with the changing of the keys private void OnGUI() if(curKey ! null) Event e Event.current if (e.isKey) keyBinds curKey.name e.keyCode curKey.transform.GetChild(0).GetComponent lt Text gt ().text e.keyCode.ToString() curKey.GetComponent lt Image gt ().color normal curKey null |
0 | Unity Screen.height Screen.dpi is not equal to the screens height in real life On mobile, I was planning on using Screen.dpi to work out the physical size of the screen and size controls accordingly. But this quick test on my Galaxy S5 proves that the numbers from Unity are wrong. 1080 480 2.25 But the screen in real life is over 2.5 inches high.. So this is way off. Any suggestions..? Right now I think I'll just leave this, and have the controls the same size in world space.. rather than risk making them worse. |
0 | How to create "broken glass" animation? I have started making a 3D game in Unity5 that consists in avoiding obstacles. It is very easy but I want to add a collision effect when I collide on the wall. I would like to slice the screen into many parts (random pieces is better) that are falling down from screen with gravity. An example of what I mean How can I do this? I've tried using a lot of different images (shapes) but I'm sure that is not the best way... Thanks for any suggestions. |
0 | How to detect RayHit on part of model and not entire model I'm building a low poly role playing Hack and Slash game. When I click it renders a sprite amp character moves to that location(with RayCast). But in this case. I don't want the click to occur on side of the bridge. Clicks should only occur in green coloured part amp not in the red part. How should I fix this problem? |
0 | What determines the hit detection ordering for graphic elements in Unity (2d game)? I have a bunch of overlapping buttons spread across several UI Canvases. The default mouse behaviour only registers hover click events with one of the overlapping buttons, which is ideal for my project. The problem is the order of which button gets activated, is not tied to the Layer it is on or the Sorting Layer the item is on. I cannot seem to control which button is the top button that gets activated. Using a RaycastAll() function returns the name of all buttons on any given point, and reflects the problem that for some reason, the buttons are arbitrarily ordered. How do you control the order in which buttons are registered by the mouse? |
0 | Is it possible to configure a unity project so it only runs on a device? I am want to give someone a sample Android Unity project and I want them to be able to run it only on a device, not the simulator. Is there a way that I can configure the project so that it will only run on a device? |
0 | How can I extend the FindObjectsByTag to filter multiple parents of the found objects? private List lt GameObject gt FindDoors(string parents) GameObject doorsLeft GameObject.FindGameObjectsWithTag(c doorLeft) GameObject doorsRight GameObject.FindGameObjectsWithTag(c doorRight) List lt GameObject gt allDoors doorsLeft.Union(doorsRight).ToList() List lt GameObject gt toRemove new List lt GameObject gt () for (int i 0 i lt allDoors.Count i ) for (int x 0 x lt parents.Length x ) if (allDoors i .transform.parent.name ! parents x ) toRemove.Add(allDoors i ) foreach (var it in toRemove) allDoors.Remove(it) foreach (GameObject door in allDoors) Debug.Log("Door Parent " door.transform.parent) return allDoors Usage var allDoors FindDoors(new string "Wall Door Long 01", "Wall Door Long 02" ) But in the function FindDoors the return allDoors is empty. I think the problem is at this IF if (allDoors i .transform.parent.name ! parents x ) Once it's Wall Door Long 01 so if it's Wall Door Long 01 it will not remove the item but next it's Wall Door Long 02 so now the it's true and will remove the even if the parent name is Wall Door Long 01 and same if it's Wall Door Long 02 And then in the end it will remove all the items. But I want it to remove only doors that the parents of them is not Wall Door Long 01 and not Wall Door Long 02 |
0 | View Full File Name in Project View Unity Is there any way to view the full name of a file in Unity Project view without having to click on it? This picture sums up my frustration |
0 | Dynamic vs Kinematic, do either of these cause a collision before OnCollisionEnter2D? Firstly, it would be a great deal of help if someone could explain to me the differences between Dynamic, Kinematic and Static (especially if there is a box for static by the name of the object. I've looked at the APIs and tried playing around with them, they are so confusing. Secondly, I understand that the physics engine evaluates first and can cause a collision (when the ball hits the paddle in my Pong game) but is there a way around this? I'm trying to send the ball in the opposite direction to which it hit the paddle by using OnCollisionEnter2D but this method gets called second and therefore the ball changes direction twice and the physics engine causes an unnecessary collision... I have looked to tutorials on the movement in pong and tried following the tutorials but get the same problem (even though their game is faultless), this leads me to think that it's the Body Type property that is causing the physics engine to produce the extra collision because theirs is an older unity version. It could possibly be the bouncy material with no friction also, I don't know much purely because I'm a newbie to unity. I wonder whether anyone has had the same problem as me and can set me free. Thanks in advance. I seriously appreciate any help I can get! ) |
0 | How to find 1 3 and 2 3 of the distance between two given points? I know how to find the middle of two given points var midpoint (pointA pointB) 2 where pointA and pointB are Vector2 I thought that var thirdBtnPoints (pointA pointB) 3 var twoThirdBtnPoints 2 (pointA pointB) 3 should give me 1 3 and 2 3 between the two points but it doesn't. I guess this might be more of a math question though, but how can I find 1 3 and 2 3 of the distance between two given points? |
0 | Unity text is very blurry. How can I fix it? Unity text is very blurry. How can I fix it? To be honest, I have no idea why it behaves this way Hope that someone faced the same problem and will be able to share how it was tackled. |
0 | How can I get the Selector dialog to include my prefabs When setting a variable for an object in Unity, for built in types there is an option on the right hand side to bring up a dialog that lists the possible values that can be chosen for that variable, for example when selecting a Sprite for a Sprite Renderer Is it possible, and if so what do I need to do, to have that list populated with the prefabs within my project? In this example, there are a number of Item prefabs (both inside and outside the Resources folder if that makes a difference), however they do not appear in that dialog. Is there an attribute I am missing that needs to be specified on the Item class, or something else to enable this? using UnityEngine using System.Collections.Generic public class Item MonoBehaviour, IIdentifiable, IFilterable SerializeField private int IdField SerializeField private bool ActiveField public int Id gt IdField public bool Active gt ActiveField public class ItemRandomiser MonoBehaviour, IWeightedObject SerializeField private List lt string gt NamesField SerializeField private List lt Item gt ItemTemplatesField |
0 | SocketException No connection could be made because the target machine actively refused it I am working on connecting a client to a server using socket connection. I have a button, when I click on the button, it's giving the below exception in Unity. "SocketException No connection could be made because the target machine actively refused it.". What will be the issue? Can anyboady help me out? Below is the code I have written for connecting to the server internal Boolean socketReady false NetworkStream theStream StreamWriter writer StreamReader reader try connect new TcpClient (host, port) theStream connect.GetStream () writer new StreamWriter (theStream) reader new StreamReader (theStream) return true socketReady true catch(ObjectDisposedException) return false |
0 | Rotate a Polygon node in Shader Graph I have a hexagon in the Polygon node I would like to rotate so the pointy side is upwards. Applying the rotation nodes, however, simply changes the color of the hexagon from white to a color in the rainbow. What does the Vector1 of the Polygon output represent and is there a way I can rotate it as if it were a texture? |
0 | How to Keep Unity From Changing Sprite When Changing Orthographic Size? so I have a simple X animation, and at the end (when it looks like a full X), it looks good on one orthographic size, but bad on another. Here's what it looks like when the size is 3 Now you can notice, there are a few pixels that look a bit off, but it still looks pretty good. Here's what it is supposed to look like So if you look closely, it is a bit different, and that's the point. However, if you change the orthographic size to.. say 5, you get this horrid thing Why is Unity doing this, and how can I fix this so that it looks how it's supposed to? Also, in this, my X is upscaled x2. Would it fix it just to have it made to the right size, and then upscaled x1 (e.g none)? |
0 | Why my calculated value is far different from actual value? I using CharacterController and not using a Rigidbody so I writing a script for downward velocity which is velocity 9.81 (time) and I declare my initial velocity as 12. Supposing from this calculation, the max height it can reach from the equation is roughly 6.7891 unit on y axis. By using the formulae distance travel initial velocity (time) 0.5g (time) 2,differentiate this w.r.t time, getting time u g 12 9.81 1.223, then max distance travel 12 (1.223) 0.5 ( 9.81) (1.223) 2 7.339 but from the coordinate below, can clearly seen the max distance travel before falling down is 13.2803unit 0.5499unit 13.8302unit? This is far exceed calculated value, wonder what went wrong? Initial coordinate of y on ground 0.5499 approximate final coordinate of y 13.2803 using UnityEngine public class NewPlayerMovement MonoBehaviour public CharacterController Controller speed of the character public float Speed 12f earth gravitational value public float Gravity 9.81f Vector3 velocity hit point of character float hp 90 bool Grounded true public void OnControllerColliderHit(ControllerColliderHit hit) Grounded true hp velocity.magnitude velocity.y 0 Debug.Log(hp) public void OnControllerColliderExit(ControllerColliderHit hit) Grounded false public void Checkstatus() if(Grounded false) velocity.y 0.5f Gravity Time.deltaTime void Update() float x Input.GetAxis( quot Horizontal quot ) float z Input.GetAxis( quot Vertical quot ) Vector3 move transform.right x transform.forward z Controller.Move(move Speed Time.deltaTime) if (Input.GetKeyDown(KeyCode.Space) amp amp velocity.y 0) velocity.y 12 Grounded false check if it grounded Checkstatus() Controller.Move(velocity Time.deltaTime) |
0 | Unity change only z axis rotation to 0 I have a child where I want the rotation to work like (parentRot, parentRot, 0). So first I set its localRotation to 0, meaning it will get the parents rotation child.localRotation Quaternion.identity But how can I make sure the world rotation (not local) value of the z axis stays at 0? |
0 | 2D character tips over sideways after collision with platform This is what happens when my player character jumps and collides with a platform from the side. The player character tilts over or ends up upside down or sometimes on its back. How can I prevent this? |
0 | How to get a Read Write Reference to Parent GameObject from a script component attached to it? I have a game object(object) with a script component(myscript) attached. I have a reference to myscript component through getComponent, and I want to change the transform of the gameObject the script is attached to. myscript.gameObject.transform (new value) The above code gives me error, Property 'UnityEngine.GameObject.transform' is read only. Is there a way to get a read write version? |
0 | Quaternion Lerp never reaches target I seem to have misunderstood something about how LERP works. Im not sure what is missing. The object is rotating as it should, but it cant seem to get it to end. The transform.rotation dont seem to reach its target even if it has done so visually. Quaternion rotationTarget Vector3 travelTarget float rotationLerpProgress float rotationLerpDuration 1f Use this for initialization void Start () Update is called once per frame void Update () if (Input.GetMouseButtonDown (0)) var ray Camera.main.ScreenPointToRay (Input.mousePosition) RaycastHit rayHit if (Physics.Raycast (ray, out rayHit)) var rayHitPoint rayHit.point travelTarget rayHitPoint var rotationDirection rayHitPoint transform.position rotationDirection.y 0 rotationTarget Quaternion.LookRotation (rotationDirection) rotationLerpProgress Time.deltaTime if (transform.rotation ! rotationTarget) if (rotationLerpProgress lt rotationLerpDuration) transform.rotation Quaternion.Lerp (transform.rotation, rotationTarget, rotationLerpProgress rotationLerpDuration) rotationLerpProgress Time.deltaTime print (string.Format ("( 2 ) progress 0 duration 1 ", rotationLerpProgress, rotationLerpDuration, rotationLerpProgress rotationLerpDuration)) else print (string.Format ("setting rotation ( 0 ) to target ( 1 )", transform.rotation, rotationTarget)) transform.rotation rotationTarget else print ("rotaton is at target! )") if (transform.position ! travelTarget) rigidbody.AddForce (Vector3.forward) |
0 | Collision Checking in Unity immediately after instantiation I'm working on a dungeon generation script and I'm having some issues detecting overlap. Each piece that I spawn has attachment points, with rotation values and an offset amount so things lineup correctly. So far this is working. After spawning, I then check to see if the piece is overlapping with another, but sometimes it seems like unity hasn't caught up with the collision system, as I check to see if a bool bOverlap is true(which gets set in an ontriggerstay function) and if so destroy the piece. However, many times the script will have gotten past this collision check portion, before the collision event fires. Any suggestions? Each piece has a rigidbody and box collider on it for the simple collisions. |
0 | Create a stack driven coroutine based state machine for Unity I am working on a game where I am using a coroutine based state machine which is mostly a multi class implementation of this link. I am using it because it allows me to create multi frame sequences. I wanted to know how would I go about making a stack based machine, so that I can overlay game states such as when I want to pause the game to show a menu i can run a pause menu state pausing the running game state, while still allowing the state objects to be rendered in the background Here is the code I am using for a state public abstract class State Inject MonoBehaviour gameObject Inject public EventSystem eventSystem StateMachine parent public State(StateMachine p) parent p public abstract IEnumerator Enter() public abstract IEnumerator Exit() public abstract IEnumerator Update() public IEnumerator Run() yield return gameObject.StartCoroutine(Enter()) while(parent.CurrentState.GetType() GetType()) yield return gameObject.StartCoroutine (Update ()) yield return gameObject.StartCoroutine (Exit()) State machine run function State Current The current state , the one at the top of the stack while(Current! null) yield return Component.StartCoroutine(Current.run()) The problem with this approach is as soon as the state machine's current state changes (That is when i push it down the stack adding a new state on top) , the while loop in the Base state class's run method will end and will call the exit coroutine causing the state to end which is undesirable as according to the stack pattern the state should be paused Moreover as coroutines work in unity, the yield return statement(in the state machine) wont return until the previous started coroutine exits , which is currently as of now responsible for starting the states . My question is how do i alter this code so as to pause the previous state (that will be pushed into the stack) instead of exiting it and starting anew state this implementation works fine if there is to be only a single state in the memory |
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 | Unity3D mobile 4G internet web request is very slow I have a windows VPS server and i have installed an Apache server on it. in my server I only have a simple text file that contains some few words. My problem is that when I'm trying to sending a web request to my server by (4G sim card internet service ) for accessing to getting data from the text file , It works very slow . Something about 30 or 50 secound ! but after first request if I try again there is no problem ! It works very fast !!! It seems This slowdown will only occur in the first connection . But in other hand if I use WI FI internet , there is no problem and every time I try to get data it works fast. MY problem is only with sim card internet ! This is part of my code IEnumerator Get Data() UnityWebRequest www UnityWebRequest.Get(servers Address "file.txt?t " UnityEngine.Random.value) yield return www.Send() string the Data www.downloadHandler.text Is there any problem in my code ? My unity version is 2017.1.1 How can i solve this issue ? |
0 | Raycast not hitting a collider I have the following simple raycast from a capsule on a cube bool hit Physics.Raycast (transform.position, Vector3.down, jumpSettings.groundJumpDistanceCheck, jumpSettings.layerMask) print(hit) When my layerMask is 8 (terrain), I have set my layer on my cube and my groundJumpDistanceCheck is 2. Then my hit is false. When my groundJumpDistanceCheck is set to Infinity. Then my hit is still false. However when I remove the distance parameter bool hit Physics.Raycast (transform.position, Vector3.down, jumpSettings.groundJumpDistanceCheck, jumpSettings.layerMask) print(hit) Then hit returns true. This is odd for me, as far as I know when you exclude the distance parameter it's supposed to be Infinity by default. But when I explicitly give Infinity as the distance, it returns false. I have also used the following code in an attempt to debug my issue, using the desired distance 2f Debug.DrawRay(transform.position, Vector3.down jumpSettings.groundJumpDistanceCheck, Color.red, 60f) As you can see, the ray does intercept the cube. I need the reycast to return true with a distance of 2f. |
0 | To move an object forward an exact distance and then stop I am using this script below to move an animated object in unity with no root motion. it simply walks across the terrain and has a timer so it waits 60 seconds until starting. void Update () if (Time.timeSinceLevelLoad gt 60) transform.Translate(0, 0, Time.deltaTime) I want the object to travel a certain distance or certain amount of steps and then stop at an exact point and stay there, is there a simple way to add to the above code to do this? does it entail xyz position reached maybe? |
0 | How to refer to a object that has just been hit by a ray cast? I would like to use RigidbodyConstraints.FreezeRotation in order to freeze the rotation of an object that is picked up. The problem is I don't know how to refer (or call) the currently selected object. The script in it's currents state is below... public class PhysGun MonoBehaviour private GameObject Player void Start () Player GameObject.Find("Player") Update is called once per frame void Update () Vector3 fwd transform.forward Equivalent to the code you had. Ray ray new Ray(transform.position, transform.forward) RaycastHit hit if (Input.GetMouseButton(0) amp amp Physics.Raycast(ray, out hit, 10f)) hit.transform.SetParent(Player.transform) Debug.Log("We hit " hit.transform.name) hit.transform. RigidbodyConstraints.FreezeRotation So, how do I call (or refer to) the object that is hit by the ray cast exactly? |
0 | faster compile and editor update in unity sometimes for some small changes, I need to recompile the code In the editor and it causes some time to be testable in the editor(sometimes more than 20, 30 seconds). I know when loading shows on the bottom right side of the editor in means that it's compiling the code and when it doesn't move it means that it's updating the editor or checking for possible updates. I need to know is there any way to make it faster? I mean, is there any option to tell unity don't recompile unchanged classes or don't consider all editor classes for changing the editor? or any other technique that makes the process faster? as I use unit tests in the editor, most of the time is consumed by updating the editor for any added function or changes on them. |
0 | How can you create a trigger collider between two moving objects? I want to create a trigger collider between two boxes. When one of the boxes moves, the trigger is supposed to change its size and shape so that its left and right edge stay attached to the two boxes. How can I implement this in C or JavaScript? |
0 | Help with transform.lookat and camera? Vector3 mousePos Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.LookAt(mousePos) This will actually make the camera follow the mouse, but it goes crazy, the camera seems to spin in circles rapidly here is actually a gif of what is happening. https gyazo.com 952da6c28e644b7b0e6500a597b6804e preview Could anyone help me figure how how to fix it? |
0 | Which of these two codes are 'better'? Making a local variable or a class variable? Im making more games and asking more stupid questions. Hopefully this one is very brief. I'm making a very basic class which just moves a Player object by applying force to a rigidbody, but it got me wondering, should I be making a class reference to the rb or just a local variable inside Update every frame? (bearing in mind it already exists in the Monobehaviour.GameObject unity parent class). I'm wondering if doing many local variables would slow down the loop as a whole(by local I mean inside the function itself and not at the top of the class hope im using the correct term) . Here is what I mean, the two ways I was thinking of doing it public class Player MonoBehaviour private void FixedUpdate() Rigidbody rb GetComponent lt Rigidbody gt () float v Input.GetAxis("Vertical") rb.AddForce(v rb.transform.forward Const.walkForce) or... public class Player MonoBehaviour Rigidbody rb private void Awake() rb GetComponent lt Rigidbody gt () private void FixedUpdate() float v Input.GetAxis("Vertical") rb.AddForce(v rb.transform.forward Const.walkForce) |
0 | How do I flatten terrain under a game object? I've got a script that makes a terrain object and paints it with textures, but I'm having an issue. When I attempt to place game objects (such as the simple water object that unity provides), I use a Raycast to determine the correct height to place the game object, but that just ensures that it is correctly placed at that particular point. How would I go about flattening the terrain under the game object so that it doesn't go into the terrain or hang out into thin air in the case of hills? |
0 | Why has my refractive water shader become reflective So I was making a water shader in unity and well it looked fine in the scene view but as soon as I went into the game view the refraction texture basically flipped up 180 degrees and made it look like the water was reflective. The problem with this is that it breaks the transparency of the shader. Scene View (how it should look) Game View (how it does look) Shader (I can't post more than 2 images) Part of the shader float4 Lerp2 lerp(Tex2D2,float4( 0.0, 0.0, 0.0, 0.0 ), Refraction.xxxx) float4 Subtract0 Lerp2 RefractionCorrection.xxxx float4 Add2 ((IN.screenPos.xy IN.screenPos.w).xyxy) Subtract0 float4 Tex2D0 tex2D( GrabTexture,Add2.xy) |
0 | How can I get a background image and game objects to fill black areas of letterbox or pillarbox? I have used the Aspect Ratio Enforcer to force my game's aspect ratio to remain as 9 16. I need to prevent some game objects and the backgrounds from being affected by the enforced aspect ratio to cover the black areas that result from other aspect ratios. How can I prevent some game objects and background images from getting affecting by the Aspect Ratio Enforcer? |
0 | How can I duplicate a GameObject with the correct number of copies? using System.Collections using System.Collections.Generic using UnityEngine public class FormationsManager MonoBehaviour public GameObject squadMemeberPrefab public int numberOfSquadMembers 20 public int numberOfSquads 1 public int columns 4 public int gaps 10 public Formations formations private int numofmembers private int numofsquads private GameObject squadToClone private List lt GameObject gt SquadMembers new List lt GameObject gt () Use this for initialization void Start() squadToClone GameObject.Find("Squad") numofmembers numberOfSquadMembers numofsquads numberOfSquads formations.Init(numberOfSquadMembers, columns, gaps) GenerateSquad() Update is called once per frame void Update() if (numofmembers ! numberOfSquadMembers) numofmembers numberOfSquadMembers formations.Init(numberOfSquadMembers, columns, gaps) GenerateSquad() if (numofsquads ! numberOfSquads) numofsquads numberOfSquads for (int i 0 i lt numberOfSquads i ) Instantiate(squadToClone) private void GenerateSquad() GameObject go squadMemeberPrefab List lt GameObject gt newSquadMembers new List lt GameObject gt () int i 0 for ( i lt formations.newpositions.Count i ) if (i lt SquadMembers.Count) go SquadMembers i else go Instantiate(squadMemeberPrefab) go.transform.position formations.newpositions i go.tag "Squad Member" go.transform.parent gameObject.transform newSquadMembers.Add(go) for ( i lt SquadMembers.Count i ) Destroy(SquadMembers i ) SquadMembers newSquadMembers In the Update I duplicate the squad if (numofsquads ! numberOfSquads) numofsquads numberOfSquads for (int i 0 i lt numberOfSquads i ) Instantiate(squadToClone) The problem is that if for example when running the game there is 1 squad and then I'm changing the value of numberOfSquads to 3 then instead duplicating more 2 squads it will duplicate more 3. And then if I will change the value of numberOfSquads from 3 to 4 it will add more 4 squads instead only 1. And I also want to make that if I change the value of numberOfSquads to be lower then destroy the last squad s. |
0 | Align UI element to gameObject in 2D I have a 2d game where I want to display UI element perfectly aligned to specific gameObjects. I have an ortographic camera and I used to Camera.main.WorldToScreenPoint() function giving it the gameobject position modified, for instance, by 1 on X component to get the UI element on its perfect right. My problem is that the element is not on the gameObject's perfect right, but sensibly above. See this schema Expectation G UI element Reality UI element G I tried also to use the WorldToViewportPoint() but it's not giving the desired result. So, I think this is the right way to go but I can't guess what I'm missing. Any clue? EDIT After a little bit more observations it seemed that the UI element alignment depends somehow on it's distance from the center of the screen (of the camera viewport I guess), so that if the gameObject is below half height the UI element y position won't be on the perfect right but slightly below it and if above half heigth will be slightly above the perfect right. Same for x coordinate. Is there a way I could control this? |
0 | Tower Defence stat storing system I'm trying to find a smart way to store and retrieve stats for a tower defence game, but am currently unsure as to which approach would be best. Description The stats system should quite basic, there are 4 different towers, with up to 5 different levels each. One important requirement is that the stats should be stored in an XML file so that the game designer easily can access and balance the stats. (He knows nothing about programming) I can see two ways of doing this By creating a TowerStats class which hold values for one type of tower for one level. Something like public class TowerStats2 public TowerType type public int lvl public int damageLow public int damageHigh public float range public float attackFrequency Then i would load the stats from the XMl file using Linq and XDocument and load it directly into a TowerStat List. I would do this for each tower so in the end there would be 4 different List's which would hold the different level stats for the specified tower. gunTowerStats 0 would hold level 1 stats of the gun tower rocketTowerStats 2 would be level 3 stats of the rocket tower When a new tower is bought by the player or when a tower is upgraded, the stats would then be taken from the List so something like UpgradeTower() lvl towerStats gunTowerStats towerLevel 1 Alternativly I could hardcode all the values, and have one big class which would go something like this gunTowerDamageLvl1 4 gunTowerDamageLvl2 8 gunTowerDamageLvl3 15 rocketTowerDamageLvl1 10 you get the point. I know that hardcoding is never never really the way to go. But does that also count for this kind of example where all possible tower attributes are known and will not change? the only thing that will change are the values of these attributes. Question I'm personally in favour of the first way, but I must admit that I find both ways a bit clumsy, would it be alright to do it one of these ways or is there a much smarter and more obvious way to deal with this that I'm completely unable to see? I hope my question is understandable. |
0 | How to detect line break in a String using UnityScript? Code var i int 0 var text String var compare String "" var isFound boolean false function Start() text AssetDatabase.LoadAssetAtPath("Assets words.txt",TextAsset).text function Update() if(!found) com("textToSearch") function com(s String) if(i lt text.Length) comText comText text i if( condition for line break) if(comText s) print("found") found true else comText "" i In the text document each word ends with a line break. So if I just found a condition for a line break then I can easily search through the document. |
0 | EventSystem first selected not highlighting I'm trying to make a menu and encountered this problem. protected static EventSystem eventSystem get return GameObject.Find("EventSystem").GetComponent lt EventSystem gt () public static void ButtonNavigation(List lt GameObject gt listButton, int firstSelected) eventSystem.SetSelectedGameObject( listButton firstSelected ) print(eventSystem.currentSelectedGameObject) But when I print out the currentSelectedGameobject it clearly says that "Status" is selected but how come it's not highlighted? I've read some article on using Co routines but is it really necessary? |
0 | Android game crashes when attempting to start wifi hotspots I have two methods that will try to start the WiFi hotspot on the android device so that others can connect and play the game.the problem is both method have problems and don't work. the first method public void ConnectWiFi() try using (AndroidJavaObject activity new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic("currentActivity")) using (var wifiManager activity.Call("getSystemService", "wifi")) AndroidJavaObject wifiConfiguration new AndroidJavaClass("android.net.wifi.WifiConfiguration") wifiConfiguration.Set("SSID", meSSID) string wifiConfiguration.Set("preSharedKey", mePassword) string wifiManager.Call("setWifiApEnabled", wifiConfiguration, enabled) catch (System.Exception E) T.text " nE " E.Message T.text " n t" E.StackTrace " n" it crashes the game and I can't debug it. the secont method public void ConnectWiFiHardWay() try using (AndroidJavaObject activity new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic("currentActivity")) using (var wifiManager activity.Call("getSystemService", "wifi")) using (AndroidJavaObject classObj wifiManager.Call("getClass")) using (AndroidJavaObject wifiConfiguration new AndroidJavaObject("setWifiApEnabled")) wifiConfiguration.Set("SSID", meSSID) string wifiConfiguration.Set("preSharedKey", mePassword) using (AndroidJavaObject wifiCfgClass wifiConfiguration.Call("getClass")) using (AndroidJavaObject booleanObj new AndroidJavaObject("java.lang.Boolean")) using (AndroidJavaObject booleanClass booleanObj.Call("getClass")) using (AndroidJavaObject methodObj classObj.Call("getMethod", "setWifiApEnabled", wifiCfgClass, booleanClass)) methodObj.Call("invoke", wifiManager, wifiConfiguration, enabled) catch (System.Exception E) T.text " nH " E.Message T.text " n t" E.StackTrace " n" this one throws an exception that says setWifiApEnabled Cannot be found I can post the complete error text if that helps. Also I followed this questions instructions. |
0 | Error Framework 'Mono .NET 3.5' not installed Recently I installed Ubuntu Mate 16.10. Unity and Monodevelop works, but when I try to compile the javascript on Monodevelop, appears an error Error Framework 'Mono .NET 3.5' not installed. (Assembly CSharp) On 14.04 all works very well but not here....what is the way to fix this problem?? I searched on the internet and I can't find the answer. |
0 | Unity Mecanim Rigidbody on Third Person Controller Gravity bug? I'm working on a third person controller which uses physX to interact with the other objects (using the Rigidbody component) and Mecanim to animate the character. All the animations used are baked to Y, and the movement on this axis is controlled by the gravity applied by the rigidbody component. The configuration of the falling animation And the character components configuration Since the falling animation doesn't have root motion on XZ, I move the character on XZ by code. Like this On the Ground if (IsGrounded()) GroundedMovementMgm() Stores the velocity velocityPreFalling rigidbody.velocity Mid Air else Continue the pre falling velocity rigidbody.velocity new Vector3(velocityPreFalling.x, rigidbody.velocity.y, velocityPreFalling.z) The problem is that when the chracter starts falling and hit against a wall in mid air, it gets stuck to the wall. Here are some pics which explains the problems Hope someone can help me. Thanks and sory for my bad english! PD. I was asked for the IsGrounded() function, so I'm adding it void OnCollisionEnter(Collision collision) if (!grounded) TrackGrounded(collision) void OnCollisionStay(Collision collision) TrackGrounded(collision) void OnCollisionExit() grounded false public bool IsGrounded() return grounded private void TrackGrounded(Collision collision) var maxHeight capCollider.bounds.min.y capCollider.radius .9f foreach (var contact in collision.contacts) if (contact.point.y lt maxHeight amp amp Vector3.Angle(contact.normal, Vector3.up) lt maxSlopeAngle) grounded true break I'll also add a LINK to download the project if someone wants it. |
0 | Custom Update Function OR Multiple TimeScales I'm trying to create some interesting variations on timescales in my game. In essence, I'd like at least two, probably three or four separate timescales. The player the player timescale is likely to be the game scene timescale always. Mobs mob timescales can be altered (slower primarily, but also faster possibly) depending on cast spells or other effects in the game. Environment like mobs, the environment may be slowed or sped up depending on some game effects that occur. This would control things like traps, torches, etc. I'm thinking about things such as a Slow Time spell that might slow most mobs, but maybe not others (bool flag), something like a time elemental or something of that nature. I'd also like to possibly slow environmental time so the player may have a single use item that would allow them to move easily navigate traps (but not have guaranteed success if they still don't see the pattern or such). Having controller scripts that are added to all objects that listen for calls to change a multiplier on Time.deltaTime could be an option, but it's clunky, would have to be in all of the scripts, would have to be accounted for in many areas (movement, combat, possibly related effects), and is just not an ideal option. Inversely, the same effect (a lich for example casting slow on a player) could require opposing things. If I had global settings that contained a multiplier for player mob object that were impacted by an effect, I could still always use a multiplier with Time.deltaTime, but I still think it would be clunky. Has anyone done this? Are there any good ideas? I've searched a bit, but didn't find anything terribly useful. I've considered custom Update() classes, though I'm not entirely sure how to implement them. Maybe extend the FixedUpdate() class that's built in to take other things into account? I know that Time.timeScale is inherently for the current scene, but could I make instances of Time that are used by different scripts FixedUpdate()? Am I overthinking this? I feel like this shouldn't be quite so difficult. |
0 | Position of the prefabs not randomizing So, I'm currently working on a game. The objects are treated as prefabs, so every time it is instantiated, the position of the object must randomize. public ObjectDisplay SpawnObject() Vector3 randomPosition new Vector3(Random.Range( 2.5f, 2.5f), 7f) GameObject obj Instantiate(objPrefab, randomPosition, Quaternion.identity, objCanvas) ObjectDisplay objDisplay obj.GetComponent lt ObjectDisplay gt () return objDisplay The randomPosition is what is supposed to be changing the positions, but what happens is that the prefabs would continue to spawn from the middle of the screen. I've tried changing the position values but that didn't do much. The code is seemingly fine, but it doesn't function the way it is supposed to. Any ideas? |
0 | Unity or Monogame or Gamemaker 2 for an experienced application developer? So i know this question has been hammered down several times but please bear with me. I used to be a C .Net application developer but i am no longer employed, i am pretty good at C . I want to get into serious game development and i dunno where to start, i used to work with unity occasionally which is a very little and i kinda find it clunky, like it works but somehow it does not feel right and feels kinda clunky. But it works with tiled map editor without much of a hassle. I Remember using Game maker studio when i was back in college and i found it very good, its a breeze to work with and even have its own tiled map editor, even seems to have some good tutorials, the only con is its price. I was initially inclined towards Monogame cause of my C background, but i neither have time nor money and resources to support me for long enough time to be able to code every single thing from scratch and i am kinda in a pretty bad situation overall right now. It just takes too much time to do anything even to make it work with a tiled map editor, and there are very few tutorials or documentation to start with. It seems like the only option for me is Unity at the moment, cause of ease of access and how easy it is to work with tiled map editor and lots of tutorials. which one do you guys think is good overall? Please keep in mind that i am currently unemployed and have very little resources to support myself, and i am a programmer so i don't even know how to compose music and do art for the game and i'd prefer if it provides some asserts to be used so i wont waste time in learning stuff when i cannot afford to spend time. I will eventually learn them but not now, its not happening now so i prefer something that comes with some sorta free asserts that can be used (mainly music and art), I mean does it even matter if all i am trying to do is earn a decent minimum living? I just want to make simple 2D NES Snes style games with multiplayer support. Thank you. |
0 | Implement Candy Crush like level graph I want to implement road map like level graph where in you can see what level are you and your friends are on. Just like we see in Candy Crush Saga.For people who have not seen Candy Crush Saga, please see the image below for your reference. I want to understand the technology I should be using here. libgdx is one option i keep hearing is best for Android gaming engine. But somehow I feel Unity for Android would provide more bang performance wise. This is my first try at gaming, please help me understand my options. |