In 2D, how can I improve character rotation using raycasts when dealing with sharp convex edges? Edit After making some edits to my polygon collider (based on Alex F's suggestion), I can indeed confirm that sharp, convex corners are causing the buggy rotation. For now I've decided to only rotate my character if its moving, so standing on a corner when velocity.x 0 won't cause my collider to rotate rapidly. However, this seems like a band aid fix, and I'm still wondering if there's a better way to handle these edges. Resuming movement after idling on a corner still causes some buggy behavior, and I'm concerned that this will compound once my rotations become more complicated or frequent Original question I'm quite inexperienced with quaternions and rotating, so I'm not entirely sure if this issue has to do with my code, the collisions shown in this question, or my game design. What I'm trying to achieve is "smooth" rotation of my character's collider based on the normal of the current surface. I've been creating a custom raycast controller in 2D from the ground up, and already know how to find all kinds of information from rays, such as the current angle of a sloped surface. My controller is coming along quite nicely, and rotation is one of the last things I'd like to tackle. It should be able to handle sloped box colliders, but also irregular ground shapes that require something like a polygon collider. I've been somewhat successful, having learned that I shouldn't set my character's z rotation directly, but instead update my entire transform.rotation with a method like Quaternion.Lerp. This has worked generally well, but I'm running into issues on irregular ground, and on corners. Notice the smooth transition from flat to sloped surfaces, but that my collider rotates rapidly when the raycast hits a corner Movement is still somewhat smooth on irregular terrain, but there is a noticeable shakiness at times. Sometimes my character's collider rotates rapidly as well (end of gif) I suspect that the shakiness on the irregular terrain is just my collider getting "caught" on the many edges that the polygon collider creates. I just don't know if this is happening because I could be doing something differently in my code, or if I need to edit the polygon collider, or is caused by something else entirely. Perhaps raycasting isn't the best way to achieve my desired behavior. SerializeField private float speed 5 SerializeField private float gravity 20 SerializeField private LayerMask collisionMask private BoxCollider2D boxCollider private Vector2 velocity private Vector2 groundNormal private void Awake() boxCollider GetComponent lt BoxCollider2D gt () private void Update() float playerInput Input.GetAxisRaw("Horizontal") velocity.x playerInput speed velocity.y gravity Time.deltaTime MoveCharacter(velocity Time.deltaTime) private void MoveCharacter(Vector2 velocity) Rotate the character Quaternion targetRotation Quaternion.FromToRotation(Vector2.up, groundNormal) transform.rotation Quaternion.Lerp(transform.rotation, targetRotation, 0.5f) groundNormal Vector2.zero CollideBelow(ref velocity) transform.Translate(velocity) private void CollideBelow(ref Vector2 deltaMovement) float rayLength 1 Vector2 rayOrigin transform.position RaycastHit2D hit Physics2D.Raycast(rayOrigin, transform.up, rayLength, collisionMask) Debug.DrawRay(rayOrigin, transform.up rayLength, Color.red) if (hit) velocity.y 0 deltaMovement.y (hit.distance boxCollider.size.y 0.5f) groundNormal hit.normal


Fixing text on the screen for Oculus Rift I would like to fix text to the screen for an Oculus Rift in Unity. The text should say something like "get comfortable and then press any key". It seems like OVRGUI.StereoBox should work for this and I've tried to copy an example I found on Github, like so public class TargetScript MonoBehaviour void OnGUI() Debug.Log("Drawing Recenter dialog.") string loading "LOADING..." OVRGUI guiHelper new OVRGUI() guiHelper.StereoBox(300, 300, 300, 300, ref loading, Color.white) Debug.Log("Stereo Box should be visible.") Debug.Log (guiHelper) The log messages indicate that this code block is definitely being hit, but no text is visible on screen. What am I doing wrong?


Tile Palette problem in Unity I am working on isometric tilemap in Unity 2019.4.8f1. In the Tile Palette panel, the selection is always 1 block away. Please see this screenshot In the screenshot, apparently I selected an empty tile, but in fact I am select the green tile with flowers. How come? Every selection is one tile away. The same issue happens in the Tilemap selection mode too. I have to select the adjacent tile in order to select the tile I want. How do I fix it? It's quite annoying. UPDATE I have added the settings of Grid, Tilemap as well as the import settings of the tile sprite sheet below. UPDATE 2 Changed the Pivot in Sprite Editor to Bottom Center Recreated the Tile Palette, and it looks like hovering 0.5 unit up.


Getting world space vertex coordinates in Unity I'd like to get world space coordinates for a specific mesh vertex. Transform.TransformPoint() seems to be what I need however I'm unable to get the correct position. In the scene I have an object called "head" at Pos (0, 0, 0) Scale (0.03, 0.03, 0.03) and I'm trying to get the position of vertex id 590 in order to spawn another object at that specific location. Mesh mesh GameObject.Find ("head").GetComponent lt MeshFilter gt ().mesh Vector3 vertices mesh.vertices Vector3 newPos transform.TransformPoint (vertices 590 ) Debug.Log (newPos) The value of newPos is not on the head object.


Press and hold camera movement with mouse in new Input System? I am transitioning to the new movement system and am having trouble figuring out how to move the camera when a mouse button is pressed and held. Here's how I did it before private void Update() Get the position of the mouse when a middle click occurs if (Input.GetMouseButtonDown(2)) dragOrigin cam.ScreenToWorldPoint(Input.mousePosition) If the MMB is still held down, calculate the distance and move the camera if (Input.GetMouseButton(2)) Vector3 difference dragOrigin cam.ScreenToWorldPoint(Input.mousePosition) cam.transform.position difference I have tried doing something similar in the new input system but it doesn't work public void OnMMB(InputAction.CallbackContext context) if (context.phase ! InputActionPhase.Started) Get the position of the mouse when a middle click occurs dragOrigin cam.ScreenToWorldPoint(Mouse.current.position.ReadValue()) else If the MMB is still held down, calculate the distance and move the camera Vector2 newPosition cam.ScreenToWorldPoint(Mouse.current.position.ReadValue()) Vector3 difference dragOrigin newPosition cam.transform.position difference Here is how I set this up inside the Input editor The Action Type of the action is Button.


Get the dropped object using IDropHandler.OnDrop In Canvas, I drag some UI objects to a panel using this code public void OnDrag(PointerEventData eventData) Vector3 screenPoint Input.mousePosition screenPoint.z 10.0f Item2Drag.position Camera.main.ScreenToWorldPoint(screenPoint) But what I can't figure out is when I dropped an object on the panel, how can I get the gameObject which has been dropped?


Unity getting Input from UI So I'm trying to get a script of mine to pass information to another static class being used for saving files as I've been told I wouldn't want that script to be instantiated. So I used a separate script to get input field text. However, I seem to be encountering a problem whenever I want to save the file. I keep getting the error "Object reference not set to an instance of the object", I have made done this though. (See code below) The class to get the name of the file public class SaveInputField MonoBehaviour public static string saveName public GameObject inputField public void getFileName(string saveName) saveName inputField.GetComponent lt Text gt ().text Debug.Log("Save file name " saveName) SaveFile.saveName saveName called whenever its been edited The static class public static class SaveFile public static string saveName public static void SaveData(Deck deck) BinaryFormatter formatter new BinaryFormatter() string path Application.persistentDataPath " " saveName ".dd" FileStream stream new FileStream(path, FileMode.Create) Debug.Log("Stream Opened") DeckData data new DeckData(deck) formatter.Serialize(stream, data) stream.Close() Debug.Log("Stream Closed")


How can I display Unity games in Flex? We have tried the following methods to upload sample Unity3D build to a desktop application in Flex HTML Loader, NavigateToURL, iFrame and resolvePath. But we only see the text content, not the 3D content. What is the solution for that? How can I host a Unity game inside Flex?


How do I reference a particular UI Image or Sprite in my assets folder? I have an Item class, and I want to associate an Image class with it. How do I get a reference to the intended Image, from my assets folder, in order to provide it as a reference to a constructor for Item? Here is my code using System.Collections.Generic using UnityEngine using UnityEngine.UI public class ItemData MonoBehaviour private List lt Item gt items void Start() items new List lt Item gt () Item sword new Item(0, "Sword", What goes here? ) items.Add(sword) Item hammer new Item(0, "Hammer", What goes here? ) items.Add(hammer) public class Item public int itemID public string itemName public Image itemImage public Item(int newItemID, string newItemName, Image newItemImage) itemID newItemID itemName newItemName itemImage newItemImage


Why my Edit Collider in Unity2D has no point to adjust size? Why when I clicked to Edit Collider of Box Collider 2D component, is not showing points for me resize the collide box?


How to make unitypackage from allseen alliance's android sdk? Im making an offline multiplayer for Android device by Unity and I found only one way to do this is the allseenalliance sdk. After download its from here I found that to use it I need to create an .unitypackage file but I cant understand the tutorial they give gt Open a CMD window. gt Add the path to Unity.exe (the Unity IDE) to your PATH, if it is not there already. gt For example, set PATH PATH C Program Files Unity Editor gt CD to each quot unity quot folder in the SDK, and run the following command in each location gt Unity.exe batchmode nographics quit projectPath CD exportPackage Assets AllJoyn.unitypackage gt This command creates the AllJoyn.unitypackage file. Please give me a noob tutorial for this or the package file, thanks. p s Is there another way to connect mobile device without internet in unity3d?


How to temporarily increase the speed of a character in a Unity game As the title would suggest, I want to give a character a speed boost for x amount of seconds, while increasing their Gameobject's mass. During this little speed boost, I also want to add a script to another player that disappears when the speed boost dies out I am new to C , and Unity in general, any help would be appreciated. using System.Collections using System.Collections.Generic using UnityEngine public class PlayerAddMass MonoBehaviour Start is called before the first frame update void Start() Update is called once per frame void Update() if (Input.GetKey(KeyCode.Q)) rb GetComponent lt Rigidbody gt () rb.mass 10 rb GetComponent lt Rigidbody gt () rb.speed 5 The code above was found on a unity website of some sorts, and I modified it to set the speed and mass numbers (I changed the 0s into a 10 and a 5) The errors I get are "rb does not exist in the current context" x 4


Problem with Animating on local position Unity Currently, I am having a Cube that needs to be animated to roll on its edge. Using unity built in animation feature, I created 4 animations (RotateUp, RotateDown, RotateLeft, RotateRight). At the end of each animation I would put an Event to call a method on my script. To be able to move the object every time the animation is played, I put the cube with animator attached inside a parent object. Below is the script attached to my cube. using System.Collections using System.Collections.Generic using UnityEngine public class RedCubeBehavior MonoBehaviour Animator anim bool isMoveTriggered false void Start() anim gameObject.GetComponent lt Animator gt () void Update() if (Input.GetKeyDown(KeyCode.UpArrow)) MoveUp() else if (Input.GetKeyDown(KeyCode.DownArrow)) MoveDown() else if (Input.GetKeyDown(KeyCode.LeftArrow)) MoveLeft() else if (Input.GetKeyDown(KeyCode.RightArrow)) MoveRight() if (isMoveTriggered) if (IsBackToIdle()) transform.parent.position transform.position transform.localPosition Vector3.zero isMoveTriggered false void AnimationFinished() anim.Play("IdleState") public void MoveUp() if (isMoveTriggered) return else Debug.Log("MoveUp") isMoveTriggered true anim.Play("RotateUp") public void MoveDown() if (isMoveTriggered) return else Debug.Log("MoveDown") isMoveTriggered true anim.Play("RotateDown") public void MoveLeft() if (isMoveTriggered) return else Debug.Log("MoveLeft") isMoveTriggered true anim.Play("RotateLeft") public void MoveRight() if (isMoveTriggered) return else Debug.Log("MoveRight") isMoveTriggered true anim.Play("RotateRight") bool IsBackToIdle() return anim.GetCurrentAnimatorStateInfo(0).IsName("IdleState") Every time the arrow key is pressed the object would rotate but in the end when AnimationFinished() is called, the cube would just roll back to its starting position (because of playing IdleState). It will only work (the object didn't return to its starting position) if I pressed the arrow twice quickly. I've tried to not call the IdleState (which is only an empty state), but what happens next is it just won't play another animation again when triggered. What should I do in order to get it work without having to press the key twice?


Adding hotbar to inventory? I have a inventory and I need to add a hotbar to access certain items. What this hotbar needs to do is when in the inventory "Menu" you add items to it and when you close the menu the hotbar moves to the bottom of the screen and you select and item, weapon, food ect, and can use it (like in Minecraft). My problem is I don't know whether I should Keep track of which items are in hotbar "spaces" of the inventory and use them accordingly, or Make a separate list for hotbar items and move them between the inventory and hotbar lists when needed or a third way I did not even think of. My inventory works by having items in a list. The item class has values such as dmg, uses, name, etc. I have an item data class I put on GameObjects that has a public item variable. I have an inventory UI class that takes the inventory list and displays them.


How do I change the game object on a button click? I have a five game objects (ornament1, ornament2, ornament3, ornament4 and ornament5) and two buttons ("Next" and "Previous"). When I click "Next", the object should change from ornament1 to ornament2. When I click "Next", again, it should change from ornament2to ornament3 when I then click "Previous" it should change from ornament3to ornament2. I have the "Next" button working, but the "Previous" button is not working. How do I change the game object on a button click? Here is my code if(GUI.Button(new Rect(10, 20, 80, 50), "Ornament1")) Debug.Log("hhhhhhhhhhhhhhhhhhhhhhh" countbool) if(count 0) Debug.Log("hhhhhhhhhhhhhhhhhhhhhhh") ornament1.transform.position new Vector3( 0.1428955f, 0.1894745f, 4.108555f) ornament1.SetActive(true) ornament2.SetActive(false) ornament3.SetActive(false) ornament4.SetActive(false) ornament5.SetActive(false) count else if(count 1) ornament2.transform.position new Vector3( 0.1428955f, 0.1894745f, 4.108555f) ornament2.SetActive(true) ornament1.SetActive(false) ornament3.SetActive(false) ornament4.SetActive(false) ornament5.SetActive(false) count else if(count 2) ornament3.transform.position new Vector3( 0.1428955f, 0.1894745f, 4.108555f) ornament3.SetActive(true) ornament1.SetActive(false) ornament2.SetActive(false) ornament4.SetActive(false) ornament5.SetActive(false) count else if(count 3) ornament4.transform.position new Vector3( 0.1428955f, 0.1894745f, 4.108555f) ornament4.SetActive(true) ornament3.SetActive(false) ornament1.SetActive(false) ornament2.SetActive(false) ornament5.SetActive(false) count else if(count 4) ornament1.SetActive(true) ornament5.transform.position new Vector3( 0.1428955f, 0.1894745f, 4.108555f) ornament5.SetActive(true) ornament3.SetActive(false) ornament1.SetActive(false) ornament2.SetActive(false) ornament4.SetActive(false) count


How to create a material that blends textures in Blender to Unity workflow I'm new to Blender and Unity and trying to figure out the best way to create a material that will use either vertex colors or a texture map to interpolate between other textures on a single mesh. This is the sort of effect you might use when you want to have a big grassy terrain mesh with a dirt path running down the middle of it and patches of rock here and there and instead of modeling each of those as separate pieces, you create a single shader that takes a grass, dirt and rock texture map and uses a fourth blending map to decide which to sample from. I come from a Maya background which provides an HLSL material shader that makes this straight forward. It's not as clear to me how to do this in Blender, and in particular the best way to set it up so that it imports into Unity cleanly. I suspect that setting up the shader using Blender's cycles shading network won't create anything Unity can recognize. Blender also has the Open Shading language, but again I'm unsure how well this will work with Unity. I could also bake all my textures, but this strikes me as wasteful of memory and bandwidth. I have experience with both HLSL and GLSL. Is trying to do this with custom shaders the best way to do about things? What's the best way to set things up so that both Blender and Unity are happy?


How do I activate a game action when a UI button is held? I want to make my button do stuff when the player holds it. In this case, I want to make a grab function when the button is down the character can grab objects, but if the button is up they do not grab it. I already have the function using the Standard Assets CrossPlatformInput. Here is how I have configured my button so far Here is my script void Update() Physics2D.queriesStartInColliders false RaycastHit2D hit Physics2D.Raycast(transform.position, Vector2.right transform.localScale.x, distance, boxMask) if (PushKey()) isGrab !isGrab if (hit.collider ! null amp amp hit.collider.gameObject.tag quot Box quot amp amp isGrab) box hit.collider.gameObject box.GetComponent lt FixedJoint2D gt ().connectedBody this.GetComponent lt Rigidbody2D gt () box.GetComponent lt FixedJoint2D gt ().enabled true box.GetComponent lt Rigidbody2D gt ().gravityScale 1 box.GetComponent lt Rigidbody2D gt ().mass 1 else if (!isGrab) box.GetComponent lt FixedJoint2D gt ().enabled false box.GetComponent lt Rigidbody2D gt ().gravityScale 6 box.GetComponent lt Rigidbody2D gt ().mass 6 public bool PushKey() return CrossPlatformInputManager.GetButtonDown( quot E quot ) With this function, the first tap on the button means quot grab activated quot and the second tap means quot grab deactivated quot , like a toggle. Instead, I want the grab to be active as long as the button is held.


lightmap equivalent with realtime shadow i'm using in Unity free edition. I try to bake a lightmap which equivalent feeling with Unity's real time light map and shadowing, like left figure. But the result is the right figure. How can i set a paremters of lighting window to get result like left figure? added here's all of screenshots.


Transform inputs don't work I'm writing a C player script for a class and when I run, the sound inputs work fine, but the movement inputs don't respond, and I don't know how to fix it. Code Rigidbody rigidbody AudioSource audioSource void Start() rigidbody GetComponent lt Rigidbody gt () audioSource GetComponent lt AudioSource gt () void Update() ProcessInputs() private void ProcessInputs() if (Input.GetKey(KeyCode.Space)) rigidbody.AddRelativeForce(Vector3.up) if (!audioSource.isPlaying) audioSource.Play() else audioSource.Stop() if (Input.GetKey(KeyCode.A)) transform.Rotate(Vector3.forward) if (Input.GetKey(KeyCode.D)) transform.Rotate( Vector3.forward)


Why isn't my method an option for onClick? Update The problem went away when I restarted Unity and tried again. The problem I am using Unity 2019.1.8f1 Personal with Visual Studio for Mac 7.8.4. I have a button named Refresh I would like its onClick handler to be the public instance method Refresh() in the class Libretto. My GameView has the Libretto script as a component The script Libretto.cs includes using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI using UnityEngine.Assertions public class Libretto MonoBehaviour, IInputHandler Other members omitted public void Refresh() Code omitted My scene Scene Libretto has a Canvas that contains a Button named Refresh In the onClick() section of the Refresh component, I selected GameView, which is a GameObject When I try setting the function, the method Libretto.Refresh() is not an option Attempted solutions Searching online, I have found these solutions, none of which work for me The method must be public. (It is.) The method must be void with 0 or 1 parameters. (It is void with 0 parameters.) The script should contain using UnityEngine.UI (It does.) Try creating a new object with just the script and use that. (This makes no difference.) Your code must compile with no errors. (It does.) Full project I have tried to make my question complete, but, if anyone wants to look at my code, it is available on GitHub in espertus UnityWordGames (a fork of Roger Engelbert's code from his book Word Games With Unity). A sibling scene, Scene Crossing, in the same project has a similar Refresh button and Refresh() method that work properly. Update It worked after I restarted Unity.


Raycast in Unity for ground detection returns false while touching ground I'm using a raycast to detect the player's distance to the ground for a hovercraft game. The raycast works correctly (returns true and also returns the distance to the first impact) until the moment the craft actually touches the ground. When the player hits the ground, the raycast should theoretically return true and return the distance as near 0f. Instead, it returns false, meaning the raycast isn't colliding with anything over the length of the ray. As a result, it can't find the distance. I'm having a hard time troubleshooting this, and I wonder if anyone can lend a fresh pair of eyes. Ray ray new Ray (transform.position, Vector3.down) RaycastHit ray result bool hit ground Physics.Raycast (ray, out ray result, optimal vertical distance 2) if (ray result.distance lt optimal vertical distance amp amp vertical force lt max vertical force) vertical force vertical acceleration if ((!hit ground ray result.distance gt optimal vertical distance) amp amp vertical force gt min vertical force) vertical force vertical acceleration body.AddForce (Vector3.up vertical force, ForceMode.Acceleration) The only time hit ground worked correctly was when I increased the thickness of the floor from 2 units to 4 units and set the ray to start from 2 units above the craft instead of from the craft itself. I don't understand why it works, though. However, in that example, ray result.distance seems to be locked at 1.10999, regardless of how far away the craft is.


Why is Cinemachine Virtual Camera locking my camera position to the Origin? I want the camera to follow a character as he moves around. So I did the following Position the camera behind and slightly above the character. Add a Cinemachine Brain component to the camera. Create a GameObject containing a Cinemachine Virtual Camera component. Set its LookAt and Follow properties to the character to be followed. Run the game. I expect for the camera to follow the character, more or less maintaining the relative position and orientation I had set for it. (ie. more or less as if the camera object was parented to it, but smoother.) If I use the Cinemachine Free Look camera, this is basically how it works, except that it only deals with following and I have to maintain the orientation manually with the mouse. But if I use Cinemachine Virtual Camera, because I don't want to deal with the free look part of it, for some bizarre reason it locks the position of the GameObject containing the camera to (0, 0, 0)! And I don't just mean it moves it there it's stuck there! If I go into the Inspector and change the position at runtime, it instantly changes back to (0, 0, 0). What can cause Cinemachine Virtual Camera to do this? And how can I make it stop?


Unity2D Repeating of code makes game lag (Spawnning script) does anyone knows how to shorten down this script and that I can edit the amount of enemies I want to spawn in, so that I don't have to keep on copying and pasting the same method below again and again, my code is also making my game a bit laggy. Which isn't a good sign. This is my code public bool fromTop false public GameObject enemy1 public float enemy1Time 2f public GameObject enemy2 public float enemy2Time 2f public GameObject enemy3 public float enemy3Time 2f public GameObject enemy4 public float enemy4Time 2f Variable to know how fast we should create new enemies void Start() InvokeRepeating ("Enemy1", enemy1Time, enemy1Time) InvokeRepeating ("Enemy2", enemy2Time, enemy2Time) InvokeRepeating ("Enemy3", enemy3Time, enemy3Time) InvokeRepeating ("Enemy4", enemy4Time, enemy4Time) void Enemy1() Vector2 spawnPoint new Vector2 (transform.position.x, transform.position.y) if (fromTop) float x1 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 float x2 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 Randomly pick a x point within the spawn object spawnPoint.x Random.Range (x1, x2) else float y1 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 float y2 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 Randomly pick a y point within the spawn object spawnPoint.y Random.Range (y1, y2) Instantiate (enemy1, spawnPoint, Quaternion.identity) void Enemy2() Vector2 spawnPoint new Vector2 (transform.position.x, transform.position.y) if (fromTop) float x1 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 float x2 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 Randomly pick a x point within the spawn object spawnPoint.x Random.Range (x1, x2) else float y1 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 float y2 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 Randomly pick a y point within the spawn object spawnPoint.y Random.Range (y1, y2) Instantiate (enemy2, spawnPoint, Quaternion.identity) void Enemy3() Vector2 spawnPoint new Vector2 (transform.position.x, transform.position.y) if (fromTop) float x1 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 float x2 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 Randomly pick a x point within the spawn object spawnPoint.x Random.Range (x1, x2) else float y1 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 float y2 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 Randomly pick a y point within the spawn object spawnPoint.y Random.Range (y1, y2) Instantiate (enemy3, spawnPoint, Quaternion.identity) void Enemy4() Vector2 spawnPoint new Vector2 (transform.position.x, transform.position.y) if (fromTop) float x1 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 float x2 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 Randomly pick a x point within the spawn object spawnPoint.x Random.Range (x1, x2) else float y1 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 float y2 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 Randomly pick a y point within the spawn object spawnPoint.y Random.Range (y1, y2) Instantiate (enemy4, spawnPoint, Quaternion.identity) Please and Thank you. )


