Multiplayer VR art gallery using different headsets I'm creating a VR art gallery using Unity3D (like a VR Museum Views with more freedom) and would like to have an environment where 1 or more users can gather together, communicate and move around (similar concept to SecondLife except in this case would be first person view (by default) with only one room location and users would be in VR). From a user perspctive, the initial screen would be a door and the user would have a mini map and a menu, turned to him herself, with specific actions. Once inside of the gallery, the users would be able to see others, "walk" or "teleport" to different locations and see the canvas The overall environment is rather simple so I've decided to get feedback from potencial users. Turns out the majority doesn't want to be alone in such environment. So, I've considered adding multiplayer (one of the users could even be guiding the others, which is interesting). Now, multiplayer makes more sense when we can more inclusive. That's where the problem starts. In this specific case, inclusive is being defined as the possibility of users to be able to be present in the environment using at least one of the following devices Android Phone (Cardboard) Oculus GO Samsung Gear VR Google Daydream Oculus Rift HTC Vive I've done some research and couldn't find someone doing it or a way to do it (considering all of the requirements). If that's possible to do, how can i do it? One thing I found was that if I didn't want the users to move around and just be watching the gallery like watching a webinar presentation in different devices, I could use VR Sync (they basically synchronize video playback on multiple VR devices). So, at the moment I can either have the environment with just one user at a time and develop the environment for all the different headsets or use VR Sync.


OnTriggerEnter error The message parameter has to be of type Collider I have a crate and I want to make it so if you are in the trigger of the crate a UI appears and says quot Click E to loot quot . I have the UI setup but the script is not working. Here is my script and after it are the errors. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class UI Appear MonoBehaviour SerializeField private Image image void OnTriggerEnter(Collider2D other) if (other.CompareTag( quot Player quot )) image.enabled true void OnTriggerExit(Collider2D other) if (other.CompareTag( quot Player quot )) image.enabled false The errors say Script Error OnTriggerEnter The message parameter has to be of type Collider Script Error OnTriggerExit The message parameter has to be of type Collider


Touchscript multiple overlapping colliders Im building a tower defense game on unity and would like to allow the player to pan the camera on a large map. I am using touchscript to handle the touches. I made a testing project with the following hierarchy Main Camera Panning object Sprite I am using the pan gesture to move the panning object which then sets the main camera's position to negative of the panning object's corrds. So far, the things that should work worked properly. There is however the issue that the sprite object is higher up the layer and thus take priority. This means that if the viewport is filled with the sprite object, you are no longer able to pan as you cant touch the panning object behind the sprite object. So the question is, 1. How does touchscript handle layering? 2. How can one achieve a passthrough effect where the sprite would handle tap gestures and the panning object handles pan gestures? 3. Can anyone suggest a better touch system for what im trying to do other than touchscript? Thanks


How can I prevent a GameObject within a ScrollView from moving? I have a ScrollView. It has children, most of which I want to scroll, but some of which I want to remain still. Think of something along the lines of a spreadsheet where the title rows columns don't move. I have somewhat succeeded, as the GameObjects I want to stay in their place do, but they are fighting the ScrollView to move. It forces them to jitter every time I scroll. Here is my current code private Vector3 originalPosition Vector3.zero private IEnumerator Start() yield return new WaitWhile(() gt transform.position Vector3.zero) originalPosition transform.position private void OnGUI() if (originalPosition Vector3.zero) return transform.position originalPosition What is causing it to jitter? And how can I fix it? (The reason I am waiting to start updating is because my GameObject originally thinks its position is (0, 0, 0)...not sure why. Maybe its related?)


"SetSelectedGameobject" only highlights button on second try (Unity 2017.3) To support the use of a gamepad in the options menu I set SetSelectedGameObject and firstSelectedGameObject (which doesn't seem to do anything) to the button in the upper left, so it's highlighted. This works fine in my pause and option menus (panels that are enabled disabled) but there's also a third panel that displays the controls as an image. On this screen the first button is set as selected but it doesn't get highlighted until I go back to the pause menu and then open the "controls" screen again. The Hierarchy The ControlsPanel looks like this click All 4 buttons are set to "automatic" and they're all accessible to the gamepad but, like I said, the first one ("Keyboard") doesn't light up the very first time I access the panel. It should be like this Click on "Controls" in the pause menu ControlsPanel is enabled "Keyboard" button is highlighted Pressing right on the gamepad highlights the next button ("Controller") What actually happens Click on "Controls" in the pause menu ControlsPanel is enabled "Keyboard" button is still grey Pressing right on the gamepad highlights the next button ("Controller") Press the "Back" button ("ControlsPanel" is disabled and "PausePanel" enabled) Click on "Controls" again This time the "Keyboard" button is highlighted The "ControlsPanel" script public Image pic public GameObject controllerChoicePanel public GameObject firstControls private String controls private bool windows void Start() controls GetControls() windows GetOS() pic.sprite Resources.Load lt Sprite gt (controls) if(windows) controllerChoicePanel.SetActive(true) EventSystem es EventSystem.current es.firstSelectedGameObject firstControls es.SetSelectedGameObject(firstControls) Any idea why it would work fine in my pause options menu but not in the "Controls" one, even though I'm doing the same thing?


Unity UI Chat Message Expanding Bubble How do you set up Unity's UI Layout system so that the chat bubble changes in size automatically based on the length of the text? What's the right use of Layout and Content Size Fitter elements? How do you turn into


Null instance on manager class extending from singleton class I have four classes class A, which is abstract and partial extending from singleton class C. class A1, which is partial and extending from class A . class B, extending from class A. class C, a singleton which has code to throw an exception if the instance is null, and otherwise uses DoNotDestroyOnLoad(). In scene view, I add class B to the scene. It works, but throws a null instance exception for class A, as it's instance is not present in scene. I think this is because class A extends from a singleton class, and it has ability to throw exceptions when the instance is null. I can not add the class A to the scene because it is abstract. What can I do to in order to add the class A component to the scene, or otherwise not to get this error?


How to organize GameObjects into logical groups in a Unity Scene? Obviously there are a Scene hierarchy, but the problem is that the scene hierarchy was not meant for organizing GameObjects because parent GameObjects affect the transformation of their children. For example what can one do to select all the decoration GameObjects? Some might be children of non decoration GameObjects and buried very deep in the scene hierarchy while others might be root GameObjects. One solution could be to add a Tag, but since Unity restrict you to only one tag per GameObject, that makes the usage of tags pointless as I have different overlapping categories. Another solution would be to name objects but that is very error prone as a typing mistake will loose my GameObject. Also the team need to memorize possible tokens in the name which allow even more room for human errors. Another solution would be to add an identifying Component, similar to how tags work in most other applications. But will there be a penalty in build time runtime in a large project because of the additional Scripts (Components)? Any other ideas how I can organize my Scene so that I can easily select a logical group of GameObjects from different unrelated parents in the editor Scene or Hierarchical view?


Changing alignment within a vertical layout group I have a vertical layout group that has text bubbles instantiated into it. Instantiating them always aligns them to "lower middle". However, I'd like to have them on opposite sides for a message app effect. Right now, I'm changing the anchoredPositions of each instantiated UI object in Update. Is there any better way of doing this?


Why the transform.localPosition never equal to the begin position of the transform? using System.Collections using System.Collections.Generic using UnityEngine public class MoveScrollView MonoBehaviour float seconds Vector3 begin Vector3 end Vector3 difference public static bool go false public static bool goBack false public static bool atOriginPos false void Start() seconds 0.5f begin transform.localPosition end new Vector3(0, 1, 0) difference end begin void Update() if (go) if (transform.localPosition.x lt end.x) var mx transform.localPosition.x transform.localPosition new Vector3(mx seconds Time.unscaledTime, 1, 0) difference end transform.localPosition if(goBack) if (transform.localPosition.x gt begin.x) var mx transform.localPosition.x transform.localPosition new Vector3(mx seconds Time.unscaledTime, 1, 0) difference end transform.localPosition if(transform.localPosition begin amp amp goBack) atOriginPos true At the Start the begin position is ( 540.0, 1.0, 0.0) also the transform.localPosition is at the same position. Then at this line 39 if (transform.localPosition.x gt begin.x) The value of the x of the transform.localPosition is 3.039021 and the x of the begin is 540 So it's getting inside and move the transform. Then when the transform has finished moving I see on this line if (transform.localPosition.x gt begin.x) The transform.localPosition x value is 540.7267 and the x value of the begin is still 540 So now it will not get inside and will not move the transform anymore. But two wrong things happened The transform stopped moving but it didn't move to it's original position only close to it. Because it didn't move to it's exact original position then the localPosition x and the begin x are never equal so the this will never be true if(transform.localPosition begin amp amp goBack) And the flag atOriginPos is never true. I want the transform to move back to it's original position and then when it's reached the original position set the flag atOriginPos to true.


reuse texture between quad objects This question is specific to unity I want to spawn multiple blocks, each representing a letter. There will be more than one copy of an alphabet. I have a big texture which contains all the letters in it. I use a prefab to Instance all the Blocks(quads) during Awake(). At runtime, I'd like to assign a texture to these quads (identifying the letter). My code looks like this void Update () if there is no active block, spawn it if (activeBlock null) this.getNextBlock (ref this.activeBlock) protected Block getNextBlock(ref Block block) block this.deQueueBlock () char letter LetterMgr.Instance.getNextLetter() based on the letter, index into texture and assign the texture indices to this block ? How can I reuse this one big texture and index into each letter amidst all these blocks (quads) ? I will be rendering this on a mobile, so will need to squeeze all the performance I can. Details 256 x 256 per letter 8 columns x 4 rows Total Texture Size 2048 x 2048 Total number of blocks 100 PS Each of the letters will be moving and will eventually come to rest. So I will have some (around 6 7) actively moving blocks and others will be stationary.


Unity build does not launch and leaves no logs errors I have released my first title Audio Infection ( https store.steampowered.com app 911580 Audio Infection ) for a bit over a year ago. Recently 1 user has so far encountered an issue where the game does not launch. He is the only user that encounters this problem. He has this issue on both Win 7 and Win 10. His system specs are fine and his drivers are up to date. The game does not leave a log file, rather it looks like it is unable to boot. There are no Windows error reports on it either. I watched it through Discord screenshare because I could not properly understand his issue. I had asked a few other random people to test my game and demo (he has the issue with both, the demo and full version) however no one else (including me) is able to reproduce this behavior. At this point I have tried updating Unity from 2018 to 2019 (no change in behavior) added manual logging (with no results) updating drivers (on his system) installing Visual C (on his system) empty project with Unity sample scene (he was able to load the sample scene!) deleting crashhandler.exe (used to fix similar issue in the past based on older threads) modifying files deleting and downloading the files What else can I try in order to figure out what is causing the issue? I am honestly clueless. Since the sample project was able to boot on his system there is definitely something wrong with the build on my end. However he is the first person with this issue. It doesn't even get to the point of launching on his system and it can't be found in the memory either. It is almost as if Windows is blocking it from launching, however that is not the case. But the result is very similar to that. There is a free demo on the store page available in case you want to see if it boots on your system. It works for both VR and non VR systems. When no VR devices are detected all VR related contents are disabled. This has been thoroughly tested and worked on loads of different Windows systems with different specs, with VR and no VR. Once again, there are no errors, no logs, the build doesn't even make it to that point, yet that exact same build works for literally everyone else on various systems. I am absolutely clueless about what to do in order to resolve this issue. Any help advice or pointers towards the right direction are greatly appreciated! PS he is not a troll, I have known this guy for a long time now and he genuinely wants to support me.


Converting UnityScript code to C What is the alternative for .ToBuiltin? I'm trying to convert this code from UnityScript (Unity's version of JavaScript) to C var polys new Array() array to collect vertex locations polys.Push((scanpoint padding) Vector2(0.5, 0.5) Pixel vs Unit Scale) var poly Vector2 polys.ToBuiltin(Vector2) I converted the first two lines like so, with no errors var polys new List lt Vector2 gt () polys.Add((scanpoint padding) new Vector2(0.5f, 0.5f) Pixel vs Unit Scale) But when I try to adapt the last line like this Vector2 poly polys.ToBuiltin(Vector2) I get two errors ToBuiltin does not exist. And also an error on the Vector2 inside the () Vector2 is a type which is not valid in the given context. How can I convert this code to C correctly?