Does interfacing not work as well when it comes to games development? I'm currently at the start of a project, and I'm following the wisdoms of my day to day career as a C developer for large web applications. Currently I have set up a bunch of interfaces. Notable of these are IActor, IHuman, ISelectable, IUIAction amp IHealth. I also have a Person class. Person implements IHuman (which implements IActor), ISelectable and IHealth and also inherits from MonoBehaviour. ISelectable has a property of IEnumerable lt IUIAction gt Actions. Actions have a property of Action click. Im sure you can see where I am going with this... The intended goal is that if a class inheriting from MonoBehaviour (person in this case) implements ISelectable and is attached to a GameObject that is clicked, a list of buttons representing ISelectable.Actions is displayed on the screen. If a class implements IHealth, a healthbar will be displayed on the screen etc etc... Now, the problem I see is I'm going to end up with huge classes. The classes are going to need properties for their health, theyre going to need properties for their actions, theyre going to need properties for what the UI panels title should be when selected, and anything else that comes up as development progresses... My other thought is to remove the interfaces like IHealth from the class itself and have them be their own class, such that IHealth will only mean a class has a property that is of the class Health and Health has all the properties relating to an objects health levels... but this removes authority from the class as to what control it has over its health. Whats the industry standard for this sort of thing, and how can I implement it effectively in my game?


Unity3D leaving and then returning to a scene Effectively, I need to know how to run a mini game and then return to a scene. I know about DontDestroyOnLoad (this) but that works for game objects only and doesn t do what I need also because it carries the objects over into the next scene. In my game you play as a computer. When you hack into a computer remotely, you have to go into a sort of mini game where you must traverse the computer for data, experience and end up owning the computer, having destroyed its security systems. My problem is that this requires being in a different scene, where the hacking 'minigame' is played out, then return. So I could just make a new scene, fine. But when I have to return to the old scene, it has to kick off from the exact point where I left to hack the computer, as if no time had past and with nothing being different. I am stuck on how to do this, because as far as I know there is no way to write a scenes data to a binary file and the read from it when loading the scene again and persistent data was the only solution I could think of. Any help is appreciated. Summary How to play the scene, load a different scene, finish that minigame and then continue from where you were in the original scene


The colors of Unity 2019 are different I currently use Unity 2018 LTS, because of my 2019 Unity colours are not really good. For example, the white is not really white but more like grey and the Shadows are really strong too even if I change the Shadow type. Why is this happening? This is Unity 2019 and Unity 2018 LTS If I change the Directional Light Color from light yellow to Full White then it is whiter, but it doesn't solve the Shadow problem.


Unet Syncing within AR Hololens I am out of options. I have tried everything I could and no matter what I do, the Transforms don't sync up. I have had multiple solutions that worked in my test, non AR project, but once I put on the HoloLens, it doesn't work. Here is what I did PlayerObject that is spawned by the NetworkManager (obviously has Network Identity component) public class ClientObject NetworkBehaviour public static ClientObject CurrentClient private void Start() if(isLocalClient) CurrentClient this public void MoveObject(GameObject obj, Vector3 position) Cmd MoveObject(obj, position) Command public void Cmd MoveObject(GameObject obj, Vector3 position) obj.transform.localPosition position And now the object that wants to get synced. It has a Network Transform with standard settings, a network identity and (obviously) no one has authority since it doesn't get spawned public class AnObject MonoBehaviour public void IWasMoved() Someone Moved this object, either by dragging it or clicking on one of it's arrows through the hololons. Vector3 newPosition (the new position i want this object to have) ClientObject.CurrentClient.MoveObject(gameObject, newPosition) That's what I have. The only thing different from the version that works on my PC without the HoloLens is that I don't set localPosition position, but instead use Translate(position) (which is obviously the non local version) I am tired of writing new code, building the project, having Visual Studio translate the code to C , start my HoloLenses and test if it works, which takes over an hour every time I do so. So is there anything fundamentally wrong with my code? Again it works on my test project just fine. I refuse to believe that it's the HoloLens's fault...


How to disable an object after it goes outside camera's viewport? I have a gameobject at a certain position in the game. I want the gameobject to be disabled once it is outside the camera's viewport, and it should become visible only when the camera focuses at that position.


Editing attached component property in Unity (C ) This might be more of a general C programming query, but since it's game dev related, I'm putting it here. I am trying to randomise a property in a custom component (C script) across several Unity game objects. hostiles is a list of game objects, each with an attached Stats component. foreach (GameObject gO in hostiles) Randomise spawn area gO.GetComponent lt Stats gt ().AreaNo Random.Range(0, 3) Perhaps unsurprisingly, all of my objects end up with the same value for AreaNo. It seems as though I m reassigning some global version of Stats.AreaNo in my loop, rather than the individual instances. What am I missing? (Sorry in advance for the noobish question!)


Using coroutines to instantiate larger GameObjects in Unity C We are making a scroller type game for mobile platforms and we got pretty far (Beta is already out). Now we are adding some additional content and are starting to experience a noticable lag when starting the game. I know about coroutines, but never actually used them, so I was wandering if it's possible to use them to instantiate larger GameObjects (or groups of objects). This is the code we use at the moment to create bullets (this is just an example, I have more similar methods) Func lt string, Pool.Poolable gt bulletCreator x gt return Instantiate(Resources.Load lt Pool.Poolable gt (x)) as Pool.Poolable and then we use this method to create a certain amount of bullets Bullets new Pool(4, () gt return bulletCreator("Bullet") ) This creates 4 bullets (it fits our game desing, the player is restricted to 4 bullets and can refill them with powerups). There are different types of bullets that we create with the same function, and we create them at the start, pool them, and then use them when they are needed. Now this is one of the "heavier" methods, and I'm trying to find a way to speed it up. I tried something like this IEnumerator CreateBullets() Func lt string, Pool.Poolable gt bulletCreator x gt return Instantiate(Resources.Load lt Pool.Poolable gt (x)) as Pool.Poolable Bullets new Pool(4, () gt return bulletCreator("Bullet") ) yield return Bullets Bullets is a global private variable of type Pool. The problem we are having is that when we try to shoot, Unity trhows the Object not set to an instance error. Is what I'm trying possible, or is it like in the regular C that no crossthread calls are allowed. If it's not possible, what are our options? I know we could probably make a short animation and run that in the coroutine while the main thread instantiates everything. Any advice is very welcome. Thanks in advance.


Sprite UV returning wrong values in script in newer Unity versions I'm recreating in Unity 2019.4 an old project I have done few years ago in Unity 5.4.0. This project consists of a tiled map editor using unity editor scripts which reads baked data files containing all information needed for each tile (like height, texture id and texture rotation) and creates the tiled mesh on the fly for a given map to be edited in unity. I have a single sprite (mode multiple) containing all tiles textures that I read when creating the terrain mesh to set the correct UV for each vertex of the mesh depending on the texture id of a given tile. In my old project using Unity 5.4.0 I can just call a tile sub sprite uv property to set in the mesh uv and it works just fine. The problem is that in Unity 2019.4 the uv property of the exact same asset (the big sprite with multiple sub sprites) returns weird values. I compared the output of the uv property used in each tile on both projects and the values are slightly different. The difference is just the order how the elements are ordered in the uv array. Lastly I noticed the sprite is showing additional options in Unity 2019. I have played with the options in Unity 2019 but couldn't notice any difference in the problem. I'll link the images showing the options in both Unity 5 and Unity 2019 bellow (respectively) Does anyone have any idea or suggestion to understand why this is happening? I tried to search for this topic but couldn't find anyone with a similar problem. EDIT the multiple sprite is being generated and imported with the tool TexturePacker.