Jerky motion when standing on hovering object In a level of a 3D FPS I'm making, I have several floating pillars that move up and down (the x and z positions are always the same). When the player stands on one of the pillars, the motion is incredibly jerky going up, but smooth going down. I think the player is sinking into the pillar slightly and then catching up. I've tried different colliders, all sorts of combinations with rigidbodys and character controllers. I've tried setting the pillar as a parent of the character and then having the player hover slightly. I've just hit a brick wall and would appreciate an outside perspective. Here's my code just in case the issue is in there. Player movement public float walkSpeed 6.0F public float runSpeed 10.0F public float jumpSpeed 8.0F public float gravity 20.0F private Vector3 moveDirection Vector3.zero void FixedUpdate() CharacterController controller GetComponent lt CharacterController gt () moveDirection new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")) moveDirection transform.TransformDirection(moveDirection) moveDirection walkSpeed if (Input.GetButtonDown("Jump")) moveDirection.y jumpSpeed if (Input.GetButton("Sprint")) walkSpeed runSpeed else walkSpeed 6.0F moveDirection.y gravity Time.deltaTime controller.Move(moveDirection Time.deltaTime) void OnCollisionStay(Collision hit) if (hit.gameObject.tag "Column") transform.parent hit.transform else transform.parent null Pillar movement float height float speed Vector3 start Vector3 end Vector3 startOrEnd void Start() speed 0.01F start new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, gameObject.transform.position.z) void Update () motionControl(speed) float randomNumber(float min, float max) float number Random.Range(min, max) return number void motionControl(float speed) if (gameObject.transform.position start) end new Vector3(gameObject.transform.position.x, randomNumber(0, 10), gameObject.transform.position.z) startOrEnd end else if (gameObject.transform.position end) startOrEnd start gameObject.transform.position Vector3.MoveTowards(gameObject.transform.position, startOrEnd, speed)


add random force and direction to rigidbodies every x seconds i need to add a windForce to multiple rigidbodies, with random direction and random force every x lapse of time. I'm using InvokeRepeating to update the windDirection so that the rigidbodies can be pushed in a different direction every x seconds. Here's the code void windRotate() windDirection.y Random.Range(0, 360) transform.Rotate(windDirection smooth) if (objectsInWind.Count gt 0) foreach (Rigidbody rigid in objectsInWind) rigid.AddForce(windDirection 10) This way the rigidbodies don't receive any force. I guess the system does not recognize the Vector3 Update of windDirection, so I need to recalculate it, bit I was not able. On the other hand if I use this rigid.AddForce(Vector3.Up 10) the rigidbodies moves but in one direction only, and it's not updated on the next windDirection change. I tried playing with the various Vector3 values (up, right etc..) and different force methods (AddRelativeForce) but nothing changed. By using Debug.Log(windDirection) i know that windDirection is updating correctly ever 3 seconds, so it should also be updated in my methods when i apply the force, but id does not work. Any suggestion? Thanks


Moving Windows Mixed Reality main camera in Unity3D programatically I'm trying to programmatically move the main camera i.e. player's point of view origin in a Windows Mixed Reality but for some reason it's not working for me (using newest latest stable Unity 2018 and HoloToolkit through which I've setup my WMR project)... I've done the following m MainCamera Camera.main m MainCamera.transform.position.Set(100f, 100f, 100f) UnityEngine.XR.InputTracking.Recenter() if (Input.GetKeyDown(KeyCode.A)) happens, but even though the code gets run, my VR view position remains unchanged, and I'm guessing at 0,0,0 (or whatever is set initially)...so how exactly do they do those movements in the WMR's UI cliff house when you use the motion controller to point to place you want to transport your view...do they actually move all of the objects showing instead? Or am I missing something really trivial when I can't move except for by moving my own body inside of VR? Maybe HoloToolkit is disabling it somehow... But how do I reenable it then to move to a predetermined places within a large life sized 3D model objects please? TIA


Detect clusters of tokens on an x y grid Ok, so I have a two dimensional grid working on integer x and y coordinates. Each of this coordinates can have one and only one token on it. The tokens have the capability of check and return an adjacent token given a direction in which to search (they'll return null in case nothing is there) I now need an algorithm to check the grid for clusters of 3 or more adjacent tokens and add each cluster to a dedicated variable (meaning than, instead of just stopping after return one cluster, it needs to check for all clusters on the board) I've been thinking for a while but came out with nothing, any help?


Unity3D Disable player input but not character movement? I'm trying to code a dash air dash for a 2D platformer. In my character controller's FixedUpdate(), I have various if statements that cause certain actions when a button is pressed. To disable player input while the dash was happening, I tried putting Dash() in an IEnumerator with a simple test code like this IEnumerator Dash() if (player.GetAxis("Horizontal") lt 0) thePlayer.GetComponent lt HeroController gt ().enabled false yield return new WaitForSeconds(0.5f) move move 2 thePlayer.GetComponent lt HeroController gt ().enabled true But since the character's physics are inside the character controller, both the player's input and the character's movements are stopped when the controller is disabled. How can I disable inputs while still allowing the character to dash?


Save Generated GameObject as Prefab I've written a script which will automatically generate a Mesh, assign a MeshFilter, MeshRenderer, BoxCollider, and RigidBody. This script is meant as a tool to rapidly create a certain class of objects (in this case, dice). I don't want them to actually generate at runtime. Is there a way to convert the GameObject to a Prefab with all of its different generated properties so that I can simply drop them into my game? Just trying to drag it into the Assets causes it to lose its Mesh. Also to note, I have it so I can generate the Mesh via the Inspector in a ContextMenu, which works well.


How to make a sun that only illuminates stuff in sunlight? I set up a scene with Gaia Pro, and it looks really nice so far. It even has a script to add a Sun object and have it circle the scene, which is pretty cool. Problem is, it's implemented as a Directional Light, which illuminates everything. I created a cavern with Digger as a part of the scene, and the interior of the cavern is brightly lit by the sun. For obvious reasons, this should not happen! What's the best way to fix the sun so it won't illuminate things that logically wouldn't be in sunlight?


Square tile navigation unity I'm looking to generate a grid style navigation system in Unity. I have created a map in Tiled and am unsure how to continue considering the tiles will have different properties. The closest example I can think of would be something akin to the Fire Emblem series of games, in which sprites navigate across the terrain using square tiles. Any advice on how to achieve this, preferably without paying for a unity asset, would be greatly appreciated. If it helps, I'm hoping to run this on a mobile device. Here is an example.


3ds max CAT Animation layers export I've made 3 absolute layers Each layers has it's own animation cycle. Now I would like to export it as FBX and import to unity3d, however, it would import only active layer. Is it possible to export it the way, it would be possible to choose later on in unity which animation cycle to play? Thanks in advance


Unity find position within range of object Say you have a gameobject that is at a certain position(this could be your player). Now say that you have a melee NPC that has to be within a certain range to hit the Player. Now you would do something like this to find out where the player is var targetPosition target.transform.position Say that the range of the NPC is 4 meaning he can be 4 units away from the player before he can start attacking him. My question is how would you subtract that to get a position that is within range? And am i doing this type of thing correctly? or is there a better way of doing it? ) Any help would be appriciated a lot!


Unity 2D Position Child Object to center of Parent Object What I'm trying to achieve is snapping a child object to the center of its parent object after dragging and dropping it. The moving object successfully follows the mouse, and drops. It also successfully selects a dynamic parent when it moves over a new node. What it does NOT do is then snap to the center of its parent. It instead jumps all over the screen and snaps to nothing. Here is all of my code using System.Collections using System.Collections.Generic using UnityEngine public class Object Moveable MonoBehaviour private Vector2 mousePos public float moveSpeed public float offset 0f private bool following private GameObject SelectedNode Use this for initialization void Start() following false offset 10 void Update() if (Input.GetMouseButtonDown(0) amp amp ((Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.position).magnitude lt offset)) following true if (following) transform.position Vector2.Lerp(transform.position, Camera.main.ScreenToWorldPoint(Input.mousePosition), moveSpeed) if (Input.GetMouseButtonUp(0)) following false Attach (Node, 0, 0) transform.localPosition SelectedNode.transform.position void OnTriggerEnter2D(Collider2D trigger) if (trigger.tag "pipenode") transform.SetParent(trigger.transform) SelectedNode trigger.gameObject