Matte reflection effect in Unity? I'm trying to achieve that kind of scene but in real time using Unity. It's basically composed of some primitives, a skybox, and a plane. I'm intrigued on how to do this effect in particular The plane acts like a mirror, but tainted and matte (and it appears to be less blurry at the bottom of the buildings... but I'm not quite sure). I have found some shaders to create mirrors in Unity but nothing about the matte effect like in this picture. Could you guide me on how to achieve this kind of effect (knowing that I'm pretty lame when it comes to write shaders but I want to learn). Thanks.


OnRoomConnected always fail (Google play service unity3d) OnRoomConnected always return false, Im stuck...(Authenticate is success). Thank you for attention. private List lt Participant gt participants public void Authenticate() PlayGamesClientConfiguration config new PlayGamesClientConfiguration.Builder() .Build() PlayGamesPlatform.InitializeInstance(config) recommended for debugging PlayGamesPlatform.DebugLogEnabled true Activate the Google Play Games platform PlayGamesPlatform.Activate() Social.localUser.Authenticate((bool success) gt if (success) Debug.Log("Authentication succeeded") CreateQuickGame() else Debug.Log("Authentication failed") ) public void CreateQuickGame() const int MinOpponents 2, MaxOpponents 2 const int GameVariant 0 PlayGamesPlatform.Instance.RealTime.CreateWithInvitationScreen(MinOpponents, MaxOpponents, GameVariant, this) region RealTimeMultiplayerListener implementation public void OnLeftRoom() SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().buildIndex) public void OnParticipantLeft(Participant participant) SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().buildIndex) public void OnPeersConnected(string participantIds) Debug.Log("OnPeersConnected") byte message Encoding.ASCII.GetBytes("Test") build your message bool reliable true PlayGamesPlatform.Instance.RealTime.SendMessageToAll(reliable, message) public void OnPeersDisconnected(string participantIds) SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().buildIndex) public void OnRealTimeMessageReceived(bool isReliable, string senderId, byte data) public void OnRoomConnected(bool success) if (success) Debug.Log("Room Connected success") MainScene ms new MainScene() ms.Waithing sprite.SetActive(true) Successfully connected to room! ...start playing game... PlayersNames 0 participants 0 .DisplayName PlayersNames 1 participants 1 .DisplayName PlayersNames 2 participants 2 .DisplayName GenerateBoard() bool reliability true string data "Instantiate 0 1 2" byte bytedata System.Text.ASCIIEncoding.Default.GetBytes(data) PlayGamesPlatform.Instance.RealTime.SendMessageToAll(reliability, bytedata) else Debug.Log("Room Connected FAIL") PlayGamesPlatform.Instance.RealTime.LeaveRoom() Loading.text "Error!" Back.SetActive(true) Error! ...show error message to user... public void OnInvitation(Invitation invitation, bool shouldAutoAccept) handle the invitation if (shouldAutoAccept) PlayGamesPlatform.Instance.RealTime.AcceptInvitation(invitation.InvitationId, this) else do some other stuff. public void OnRoomSetupProgress(float progress) Debug.Log("Room Progress Waithing players") List lt Participant gt participants PlayGamesPlatform.Instance.RealTime.GetConnectedParticipants() show the default waiting room. if (participants.Count ! 3) PlayGamesPlatform.Instance.RealTime.ShowWaitingRoomUI() Debug.Log("Room Progress Waithing players") else Debug.Log("Room Progress 100") MainScene ms new MainScene() ms.MoveToGame() PlayersNames 0 participants 0 .DisplayName PlayersNames 1 participants 1 .DisplayName PlayersNames 2 participants 2 .DisplayName


Asset is up to date but does not have a correct hash assigned in GuidPersistentManager I have a ScriptedImporter that generates a few extra assets, this works fine except when I re import it after version upgrade, I get the following message Asset with guid 'bbe94cef9d5f3464ab6ba6913e6747a2' and path '...' is up to date, but does not have a correct target hash assigned to it in the GuidPersistentManager UnityEngine.UnitySynchronizationContext ExecuteTasks() Inside that ScriptedImporter I've tried File.Delete, AssetDatabase.Refresh, AssetDatabase.ImportAsset but neither helped out, only when I delete it manually it does work. Furthermore, that error message is quite useless as basically Unity handles it but still notifies you. Note that the asset generated is next to the format being imported, this is because if for instance you create a texture and add it to the AssetImportContext then it becomes readonly in the Inspector and cannot be tweaked further. So basically I generate a PNG file in same folder which then has the usual TextureImporter that can be edited as will. Question How to avoid incorrect GUID errors when re importing an asset generated by a ScriptedImporter? Alternatively, how to solve this incorrect GUID clash when overwriting an asset?


Difference between Unity's Camera.ScreenPointToRay and Camera.ScreenToWorldPoint? What is the difference between Unity's Camera.ScreenPointToRay and Camera.ScreenToWorldPoint. And where we can use these. I've watched some tutorial and documentation but I didn't get a clear understanding.


in unity, lightmap comes out blurry on android device as you see, shadow is blurred. (see the tree's shadow) What settings should I add?


Unity Editor Get Mouse coordinates on left click on Scene Editor I need a simple script which does the following When I left click somewhere in the Editor Scene (doesnt matter if there is an object under the cursor or not) Do NOT deselect the current selection in the Inspector. Do not select the object under the cursor. and Just print the mouse X and Z interception with the Y Plane in the Debug.Log() i stumbled on many solutions but somehow i couldnt get this to work. i tried HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive)) and Tools.current Tool.None both seem to do nothing ..... X.x EDIT Happens that "HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive)) " needs to be inside public void OnSceneGUI() and called every frame to "block" the mouse clicks on the editor. i thought it toggles it off. still the problem of the mouse coordinates persists.


Instantiate objects in a List and use it Why does the following code not work? I want to instantiate prefabs in a list and then use it as a GameObject like that public GameObject prefab void Start() ArrayList players new ArrayList() for(int i 0 i lt 5 i ) players.Add( (GameObject)Instantiate(prefab)) players 2 .transform.position new Vector3(1, 1, 1) there is an error message


Work With Sounds in Unity I have a script in which I defined different functions for each button and assign them their appropriate functions. I defined if statements for them and now I want every button to play it's music when if is true. in OnClick I assigned the script but it didn't work and when I added AudioSurce to it under play () function, it played my sound on button click not when if was true. here is my script public class MainMenu3 MonoBehaviour SerializeField Button WhitePlane SerializeField GameObject wood1 public static int chnum public bool isPlanesold void Start () PlayerPrefs.SetString ("BluePlane", "on") if (PlayerPrefs.GetString ("WhitePlane") "on") wood1.SetActive (false) UIManager2.coin score PlayerPrefs.GetInt ("Score") isPlanesold PlayerPrefs.GetInt ("isPlanesold") 0 ? false true public void BuyWhitePlane () if (PlayerPrefs.GetString ("WhitePlane") "on") PlayerPrefs.SetInt ("isPlanesold", 1) chnum 2 PlayerPrefs.Save () SceneManager.LoadScene ("Menu2") else if (UIManager2.coin score gt 1) this.GetComponent lt AudioSource gt ().Play () PlayerPrefs.SetInt ("isPlanesold", 1) chnum 2 PlayerPrefs.SetInt ("Score", UIManager2.coin score ) PlayerPrefs.SetInt ("Score", UIManager2.coin score) PlayerPrefs.Save () PlayerPrefs.SetString ("WhitePlane", "on") SceneManager.LoadScene ("Menu2") else Debug.Log ("You Don't Have The Score")


How can I represent collection of distant but visit able stars while using minimal resources? I have recently started to plan a project in Unity that will be for Android. I have a database that consists of over 150,000 stars (may trim this down if I O cripples the overhead). The game will hopefully consist of a free to explore universe creating the illusion that the user is flying in a realistic representation of the stars. My biggest concern at the moment is how do I create a realistic environment with these starts, while keeping the resource impact on the phone to a minimum? Some people mentioned using octrees, would this be wise? This is my first game that I am looking to create so any help would be much appreciated to this novice!


Rotate an object with 'Quaternion.Slerp' in world space I'm currently working on a multiplayer skydiving Unity game in which i rotate the players like this transform.rotation Quaternion.Slerp(transform.rotation, desiredRotation, delta) Now this rotates the player relative to it's own rotation. I know rotation in world space is done by multiplying the quaternion of the desired positon with the quaternion of the current position like this localRotation transform.rotation desiredRotation worldRotation desiredRotation transform.rotation But how do i slerp to that position in world space? Thank you all in advance and have a great day!


Worker threads are not being utilized in Time rewind system, is this job system really multi threaded? I am trying to make a simple time rewind mechanic. It's working but it becomes slower as number of game objects increases. I decided to give Job System a shot. My idea is to interpolate between positions and rotations for N game objects in parallel. It is certainly running faster than single thread execution. However, when I see the profiler, the worker threads are sitting idle. Here's the screenshot And here's the IJob code using System using System.Collections.Generic BurstCompile struct RewindJob IJob public int RewindableIndex ReadOnly public NativeArray lt Vector3 gt positions public NativeArray lt Vector3 gt finalPositions public float currentTime public void Execute() rewind code for interpolating b w positions and this is how I schedule RewindJob for each entity like this in main thread NativeArray lt Vector3 gt finalPositions new NativeArray lt Vector3 gt (m Objects.Count, Allocator.TempJob) for (int i 0 i lt m Objects.Count i ) NativeArray lt Vector3 gt positions new NativeArray lt Vector3 gt (count, Allocator.TempJob) TimeRewindable rewindable m Objects i for(int yo 0 yo lt count yo ) positions yo rewindable.m Transforms yo .position RewindJob rewindJob new RewindJob() rewindJob.finalPositions finalPositions rewindJob.positions positions rewindJob.RewindableIndex i JobHandle handle rewindJob.Schedule() handle.Complete() positions.Dispose() for(int i 0 i lt m Objects.Count i ) m Objects i .transform.position finalPositions i m Objects i .transform.rotation finalRotations i finalPositions.Dispose() finalRotations.Dispose() What I can understand is it's not real multi threading but context switching. Can anyone just explain a little bit what's happening? Thanks.


How do I call out an IEnumerator from another script to a script which also contains IEnumerator? It is a Game Manager public class gm MonoBehaviour public IEnumerator spawnTile() ..... I want this IEnumerator spawnTile to be called on this script public class gmSidePlatform MonoBehaviour void Start() NextSpawnSidePlatform.x 30.5f StartCoroutine(SpawnSidePlatform()) IEnumerator SpawnSidePlatform().... I did follow the instructions of calling other scripts by using Public gm gameManager1 But the variables from the gm script didn't appear on this (gmSidePlatform) script. I don't know what to do...


Unity, Player isnt following along the waypoints I have a player with a Rigidbody, I want it to follow along the Waypoints, I have a script for it I tested it first on a Cube, everything worked fine, but on my character it just moves Towards the first waypoint then stays on the first waypoint instead of going ahead. Even if I comment out the LookAt Code section its not working. It could maybe cause the Y position of the waypoints that my player is stuttering, I changed it now. It is now moving along but stuttering much. Here is a picture of the problem Here is my code public GameObject waypoints public float grindSpeed public float turnSpeed public int currentWaypoint private Animator anim private Rigidbody rb public bool isGrinding false void Start() anim GetComponent lt Animator gt () rb GetComponent lt Rigidbody gt () void Update() MoveAlongWaypoints() if(isGrinding) anim.SetBool ("isOnGrinding", true) else if(!isGrinding) anim.SetBool("isOnGrinding", false) void MoveAlongWaypoints() if(isGrinding) TRANSLATE transform.position Vector3.MoveTowards(transform.position, waypoints currentWaypoint .transform.position, grindSpeed Time.deltaTime) ROTATE var rotation Quaternion.LookRotation(waypoints currentWaypoint .transform.position transform.position) transform.rotation Quaternion.Slerp(transform.rotation, rotation, turnSpeed Time.deltaTime) if(transform.position waypoints currentWaypoint .transform.position) currentWaypoint void OnTriggerEnter(Collider other) if(other.gameObject.tag "GrindWayPoint") Debug.Log ("Waypoint!!") isGrinding true


unable to map one object position to another object over network objective I have a player which instantiate by network manager class. I want to map sync its position rotation to another object which is also instantiate by my player object. (what it i have tried) Below code is attached to my network player which instantiating another object (mimic object) void Start() if (isLocalPlayer) CmdInstantiate() Command void CmdInstantiate() This Command code is run on the server! mimic (GameObject)Instantiate( mimicObject) spawn the bullet on the clients NetworkServer.Spawn(mimic) void Update() if (!isLocalPlayer) return CmdMimicObjectPosSync() updating position on server Command void CmdMimicObjectPosSync() position sync method mimic.transform.position this.transform.position mimic.transform.GetChild(0).position this.transform.GetChild(0).position mimic.transform.GetChild(1).position this.transform.GetChild(1).position mimic.transform.GetChild(2).position this.transform.GetChild(2).position it is working fine on the player side but another player who has joined the network unable to see it although mimic object has instantiated but its value remains same (no change). Mimic object has attached network identity and network transform.


Updating settings UI from script also triggers method to update settings from UI interaction My application has a UI for settings which is a mixture of textboxes and scrollbars with which users can interact. I have created a class for these settings and create an object to store them. The user can also give command line arguments to apply settings from a file. I have a function that loads this data into the UI from the object (i.e read from a file) and another function that changes object data when user make changes to the UI. My problem is if I load the data from file into UI, the function responsible to reflect these changes in the UI fires up but the other function also fires up because changes were made to the UI. So what should I do to overcome this? Should I implement some kind of state mechanism that would tell code that user has made the changes, or setup some flag which will mark that the data is loaded from a file. If you can suggest some design patterns to follow?


How to make a catapult work with physics and colliders? This should be my final question regarding getting a catapult to throw something in unity. On my last question, someone suggested starting with something simpler (which I apologize for not doing earlier). It worked, so in my test project I put some shapes together to roughly approximate my catapult to see if it could throw something. here's the code on arm rotation parent(which I made so that the arm rotated like a catapult arm) if (Input.GetKey(KeyCode.Space)) rigidbody.AddTorque(new Vector3(0,0,1)) This version rotated and pushed the ball along with it,but it didn't throw it very much. Weird things started to happen when I increased the z magnitude of the torque vector(to 5). Here are my physics settings Arm rotation parent rigidbody with interpolate on, frozen every way except z rotation ball guide kinematic rigidbody with interpolate on mesh collider with its shape floor default cube box collider kinematic rigidbody with interpolate on cube(this is the arm connecting the cup to the center) default box collider for cubes kinematic rigidbody with interpolate on ball sphere collider gravity rigidbody with interpolate on When I spin the arm, the ball almost completely passes through the floor, barely affected by it. On the next rotation, it does the same thing. here's a gif of what it does How do I get the cup of the catapult to interact more accurately and completely with the ball? I increased the physics fps to 100 to see what would happen, and that didn't fix it. Let me know if you need more info, thanks!


Pull OVRCameraRig over RTS map via touch controller grabbing gesture Currently developing a little prototype RTS with the Oculus VR devkit. I want to implement camera movement via "grabbing" onto the world space with a touch controller and move the OVRCameraRig object on the X and Z axes. For the prototype purpose, I rather decided to go with a simpler approach, namely just pull the map around, since it's not that big, and not much is happening on it. So far I got this script public class MapMover MonoBehaviour private bool movementEnabled Transform map Transform leftController Vector3 offset public bool IsMovementEnabled get return movementEnabled private void Awake() leftController GameObject.Find("LeftHandAnchor").transform public void BeginMovement() offset transform.position leftController.position movementEnabled true public void EndMovement() movementEnabled false private void LateUpdate() if (movementEnabled) transform.position new Vector3( (leftController.position.x 1.1f offset.x), transform.position.y, (leftController.position.z 1.1f offset.z) ) BeginMovement() is called when I press the Hand Trigger on the left Touch controller. My current results are unproductive The first BeginMovement() call is sufficient, but the movement of the map is very minimal, since the controller models are tiny and their position clamps around 1.0f and 1.0f. The second call of BeginMovement() makes the map do a jump to either side before going back to the minimal movement. My question is, what exactly am I missing? Is there a simpler approach to this?


Unity running GPU intensive operations in editor mode I have written an erosion simulator that I want to execute from the editor (for generating terrain and such outside of play mode). Unfortunately, when I crank the parameters on my simulation, unity hangs. The UI becomes unresponsive, none of the menus work anymore. However, the process is still running windows doesn't claim that the program is no longer responding. The weird thing is that task manager claims that the GPU is sitting at zero utilization while Unity hangs. My (CPU side) erosion code looks something like this (executed via editor script) HydraulicCompute.SetFloat(" ErosionRadius", ErosionRadius) HydraulicCompute.SetBuffer( erosionId, "HeightMap", heightMap) HydraulicCompute.SetBuffer( erosionId, "Droplets", dropletBuffer) int threadGroupsX Mathf.CeilToInt(mapSize 8.0f) int threadGroupsY Mathf.CeilToInt(mapSize 8.0f) for (int i 0 i lt 100 i ) HydraulicCompute.Dispatch( dropletId, Mathf.CeilToInt( dropletBuffer.count 1024.0f), 1, 1) HydraulicCompute.Dispatch( erosionId, threadGroupsX, threadGroupsY, 1) When the size of the dropletBuffer is bigger than 12,000 (32 bytes per droplet), and the heightMap buffer larger than 1024x1024 (4 bytes per pixel), then I run into the aforementioned problem. I would guess that the issue occurs either because there is a problem with the buffer sizes, or that the frame takes too long and Unity times out. When I comment out the Dispatch calls Unity is able to allocate and populate the buffers instantaneously (at least it looks really quick). While that doesn't rule out the potential buffer problem, it certainly makes it seem less likely. So what exactly is the problem here? Is it a memory problem? Or is the frame timing out? Or something else entirely? Is there a prescribed way to doing this kind of intensive GPU work in the background in editor mode? I've looked at the Job system, but that seems to be CPU side only... EDIT I have managed to put together the following snippet which always crashes on my GPU (NVIDIA 980ti) numthreads(1,1,1) void CSMain(uint3 id SV DispatchThreadID) for (int i 0 i lt NumIterations i ) HeightMap 1024 512 512 0 When executed as 1 thread group for 1 iteration ( NumIterations 1), this crashes my GPU driver. I am running on the latest version. I have no idea as to what might be causing the problem, windows event viewer just lists a nvlddmkm error, which apparently means it could be just about anything. It's frustrating to say the least.


Bullet prefab gets stuck to target after hitting As the title says, I am having an issue with prefabs I am trying to make a bullet follow a curve and then hit a target using this method private IEnumerator BezierShooting() GameObject shotInstance new GameObject() shotInstance Instantiate(shotPrefab, transform.position, Quaternion.identity) Vector3 currentPosition new Vector3() if (shotInstance ! null) while (t lt 1 amp amp shotInstance ! null) currentPosition Mathf.Pow(1 t, 3) controlPoint0.position 3 Mathf.Pow(1 t, 2) t controlPoint1.position 3 (1 t) Mathf.Pow(t, 2) controlPoint2.position Mathf.Pow(t, 3) controlPoint3.position Debug.Log(currentPosition) shotInstance.transform.position currentPosition t 0.02f yield return new WaitForEndOfFrame() else currentPosition transform.position t 0 yield break Where t is a float variable that I initialised before as well as the transforms controlPoint0, controlPoint1, controlPoint2 and controlPoint3. The bullet is succesfully following the path that I created, however the problem is that once the bullet hits an object in position (x, y, z) and gets destroyed, if I call the method again the prefab will spawn in the last position it was on. I thought that final else statement would do the trick, but appearantly I am missing something. Can somebody help me please?


How does one get sprites to hide unhide using OnMouseDown() in Unity? I'm right now using Unity for a school project and I need to be able to hide and unhide sprites for "expansions". I've looked all over the internet for this and I can't seem to find an answer. Here is the script so far using System.Collections using Systems.Collections.Generic using UnityEngine DisallowMultipleComponent public class addBlock MonoBehaviour void OnMouseDown() Debug.log(gameObject.name)


Cannot use imported image with Unity's UI controls I know this question sounds banal but its a problem. I received a project and opened it. Now I try to edit it by adding my own images. I do the import but the image does not show up when selecting images, for example, for a button What is the correct folder in this case?


Creating a curve path for gameObject which reacts to Triggers I am trying to create a path for a gameObject which will bounce off other gameObjects if it hits them. Can I get an idea on how I could possibly get this curve path set up. Stuck on ideas. I don't want to use ITween and I can't simply define the entire path via ITween either. I need to account for whether it hit another gameObject and cause it to carry on the path or just fall through. Attached the image below for clarification. I need the circle(purple) gameObject to bounce along the white path provided the rectangle(green) gameObject is in place to cause a Trigger and let the path carry on or the circle gameObject just simply falls through. There is only 1 green gameObject at any point of time which moves to one of the 3 possible positions. Placed 2 just for clarification.