Add oceans to an earth model with only continents? I have the following earth model, it only has continents I wanted to add water but as you can see, some of the continents are now hidden due to the water sphere being more round than continents I tried the following downscale water sphere, kinda works but only when it's significantly smaller, overall result is then unconvincing. change shader and render queue offset, does not do anything actually. I was hoping that maybe there could be a way to render transparent parts of this earth model as a specific color or eventually another material. Please do not suggest to use another earth model, I wouldn't have asked the question otherwise )


How to address a function inside an if condition using C in unity 3D I am new to game development and have very limited idea of C syntax. I was watching unity 3D tutorials of UI and thought of using ModalPanel.cs and TestModalWindow.cs In a quiz game where 3 choices are there of a question and total 5 questions are there Now suppose in public void TestNYCI () modalPanel.Choice( " string? ", icon, TestYesFunction, TestNoFunction, TestCancelFunction) Here I want to use an if loop if ( condition) where condition means choosing of a function among TestYesFunction, TestNoFunction, TestCancelFunction Statements If suppose TestYesFunction is true I want to increment the count and write it as score And will repeat the process in rest of the 5 functions. Can someone please provide a suitable syntax to address the problem.


Lerp UI Color outside update method? I'm able to Lerp the color of a UI panel within the Update method. However I'd like to trigger behavior a single time when needed. If I put it in a method and call it it only changes for a brief time and doesn't fully complete. I could probably set a bool flag within the update method but that seems sloppy.


How to detect speed on collision The problem with OnCollisionEnter2d is that it only gets called when there is a collision but what I wanted is to get the current speed of object at the moment of impact until the object stops moving. So that I if the object stops moving after impact I will call another function. void OnCollisionEnter2d(Collision2D collision) Debug.Log(speed) problem this will only give the speed at the moment of impact if(speed lt 0) blah blah I also tried putting speed variable on the Update() void Update() var currentVelocity player rb.velocity speed currentVelocity.magnitude


Unity how do I make an input only available to the code? I have a simple function attached to a button. I then decided to change it by adding an input. The problem is that the function won t run unless I specify the input in Unity via the inspector. I don t want to do that because it will affect the function and I have already changed it inside. I already set the input when I run the function so there s no need to set it again in Unity this is a problem because the input is going to be different depending on different scenarios. How can I overcome this? public void Eruption(string biome) if (biome sea ) do something


Can't see which line exceptions occurred on in script source files After updating Unity to the new 2017.1.0f3 version, I can't see which line in a source file an exception occurred on. Example I can't see the source of the error by double clicking in the console either, which would usually redirect me to the source file in Visual Studio. I can still see exceptions from the Unity and Mono API. I have managed to temporarily fix it by going to the PlayerSettings and switching "Scripting Runtime Version" from "Stable (.NET 3.5 Equivalent)" to "Experimental (.NET 4.6 Equivalent)". This happens to all MonoBehaviour scripts.


How can I make the cursor avoid something completely? I wrote some code for a UI button that causes the mouse to avoid it. I realize this is kind of a weird thing to do in a game design wise, but this is a really weird game. I need a button that is not only unclickable, but also unhoverable. I got it mostly working, but I cannot seem to change the position before the mouse is drawn, probably because mouse movement is handled by the OS, unless there is a problem with my code that I missed. As a result, pushing the mouse against the button boundaries results in a stutter. The mouse briefly appears over the button before I can move it, so it is still possible to click the button. A demonstration of the button avoidance and stutter https youtu.be 7tgIrJ vMDg DllImport("user32.dll") public static extern bool SetCursorPos(int X, int Y) DllImport("user32.dll") public static extern bool GetCursorPos(out Point pos) ... void Update () var mousePos Input.mousePosition if (Application.isFocused amp amp isOver) Get the current mouse position from OS so we can change it Point cursorPos GetCursorPos(out cursorPos) if (oldMousePos.x gt xMin amp amp oldMousePos.x lt xMax) Coming from above or below. Figure out which one and move mouse accordingly if (oldMousePos.y gt uiPos.y) cursorPos.y (int)(rt.rect.height 2 (mousePos.y uiPos.y)) else cursorPos.y (int)(rt.rect.height 2 (uiPos.y mousePos.y)) else Coming from either left or right. if (oldMousePos.x lt uiPos.x) cursorPos.x (int)(rt.rect.width 2 (uiPos.x mousePos.x)) else cursorPos.x (int)(rt.rect.width 2 (mousePos.x uiPos.x)) Give new coordinates to OS to update mouse position SetCursorPos(cursorPos.x, cursorPos.y) else track the old position to know what direction they moved their mouse from so we can put it back oldMousePos mousePos I tried using the Cursor API to force it to software mode thinking that might fix it, but it still stutters, and I would prefer to use the default cursor anyway, and hardware mode if possible. Is there any way to work around this or remove the stutter?


My GameObject keeps spawning when it shouldn't I'm trying to instantiate a new gameObject when the current gameObject gets to a select point. The problem comes when the program gets to the second if() statement. It sets the floorsSpawned to 1 and when it does, the game object instantiates a bunch of times. Shouldn't the floorSpawned be set to 2 in the first if() statement and only instantiated once? public class FloorMovement MonoBehaviour public GameObject floor SerializeField int speed 10 public int floorsSpawned 1 Start is called before the first frame update void Start() Update is called once per frame void Update() transform.Translate(Vector2.left Time.deltaTime speed) if (transform.position.x lt 18.0 amp amp floorsSpawned 1) floorsSpawned 2 Instantiate(floor, new Vector2(11.5f, 2.0f), Quaternion.identity) if (transform.position.x lt 40.25 amp amp floorsSpawned 2) floorsSpawned 1 Destroy(floor, 3)


Unity3D How to get highest value for acceleration from Input.gyro I'm trying to develop an app that can detect car acceleration, braking and cornering speed. I need to detect device acceleration. Is that acceleration high or low?. Like flo app on Google Play. I'm using gyroscope and I need to get highest value for user acceleration (x, y, z axises) from gyroscope. Values of x, y and z are changing every frame. I need to achieve highest value of this 3 axis for later use. Now my current code looks like this using UnityEngine using System.Collections using UnityEngine.UI public class NewBehaviourScript MonoBehaviour public Text x, y, z void Start() Input.gyro.enabled true void Update() x.text Mathf.Abs(Input.gyro.userAcceleration.x).ToString() y.text Mathf.Abs(Input.gyro.userAcceleration.y).ToString() z.text Mathf.Abs(Input.gyro.userAcceleration.z).ToString() Thanks for any help


Gradle Build Error Unity 2019.1.6 I found out that unity has deprecated the internal build system and has defaulted to gradle. I've not built with the gradle build system before, and now after upgrading to unity 2019.1 full version, I can't build an android project. And, I installed the android module using unity hub, what can I do to fix this? Screenshot1 Screenshot2 Screenshot3 Screenshot4 Screenshot5 Screenshot6


Reusing tilemap segments I'm wondering how I can incorporate reusable tilemap segments in my workflow. For example I construct a room out of my tile palette, and I want to reuse this room in multiple places. Is there some way to "prefab" a section of a tilemap? I haven't found such a thing. Or perhaps I should just prefab the whole tilemap, and use multiple tilemap objects within one grid? Won't that introduce significant overhead? What if I want to prefab a section of a tilemap with some additional, non tilemap objects?


"Create Test Script in current folder" button is grayed out in Unity I thoroughly read the Unity Test Runner documentation. It is said in the documentation that the button may be disabled only if the creation of the script will lead to an error. This option is disabled if adding a test script would result in a compilation error. But I do not understand this. How could a creation of the script possibly lead to an error? I will be grateful for any help provided. I found here a little bit more info, but it did not help me out.


Up down powerbar computation at server side I aplolgize if my question is unclear, because I don't know how to formulate the problem. I have a player that can do damage with a weapon. The weapon has a min and max damage. Holding the space bar makes a power bar grow and degrow on time, and the hit is fired when the space bar is released. This kind of mechanics is quite everywhere. I manage to do that in Unity with a scrollbar, using delta time to add or substract some damage on time. However, my game is networked, and I don't want the user to send to the server the damage done, just that the strike is performed and make the server compute the damage done. Here is a graph to better explain my requirement I don't want to do it with add and substract at every delta time at server side because of potential compute costs at many parallel games, and the desync risk. I need a formula or a simple algorithm to get the damage at hit time based on time. Thanks for any help.


How can I Debug.Draw different shapes in unity? I want draw new shapes in Sence for example I want Debug.DrawSphere can I Debug.DrawCollider? Is possible that I Debug.DrawSphereCast


Two game object efficient and fast on off switch I have two game object, on GUI button click i am toggle between them but the problem is one game object which is small contains less vertx etc., is loading fast while the other which heavy taking time. How do i efficiently and quickly load it ? I don't want to show loading window i want to load that game object quickly?


Unity C How to make 3D objects move in the grid? I want to move and deploy 3D objects in the grid, like bakery 2(Storm8 Studios). How do you make a grid like that? For example, make a 5x5 grid and move it to a touchdrag. I'd like you to give me some advice. Pictures for reference https lh3.googleusercontent.com Kwp9i9ExRboeQCtM65sztw3tqEL9R76zZzB9U6j5vs98ueF9ksOU3huMdZqv4KPDZ2E w2590 h1430


Object shrinks at same rate no matter what I am using the following code to shrink a sprite public bool shrinking false public float targetScale 0.1f public float shrinkSpeed 0.1f void Update () if(shrinking) mySprite.transform.localScale Vector3.one Time.deltaTime shrinkSpeed if(mySprite.transform.localScale.x lt targetScale) shrinking false However, no matter what I change shrinkSpeed to, the object shrinks at the same rate. I know it probably has something to do with putting it in the update function but where should I move it to fix the problem?


how to get camera width in unity Problem I have a spawn manager written in c which spawns my game object, i use screen.width, to set the maximum screen with and screen.width to set the minimum screen width for the spawning, but my game object spawns way off the screen. I am using a portrait camera 2 3 instead of free aspect as my camera view, as i want my game to be in portrait mode how do i make my game object spawn within the camera widths(max and min)? my code public class SpawnManager MonoBehaviour public int maxBalloons 100 public GameObject balloon public float horizontalMin Screen.width public float horizontalMax Screen.width public float verticalMin 5.0f public float verticalMax 1.0f private Vector2 originPosition void Start () originPosition transform.position Spawn () void Spawn() for (int i 0 i lt maxBalloons i ) Vector2 randomPosition originPosition new Vector2 (Random.Range(horizontalMin, horizontalMax), Random.Range (verticalMin, verticalMax)) Instantiate(balloon, randomPosition, Quaternion.identity) originPosition randomPosition