Subsurface Scattering Transmittance I have a question related to SSS and especially transmittance. I've looked at several papers about that topic, most of them from Jorge Jimenez, which are very interesting and, I admit, a bit hard for me. Here is one of the papers http www.iryoku.com translucency I have some difficulties to understand the way it works and the way it calculates the distance the light traveled through the object. I think that I understand the very big lines but I am also a bit confused as I am trying to integrate this into the Unity engine and I have some difficulties to match Unity engine available values such as the shadows maps, the shadows coords, etc... to make them fit the way they are used in the paper. So here it is, I am a bit lost in the "in between" and I hope that somebody might be able to help me. Thanks a lot. EDIT added the shader code from referenced paper float distance(float3 posW, float3 normalW, int i) Shrink the position to avoid artifacts on the silhouette posW posW 0.005 normalW Transform to light space float4 posL mul(float4(posW, 1.0), lights i .viewproj) Fetch depth from the shadow map (Depth from shadow maps is expected to be linear) float d1 shwmaps i .Sample(sampler, posL.xy posL.w) float d2 posL.z Calculate the difference return abs(d1 d2) This function can be precomputed for efficiency float3 T(float s) return float3(0.233, 0.455, 0.649) exp( s s 0.0064) float3(0.1, 0.336, 0.344) exp( s s 0.0484) float3(0.118, 0.198, 0.0) exp( s s 0.187) float3(0.113, 0.007, 0.007) exp( s s 0.567) float3(0.358, 0.004, 0.0) exp( s s 1.99) float3(0.078, 0.0, 0.0) exp( s s 7.41) The following is done for each light 'i'. Calculate the distance traveled by the light inside of the object ('strength' modulates the strength of the effect 'normalW' is the vertex normal) float s distance(posW, normalW, i) strength Estimate the irradiance on the back ('lightW' is the regular light vector) float irradiance max(0.3 dot( normalW, lightW), 0.0) Calculate transmitted light ('attenuation' and 'spot' are the usual spot light factors, as in regular reflected light) float3 transmittance T(s) lights i .color attenuation spot albedo.rgb irradiance Add the contribution of this light color transmittance reflectance


Sprite is getting out of screen when changing resolution Unity Hello I am making this layout I used sprites for birds but used UI for the blue food thrower. I used UI for it so it will not get cut when screen resolution changes. But I also need to add food itself which I need to make 2D to interact with birds. Now It is not visible over UI, So I changes Canvas Render Mode to world space. But I cannot adjust text in that mode. Its not visible. Then I tried converting the food thrower to Sprite but it get cut. Any authentic and cleaner way to do it?


Why does changing texture change it for both objects? I have two identical objects in my Unity scene. When I change the texture of one, the texture is changed on the other, almost as though the first one is a prefab. Why is this happening and how can I treat them independently? Steps taken Import .obj file and two .png files Drag object into scene Look at the object in the hierarchy (where the list of all objects in the scene is) It has a child called pSphere1 pSphere1 has a mesh renderer with 2 materials on it RedGold and pSphere1Mat It also has two components controlling each of these materials In those control components, I can select a shader from the dropdown and I can also select a texture. For either one of them, if I change the texture say to PolkaDots, both objects have their materials changed, instead of only the one I am working on.


Distributed Rendering in the UDK and Unity At the moment I'm looking at getting a game engine to run in a CAVE environment. So far, during my research I've seen a lot of people being able to get both Unity and the Unreal engine up and running in a CAVE (someone did get CryEngine to work in one, but there is little research data about it). As of yet, I have not cemented my final choice of engine for use in the next stage of my project. I've experience in both, so the learning curve will be gentle on both. And both of the engines offer stereoscopic rendering, either already inbuilt with ReadD (Unreal) or by doing it yourself (Unity). Both can also make use of other input devices as well, such as the kinect or other devices. So again, both engines are still on the table. For the last bit of my preliminary research, I was advised to see if either, or both engines could do distributed rendering. I was advised this, as the final game we make could go into a variety of differently sized CAVEs. The one I have access to is roughly 2.4m x 3m cubed, and have been duly informed that this one is a "baby" compared to others. So, finally onto my question Can either the Unreal Engine, or Unity Engine make it possible for developers to allow distributed rendering? Either through in built devices, or by creating my own plugin script?


Why does the drag fail when I move too fast? I got this code that drags a 2d sphere when i touch the screen using System.Collections using System.Collections.Generic using UnityEngine public class Dragstick MonoBehaviour private Vector3 offset void Update() if (Input.touchCount gt 0) Vector3 touchPosWorld Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position) Vector2 touchPosWorld2D new Vector2(touchPosWorld.x, touchPosWorld.y) RaycastHit2D hitInformation Physics2D.Raycast(touchPosWorld2D, Camera.main.transform.forward) if (hitInformation.collider ! null) GameObject touchedObject hitInformation.transform.gameObject switch (touchedObject.tag) case "Player" Debug.Log("Touched Sphere " touchedObject.transform.name) touchPosWorld.z 0f transform.position touchPosWorld break Thing is, if I move my finger too fast, the drag stops and the sphere drops... also it runs kind of slow when i execute it... Any help about what am I doing wrong? Maybe I'm making things too complex, drag and drop of a sphere should be really easy but functions in unity have changed a lot. Thanks in advance!


Can you get polygon collider 2d shape from a sprite? When you create an object with polygon collider 2d from inspector, unity automatically generates polygon collider that approximately fits the sprite. My question is if there is a way to do that when creating an object from a script? While searching for a solution I found that each sprite has a sprite mesh which has vertices. I tried setting those as a path for my collider, but the result is a mess their order appears to be messed up. My current code Sprite spr I get that in other part of the code GameObject go GameObject)Instantiate(prefab,gameObject.transform) go.GetComponent lt SpriteRenderer gt ().sprite spr go.GetComponent lt PolygonCollider2D gt ().SetPath(0, spr.vertices)


Enemy doesn't fire at player My script looks pretty good but it says Target variable has not been assigned value. public GameObject AntagonisticElement public GameObject Target public float bulletSpeed public float enemySpeed public float bulletDestroyTime public GameObject explsn public GameObject bulletPrefab public Transform bulletSpawn Vector3 pos public float min 20 public float max 10 public int MaxCounter public int CounterStatus int numberofEnemy Use this for initialization void Start() Update is called once per frame void Update() if (CounterStatus lt 0) if (numberofEnemy lt 3) Vector3 creationPoint transform.position creationPoint.y 0.5f Instantiate(AntagonisticElement, creationPoint, transform.rotation) CounterStatus MaxCounter numberofEnemy else CounterStatus transform.LookAt(Target.transform.position) if (Vector3.Distance(transform.position, Target.transform.position) gt min) transform.position transform.forward 4 Time.deltaTime if (Vector3.Distance(transform.position, Target.transform.position) lt max) shootAt() void shootAt() Instantiate(explsn, bulletSpawn.position, bulletSpawn.transform.rotation) var bullet Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation) bullet.GetComponent lt Rigidbody gt ().velocity bullet.transform.forward bulletSpeed


Kinetic sand simulation I want to simulate Kinetic sand's behavior in my game. I could implement operations such as slicing and cutting using simple mesh cutting algorithms but I want to implement complicated operations such as follows Ref video link https www.youtube.com watch?v 3clqk2U3T9Y Squishing (Time frame 1 37 to 1 40 in the ref video) Scooping (Time frame 8 53 to 8 57 in the ref video) I have the following questions What physics simulation algorithms can be used to implement the above 2 operations? I want to implement this concept for mobile devices. Will it be computationally heavy to simulate such physics on mobile devices? if yes, are there any workaround solutions for this type of simulations? I would appreciate any suggestions and thoughts on this topic. Thank you.


Control the movement space for an object? I want my object not cross the limit of quot AiX AiZ quot values. When object cross this limit it faces like walls that block him but not stop him from movement. public GameObject Player, middleObject public float high, upForce, speed public float PlayerDistance, AiX, AiZ, PlayerNum public Vector3 PlayerPlace,PrediactPlace void Update() Quaternion currentRotation transform.rotation Quaternion wantedRotation Quaternion.Euler(0, 90, 0) transform.rotation Quaternion.Lerp(currentRotation, wantedRotation, Time.deltaTime 10) AiX gameObject.transform.position.x middleObject.transform.position.x AiZ gameObject.transform.position.z middleObject.transform.position.z if (PlayerNum 0) control it from inspector Player null else Player GameObject.FindGameObjectWithTag( quot GPlayer quot ) PlayerDistance Vector3.Distance(gameObject.transform.position, Player.transform.position) PrediactPlace Player.GetComponent lt PlayerCtrl gt ().Point.position if (AiX lt 2 amp amp AiZ gt 2 amp amp AiZ lt 7 amp amp AiZ gt 7) transform.position Vector3.Lerp(transform.position, PrediactPlace, Time.deltaTime speed)


What is wrong with this character slope math? I'm making a sidescrolling platformer and have implemented some code that should convert the characters speed to an X speed and Y speed based on the angle of the surface they are on. This actual math for this was taken from a web page and I don't know if it's right or not. xSpeed and ySpeed are derived from speed, based on the angle xSpeed speed Mathf.Cos(angle) ySpeed (speed Mathf.Sin (angle)) gravity The angle is found with this code RaycastHit ground Physics.Raycast (transform.position, Vector3.down, out ground, 1.5f) Debug.DrawRay (transform.position, Vector3.down.normalized, Color.green, 2, false) if (ground.collider ! null) angle Vector3.Angle (ground.normal, Vector3.up) else angle 0 This works fine when walking on a flat surface, but freaks out when walking on a slope. I believe the problem lies with the angle itself.


How to clear the content of a Rendertexture? I want to clear the content of a RenderTexture in runtime. Basically I have this script void OnRenderImage(RenderTexture source, RenderTexture destination) RenderTexture TempRT new RenderTexture(cam.pixelWidth, cam.pixelHeight, 24) RenderTexture whiteRT new RenderTexture(TempRT.width, TempRT.height, TempRT.depth) Graphics.Blit(source, whiteRT, WhiteColorisation) if (Gauss) Graphics.Blit(whiteRT, TempRT, PostOutline) Graphics.Blit(TempRT, destination, GaussianBlur) else Graphics.Blit(whiteRT, destination, PostOutline) the problem here is The 2 newly created Rendertextures' Memory is not released anymore. So I changed it like void OnRenderImage(RenderTexture source, RenderTexture destination) RenderTexture tempRT RenderTexture.GetTemporary(cam.pixelWidth, cam.pixelHeight) RenderTexture whiteRT RenderTexture.GetTemporary(cam.pixelWidth, cam.pixelHeight) Graphics.Blit(source, whiteRT, WhiteColorisation) if (Gauss) Graphics.Blit( whiteRT, tempRT, PostOutline) Graphics.Blit( tempRT, destination, GaussianBlur) else Graphics.Blit( whiteRT, destination, PostOutline) RenderTexture.ReleaseTemporary( whiteRT) RenderTexture.ReleaseTemporary( tempRT) Now I dont get "new" Rendertextures anymore, but used ones. It just draws something over a existing Texture, instead over a new "white" page. The only thing i want is... that " whiteRT" and " tempRT" to be "new" ones, and the memory free. The Obvious solution does not work void OnRenderImage(RenderTexture source, RenderTexture destination) RenderTexture tempRT new RenderTexture(cam.pixelWidth, cam.pixelHeight, 16) RenderTexture whiteRT new RenderTexture(cam.pixelWidth, cam.pixelHeight, 16) Graphics.Blit(source, whiteRT, WhiteColorisation) if (Gauss) Graphics.Blit(whiteRT, tempRT, PostOutline) Graphics.Blit(tempRT, destination, GaussianBlur) else Graphics.Blit(whiteRT, destination, PostOutline) tempRT.Release() whiteRT.Release() If I use the code above, in the profiler my object count rises and rises (until i get a crash) How can I solve this problem?


How to Make Snaky Inchworm Motion With Armature Staying Upright I have a series of connected bones in a straight line. I want to be able to rotate each bone vertically and or horizontally so that it can slither and arch randomly kinda like a snake mixed with an inchworm. When I do this, however, the axes get entirely botched. If I rotate one bone horizontally (i.e. on Y), then vertically (i.e. on X), then back horizontally the the other way, the bone is now rotated on the third axis (i.e. Z). This is further compounded when all the bones are trying to do the same thing. How can I keep these pieces "upright" while doing all these random rotations? Edit I think it comes down to this concept. If transform.right (0.9, 0.2, 0.4) and transform.forward is ( 0.3, 0.2, 0.9), how do I calculate how much I should rotate about transform.forward to make transform.right (x, 0, z) from (0.9, 0.2, 0.4)?


The character does not stand still on the moving platform I'm trying to create a simple platforming game. I have an animated platform moving in 2 opposite directions. I use this simple code to make the character move along with the platform while he is standing on it public class PlatformMoving MonoBehaviour private void OnTriggerEnter(Collider other) gt other.transform.parent transform private void OnTriggerExit(Collider other) gt other.transform.parent null The character moves with CharacterController.Move(). When he stands still on the platform and movement vector equals to Vector3.zero, he moves in the direction opposite to the platform movement direction and can even fall down from the platform. But if I comment charController.Move(movement) line in a character motion script, everything works properly and the character does not move when he shouldn't do that. How to solve it?


Ground texture comes up blurry using the UV Rect Tool Im trying to recreate the ground as this sample sprite sheet https opengameart.org content post apocalyptic expansion I downloaded the sprite sheet and extracted the top left block and saved it separately and added it as a default object not Sprite UI. I then added a UI Raw Image to my scene, added the imported texture. But as I expand it, it becomes blurry, even the UV rect does not seem to help. I though the UV rect was supposed to repeat the texture. Am I doing this wrong?


How can I set the remaining distance of the nav agent? I have an issue with the nav agent in my game. That I am using the remaining distance to determine the next state of the AI. When the navagent is first given a destination it uses the previous distance until it is next updated. So my plan is to find the memory of the remaining distance and alter it when I set the destination. Is that possible or is there a better way?


Unity Set new Origin using empty GameObject You used to be able to set a GameObject with your Mesh as a child of an Empty GameObject. By rotating the Empty the Mesh would rotate around the position of the Empty. Now after the update it seems it's auto calculating a Median Point. Here's the problem https www.youtube.com watch?v gxB 6c75oP0 I should be able to keep the original Origin of the empty GameObject no matter what children it gets. What happened to Unity? This is how it used to be https answers.unity.com questions 609267 how to change the origin of a gameobject.html


Can Java be used for developing games for Android in Unity3D I only know Java Programming Language and no other. Can I develop games for Android in Unity3D using Java?


Keep gravity velocity the same all the time I have 2D rigidbodies that fall to the ground, however they speed up while falling. Also, when they freeze in the air and then unfreeze, the velocity is set to 0 and they gradually start speeding up again. How can I keep the velocity constant at all times, until they hit the ground?


How can I create a cel shaded, comic book appearance in Unity? I am working in Unity, I have imported the post processing stack and I own a license to Amplify. But I'm having trouble making my models appear cel shaded enough to make them appear as if they are from a comic book. I'd specifically like to achieve a result similar to that of Telltale's games like Wolf Among Us and Game of Thrones. Here is a in editor screen capture of the effect shader values How can I get effects such as below?


Composite collider 2D mysteriously adds x velocity to player rigidbody As you can in the gif above there is an x velocity being set in the players rigidbody upon contact with the tilemap surface (Tilemap collider using composite). It was fine when I was using standalone colliders but now this happens. Is this a bug or am I missing something. Help is much appreciated. Unity ver. 2019.4.8f1


Drawing a grid over a terrain using a mesh Shader Depth and Z Buffer What I'm trying to achieve is rendering a (huge) tile grid over a terrain. For that I'm using a generated mesh of quads, one for every tile, whose vertices Y value is the same of the terrain to "shape" this mesh like the terrain. My problem is that this mesh should be rendered always over the terrain, keeping every other object rendered on top of this grid. As you should guess I'm a beginner in shader programming. So here are some caps Rendering the mesh with simple unlit transparent shader (with ZTest, ZWrite and Cull values) As you can see there are problems with the z fighting, when the grid should always be drawn on top. Rising the terrain won't solve it, since the terrain have lots of "peaks" and the quads should be planes with lots of vertex to be able to follow the terrain (or rising a lot the grid which will cause it to float over the terrain). Changing the ZTest to Always Here I've the problem that the tiles behind the mountains are still drawn when they shouldn't, which make sense since it's ignoring z ordering, and therefore rendering over other objects too. I've tried using a another shader pass to first write to the z buffer to avoid rendering the tiles behind the mountains with no success. I guess I'm missing something related to the terrain shader, but I have no clue what it may be. Any help will be much appreciated.


Collider for Unity Line Renderer I have several line renderers that are using as gas pipelines. A user can select one end of the pipe and attach it to one connector. Now the problem is some pipes (line renderer) are overlapping and penetrating with each other. Is there any way to avoid penetration using colliders so they look realistic?


No animation clips in assets folder I'm trying to import an FBX file made in Blender into Unity so I can use the actions created in Blender in a Unity animation state machine. A lot of sites seem to suggest that simply dropping the FBX file into the assets will automatically import animation clips, but that doesn't seem to be happening. Unity does however recognize the discrete actions created. Tutorial image My screen image I used the Blender export settings "Include Animation" and "All actions", but not "Include Default Take" as people recommend. For reference, I'm trying to follow the animator controller tutorial at unity3d.com How can I retrieve my animation clips from the fbx file, or is there another way to insert them into the Animator? Thanks!


Unity UI Objects edges are not smooth I have this Unity UI Image placeholder and here is the snapshot As you can see its edges are not smooth. First I thought this is editor problem but after making the build it remains the same. What i am missing?


How can I place prefabs into a world in Unity? I've looked around for a bit and can't seem to find any way to get a prefab with "Resource.Load" and then to place that object into the world. I'm making a roguelike so when the player enters a room, all rooms around load in. The room to the top would load a random prefab from a list of rooms, check if there's already a room where it wants to go and then PlacePrefab(transform.position, transform.position 10units) So it would place the prefab 10 units above where the current room is (All code for the rooms will run from a centre object and the prefab would be placed on the centre.) Thanks in advance for any help )


Jagged shadows with default settings This is what it looks like no matter the settings I use when I try to use shadows in Unity. Changing the Bias or the Normal Bias does effect the shadows, but I cannot get the shadows to be smooth with any settings. Making the model bigger does fix this, but I would optimally not scale the model up, as it is already at 10.


Batching texture to texture rendering in Unity on the gpu I'm working on a 2D sidescroller within Unity 5.1. The terrain is intended to be semi infinite in all 4 directions, procedurally generated using a noise algorithm. I'm using a 3x3 grid of quads as "chunks" that I shift update as the camera pans around. The issue I'm having is related to the dynamic texture I have tied to each chunk. When they need to be created rather than just shifted around, I'm not quite sure how to render individual tiles from a single texture to specific locations on another texture without using system memory. Using setpixels, I believe it is passing color data each apply to the gpu side. Using gui graphics with a rendertexture to drawtexture or any variants seems to be doing individual draws per call rather than giving me the opportunity to batch them. Using the native gameobjects has FAR too much overhead considering I'm trying to make tiles only be 8x8 pixels in size (meaning higher screen res more on screen tiles). So, is it possible within Unity to do a low level texture to texture render blit draw whatever without pulling texture data into system memory AND still batching same material texture calls together without having to buy some toolkit from the asset store? If any of this doesn't make sense, please ask anything you need to be able to help me and I'll update as needed. Thanks!


Texture not working on object I have a project that I'm having a bit of trouble with. Let me try and explain. In short, I'm trying to apply a texture to an object, but instead it is a solid color. I built a building in "Autodesk 123d design", and exported it as stl. Then I used an online converter to convert it to obj, then added that to the unity scene. I created a material with a texture and tried to apply it to the object, but it was a solid color. I think the UVs on the object might be messed up. I tried some things in blender, but had no luck. Any ideas on how I can fix this? Edit Here is the 3D model I'm working with http www.123dapp.com 123D Design Conisbrough Castle Keep 4578568


Player Flying after colliding Unity I have a Player with a capsule collider on him and i have various objects in the scene. Most of the objects have either mesh collider or box collider enabled. When i move my player and the player collides with any object, my player just starts flying into space, literally. Any way to fix this? Thanks in Advance. The code i have on my player is this using UnityEngine using System.Collections public class Controller MonoBehaviour Animator anim Rigidbody rbody float inputH float inputV int Life 20 bool Dead false public float sensitivity 10f void Start () anim GetComponent lt Animator gt () rbody GetComponent lt Rigidbody gt () void Update () if (Dead false) inputH Input.GetAxis ("Horizontal") 50f inputV Input.GetAxis ("Vertical") 20f anim.SetFloat ("inputH", inputH) anim.SetFloat ("inputV", inputV) float moveX inputV Time.deltaTime float moveZ inputH 0.5f Time.deltaTime this.transform.position this.transform.forward moveX this.transform.position this.transform.right moveZ transform.Rotate(0, Input.GetAxis("Mouse X") sensitivity, 0) if (Input.GetKey (KeyCode.Z)) Life if (Life 0) Dead true anim.SetBool("Dead",Dead)