Real Time Physics Based Mesh Deformation I'm working on a game through unity that draws one of is essential elements from traditional tool forging techniques for building tools and such. I want the feel of the game to be able to create a tool that is truly yours and slowly make it better in both design and functionality over time. One major thing I cant't seem to figure out is to be able to take a mesh (in this case a hot piece of meta) and deform it in such a way that you aren't loosing any of the mesh, its just being shifted slightly with each hit of a hammer (or in my testing case click of a mouse). I have looked all over youtube and various forums and I can't seem to find an efficient way of going about it. Any thoughts?


Can a Component.gameObject be null in Unity? Can a Component.gameObject be null in Unity? If it can what can cause it to be null? The context for the question is a NullReferenceException I got from the users, which specifies only method, but not line in which it occurred. So, I suspect that there may were conditions which cause Component.gameObject to be null.


How to create fallout intensity on a generated mesh in Unity? So I was able to generate a circle mesh in Unity to basically see the other characters when they are inside of it, and hide the characters when they are outside of it, and partially hide and show the character if they are partially in or outside of it. Below is an image of what I was able to generate, but the thing is, the edges are very sharp and I would like to have some Fallout Intensity on the mesh. Just like with Lights in Unity, where they have a fallout intensity at the edge of the lights. Image of Generated Mesh As you can see, the edges of the mesh are very sharp and thats not the kind of effect am after, I would like to add some fallout to that, and adjust it. Here is The Code That Generates The Mesh using UnityEngine using System.Collections using System.Collections.Generic public class FieldOfView MonoBehaviour public float fieldOfView 360f public int numberEdges 360 public float initalAngle 0 public float visionDistance 8f public LayerMask layerMask private Mesh mesh private Vector3 origin private void Start() mesh new Mesh() GetComponent lt MeshFilter gt ().mesh mesh origin Vector3.zero private void LateUpdate() GenerateUpdateMesh() private void GenerateUpdateMesh() float actualAngle initalAngle float incrementAngle fieldOfView numberEdges Vector3 vertices new Vector3 numberEdges 1 int triangles new int numberEdges 3 vertices 0 origin int verticeIndex 1 int triangleIndex 0 for (int i 0 i lt numberEdges i ) Vector3 actualVertices RaycastHit2D raycastHit2D Physics2D.Raycast(origin, GetVectorFromAngle(actualAngle), visionDistance, layerMask) if (raycastHit2D.collider null) No hit actualVertices origin GetVectorFromAngle(actualAngle) visionDistance else Hit object actualVertices raycastHit2D.point vertices verticeIndex actualVertices if (i gt 0) triangles triangleIndex 0 0 triangles triangleIndex 1 verticeIndex 1 triangles triangleIndex 2 verticeIndex triangleIndex 3 verticeIndex actualAngle incrementAngle We form the last triangle triangles triangleIndex 0 0 triangles triangleIndex 1 verticeIndex 1 triangles triangleIndex 2 1 mesh.vertices vertices mesh.triangles triangles Vector3 GetVectorFromAngle(float angle) float angleRad angle (Mathf.PI 180f) return new Vector3(Mathf.Cos(angleRad), Mathf.Sin(angleRad)) public void SetOrigin(Vector3 newOrigin) origin newOrigin What do I do here to add some Fallout Intensity? All the help is really appreciated. And Thank you in advance.


How to clip what is outside scroll view when using a custom UI element? I have created a custom UI element (that use CanvasRenderer). Here is code Mesh mesh new Mesh() Rect drawArea GetComponent lt RectTransform gt ().rect using (VertexHelper helper new VertexHelper()) helper.AddVert(new Vector3(drawArea.xMin, drawArea.yMin), Color.white, Vector2.zero) helper.AddVert(new Vector3(drawArea.xMin, drawArea.yMax), Color.white, Vector2.zero) helper.AddVert(new Vector3(drawArea.xMax, drawArea.yMax), Color.white, Vector2.zero) helper.AddVert(new Vector3(drawArea.xMax, drawArea.yMin), Color.white, Vector2.zero) helper.AddTriangle(0, 1, 2) helper.AddTriangle(2, 3, 0) helper.FillMesh(mesh) var canvas GetComponent lt CanvasRenderer gt () canvas.SetMesh(mesh) canvas.SetMaterial(Material, null) It creates a simple rectangle that is same size as rect transform. It works great. However if I put this inside a scroll view, everything that is outside scroll area viewport is rendered (while it should be clipped). The scrolling works as it should (rectangle get scrolled by changing position when scrollbar is used). I have tried to call canvas.EnableRectClipping(...) but without success.


unity how to automate changing sprite editor setting I have a bunch of hex tiles that I want to import into a tile palette. However their pivot point needs to be set to y 0.35 when the default is 0.5 I could edit the import settings in the sprite inspector or change the pivot point in the sprite editor but that takes forever with hundreds of tiles. Is there any way I could automate that?


What causes this z position change? This is a follow up on the following thread. I'm applying a code that will move an object just outside the camera's frustum. I have used the same code in other projects, and it worked fine. However, I'm using it with URP now, and I'm experiencing a z position change while I expected only a x position change. And I just don't see why it does that. I have recorded a video here. If I press the button, the cube should be moved to the left only. But it also moves to the back (z position). And this is the script that I have applied to the cube in the video using System using UnityEngine public class PlaceOutsideCamera MonoBehaviour public void PlaceOutsideFrustum(Transform uTransform, bool uLeft) uTransform.position pPlaceOutsideFrustum(uTransform, uLeft) public static Vector3 pPlaceOutsideFrustum(Transform uTransform, bool uLeft) var frustumPlanes GeometryUtility.CalculateFrustumPlanes(Camera.main) Ray ray Plane plane if (uLeft) 1. ray Camera.main.ScreenPointToRay(new Vector3(0, Camera.main.pixelHeight 2f, 0)) plane frustumPlanes 0 else ray Camera.main.ScreenPointToRay(new Vector3(Camera.main.pixelWidth 1, Camera.main.pixelHeight 2f, 0)) plane frustumPlanes 1 float fDistance Mathf.Abs(Camera.main.transform.position.z uTransform.position.z) 2. var borderPoint ray.GetPoint(fDistance) 3. var frustumOutside plane.normal Bounds b BoundsFromTransform(uTransform) 4. var halfDiameter b.size.magnitude 2f return borderPoint frustumOutside halfDiameter public static Bounds BoundsFromTransform(Transform uTransform) try Bounds bounds new Bounds(uTransform.position, Vector3.zero) wir h tten auch einfach new Bounds() nehmen k nnen, meint Manfredas foreach (Renderer renderer in uTransform.GetComponentsInChildren lt Renderer gt ()) bounds.Encapsulate(renderer.bounds) Vector3 nOff bounds.center uTransform.position return new Bounds(nOff, bounds.size) catch (Exception ex) UnityEngine.Debug.Break() return new Bounds() public void OnGUI() if (GUI.Button(new Rect(0, 350, 100, 50), "DoThis!")) pDoThis() private void pDoThis() this.PlaceOutsideFrustum(this.transform, true) Can anybody tell me why my code does this? I just don't see it. Thank you very much for the help! Edit Here is another video that shows the camera position in the Inspector.


Rotation around arbitrary vector (using quaternions?) I currently have a camera which orbits a specific target object, always looking at it. The user can drag the mouse to move the camera left right up down and the camera will move over the surface of a sphere of fixed radius (note, I clamp the vertical angle to 89 ). Currently it looks something like this... Store position of camera for future reference private Vector2 rotation new Vector2(120, 25) Was intended to be the vector from planet to target. Only works with up private rotationalPole Vector3.up if (isDragging) rotation new Vector2( Input.GetAxis( quot Mouse X quot ) xSpeed radius 0.02f, Input.GetAxis( quot Mouse Y quot ) ySpeed 0.02f) target is the GameObject to center on... var pos target.transform.position camObj.transform.position pos (Vector3.back actualRadius) camObj.transform.LookAt(pos, rotationalPole) camObj.transform.RotateAround(pos, Vector3.right, rotation.y) camObj.transform.RotateAround(pos, rotationalPole, rotation.x) This works fine when up is in the y direction. Now, however, instead of an object on the ground, the target is something in orbit around a planet (currently on an equatorial orbit but hopefully on an arbitrary one in future). I want the camera to behave the same as before, but with up being the vector from the center of the planet through the target. Nominally forward will be the direction of orbit (but since the user can spin through 360 quot horizontally quot , that's less important). Currently it looks like this... Basically, I'd like to rotate the image above counter clockwise by 90 (which I believe I can do by playing with the camera transform's up and right vectors) but also that my arbitrary rotation honors the new orientation. Some research shows that I need to use quaternions but while my mental model for basic trig is fine, I can't picture how to use quaternions correctly in this situation. Following on from Jon's answer below... I've now got the following. var planetToTarget (target.transform.position planet.transform.position).normalized quot Reset quot the camera before I do any transforms this.transform.position target.transform.position tgtMovement actualRadius this.transform.up Vector3.up this.transform.LookAt(target.transform.position) var camToTarget (transform.position target.transform.position).normalized Debug.Log(string.Format( quot targetMotion 0 , planetToTarget 1 , camToTarget 2 quot , tgtMovement, planetToTarget, camToTarget)) Line that's not working... this.transform.Rotate(camToTarget, 90) To be added in when the above is working... this.transform.Rotate(Vector3.Cross(camToTarget, planetToTarget), rotation.y) this.transform.Rotate(planetToTarget, rotation.x) this.transform.up planetToTarget The uncommented code (excluding the last line) keeps the camera behind the target, looking forward... Initially, I get targetMotion (0.0, 0.0, 1.0), planetToTarget ( 1.0, 0.0, 0.0), camToTarget (0.0, 0.0, 1.0) Which generates However, as the target moves around the planet, it changes to targetMotion (0.4, 0.0, 0.9), planetToTarget ( 0.9, 0.0, 0.4), camToTarget ( 0.4, 0.0, 0.9) By which point, the camera is slewing to the side... So I'm clearly still missing something. I don't appear to be rotating around camToTarget correctly?


Better way of handling the relation between Bullet and Enemy I was wondering how should I design this relation in terms of "better OOP"? Should I have a Singleton EnemyManager which contains a list of enemies (EnemyList) then Bullets can access the EnemyList to check for collision? Or should I just pass EnemyManager as a reference to each Bullet so Bullets can still access the EnemyList but not in a Singleton way? Or is there any other better ways of doing? Please advise.


Retrieve the original prefab from a game object How would one proceed to retrieve the original prefab used for instantiating an object? In the editor these two functions work Debug.Log(PrefabUtility.GetPrefabParent(gameObject)) Debug.Log(PrefabUtility.GetPrefabObject(gameObject)) But I need something that works in the release version. I have objects that can be transported between scenes ands I need to save their data and original prefab to be able to instantiate them outside of the scene they have been originally instantiated. ie Game designers create new prefabs. Game designers create objects from prefabs and place them in scenes (50 to 150 scenes). Game is played and objects are moved across scenes. Game is saved and infos about objects which have moved are saved in the save streams (files or network). This is where I got stuck. Currently, to palliate to the shortcomings, we're saving the name of the prefab in the prefab. But each time a prefab is moved, renamed or duplicated the string must be changed too, sometimes the objects created from the prefab keep the original name (game designer might have edited the prefabPath field). Maybe there is a better way to achieve proper save games without having to access to the original prefab name. But currently we keep the saves segmented on a per level basis (easier and safer to save load to files and transfer the save games to from servers)


Get type of the object where attribute was declared Hide In Derived Inspector Attribute I want to implement a custom Unity inspector attribute, like usual ones HideInInspector or Range(0, 100f) . This attribute should hide a field from the inspector if it's inherited from a base type, rather being defined directly in the type of the object we're inspecting. So, for example, if I have these classes... public class Enemy MonoBehaviour SuperField public int EnemyHealth public class GiantMonster Enemy SuperField public int Armor then the inspector for a base Enemy should show a control for the EnemyHealth variable, but when inspecting a GiantMonster we should not see a control for this variable. So far I have my attribute public class SuperFieldAttribute PropertyAttribute which has its own PropertyDrawer CustomPropertyDrawer(typeof(SuperFieldAttribute)) public class SuperFieldDrawer PropertyDrawer public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) ... Inside OnGUI I need to access find the type where the field we're drawing was declared with the SuperFieldAttribute . So if SuperFieldDrawer.OnGUI() is called for the SerializedProperty corresponding to GiantMonster.EnemyHealth, I should be able to determine that the type where EnemyHealth was declared is Enemy and not GiantMonster. (I'll use this to hide the field so it's not drawn) And if SuperFieldDrawer.OnGUI() is called for the SerializedProperty corresponding to GiantMonster.Armor, I should be able to determine that the type where Armor was declared is GiantMonster itself. (Meaning I should proceed and draw the field) So far I've found ways to access the type of the component we're inspecting, but not the type where the field was first declared, so that's the missing piece I need to fill in. It's OK if I use reflection and so on any method is good, performance isn't a concern.


Handling exact collisions on character controller and or other objects in unity? (eg. head shot, chest , leg,etc) Hello all I have been working on games in Unity for a long while (making slow progress as I do it purely on my own , and of course you helpful people here on gamedev.stackexchange!) I've made lots of capsule characters of my own using Rigidbody and without Rigidbody and on a basic level they work fine. But i now want to detect exact points of collisions (for example if a bullet hits his head, or hand or knee etc etc) I've been trying to read as much as I can find about this, but honestly can't find the answer i need. I believe I would achieve it by making several colliders on the character. But I don't know exactly how this would work , also I have seen some guides saying that I should use OverlapSphere but again there wasn't exact instructions and I can't figure out how to do it. Also, when I add some sphere colliders to my character, they dont stay in the correct position in relation to the model once it is animated (eg. Crouching, or running, the leg spheres pop out of his legs for example). Could anyone here provide an explanation of how I can do it?


Bullet spread changes depending on the camera direction I'm working on an FPS game. I want to make a little bit of difference in shooting direction, only on the horizontal axis. To do this, I wrote this code Temp Shake Horizontal.x Random.Range( 0.1f, 0.1f) if (Physics.Raycast(the camera.position, the camera.forward Temp Shake Horizontal, out BulletDecal Hit, Mathf.Infinity)) Quaternion HitRot Quaternion.FromToRotation(Vector3.forward, BulletDecal Hit.normal) decals Objs decal Index .transform.position BulletDecal Hit.point decals Objs decal Index .transform.rotation HitRot But I don't know why, when I rotate the camera, the result is changing! Here is what it looks like when I face in one direction (this is the intended result) But when I rotate the camera about 90 degrees to the left or right, the result is no horizontal variation the bullets all line up in a vertical column. Why does this happen, and how can I solve this issue? I want the result to always be like the first picture, with random variation side to side.


Invoking a common method after a button press I want to implement a common method that handles several numeric values and performs and action based on those values. So I have buttons with specific methods to change this values without affecting the rest. However I want to link them all to a final method that runs right after the press of a button, so this way the game will change only when the player chooses to change it and changes according to the players decisions. How can I implement this in my script? Most of my methods are like this public void "ButtonIDGoesHere" (int "SpecificVariable") Add, Sub, Multiply, etc. What can I add so that it goes to a common method right after it executes its instructions?


Instantiate an object and translate it randomly My goal through this code in C is that each time the player presses the Q I create a cube at a fixed position given by another object, then begin translating it in a random direction. ie. first press a cube is created at the spawn point and moves away in direction 1 second press a cube is created at the spawn point and moves away in direction 2 third press a cube is created at the spawn point and moves away in direction 3 I don't understand why the code below does not work using System.Collections using System.Collections.Generic using UnityEngine public class spawn random trajet MonoBehaviour public GameObject Spawn, Spawn2 public Transform origineSpawn public float moveSpeed 5f void Update () if (Input.GetKeyDown (KeyCode.Q)) int random trajet x Random.Range ( 10,10) int random trajet y Random.Range ( 10,10) int random trajet z Random.Range ( 10,10) Spawn2 Instantiate( Spawn, origineSpawn.position, origineSpawn.rotation ) as GameObject transform.Translate ( random trajet x Time.deltaTime moveSpeed, random trajet y Time.deltaTime moveSpeed, random trajet z Time.deltaTime moveSpeed )


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?


How do i make a list of generic classes? First of all, I want mods in my game, as stated in a previous question, I want to do that via registries. Users make content known to the game in the form of 'Registering' it, then it can be used in several other stuff. Registering a block to have it appear on the terrain is one example. Registering is done in the form of events, where each registry has an OnEntryCollection event with a list where other classes subscribe to in order to add Entries, and then it gets invoked to gather said entries. Basically I have a registry system, where there's a large meta registry(The Game registry) that has a list of smaller Registry lt T gt registries, each dedicated to a type (a block, an item, etc). I want to be able to add to these registries via a Registry.Add(T obj) method, but I'm not exactly sure how to do that because in order to store them I had to use an empty interface I made (IRegistry). This is meant to be a way for me to add Entries in through code, from specific files I parse in, while also allowing modders to add in custom content through registry events I will add later. Nothing is meant to be added in through the inspector, rather registered in through events. My code Game Registry SerializeField List lt IRegistry gt registries new List lt IRegistry gt () Registry public class Registry lt T gt IRegistry where T IRegistryEntry Dictionary lt ResourceLocation, T gt EntryDictionary new Dictionary lt ResourceLocation, T gt () public delegate void registryAdditionHandler(List lt T gt entries) public event registryAdditionHandler OnRegisterAddEntries ResourceLocation keyName public Registry(ResourceLocation keyName) this.keyName keyName public void Register(T entry) EntryDictionary.Add(entry.GetRegistryName(), entry) public void Remove(ResourceLocation loc) EntryDictionary.Remove(loc) public T Get(ResourceLocation key) return EntryDictionary key public int Count() return EntryDictionary.Count public bool ContainsEntryKey(ResourceLocation key) return EntryDictionary.ContainsKey(key) public bool ContainsEntryValue(T value) return EntryDictionary.ContainsValue(value) public bool TryGetValue(ResourceLocation key, out T value) if (EntryDictionary.TryGetValue(key,out value)) return true return false public ResourceLocation getRegistryName() return keyName IRegistry interface public interface IRegistry


When do you use StartCoroutine and when Invoke? I am confused. Both seem to do the same thing Delay a method. Both Invoke and StartCoroutine allow you to call a method by name (string). StartCoroutine("functioncalls", 2f) StartCoroutine(functioncalls()) Invoke void Call() Invoke("FunctionCall",2f) void FunctionCall() Debug.Log("this function run") StartCoroutine void Call() StartCoroutine(functioncalls()) IEnumerator functioncalls() yield return new WaitForSeconds(2f) Debug.Log("this function run") Both do the same thing, or not? What exactly is the difference between Invoke and StartCouroutine? In which situation would I use one and when the other?


Unity Emission Material on Top of UI I've already uploaded this question in the Unity forums but only got a response but not an answer or solution. Here's a link to the original post https forum.unity.com threads emission material on top of ui.1032337 ?fbclid IwAR1X3sXn1X8XcEXHXjD3wffiQxuDK6KAjMF57XDv9RUb1FsofklORfDeRm0 In my latest project I tried to do a transition between scenes in the most simple way Darkening the screen. The problem is, when the image goes fully opaque (alpha 1), there are emission materials that are clearly visible quot through quot the image. This only happens to the emission type I'll leave three screenshots, screen before the image gets opaque, the screen after the image goes opaque and my canvas components. Edit Using UniversalRP HighQuality(UniversalRenderPipelineAsset)


how to change default third player controls in unity, to work with touch? I am developing a game for my project using Unity 3d and have currently used the third player controller available in standard asserts. I have to export it in android phone so need to modify the player controls to work with touch inputs... But I am a beginner and finding it very complex to modify the ThirdPersonController script...


Why the lockState of the doors is all the time false even if in the editor I set one of them to true? In the DoorsLockManager in the class DoorClass I changed in the editor one of the lockState to true but when running the game they are all change to false including the one I tried to set to true. Not sure why if I set it to true it's changing back to false. using System.Collections using System.Collections.Generic using System.Linq using UnityEngine ExecuteInEditMode public class DoorsLockManager MonoBehaviour System.Serializable public class DoorClass public bool lockState public DoorClass doorclass private List lt HoriDoorManager gt Doors new List lt HoriDoorManager gt () private void Start() var doors GameObject.FindGameObjectsWithTag("Door") doorclass new DoorClass doors.Length for (int i 0 i lt doors.Length i ) Doors.Add(doors i .GetComponent lt HoriDoorManager gt ()) doorclass i new DoorClass() Doors i .doorLockState doorclass i .lockState And the HoriDoorManager script using UnityEngine using System.Collections using System.Collections.Generic using System.Linq using System public class HoriDoorManager MonoBehaviour public List lt DoorHori gt doors new List lt DoorHori gt () public bool doorLockState private void Awake() if (transform.parent ! null) Transform parent transform.parent var children parent.GetComponentsInChildren lt Transform gt () if (children ! null) foreach (Transform door in children) if (door.name "Door Left" door.name "Door Right") doors.Add(door.GetComponent lt DoorHori gt ()) ColorDoors(Color.red, Color.green, doorLockState) void OnTriggerEnter() if (doorLockState false) if (doors ! null) for(int i 0 i lt doors.Count i ) doors i .OpenDoor() private void ColorDoors(Color red, Color green, bool state) List lt Transform gt children new List lt Transform gt () for (int i 0 i lt doors.Count i ) foreach (Transform child in doors i .GetComponentsInChildren lt Transform gt ()) if (child doors i .transform) continue var renderer child.GetComponent lt Renderer gt () renderer.material.shader Shader.Find("Unlit ShieldFX") if(state true) renderer.material.SetColor(" MainColor", red) else renderer.material.SetColor(" MainColor", green) public bool GetLockState get return doorLockState set doorLockState value


Object not clamping after applying force impulse? I am having issue with clamping the vertical position of my character after applying force. This causes a jittery effect in my character. There are other several ways I think of, but I dont know if its the right way. Use translate, but ive read somewhere that if I am dealing with physics its better that to use addforce. Add an invisible gameobject with a collider to set bounderies. and third is clamp its movement while using addforce which in my case does not work. here is my code which I call on the update. rb player.GetComponent lt Rigidbody2D gt () Vector3 clampedPOS player.transform.position clampedPOS.y Mathf.Clamp(player.transform.position.y, 6f, 4f) player.transform.position clampedPOS rb.AddForce(Vector2.up upForce, ForceMode2D.Impulse) could someone help me with these?


Unity C Modifying eulerAngles with slider issues I'm using a slider to rotate an object on the z axis. The slider has a value of 1 360 (Whole Numbers) when the slider is moved, I use that value for the eulerAngles z axis value. (NOTE The object is part of a child parent 'string' of instantiated objects and it should only ever rotate on the local z axis). This method is working for some objects in the 'string', but not others. When it's not working, the object I'm trying to rotate spins wildly on the z axis because the objects z value is not a reflection of the slider value (I tested this in the inspector). I can't figure where these 'random' slider values are coming from. Here is the rotation function I'm using for the sliders On Value Change event public void SliderRotate () Target.transform.eulerAngles new Vector3( Target.transform.eulerAngles.x, Target.transform.eulerAngles.y, mySlider.GetComponent lt Slider gt ().value) BTW If I change the x and y values to zero, the problem goes away. However, the objects then loose their correct orientation to their parent (I need the x and y to stay where they are). Thanks in advance for any insight you can offer into this issue. Windows Unity 5.3.5f1 Here is an image that might help clarify


Unity Input System On Screen Button doesn't work with touchscreen 2019.3.2f1 I am trying to make my player jump whenever the space button is pressed (if a keyboard is present), and I'm adding a on screen button for players on mobile. The on screen button works fine in the editor but when I try the game in a device the on screen button doesn't work. Here's how things are set up Change the Active Input Handling to Input System Package (New) on the player settings. Create the Jump action for the Player action map. Bind lt Keyboard gt space to my Jump action. Add a PlayerInput component to my player object, pass my actions file to it, and set up the events to call for each action. Change the StandaloneInputModule to an InputSystemUIInputModule in my event system object. In my canvas I add an image and add OnScreenButton component to it (I do NOT add a Button component). Set the control path to lt Keyboard gt space. When I try the game on the device the rest of the UI buttons work fine except the on screen button. On the editor though (using mouse input), the on screen button works fine. This is my first time using the Input System, I had actually found it somewhat nice to work with, however this does seem really strange. It is either a really strange bug (unlikely), or I messed up some setting (the setup process feels really convoluted actually).


Set Non Looping Animation Time to Seconds I have an animation that does not loop. It plays for the default duration (n seconds), then stops on the last frame. This is exactly what I want to have happen, but I want it to play for m seconds, not n seconds. I do not know how long n seconds is. I have to get it exactly to m seconds, because it is a changing variable. So estimating will not work. I need it to match up exactly with another animation. How can I stretch an animation to last an exact number of seconds?


Using a mesh stencil with 2D lighting in the Universal Render Pipeline I've followed the CodeMonkey tutorial on using a dynamic mesh as a stencil for a field of view or visibility polygon effect, and have got it working using the latest version of Unity and its Universal Render Pipeline (I believe this uses a Forward Renderer). I'd like to use the 2D lighting and this requires a 2D Renderer, which I have also got working. Unfortunately I can't figure out a way of combining these. I've got a Universal RenderPipeline and added my 2D Renderer and the Forward Renderer to the renderer list, but it only allows one of these to work (I'd assumed it would trigger in order). How can I get both of these effects working together, or if it isn't possible, is there a recommended approach for combining 2D lighting and stencil masking?


What is a proper way to handle player inputs based on different states? So, I have two ideas how to do that Use enum to define current state and check current state value before running certain method group in Update. Code void Update() switch(currentState) case 1 InputGroup1() break case 2 InputGroup2() break lt ... gt And so on. I don't think that this is a good idea because of possible performance drops. Same concept about current state, but instead of checking it and running method groups, "head" script will check current state and activate corresponding script, disabling others. For me it looks like best way in terms of performance and usability. And also, is it better to keep all input checks in one giant script component and call functions you need from it? Essentially creating centralized Input Manager.


Will importing more items from unity packages increase the build size? I'm developing a GoogleVR (formerly Google Cardboard) application and need to import the GoogleVR SDK. While I only expect to use some of the items available in the Unity package, I'd like to import them all at once and save potential headaches later when I can't find something I might need. However I'm worried that including everything in the project may affect the build size, which would be troublesome on a mobile application.


Unity Why does playModeStateChanged get called after Start? I have this InitializeOnLoad public class MyClass static MyClass() EditorApplication.playModeStateChanged x gt PlaymodeStateChanged() private static void PlaymodeStateChanged() Debug.Log("Play mode changed") and another class with a Debug.Log("Start()") in the Start method. When I hit play I see on the log output Start() Play mode changed Shouldn't playModeStateChanged get called before Start is called on all objects? Any way to go around this? I need this so I can initialize an object before other objects that need to reference this one run Start. Thanks in advance!


Stopping the texture2D from stretching in RawImage I am working with a RawImage texture which is fully stretched, filling up the entire scene. I am using some code to download images from website and then show them on the RawImage, the code is simple, I use WWW to start a download, use WWW.texture as the Image I want to show in RawImage, I do RawImage.texture WWW.texture and then I get the image but the Image is getting scrteched, I don't want to stretch the image but just fill instead, Just like a windows Wallpaper setting. Not to stretch or tile the image but to just fill it. I tried an approach to rotate the image via code but that still leaves some stretching in the image, if I use a portrait image( height is greater than width) I rotate the image from showing in landscape mode(which you can imagine, stretches the image a lot) to portrait mode by using some pixel conversion code, nothing special. Some images are displayed ok, because they fit the native size of the scene but for some stretching occurs. Is it possible to completely remove this stretching? I am surprised Unity doesn't have an option for changing how a texture can be displayed in RawImage. Maybe I am missing something,


Pivot not updating programmatically I have a canvas. It has an empty game object as a child. That object has a RectTransform component. The RectTransform pivot value is set to 0.4, 0.5 (x, y). In some code I wanted to update the pivot value using the following Debug.Log(((RectTransform)transform).pivot) logs (0.4, 0.5) ((RectTransform)transform).pivot.Set(0.3f, 0.8f) Debug.Log(((RectTransform)transform).pivot) logs (0.4, 0.5) I don't know why the set command is not working. The tooltip for Set is "Set x and y components of an existing Vector2"


Integrating accelerometer data samples to get velocity and displacement I am working on an android app built in Unity that would allow the users to track their movements by just using the data coming from the device sensors. I have read about similar issues already and I am aware that this approach doesn't really give any good results in practice, due to the inaccuracy of the sensors, but I still need to measure the performance of this method for research purposes. My implementation makes use of the Unity function InvokeRepeating to fetch the acceleration values at a certain rate and to then calculate the velocity and displacement by using a two step integration private readonly float dt 0.001f private void Start() ... Input.gyro.enabled true Input.gyro.updateInterval 0.001f InvokeRepeating( quot AccelerationSample quot , 0.0f, dt) private void AccelerationSample() Vector3 data Input.gyro.userAcceleration 9.81f Fetch the current acceleration lastAccel data kFilteringFactor lastAccel (1.0f kFilteringFactor) Apply Kalman filter totalAccel data lastAccel Accumulate the acceleration value vel initVel (totalAccel dt) Calculate the current velocity initVel vel Update the initial velocity for the next frames distance vel dt Calculate the distance from the velocity value The raw acceleration values are multiplied by 9.81f to match the real world acceleration (since the values coming from the gyroscope are normalized) and are filtered through a Kalman filter to reduce noise. The acceleration values are accumulated in order to take into consideration both the positive and negative parts of acceleration that the gyroscope provides when the device moves. The velocity and displacement values are then calculated using simple physics formulae. This approach gives decent results when considering acceleration and velocity only. Though the displacement value does not seem to be updating as fast as I expected, and sometimes the calculations go completely off. Also, when the acceleration goes back to zero after any movement, the evaluated velocity does not go down to zero as well, therefore I need to find some conditions under which I can safely reset its value. I hope I was able to properly describe the issue and that some of you might help me to revise my implementation and or give me any hints on how I should go about the problem.


Force Unity To not use computer gpu for testing purpose I want to check that how my game behaving in GPU less pc. For this reason, i want to ask that is there any way to test it? Currently, i am using two pc for this purpose. One is without the GPU. Can i use my same pc and force unity to not use GPU?


Unity game crashing when dialogue with NPC initiated I have 3 NPCs in my "Game". When the player walks up to any of them, they're supposed to have their own dialogue I've tested this, and they do. I tried to create a display that shows this dialogue text using a TextMeshProUGUI attached to a blank GameObject called dialogDisplay (tagged DialogDisplay). There is one DialogDisplay object in the scene that I'm trying to get each of my NPC's to use. I tried to make the display object inactive in the NPC Start() function, and enable it when it's time to display the NPC's next sentence. When I run my game, I get an error on line 21, where SetActive() is called "Object Reference Not Set to an Instance of an Object". Here's the NPC script (DisplayNextSentence() is at the bottom, where dialogDisplay is used) public class NPC Character private bool charInRange public Dialogue dialogue public bool talkedTo false private Queue lt string gt sentences public TextMeshProUGUI textPro public GameObject dialogDisplay private bool isTalking Use this for initialization void Start () charInRange false textPro FindObjectOfType lt TextMeshProUGUI gt () dialogDisplay GameObject.FindGameObjectWithTag("DialogDisplay") dialogDisplay.SetActive(false) Update is called once per frame void Update () if player is in range and presses space, triggers NPC dialogue if (charInRange amp amp Input.GetKeyDown(KeyCode.Space)) TriggerDialogue() if Player gameObject is in NPC collider, player is in range void OnTriggerEnter2D(Collider2D other) if(other.gameObject.tag "Player") charInRange true if player exits NPC collider, player is not in range void OnTriggerExit2D(Collider2D other) if (other.gameObject.tag "Player") charInRange false if NPC has been talked to before, displays next sentence if not, loads dialogue and displays first sentence private void TriggerDialogue() if (!talkedTo) talkedTo true StartDialogue(dialogue) else DisplayNextSentence() loads a queue with lines from Dialogue and displays first sentence public void StartDialogue(Dialogue dialogue) sentences new Queue lt string gt () foreach (string sentence in dialogue.sentences) sentences.Enqueue(sentence) DisplayNextSentence() displays next sentence in the queue public void DisplayNextSentence() string sentence bool done false if last sentence in the queue, display it again if (sentences.Count 1) sentence sentences.Peek() textPro.text sentence Debug.Log(sentence) return sentence sentences.Dequeue() textPro.text sentence dialogDisplay.SetActive(true) while (!done) Debug.Log("In WHile Looop") if (Input.GetKeyDown(KeyCode.A)) done true dialogDisplay.SetActive(false) Grateful for any insight or tips you can provide. Happy to provide further information if it helps. Thank you!


RTS game unit structure I want a way to make a lot of different units without having to program stuff like moveTo and Attack actions more than once The way I see it, there are 2 ways I can do this. A single generic Unit class with flags that specifies what it can can't do (then create instances in a static array and grab them when needed) Abstract unit class with abstract methods for Unit specific actions like (Attack, Harvest, Patrol), which then all need to be implemented in the subclasses, even if the unit can't actually harvest anything. the first way of doing this seems the simplest, but i would end up having a lot of code being unused for the majority of the units. the second way could also work. But if i decide to have two different units that can harvest resources, i'm gonna have the exact same code in two different classes, which doesn't seem like the right way to do it. Is this even the right approach to this problem? In a game like AoE, every unit has, what i presume is, some kind of List of Actions Orders, I would really like to know how to achieve something similar to that, where i can just code each Action Order once, and then give it to all the units that need said Action. If i'm unclear (highly plausible) or you need more information on what exactly i'm looking for, just ask me in a comment.


Question about references I have an enemy game object and an item game object. Enemies have an ItemDrops script attached. Items have a DisplayItemLabel script attached. Attached to each enemy public class ItemDrops MonoBehaviour public Transform itemPrefab private EnemyHealth enemyHealth private float originToGroundDistance private Vector3 offset private bool itemDropped private bool numberGenerated private float randomNumber private ItemData itemData public string nameOfDroppedItem void Start() enemyHealth GetComponent lt EnemyHealth gt () itemData GameObject.Find("Item Manager").GetComponent lt ItemData gt () void Update() Initialized in Update instead of Start because enemy floats to 1.083333 on the Y axis after some time after Start originToGroundDistance transform.position.y 0.25f offset new Vector3(0f, originToGroundDistance, 0f) if (enemyHealth.isDead amp amp !itemDropped) if (!numberGenerated) RandomNumberGenerator() Debug.Log(randomNumber) if (randomNumber lt 1) SpawnItem(itemData.coin) private void RandomNumberGenerator() numberGenerated true randomNumber Random.value private void SpawnItem(Item item) itemDropped true nameOfDroppedItem item.itemName Instantiate(itemPrefab, transform.position offset, Quaternion.identity) Attached to each item public class DisplayItemLabel MonoBehaviour private GameObject itemLabel private Text itemNameText void Start() itemLabel transform.Find("Canvas Item Label").gameObject itemNameText itemLabel.GetComponentInChildren lt Text gt () itemNameText.text "Item Name" itemLabel.SetActive(false) void Update() ClampLabelToItem() private void ClampLabelToItem() Vector3 offset new Vector3(0f, 16f, 0f) Vector3 desiredPosition Camera.main.WorldToScreenPoint(transform.position) offset itemLabel.transform.position desiredPosition itemLabel.SetActive(true) Item is not a child of enemy for multiple reasons I can think of. One is that enemies are destroyed when they are killed. With that said, how do I get the item to know who dropped it or get the enemy to know which item it dropped? MY GOAL is to get itemNameText.text "Item Name" to say something like itemNameText.text itemDrops.NameOfDroppedItem but I can't use GameObject.FindGameObjectWithTag("Enemy").GetComponent lt ItemDrops gt () because it won't always grab the correct enemy and thus the correct ItemDrops script. I also can't set DisplayItemLabel.itemNameText.text nameOfDroppedItem in the SpawnItem function because it wouldn't know which item's DisplayItemLabel script to get. So clearly, I'm having issues with references. What should I do?


Animation with pivot modification in Mecanim Assume I have two animation cycles Walking Crouching Both assume that the model's pivot is on the same level as the model's feet. Now I also have two animated transitions Get on all fours while walking Climb onto a (table) The first is not too complex. The model walks upright, then gets down on all fours (animation 1) and crouches. Pivot remains on the same level, all fine. What I want However, I can't get my head around the second transition. I want the model to walk up to the table (pivot on ground level) climb onto the table (animation 2) (pivot..?) crouch on the table (pivot on table level, 1 m above ground) What I have The climbing animation (2) assumes pivot to remain on ground level and simply animates the model's climbing up. I built a StateMachineBehaviour which raises the model to the table level as soon as the climbing animation is complete. From then on the pivot is on table level and the crouching can continue. This seems to work fine in a standalone application, however, in multiplayer, where the models' transform and animator state are not necessarily synchronized in the same frame, this prooves problematic. One can clearly see the model jump when the change in the model's position arrives one frame earlier than the switch from climbing to crouching animation. What I tried I thought it might be a better idea to have the pivot move gradually from ground level to table level over the duration of the climbing animation (2), instead of having one instant jump at the end. This way network synchronization would be much more robust because of the relatively small change per frame. Also this approach would much closer resemble the actual thing that's happening in the real world, which is generally a good thing. I tried offsetting the root transformation of the animation clip, and accomodate the modification by adding the negative offset to the root bones. This however did not work, as there seems to be no animatable translations in Mecanim animation clips. So im stuck at this approach. Question Is there a better way? A simpler way? How are you guys tackling this?


Can't drag image onto scene First time trying Unity and I'm having trouble with importing assets. border horizontal.png is fine, but I can't drag border vertical.png onto my scene. It also doesn't have an arrow next to it in the asset menu. What is going on here?


Flow effect to static water on a isometric city Hello everyone I want to give the idea that the river in my city is flowing but I am having an hard time to figure how. Do you have any idea of what I should look into to?


Animated textures for models How to write a shader? Was watching some Rocket League and notice there was animated decals and wheels. . I would like to implement something similar to the effects in the image above. How would I go about writing a Unity Shader to do the wheel effect? I don't know much about Shaders, but can I edit the standard Unity Shader to do the animation effect?


Best client server architecture for a mobile management game? For the past year I have worked on a small company that develops a traditional browser based strategy game, of the likes of Travian or Ogame, but using a more interactive approach like Tribal Wars 2. The game is made in a simple php server without frameworks and a simple mysql database, and all of the game happens in a single static page that is changed through ajax calls and has a map made in pixi.js. The automatic updates are delivered to the client side through polling the server which then queries some specific database tables made for the purpose for changes. While this approach is solid and works, it has 2 big problems Having a mobile app is increasingly more important and there are not enough resources for having two separate codebases. Having a app which is simply a wrapped webview is also not a solution because the performance of a really complex page with a giant webgl map is, while usable, really subpar Polling the server for changes creates a lot of programing challanges that make some simple tasks really complicated and creates a lot of convoluted code if we dont want to hurt the game performance, as we are not going make dozens of database queries every 5 seconds. I want to start developing a game idea that I have that is basically inserted in the same genre and which is going to be, at least initially, mobile only. The real problem here is that after reading a lot on the internet, I am confused on what should be a good client server architecture for me to start prototyping in a way that I do not run in the problems mentioned above. Basically, above all, I want the server to be able to know which page screen state is each client looking at, and be able to send them messages when another client changes something on that specific screen. It would also be nice if the solution is something lightweight on the server side to be able to scale a little. Client side I was thinking about Unity because of being cross platform, of all the environment around it (ads, analytics, a lot of support and answers on the internet), and because I have previous development experience with it. Server side is the real question. Simple http calls will not work and so PHP is out of the equation. I have though about using node.js with socket.io to use websockets solving the polling problem. Is this a good idea? Would it be better to store the game state in a relational or nosql database in this case? Would this work on unstable mobile conections? Lots of people seem to use a c and sockets for unity. Would this be overkill in this situation? Taking this approach how would the data be stored? would it be feasible with a linux server or would I need a windows server? Would this work on unstable mobile conections? Don't know, I'm open to suggestions. tl dr I want to make a mobile management game in unity but am confused what to choose for the server side architecture considering that I want the server to be ablose to send a message to the client without the client asking for it. Is there anything I should take in account? Sorry for the broad question and thanks for the help.


What sprite size should I use for 2D game? I try to create a 2D game for Android. It looks like Cut the rope (it isn't a clone but it have same level representation) if it has a value. My problem that I can't understand that optimal sprite sizes I should use. I.e. what target screen resolution should I use to sprites didn't have anomalies on HD devices (like Samsung Galaxy S7 and etc., phones and tablets)? To make my question is clearer I ask about this 1 unit X pixels for xxhdpi screens. What is X? P.S. Sorry if it's a duplicate I will be grateful for link on this post cuz I couldn't find it.


How can I check if component is enabled? using System.Collections using System.Collections.Generic using UnityEngine public class CameraInformation MonoBehaviour public string currentCameraState Start is called before the first frame update void Start() var components new List lt Component gt () foreach (var component in GetComponents lt Component gt ()) if (component ! this) var fullName component.GetType().FullName if (fullName.StartsWith( quot Cinemachine quot )) currentCameraState component. Update is called once per frame void Update() private void OnEnable() private void OnDisable() At this line I want to assign the string the component status if it's enabled true or false.


Unity Android Immersive mode leaving a black bar in the soft key area? The black bar is not hiding anything. Everything is drawn above it. But the black bar is there in place of the soft keys even when they are hidden. I don't know how to hide it and render using whole screen. The bar is only visible with device having soft keys not for device with physical keys. I have set the Screen.fullScreen true. Unity 2018.3.4f1


Adding underwater shadow to 2D top down boat I have a boat hovercraft sprite in my game. It's topdown 2D view, but it's actually a 3D scene, for better lighting and other effects. I want to add a buoyancy effect, so that the hovercraft floats with the waves and has a little margin for going under water, like a real boat. So when idle or when going off a ramp, when landing in the water it will kinda "bounce" a bit under and then back up. But the problem is the water and boat sprites are on top of each other (because it's 2D). See this picture So it can not go underwater, because then the water will be on top. But I still want those edges of the vehicle to be a bit darker as it floats. I already have an effect that changes the Y value to make it float up and down. But now the edges have to become a bit darker to show they go underwater. I kinda have this idea to add a 3D capsule and make it move up and down through the sprite to simulate this So as the boat and the capsule go down with each wave, it could mask the sprite, and the visible part (marked with black lines in the image below) could be made darker. To simulate the "under water" effect. Later I will also add foam and stuff, but the first problem is the underwater part. So how could I mask my sprite inside this capsule, and more importantly, make the "outsides" (so the parts of the sprite not touching the capsule darker? Any help would be greatly appreciated! )


Unity 2D switch direction in an auto runner I'm new to Unity and I'm trying to make a 2d endless runner (something like Super Meat Boy Forever), and one idea was that when the player touches a wall he would change direction. I tried to implement the mechanic, but in game is very strange and buggy. My idea was to change the speed value from positive to negative and vice versa when the character collides to a wall (I used a layer mask for that). If someone could help me I would be very grateful. Here is the code using System.Collections using System.Collections.Generic using UnityEngine public class Movement MonoBehaviour public float speed public float jumpForce private Rigidbody2D rb public bool grounded public bool walled public LayerMask whatIsGround public LayerMask whatIsWall private Collider2D myCollider Start is called before the first frame update void Start() rb GetComponent lt Rigidbody2D gt () myCollider GetComponent lt Collider2D gt () Update is called once per frame void Update() grounded Physics2D.IsTouchingLayers(myCollider, whatIsGround) walled Physics2D.IsTouchingLayers(myCollider, whatIsWall) rb.velocity new Vector2(speed, rb.velocity.y) if (Input.GetKeyDown(KeyCode.Space) Input.GetMouseButtonDown(0)) if (grounded) rb.velocity new Vector2(rb.velocity.x, jumpForce) if (walled) speed speed


With a Texture Atlas that has 128x128 tiles, how can I use that in Unity3D? So I've got a working texture atlas that has tiles fitting 128x128. However, I can't quite figure out how to use them. I know it's probably got something to do with TileRenderer.material.SetTextureScale(" MainTex", new Vector2(0.25f, 0.25f)) TileRenderer.material.SetTextureOffset(" MainTex", new Vector2(0 0.25f,0)) but I'm not sure where to take it from there. Can anyone offer some advice? The size of the image is 1024x128 if that helps, which I think it might.


How to draw a line in 3d space? I have a top down billiard game. And on click tap the ball moves in the clicked direction like in the image below Now, I want a line to be drawn in the direction where the mouse is hovers or the finger is swiped, here is my update code void Update () this should make the line, why not working? Vector3 forward transform.forward Debug.DrawRay(transform.position, forward) Debug.DrawLine(transform.position, transform.position forward 10000) if (Input.GetMouseButtonDown (0)) Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit, 100.0f)) Vector3 startPos transform.position Vector3 clickPos new Vector3(hit.point.x, hit.point.y, transform.position.z) Vector3 direction Direction (clickPos startPos) direction rb.velocity new Vector3(direction.x 5, direction.y 5, 0) I tried DrawLine, Drawray, any ideas?


Environment collision in a pseudo 3d 2d space The game is a 2D brawler with depth movement in the vein of Golden Axe, Final Fight, Castle Crashers etc. Characters and environment are all 2d sprites as well. I've had no real issue setting up collision between characters to take the depth into account either. However, it's just not a proper brawler without higher ground to jump to and pits to throw the enemy into, and that is where I run into a bit of an issue with how best to implement it. I considered making the collision boxes for the level in the 3D space and having the sprites just translate the z movement of their game object into y movement of the visual component, but I don't particularly like that approach because it feels difficult to work with for doing the level design of matching 3D colliders to a drawn backdrop and placing objects in there. Any suggestions for a design that is the 2D first, so to speak? Ideally being able to "paint" height levels and pits in the 2D design wise. If it matters, I'm working in unity with a primarily 2d space (though involving the third dimension here will be necessary), but I think the base design problem would be fairly engine language agnostic.


Why Sorting process not happening? I created 10000 array and assigned value 1 and 0 to it, then used gizmos to generate 10000 cubes. I paint it black or white depending on the assigned value. After that I use the bubble sort algorithm to sort the cubes, expecting all black cubes pieled on the bottom but when I run it, the sorting does not happen and I can't spot where my mistake is. using UnityEngine public class NewBehaviourScript MonoBehaviour int x int y int z int , array1 new int 100, 100 int temp Start is called before the first frame update void Start() for (x 0 x lt 100 x ) for (y 0 y lt 100 y ) array1 x, y Random.Range(0, 2) Debug.Log(string.Format( quot 0 , 1 , 2 quot , x, y, array1 x, y )) OnDrawGizmos() void OnDrawGizmos() for (x 0 x lt 100 x ) for (y 0 y lt 100 y ) Vector2 pos1 new Vector2(0 x, 0 y) Gizmos.DrawCube(pos1, transform.position) Gizmos.color (array1 x, y 1) ? Color.black Color.white void update() for (z 0 z lt 100 z ) for (x 0 x lt 100 x ) for (y 0 y lt 100 z y ) if (array1 x, y gt array1 x, y 1 ) temp array1 x, y array1 x 1, y array1 x, y array1 x, y temp OnDrawGizmos()


How can I use another script from a script? The first script is very long, and I need to use only the top of it using System using System.Collections using System.Collections.Generic using UnityEngine public class mBitmap2MeshV30a MonoBehaviour public Texture2D SourceTexture private float Pixel vs Unit Scale 1 public float extrudeDepth 1 private Vector2 scanpoint private bool gotStart false private int maxsteps 512 public bool invertFaces false private Mesh srcMesh private mMeshExtrusion2.Edge precomputedEdges private List lt ExtrudedTrailSectionBM3 gt sections public class ExtrudedTrailSectionBM3 public Vector3 point public Matrix4x4 matrix public float time I need to assign a value to SourceTexture from another script. This is the other script void Start () text2d new Texture2D(10, 10, TextureFormat.ARGB32, false) System.Drawing.Font myf new System.Drawing.Font(FontFamily.GenericSerif, 12) Image myimage DrawText("Hello", myf, System.Drawing.Color.Red, System.Drawing.Color.Black) Bitmap mybitmap new Bitmap(myimage) MemoryStream msFinger new MemoryStream() mybitmap.Save(msFinger, mybitmap.RawFormat) text2d.LoadImage(msFinger.ToArray()) filter.GetComponent lt Renderer gt ().material.mainTexture text2d mBitmap2MeshV30a bb new mBitmap2MeshV30a() bb.SourceTexture text2d The problem is I can't make a new mBitmap2MeshV30a bb new mBitmap2MeshV30a() . Both scripts are attached to the same GameObject, in the hierarchy.


How to use Left Shift to run Unity? So, I need to use LShift to run, but I can't exactly figure out how to do so.... I don't know what to use.... Here my code using UnityEngine using System.Collections This script moves the character controller forward and sideways based on the arrow keys. It also jumps when pressing space. Make sure to attach a character controller to the same game object. It is recommended that you make only one call to Move or SimpleMove per frame. public class Move MonoBehaviour CharacterController characterController public float speed 6.0f public float jumpSpeed 8.0f public float gravity 20.0f public Transform charBody private Vector3 moveDirection Vector3.zero public float mouseSense 11f public float runSpeed 12f public bool isRunning false void Start() characterController GetComponent lt CharacterController gt () void Update() if (characterController.isGrounded) We are grounded, so recalculate move direction directly from axes moveDirection transform.forward Input.GetAxis( quot Horizontal quot ) transform.right Input.GetAxis( quot Vertical quot ) moveDirection speed moveDirection transform.right Input.GetAxis( quot Horizontal quot ) transform.right Input.GetAxis( quot Vertical quot ) moveDirection speed if (Input.GetButton( quot Jump quot )) moveDirection.y jumpSpeed Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below when the moveDirection is multiplied by deltaTime). This is because gravity should be applied as an acceleration (ms 2) moveDirection.y gravity Time.deltaTime Move the controller characterController.Move(moveDirection Time.deltaTime) float MOUSEY Input.GetAxis( quot Mouse Y quot ) mouseSense Time.deltaTime float MOUSEX Input.GetAxis( quot Mouse X quot ) mouseSense Time.deltaTime charBody.Rotate(Vector3.up MOUSEX) So, when left shift is clicked I want the speed to change to runSpeed... Can I please have some help doing so? Thanks


How to render the sprites for a 2D soft body physics system This is not a question as to how to achieve soft body physics, but rather if I have a mass spring system how to modify a sprite with that information. I am using unity so I dont have access to vector based graphics.