Design pattern for world objects caching I'm developing in Unity a voxel generated terrain and I'm trying to find an extensible design pattern for voxels and more in general, world objects caching. E.g. storing in a 'ChunkCache' class only the nearest Chunks and updating it after a set amount of time As of now, I'm using a static World class with the following members in pseudocode static class World Player reference Enemies reference WorldCache reference etc. The WorldCache instance contains a list of objects all deriving from the same base class 'Cache'. The implementation so far calls worldCache.update() method with an enum indexing this list of 'Cache' objects WorldCache class List lt Cache gt differentTypesOfCache void update(Enum whichCache) differentTypesOfCache whichCache .update() The problem I'm facing with this design pattern is different types of derived Cache classes need different types of information (e.g. a ChunkCache class will judge wether a chunk needs to be removed from the cache depending on the player's distance from the center of the chunk, whereas other types of derived Caches may need differing information) and as of now the only way to gather this information is to directly query the static World class members. Also if a certain Cache object requires information from another Cache object, it starts to look spaghetti. Is there a completely different pattern better suited for this scenario, or a way to modify the existing one for the better?


All scripts in Unity game can not be loaded I can not provide a "why" here, because as far as I can tell it happened spontaneously after saving an edit to one of my scripts, it just started happening. But here's the problem Every single one of my scripts, while still in the same Scripts file, can no longer be found and loaded. All the Script Components (take the Game Manager component for example) now look like this or like this Attempting to locate the scripts by going Add Component Scripts Desired Script doesn't work, because there isn't even a Scripts item in the Add Component menu. I have already looked this up, and none of the answers I found were applicable Yes, every script's file name is the same as the Class name within them I have tried reimporting all assets (Assets Reimport All), no success. Taking all scripts out of the project, restarting unity and then reimporting the scripts. Nothing Removing all script components, then reapplying them. It didn't work because, as I said, there was no Script item in the Components menu. This is a pretty game breaking, literally, because this is a hobby game (I'm not doing this as a job, it's just in spare time). If I can't restore the game as it was, I won't be able to bring myself to restart it. So any help is greatly appreciated.


Unity get screenshots from various resolutions To upload my app to Google Play I need to provide various screenshots. Thing is, I have only one tablet, no phone and I don't feel like virtualizing a bunch of devices. Is there a way to create screenshots of different sizes? Like what would a 7" 1280X720 tablet see?


Level Asset design for performance Unity I am a big fan of modular assets. Currently I am designing a 3d game for mobile and I don't know how I should create my levels to get the most out of the device. Should I... create lots of "small" (1x1x1 meter) assets and build my level using them or create one geometry for the entire level? What about textures? Should "all" objects share one highres texture and only display their part using the right UV settings (like say in minecraft)or should I create an individual texture for each object?


Unity3d Run In Background setting not working in fullscreen standalone I've ran in to an odd issue with my Unity3D game completely pausing in certain scenarios, even with the Run In Background player setting on. For reference I'm on Windows 7 Ultimate using Unity 4.3.3 In The Editor If I tab out of the editor while the game is running everything keeps working fine. In Windowed Mode If I'm running the standalone in windowed mode and tab out, everything keeps working fine. However, if I grab the top bar on the window to move the window around, the game pauses until I release the window. Nothing updates, nothing runs while it's paused. In Fullscreen Mode If I'm running the standalone in fullscreen mode and alt tab out the game pauses. Not resuming until I tab back in to the game. This is causing issues with the multiplayer aspects of my game, because the client stops sending messages to the server whenever they alt tab out or move the window. I know the graphics device is getting lost when I tab out, because I get this error in my log HandleD3DDeviceLost HandleD3DDeviceLost still lost Skipped rendering frame because GfxDevice is in invalid state (device lost) But that should only cause the game to stop rendering, which is fine. I just need the update loop to continue.


Video playback on mobile can't seek to the end My Unity3D game needs to play videos on mobile devices (using Handheld.PlayFullscreenMovie()). Seeking works badly. If I tap the video progress bar near the end (expecting it to play the last second then finish), playback jumps back a full 10 20 seconds, depending on the video. What should I try to make it easier for the player to seek within the file? Force additional key frames? I'm currently encoding with HandbrakeCLI and the following settings preset "AppleTV" x264 tune animation x264 preset veryslow


How to remove a scene after the another one has loaded 2 3I'm having this problem in Unity where I load a new scene, but the original is still overlapping it. How would you remove the original scene?


Unity installed version higher than game project version can't open the game project anymore Long story short I had to uninstall Unity and Unity Hub and reinstall them again. I ended up installing Unity version 2020.2.1f1. Some of my game projects were made using version 2020.1.6f1 Now I cannot open them there is a yellow warning triangle next to those games in Unity Hub. I am installing version 2020.1.17f1 as I type these. So my questions Is there no backwards compatibility between newer versions of Unity and older games? How do people deal with this? I've heard people transition their games during development into newer versions of Unity but I wasn't even able to open the games made with older version. How would I go around this if I had spent 2 years or more of development time and was suddenly locked out from my game project how do I prevent situations like these? Here are my Unity versions installed And here are my games (tutorials mostly) I may have answered my own question, but still need your input guys. I just noticed that there is a 'Select Version' dropdown on the right that allows me to open a game project in Unity version I have installed on my system. Is this how you deal with those issues?


How to use sprite as font in Unity? I've started working on my first game in Unity It's very simple, there's a spinning block in the middle, and there are spinning blocks coming from all sides. When they hit the middle block, you lose a life. You have 3 lives. I've hit a bit of a brick wall, here, though I can't seem to find anywhere how to use a sprite atlas as a font, or at least be able to sprite my own font. Does anyone know how to do this?


Destroy chunked block like Minecraft I am trying to do a Minecraft like game (like every one have already tried I guess) and i went across the problem i expected lag with world Generation. I did lot of searching but i can I tried to combine them into a bigger mesh, which work, but not i can destroy a single block. So how can I place destroy chunked (mesh combined) block? If i cant, can someone clearly explain me a solution (i am not fluent in english nor with programming expressions, i can code tho) and how to do it (with a script example if possible ) ) ? Thanks in advance ! I generated my world using 2D perlin noise. Once i have the blocks, i split them into 16x16x100 chunk meshes. Before Making chunks, i first tried to combine all of them into one block (using the unity manual), but the result is only one cube placed at 0,0,0. Where are all the other cubes ? using System.Collections using System.Collections.Generic using System.Linq using UnityEngine public class ThisWorldGen MonoBehaviour public GameObject blockPrefab public GameObject grass public GameObject dirt public GameObject rock private string blockTag private GameObject stockin public int amp public int freq private Vector3 mypos SerializeField private Material material private Vector3 blockLocations public List lt MeshFilter gt meshes new List lt MeshFilter gt () void Start() Generate() void Generate() amp Random.Range(0,100) freq Random.Range(30,100) mypos this.transform.position int cols 100 int rows 100 float startTime Time.realtimeSinceStartup region Create Mesh Data MeshFilter blockMeshes Instantiate(blockPrefab, Vector3.zero, Quaternion.identity).GetComponent lt MeshFilter gt () for(int x 0 x lt cols x ) for(int z 0 z lt rows z ) float y Mathf.PerlinNoise ((mypos.x x) freq,(mypos.z z) freq) amp y Mathf.Floor(y) for(float hy y y gt 0.0F y 1.0F) blockMeshes.transform.position new Vector3(mypos.x x,y,mypos.z z) move the unit cube to the intended position meshes.Add(blockMeshes) int i 0 MeshFilter listMeshes new MeshFilter meshes.Count foreach(MeshFilter cubesToAdd in meshes) listMeshes i cubesToAdd i CombineInstance combine new CombineInstance listMeshes.Length int w 0 while(w lt listMeshes.Length) combine w .mesh listMeshes w .sharedMesh combine w .transform listMeshes w .transform.localToWorldMatrix listMeshes w .gameObject.SetActive(false) w Debug.Log (combine.Length) transform.GetComponent lt MeshFilter gt ().mesh new Mesh() transform.GetComponent lt MeshFilter gt ().mesh.CombineMeshes(combine) transform.gameObject.SetActive(true) endregion Debug.Log("Loaded in " (Time.realtimeSinceStartup startTime) " Seconds.") (the world was generating randomly and perfectly before trying to merge the meshes)


Creating outline from a collection of points following the concavity I am trying to create an outline from a collection of points. I found this solution for Convex Hull. I specifically picked this implementation https en.wikibooks.org wiki Algorithm Implementation Geometry Convex hull Monotone chain Edit I can't find an algorithm that will find the concavity of the region specified in green. The yellow line is the Hull from the algorithm amove I have the point is defined as Serializable public struct Point IComparable lt Point gt , IEquatable lt Point gt public int X public int Y public static int Cross(Point o, Point a, Point b) return (a.X o.X) (b.Y o.Y) (a.Y o.Y) (b.X o.X) Here is the implementation of the algorithm public static List lt Point gt ConvexHull(List lt Point gt points) if (points null points.Count lt 3) return points var size points.Count var k 0 var hull new Point 2 size points.Sort() build lower hull for (int i 0 i lt size i) while (k gt 2 amp amp Point.Cross(hull k 2 , hull k 1 , points i ) lt 0) k hull k points i build upper hull for (int i size 1, t k 1 i gt 0 i) while (k gt t amp amp Point.Cross(hull k 2 , hull k 1 , points i 1 ) lt 0) k hull k points i 1 var result new List lt Point gt (hull) if (k gt 1) result.Resize(k 1) remove non hull vertices after k remove k 1 which is a duplicate return result


Exclude a certain folder from Unity? I work with a small team of three people, and we use the collaborate service within Unity to share our progress. One of the folders we have inside our Unity project is an "OffGame" folder, which includes a tool I created specifically to help with the creation of certain assets. It's not actually supposed to be part of the game, but since I'm often making changes to it, I figured I'd include it in the Unity project. The Unity project temporarily makes use of certain files inside said OffGame folder, however, once the game is done, those files will be moved outside of that folder and integrated into the game proper. Since that OffGame folder is not supposed to be part of the game and I only included it there to share it to my teammates over the collaborate service, I don't want it to be treated like a normal folder for the game. Specifically, I don't want Unity to create a bunch of useless meta files for each file in that folder, or to act like a stray .js file in there is part of the project. I actually got compile errors because Unity kept thinking it had to include all the .js files in that folder. How can I make Unity ignore that folder?