How can I rotate an object with random speed with some delays? using System.Collections using System.Collections.Generic using UnityEngine public class Turn Move MonoBehaviour public int TurnX public int TurnY public int TurnZ public int MoveX public int MoveY public int MoveZ public bool World Use this for initialization void Start () Update is called once per frame void Update () if (World true) transform.Rotate(TurnX Time.deltaTime,TurnY Time.deltaTime,TurnZ Time.deltaTime, Space.World) transform.Translate(MoveX Time.deltaTime, MoveY Time.deltaTime, MoveZ Time.deltaTime, Space.World) else transform.Rotate(TurnX Time.deltaTime,Random.Range(3,300) Time.deltaTime,TurnZ Time.deltaTime, Space.Self) transform.Translate(MoveX Time.deltaTime, MoveY Time.deltaTime, MoveZ Time.deltaTime, Space.Self) This is the random part Random.Range(3,300) but sine it's changing the random numbers too quick the changes are almost not visible. I want somehow to make that if for example the next random will stay for example 5 seconds at this speed number then move to the next random number and again stay at this number 5 seconds and so on. Tried this using System.Collections using System.Collections.Generic using UnityEngine public class Turn Move MonoBehaviour public int TurnX public int TurnY public int TurnZ public int MoveX public int MoveY public int MoveZ public bool World private bool IsGameRunning false Use this for initialization void Start () IsGameRunning true StartCoroutine(SpeedWaitForSeconds()) Update is called once per frame void Update () IEnumerator SpeedWaitForSeconds() var delay new WaitForSeconds(3) define ONCE to avoid memory leak while (IsGameRunning) if (World true) transform.Rotate(TurnX Time.deltaTime, TurnY Time.deltaTime, TurnZ Time.deltaTime, Space.World) transform.Translate(MoveX Time.deltaTime, MoveY Time.deltaTime, MoveZ Time.deltaTime, Space.World) else transform.Rotate(TurnX Time.deltaTime, Random.Range(3, 300) Time.deltaTime, TurnZ Time.deltaTime, Space.Self) transform.Translate(MoveX Time.deltaTime, MoveY Time.deltaTime, MoveZ Time.deltaTime, Space.Self) yield return delay wait but that just rotate the object once each 3 seconds. and not rotating it all the time with speed changing every 3 seconds. but now it's not rotating for 3 seconds it rotating every 3 seconds. better to describe what I want is like intervals. The object should spin all the time nonstop like i Update but then each 3 seconds to change for a random speed. for example spin at speed 5 ....after 3 seconds spin at speed 77 ....after 3 second spin at speed 199


Managing data for large number of levels in Unity? I am making a Unity game vaguely in the vein of Candy Crush Saga for a client and am moving in circles trying to decide how to manage the data for all of their levels. In brief, they want to divide the game into multiple regions that each have 100 levels. For example, you might go to the world map, select Teddy Bear Islands, and then go to the winding path style level select screen similar to King's "Saga" games. My goal is to have the levels be procedurally generated, so the data for each level will consist of dozen or so parameters instead of hundreds of variables. There will only be one scene, and the levels will be built by running the parameters through an algorithm. The game isn't a match 3, but for comparison, imagine if your level data for a match 3 was just basic parameters like the number of each type of piece and the target score, and each time you started a level it would randomly arrange pieces based on the input parameters (instead of you manually declaring the position of each piece). The data for a level will look something like int targetScore int levelType float difficultyModifier int numPieceA int numPieceB int numPieceC int numPieceD I haven't worked with such a large data set (in terms of the number of levels) in Unity before and am unsure how to structure it. In a less editor driven engine, I would probably just store all of the levels in XML files. However, since this is a Unity project I feel like I should be making an editor based solution that will be easier for the client to work with in the future. With an XML driven approach, I imagine that I would have an XML for each region containing all of the 100 levels in that region, and each location on the world map would be linked to one of the XML files. When the user selected a region, it would read the levels into an array, and link each of the 100 level buttons to an array index. For a more editor driven approach, I might create custom editor windows where the regions and levels can be defined, and then link the region and level buttons to the data from the editor window (I haven't done much with editor windows yet and am not entirely sure how to tackle this approach). Or I could create a serializable LevelData type and a simple MonoBehavior with a public array of LevelData so that the levels could be defined on GameObjects in the inspector. Each solution has pros and cons, and I'm stuck on what to do. Is there a conventional approach for managing such a large number of levels in Unity? Should I try one of the above approaches, or is there a better solution?


C JSONs not formatting array of objects stored inside another object. I know the title is a bit confusing because I don't really know how to phrase this. This is what I have System.Serializable public class Sector public string name public Vector3 sectorPosition public float sectorRadius public buildingComponent components System.Serializable public class buildingComponent ScriptableObject public string componentType public Vector3 componentPosition public Vector3 compenentRotation When I try converting this into a json string like this Sector ssector new Sector() ssector.name "sTom" ssector.sectorPosition Vector3.up ssector.sectorRadius 2 ssector.components new buildingComponent 3 print("component length " ssector.components.Length) ssector.components 1 new buildingComponent() ssector.components 1 .componentPosition new Vector3 (1, 2, 3) string sdata JsonUtility.ToJson(ssector) I end up with the following "name" "sTom","sectorPosition" "x" 0.0,"y" 1.0,"z" 0.0 ,"sectorRadius" 2.0,"components" "instanceID" 0 , "instanceID" 341752 , "instanceID" 0 The components array is not actually being formatted, it's only saved with an instanceId or whatever this does. Is there any solution to this or will I have to go with an alternative formatting. I just want to save this data on a server but I only get one string to do so, so I have to format everything into one string. Thanks in advance!


Enable and disable different component on a Gameobject So far I am not clear how do you actually access the various components on a game object, to enable and disable them. I have a component that has various scripts and elements, like a camera, transform, audio listener and few other custom scripts. It is in the scene, so I try to access to it via script private GameObject player player GameObject.Find("the player") So far so good if I want to access for example to the camera, and enable or disable it, I can do it player.GetComponent lt Camera gt ().enabled true This disable correctly the camera, or eanble it, depending from the paramenter that I pass. Now, if I want to access my script, called "playerscript" I can't do the same thing, since I get an error player.GetComponent lt playerscript gt ().enabled true Not sure why I get an error I have a class that is called "playerscript", that is attached to that player object, but instead, VS complain. This is the error message Error CS0246 The type or namespace name 'playerscript' could not be found (are you missing a using directive or an assembly reference?) I did try to use also GetComponentInChildren, but the result is the same. If I have the object player, which hold a reference to the original game object instantiated in the scene, why I can't simply access all the elements attached to it, via GetComponent and dot notation? I believe this used to work time ago, but in Unity5 I can't get this to work. EDIT This is the content of the playerscript class using UnityEngine using System.Collections public class playerscript MonoBehaviour Use this for initialization void Start() get the instance of the button from UI manager void OnTriggerEnter(Collider world item) enable item animation void OnTriggerExit(Collider world item) disable item animation


Game Object will NOT stretch across entire content area I'm loading prefabs into a content area using a content size fitter and vertical layout group. I've tried multiple things to get the loaded prefabs to stretch across the entire content size (including the Unity Manual for this issue), but I'm at an impass. I'll post a screenshot below to show what I'm working with Here's how I'm loading in the prefabs in case this is where i'm screwing up void CreateRaceSelect() for (int i 0 i lt races.races.Count i ) raceButton (GameObject)Instantiate(raceButtonPrefab) raceText raceButton.transform.FindChild("Text").GetComponent lt Text gt () raceButton.name i.ToString() raceButton.transform.SetParent(content.transform) raceButton.GetComponent lt RectTransform gt ().localPosition new Vector3(xPos, yPos, 0) raceText.text races.races i .ToString() yPos (int)raceButton.GetComponent lt RectTransform gt ().rect.height I'm sure this is a minor screw up but at this point I have no other ideas.


Serialize classes in unity c Is there some best practices to serialize objects to file on mobile devices in Unity using C . I've tried to search it myself, but found only this link. However, it looks like here they are trying to cache AssetBundles. I'm new to Unity, but I have some experience in iOS (swift) development. Here we have opportunity to cache some objects(variables) in local storage, to avoid overusing network. So I wanted to create some static class (for example Storage), which caches variables to file permanently and return them by some key.


Unity Hub 2.3.0 Buggy Setup? I recently downloaded the new Unity Hub 2.3.0 setup and since I hadn't used (or downloaded Unity Core) using the previous version of the Hub, I simply deleted the folder containing Unity Hub instead of uninstalling it like any normal person would. Now, every time I open the Unity Hub Setup and try and install it, it always shows the same "Installation Aborted, could not install successfully," error. I can't even uninstall the previous version from Windows Settings! I've tried changing the destination folder, but still doesn't work. Any help is appreciated! P.S. This error occurs when installing UnityHub, not the Unity Core Platform! I've also looked at all other similar posts. Thanks.


Unity yield WaitForSeconds() not working I am new to Unity development. I started learning Unity by reading tutorials, demos, examples, and watching videos. And I am having some trouble with using this timer. Here is my code void OnCollisionEnter(Collision colli) if (colli.collider.name "Car") Debug.Log("On Collision naz . ") Destroy(Car) Destroy(this.gameObject) GameObject clone (GameObject) Instantiate(Bum, transform.position, Quaternion.identity) StartCoroutine(deleteObject(clone)) Just want to delete "clone" object after 1 second IEnumerator deleteObject(GameObject bum) Debug.Log("chuan bi destroy naz . ") lt run normally yield return new WaitForSeconds(1.0F) Debug.Log("Destroy rui naz , '") lt not display Destroy (bum) Why won't this object be destroyed after 1 second?


how to duplicate a button via script? I have the following code public GameObject characterButtonPrefab public GameObject characterButtonContainer public GameObject optionsContainer public GameObject charButtons private int charButtonsIndex 0 private Text cBT private string buttonTexts new string "Strength 5", "Agility 5", "Intelligence 5", "Charisma 5", "Diplomacy 5" private void Start() LevelIsOver false IsNextWave false Time.timeScale 1 for (int i 0 i lt charButtons.Length i ) int size charButtons.Length cBT new Text size GameObject container (GameObject)Instantiate(characterButtonPrefab) container.transform.SetParent(characterButtonContainer.transform, false) cBT i characterButtonPrefab.transform.FindChild("Text").GetComponent lt Text gt () cBT i .text buttonTexts Random.Range(0, buttonTexts.Length) charButtonsIndex if (charButtons.Length gt 0) GameObject currentChar (GameObject)Instantiate(characterButtonPrefab) currentChar.transform.SetParent(optionsContainer.transform, false) currentChar.transform.SetSiblingIndex(0) currentChar.GetComponent lt Button gt ().onClick.AddListener(() gt CharacterSelection()) I declared the size of array to 20 in the inspector and everything work fine. The buttons are created and text changed. The question is how do I duplicate the first button in that array to another panel ? I have searched the internet but nothing found about this. I have tried this GameObject currentChar (GameObject)Instantiate(charButtons 0 ) currentChar.transform.SetParent(optionsContainer.transform, false) currentChar.transform.SetSiblingIndex(0) currentChar.GetComponent lt Button gt ().onClick.AddListener(() gt CharacterSelection()) But I get ArgumentException The Object you want to instantiate is null.


game button animation lag with Photon Friends, I am making games using photon. But I could not do the delay animation as described in this link. The action appears to be late on the player according to the ping. Can you give an ideas about this?


How to handle data for a competitive multiplayer games I am kinda new to Multiplayer Games and I am really wondering how I should handle my data Should each player send and update their data to the database (server) everytime one of their essential variables changes (like health or ingame currencies), or should they save the data as long as the game is running and then update the data all at once at the end of, lets say, each round? I was thinking about using Firebase and Unity and here's a scenario Let's say 2 players connect to a game. Then one of them gets damage and the other one gets gold. Does the data change get sent to the FireBase Database immediatly or should I just update everything when the round ends they disconnect?


Layers in Unity won't drag I'm trying to rearrange my layers in Unity but I can't seem to drag them. When I try to do this I'm in edit layers under the heading sorting layers and I click on the symbol and try to drag it but it won't move. I also tried restarting Unity twice but it won't resolve the problem. Could someone help me with this?


How to implement the swipe up and down number select Unity3d I want to implement the UI like in the image. I want the users to select the number by swiping up and down. I found the tutorial on the YouTube which is similar to the what i wanted (https www.youtube.com watch?v mL FLsV3WRs) But it shows only the numbers from 0 to 9. I want to show from 1 to N (n can be any number). Any idea to help me to get this would be great.


How to reach IK Pass and weight by script? I need to reach IK Pass box, and control the weight by time from 1 to 0. I tried GetLayerIndex and did not give me any of those options.


If statements seem to act as though the condition is always true I have other scripts in the same project using boolean if statements that work fine, but I've tried multiple methods of testing if the if statements below are working and none of them worked! I don't really know what to ask because I don't know whats going on. I've tried placing theae statements in Update and Start, and in both instances the if statement completely ignored the check and just executed the contents of the block as though the check evaluated to true. void OnTriggerEnter(Collider other) if(other.gameObject.CompareTag("Player")) working true Extremity false if(Extremity) Instantiate(Cannon, transform.position, transform.rotation) Extremity !true The false statement is only in there to show that even when the bool is set to false immediately before the check, it still runs the Instantiate method inside as though it were true.


How can I make an instantiation random? I'm trying to do it so when I have an instantiated an item upon the game starting, it is random as to whether it actually instantiates or not. Here's the code I have so far public GameObject anyItem void Start() Instantiate(anyItem, new Vector3(0, 0, 0), Quaternion.identity) Instantiate(anyItem, new Vector3(11, 0, 0), Quaternion.identity) How can I do it so these items (individually, not both together) are decided randomly as to whether they will actually be instantiated or not?


Why does setting a static member value in MonoBehaviour child class constructor have no effect? I am following a tutorial for Unity. I don't know C but I know other similar languages. I got the tutorial to work. Here is the script I used. using System.Collections using System.Collections.Generic using UnityEngine public class PlayerMove MonoBehaviour private Rigidbody rb public float speed Use this for initialization void Start () speed 3.5f rb GetComponent lt Rigidbody gt () Update is called once per frame void Update () float fx Input.GetAxis ("Horizontal") float fz Input.GetAxis ("Vertical") rb.AddForce (new Vector3 (fx, 0, fz) speed) This goes slightly against my C instincts, which are to put initialization values in a constructor. public PlayerMove () speed 3.5f void Start () rb GetComponent lt Rigidbody gt () This doesn't work. In Unity, the speed field has an initial value of 0. Why does setting the initial value in a constructor not work?


Getting distance between point of an object and another object in Unity First, I'd like to apologize because this is a very basic and repetitive question, but I am completely new to game development. I understand that I can find a distance between two objects using float dist Vector3.Distance(other.position, transform.position) However, how can I find the distance between a point of one object to other object? For instance let's say my object is this sphere Now, how can I return an array that says that there are no objects to the left (null), in the front there is an object at 1, and to the right there is an object at 0.5? Thank you for your patience and understanding


Food Game using Online Searchs I am thinking of making a simple game with Unity. The aim would be to keep a person healthy by feeding it well balanced food and drinks. Rather than hard codding every single type of food or drink I can think of I was thinking of letting the player choose any type of food he wants and then screen the internet for it's calorific value, saturated fat, sugars etc ... This would make the game much more enjoyable than being limited by the foods I can think of. I was wondering how you would go about doing that ? Could I use an API to extract data from google or wikipedia. I noticed that when you type " food calories" in Google you get a return from the Wikipedia page like this Obviously, there is a way of extracting the data from Wikipedia and I could automate the searchs by taking the player's entry as a string and running a search with it. How would one recommend going about this ? Also, is it safe ? Thanks


Unity Raycasting only hitting mesh colliders from particular directions I have a game which involves clicking to select some objects. Each of the objects has a mesh collider attached to it so that objects can be clicked, handled by the following if (Input.GetMouseButtonDown(0)) if left button pressed... Find hit object Ray ray task scene.main camera.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit)) execute some function() Now this works fine when I run the game in the editor. However, when I build and run in the browser some objects are not being selected when clicked, and it seems to be objects that are created from particular meshes. I have tried changing the mesh import settings to generate colliders but this doesn't seem to do anything changing Prebake Collision Meshes in build settings, which again doesn't solve the problem Changing mesh collider cooking option to both 'everything' and 'none' Setting 'Queries Hit Backfaces' to true in physicsmanager settings making setting the meshes to convex, which does then work in the build but is not ideal. EDIT I've noticed that the raycasting is actually working for the problem objects but only from particular directions. Is this because, according to the manual 'Faces in collision meshes are one sided. This means objects can pass through them from one direction, but collide with them from the other.' Any thoughts on what might be causing this?


Unity Blurry on new Windows 4k Computer I just got a Razer 14 Inch 4k with a GTX 1060 and am having some blurry rendering in unity. Also the cursor is tiny... Here is a screen shot As you can see, the rendering is really blurry. I came from a mac and did not expect unity to look worse after switching to a computer with a great screen res and graphics card... Please help! EDIT I am still getting jagged shadows but now I seem to be able to fix it with changing shadow distance in Quality Project Settings But then the shadow disappears really quick if i have low shadow distance...


How to generate objects at specific intervals and make them move with same speed? I'm creating an infinite runner where character has to jump on randomly generated pillars. The pillars are positioned with a gap between each of them. The gaps are dmin and dmax. In addition to this, i want the pillars to move to the left of screen with increasing velocity. But they all need to move with same velocity so that the gap in between them is maintained. I have the script as follows pillar is a prefab.go is an empty gameobject which will later be used to Instantiate pillars. first is the first pillar, manually positioned in the scene. using UnityEngine using System.Collections public class GM MonoBehaviour float tempx,dmin 1.3f,dmax 3.5f GameObject bins Vector2 speed,pos,tempvel public GameObject pillar,go public Transform first Use this for initialization void Start () speed new Vector2 ( 0.005f,0) tempx first.transform.position.x tempvel new Vector2 (0, 0) void Update () if ((Vector3.Distance (go.transform.position,transform.position) lt 40f)) tempx Random.Range(dmin,dmax) pos new Vector2(tempx, 2.22f) go Instantiate(pillar,pos,Quaternion.identity) as GameObject bins GameObject.FindGameObjectsWithTag("trash") tempvel new Vector2 ( 0.0005f, 0) foreach (GameObject bin in bins) bin.GetComponent lt Rigidbody2D gt ().velocity new Vector2(Random.Range( 0.005f, 0.05f),0) bin.GetComponent lt Rigidbody2D gt ().velocity tempvel Problem is, the speed of pillars increases way too fast. They move to the left at nearly invisible speeds. Also, after a certain speed, the gap between the pillars increases. They become so far apart, one is in camera view, another is somewhere far away. Is there a way to accomplish this?


Why does applying force to a game object apply force to children, as well? I have a script on my player to move. I do not have root motion applied because, root motion does not work perfectly so I'm manually adding velocity to the player. The player is holding a ball and the ball is a child of the player. However, when I apply force to the player it seems to apply force to the ball so he stops holding it and it is just floating around instead. My player and my ball both have rigidBodies and I'm applying force like this. var velocityX horizontal HorizontalSpeed Time.deltaTime var velocityZ vertical VerticalSpeed Time.deltaTime rigidBody.velocity new Vector3(velocityX, 0f, velocityZ) I know as a hack I can apply a late update to the ball, but I'd rather understand what is going on. Can anyone help me figure this out?


3D visual effects on videos I'm trying to get some hands on experience with 3D visual effects on videos. Similar to those AR apps, I want to add a 3D model with effects, say a dragon, to a video. Something like this famous demo https youtu.be u5hQpRbHERg But I don't really want to make it this fancy with camera tracking. I like to start with the simplest approach probably just placing a dragon on the field (like its last scenes) with fixed camera. What's the best way to do it? Some tutorials would be very helpful.


Unity not opening in Ubuntu I installed the latest version version of Unity for Linux from the official website, but when I try to launch Unity, it displays a blank dialog box. I waited for a long time, but nothing happens. These are my system specifications. I was running Unity on the same computer, several months ago, using Windows. Model Thinkpad R500 Processor Intel Core 2 Duo CPU P8600 2.40GHz 2 RAM 2Gb DDR3 RAM Storage 155Gb HDD Graphics Card ATI Mobility Radeon HD 3400 Series 128mb dedicated GFX Why is it doing this? Is there a problem with the latest build? What should I do to fix it?


Remove delay when changing axis input in the Unity Input Manager I had a problem playing with the Input Manager, where for example When Horizontal ( ) is pressed, it increase its value but, when Horizontal ( ) is pressed, the horizontal value stays positive for a little, but keeps decreasing. This causes the character to continue playing "right" animations and still moving to right for a few seconds, instead of instantly playing 'left" animations and moving to left. The problem also makes the character movie a little after the player releases the key. I have also used Input.GetKey(), but that means the player cannot change the setting from the game launcher, and I don't want to create player setting in game, for now. What I am trying to achieve is when Horizontal ( ) is pressed, then the player presses Horizontal ( ), it should instantly turn left without delay. When the player is not pressing any Horizontal key, it should stop moving horizontally, instantly. This problem also appears along the Vertical axis. How do I make it so input snaps to 1 or 1, with out slowly moving back and forth?


How to create a "border" effect in Unity? Okay let me start off by saying I have searched for several days on this topic, and it seems that either nobody posted anything about it, or it is on the internet, but too far buried under piles of useless information for me to find. I have created a custom terrain algorithm in Unity and have built a parser to read provinces onto the map. The short version description of the parser is that it goes into the assets folder, finds "map provinces.png", reads the borders of the provinces as vertices, reads "map height.png" to determine the height of the visual terrain, and reads "map terrain.png" to determine how much of each province is of each terrain (for example, Paris can be 95 urban, and 5 forest in my setup). I want to make each and every one of the 500 european provinces start with a player. The idea is that the players will fight small scale wars for 30 40 turns, by which point most or all small players will be absorbed into the most successful players country. These will then fight for 60 80 turns for dominance, with alliances being forged and broken and countries being destroyed. The problem is described below Each player has his own unique color. Many of the players will obviously have similar colors, and I do not want 2 dark red countries bordering eachother without some easy way to see the border. I want to basically draw a line in between any two provinces that belong to different players and border each other. I am having trouble finding a way to easily do this, as my current solution tests all provinces if they border foreign provinces, and runs a rather expensive test on each of the bordering provinces vertices to see if they border eachother, then stores those vertices as vectors and draws a line from each vertex to its others. I have considered using a shader to accomplish this, but was unsure if that was the right approach and whether or not that would (or could?) be more efficient.


Black screen when building apk Unity Alright, I have a bit of a confession to make I accidentally posted this question in the wrong place Stack Overflow. Whoops. Anyway, here's my problem. Sorry if you've seen this before. Here's the original post. I've been struggling with this issue for a few days now. Windows builds for my game work fine, but when I build it to Android, it loads, shows the "made with Unity" screen, then fades to black. Now, I know the next scene (an animated logo) is running because it is playing the audio in real time. However, nothing in the scene is visible. Then, the UI for the in game loading screen appears. Normally, the game would then load, and it does, but again, the camera thinks there are no sprites in the scene. I can still play the game, and the audio sounds just normal, but I can't see. Then, when I die, the game over UI appears, and I can use it as normal. The shop menu works absolutely fine, but the game itself does not. It's as if Unity decided that all SpriteRenderers in the game just didn't exist, and that the camera background color was now black. There are no scripts or animations causing this directly, as it does work in editor and on a PC build. The game also works fine using Unity remote, but the build has the issue. I also made sure that none of the textures were too large for Android (to the point where not one of them is larger than 256x256, which looks terrible but proves a point). Now, before anyone asks, yes, I have seen the other question on this topic, and no, sadly, it did not help. My camera is set to "solid color", not "don't clear." I tried "skybox" too, just to be safe. I have also tried disabling post processing, hoping that Android was just unable to handle it. It did nothing. I have even tried entirely disabling all of the sprites in the scene, but even then, the background is still black, indicating that the camera is still not playing nice. Also, here is a screenshot showing the quality settings for the Android build.


Prefabs scaling change also the original prefab I want to work with a prefab as local and global variable? something like that. So my question is how to change a prefab scale without affecting the original prefab.


Unity Ragdoll moves away from parent So this is a weird one. I've looked it up but can't find anyone with similar issues. Basically I have a simple combat system and after the enemy health is zero I go through each rigidbody component in the enemy object and add a force to make it go flying on death. For some reason, the parent object isn't affected and stays still while the Skeleton goes flying. Does anybody know how to make the parent object follow the skeleton, or make the skeleton follow the parent because as of now they act as separate entities? I've tried just adding force to the parent but that only moves the parent object and none of the children. Would appreciate any advice! Thanks.


Texture2D GetPixels Finding pixels that are not transparent. Problem as finding more than expected I am trying to make a level design system where I use a low resolution png file with certain pixels filled. My code will turn this location of the pixel in the image into placement of platforms in my game. But I test the following code with a png i made with only 1 pixel in it (the rest are transparent). But the result is it finds 4 every time. Is it possible there is a discrepancy between the Gimp png and the texture that Unity sees. (In GIMP I used pencil 100 hardness 1px width. There are also settings for 'resolution' of the image, which i left at defaults) public class LevelBuilder MonoBehaviour public Texture2D sourceTex Color32 pixels int pixelsFound 0 private void Start() pixels sourceTex.GetPixels32() for (int i 0 i lt pixels.Length i ) if (pixels i .a ! 0) Debug.Log("found colored pixel. total " pixelsFound)


How do you get the world position from the screen position in a URP shader graph used in a ScriptableRenderPass? I'm using a shader graph in the Universal Shader Pipeline (URP) to do some post processing in a ScriptableRenderPass. How do I get the world coordinates of the screen position? I have tried using the View Direction node, set to World And I have tried the Screen Position node, with either a Transform node or Transformation Matrix node Neither seems to be working because the colors change as I move the camera around, but I would expect the color to stay the same since the world position of the GameObject in the view is not changing. Any suggestions?


Best data types for DNA, edibles and creatures So I am making a sort of continuous evolutionary system in the Unity3D engine. Currently I have a DNA class that has values that gets applied to a Creature object on initializing e.g. public class DNA public float maxSpeed public float foodWeight public DNA(float maxSpeed) this.maxSpeed maxSpeed this.foodWeight foodWeight Where every Creature has a public DNA variable that gets set when instantiating a population of Creatures via a GameManager class. In this "ecosystem" I want to have the creatures crave for food and try to avoid the poison. My question isn't about the reproducing or natural selection part, but more about what the best kind of data type for each object is. Since I want the project to have expandable amount of Creatures, sorts of food etc. Is the best way to handle all data via one GameManager, or should I seperate it in for example CreatureManager, FoodManager etc.? Maybe a PopulationManager of some sorts? Is the current setup for the DNA data optimal? Also, currently I have food and poison just as two prefabs and detect collision (and add or substract health whether it's food or poison via tag), wouldn't it be smarter to create a struct for food and poison so I can later on expand on this? Sorry if any of the given information is unclear or a bit vague, please say so if this is the case! I would be glad to clarify and add any needed information. Thank you for reading through the entirety of my question, thanks for your time! )


Getting the angle between three points? I have three points, A, B and C (stored as Vector2 in Unity). I am trying to find the angle at point B if there were a line AB and and a line BC. I know, this should be a simple google search, and I have found several methods but for some reason, they ALL return totally unexpected results with my data set! I checked to make sure that the three points I pass to compute the angles are indeed the correct (x,y) coordinates, and that same data is used elsewhere in my code without any problems. Considering that all functions return strange results, it must be that I am not understanding something here... here is one formula Vector2 A some vector2.normalized Vector2 B some vector2.normalized Vector2 C some vector2.normalized float Angle Mathf.Atan2(B.y A.y, B.x A.x) Mathf.Atan2(B.y C.y, B.x C.x) Here's another that I tried where p0,p1,and p2 and just vector2's function findAngle(p0, p1, p2) var a Math.pow(p1.x p0.x, 2) Math.pow(p1.y p0.y, 2), b Math.pow(p1.x p2.x, 2) Math.pow(p1.y p2.y, 2), c Math.pow(p2.x p0.x, 2) Math.pow(p2.y p0.y, 2) return Math.acos((a b c) Math.sqrt(4 a b)) The data is a List of Vector2 control points for creating Bezier curves. I want to calculate the angle between index 0,1,2 then 2,3,4 then 4,5,6 etc. with the middle index as the angle needed. I understand that both formulas return radians, but converting to degrees returns sometimes 180 for all points even though the points are all different and the angles vary greatly, sometimes 0 (if I switch the points around), and in the case of the atan2 function above, it gives numbers that "look" like angles, but plotting the points, one can see that the angles do not correspond to the visual plots... I must be doing something very dumb here and I'm not great with math so any hand holding is much appreciated. Here's an image of the output


How can I make a character Blink effect in Unity? I am making a game where I am making a health script where I have made a blueprint of what needs to be done. I'm trying a blinking effect after the character is hurt. Can someone help me make a blink effect in Unity for JS?


How do i create a random planet generator and use it on Unity? For example https managore.itch.io planetarium Something like this, create random sprite circles who at least are realistic looking, as far as realism can be pixel, I don't think this can be done on Unity alone so i think i might need to implement it after i coded it in another language or another engine, so my how do i do it? can i do it on unity? and how would i implement if i decided that unity isn't fit for this thing? The usage of the planets will be throughout the game and will be used as the main planet so it is of great value to the game


Large Scale Case Handling for 2D Procedural Environment I am creating a procedurally generated side scroller and I have a question regarding proper code structure Architecture when it comes to connecting different platforms and large scale cases. There are various platform types I need to connect (e.g. a hill which leads into a tunnel which then leads into a cave, etc). I can successfully generate and connect the meshes using a bezier curve. My problem is that the way I am handling each platform connection case seems very clunky inelegant the more I expand. Currently I am using switch statements to handle each scenario like the above mentioned. Below is a small snippet of how I am handling each case. public void SetTransition(int PrevPlatform, int CurrPlatform , Vector3 LastPosition) switch (PrevPlatform) case 0 GroundTransition (CurrPlatform,LastPosition) break case 1 CaveTransition (CurrPlatform,LastPosition) break case 2 WaterTransition (CurrPlatform,LastPosition) break case 3 TunnelTransition (CurrPlatform,LastPosition) break case 4 WallJumpTransition (CurrPlatform,LastPosition) break From here I have separate functions that handle the cases using more switch statements. The problem now is that I am starting to have a large number of branching functions that are relying each case. My code structure is becoming this large tree of switch statements. For the most part it works but I wanted to reach out to other developers before I continued this route. Is there a more effective, organized methodology to handling large scale cases?


Point to using vSyncCount higher than 1? Is there a point to using QualitySettings.vSyncCount higher than 1? From my understanding it sets the framerate to fractions of the screen refreshrate (i.e FPS refreshrate vSyncCount). So 1 is standard VSync and 2 to 4 make no difference compared to 1 for eliminating tearing and only artificially limit framerate. The only use for this that I can think of is for reducing power draw for battery driven devices like phones. Am I missing something?


SVG textures for 3D game objects in Unity? Is there a way to make textures using vector graphics and use it for 3d models so that textures would be object size independent and won't get blurry?


How do I fix this "java.lang.ClassNotFoundException" error? I received my first crash report via the Google Developer Console, yesterday, and I'm completely lost. This is my error message java.lang.ClassNotFoundException Didn't find class "com.unity3d.player.UnityPlayerNativeActivity" on path DexPathList zip file " mnt asec com.JamaludineDolley.NinjaBallDash 1 pkg.apk" ,nativeLibraryDirectories vendor lib, system lib, vendor lib How do I fix this java.lang.ClassNotFoundException error?


Is ArrayLists so slow that it is doomed to kill performance in Unity? I was reading Which Kind Of Array Or Collection Should I Use? The document states to use list for the most performance. "...They are the fastest array in unity. For this reason, built in arrays are the best choice if you need the fastest performance possible from your code (for example, if you're targeting iPhone)...performs significantly faster than ArrayList." I am inclined to use list besides performance issues as well because... If you're using List you won't have to cast objects since it's generic and use a T backing storage (at least .net does this). ArrayList have to cast everything to object and cause boxing with value types. faster for value types as it avoids boxing., strongly typed elements. But it got me to wonder, since everyone seems to favor to make a degrading statement about ArrayLists, is ArrayLists that horrible? If so why does it even exist? Is it more of trace of supposedly deprecated codes?


Camera follow rotating ball ortogonal direction I have a ball, that has been moved via addForce. It colides in the scene with objects, leading to rotation in all axes. I want a camera to follow this ball but from the side (direction ortogonal to the move vector and UP vector). No matter what I do, I cannot get this working. The closest I get is almost correct, but camera "bumps" during frames. I have used this in camera script to attach camera to the ball and move it with it this.transform.LookAt(this.cannonBall.transform.position, Vector3.up) this.transform.position ball.transform.position No I need to rotate camera 90 degree aroun up axis and move it a little backward to track ball from the side. How can I achive this? If I use this.transform.Rotate(Vector3.up, 90, Space.World) It mess up lookAt


main camera not covering whole screen in unity3d I have been using unity and i got a problem where my main camera is covering only the first half of the floor i made. camera position is left and the floor is rotated ,i m posting an image please help . I have shown a player white coloured and an enemy pink coloured .player is not shown as you can see.


UNET start game with friend by finding their name, Android There is a game at the google play store called Fun Run 2 Multiplayer Race. I loved its feature to find friends by writing their names, and then to play with them. Is it possible to achieve that with UNET? How? Another one is called Virtual Table Tennis. There I have a lobby full of people from whom I can choose. Can I achieve that with UNET? How?


Unity How do I fix the players model rotation in a NetworkManager to spawn properly? How do I fix the players model rotation in a NetworkManager to spawn properly? I created a game with the NetworkManager code. Player Model is a cone I made and imported. all works fine but when the NetworkManager spawns the player model it is sideways. I have tried turning it in 3ds but the player remains sideways when it is spawned by NetworkManager on run, Ohterwise the model is fine in unity, and no matter how I rotate it, in or out of unity , The NetworkManager Rotates it. All other objects attached to the main object remain with proper orientation all, All other objects including instantiated ones appear properly.


How to simulate an elastic force, using Hinge Joint ? I've a bucket connected to a rope. I would like that when a ball fall in my bucket , my bucket "bounce"down and up .. like it is connected to an elastic rope. How can i do that ? Thanks


how to create a curve movement of slider in unity I am trying to create a curved (not circular) movement of slider. Here is my demo images for reference I have watched some tutorial but those are for circle images. I want to make this movement along the arrow images below car. Also if this can be done with just images without using slider that will be ok too. I just this done the simpler and easy way.


Add picture in the Hierarchy view in Unity How can I add a picture in the Hierarchy view in Unity? For example, Dragon bones does it automatically. Here it is As you can see there is a picture on the right of the gameObject name.


Unable to add AR session I am new to unity and i am trying to make a AR app. I have installed AR foundation, Arcore Xr plugin, Arkit XR plugin via package manager. Then if i go to the Hierarchy panel to add a AR session and right click, I am not seeing any XR option to add a AR session. What should i do now? Anyone please help me.


Make enemy follow player intelligently I was trying to make a script to make my enemy follow my player intelligently (but not too much) and I want to know if there was a better way to do it (of course there is but I wanted to find a way myself) Here is what I did I wanted my enemy to detect the player when he approach a certain distance from him. I have a varibale to determine what distance the nemy have to back up (when player is too close) and when it has to follow the player (player too far). Now, I didn't wanted the enemy to just forgot there is an intruder when the player goes around a corner and they can't see him. When the enemy sees the player directly (raycast), they rotate toward him and start following him directly by normalizing the difference of their 2 position. Now is the tricky part i'm not sure about. My player has a list that keeps the 1000 last positions of my player and that update every 0.01 second to add the lastest position and remove the oldest. If the enemy can't see the player directly (!raycast) he goes through all the positions in the list by checking for every Vector3 1 is there something between the enemy and this position ? 2 is there something between this position and the player ? Then it add up the distance between the enemy and the point and the distance between the point and the player and checks 3 is the lenght of the path by going at this point shorter than the last shortest path ? if it's smaller, it's assigne to the best point. If it detected a point that matches these conditions, it goes at it and if it doesn't see the player, it continues checking for new points. If no point matches the condition, he just stop following the player (the enemy lost him). All this works with raycasting to check positions, presence of objects between enemy, player and points and path to go.


addressables unity unknown async error public AssetLabelReference imgs List lt IResourceLocation gt myImgs new List lt IResourceLocation gt () SerializeField List lt Texture2D gt loadedImages new List lt Texture2D gt () private void Start() Addressables.LoadResourceLocationsAsync(imgs.labelString).Completed imgReady void imgReady(AsyncOperationHandle lt IList lt IResourceLocation gt gt op) myImgs new List lt IResourceLocation gt (op.Result) insta() void insta() Addressables.LoadAssetsAsync lt Texture2D gt (myImgs, cb) void cb(Texture2D s) loadedImages.Add(s) I get the locations of the images but not the asset themselves I get an error of Exception encountered in operation Resource(Man.png) Unknown error in AsyncOperation UnityEngine.ResourceManagement.Util.DelayedActionManager LateUpdate() (at


Animation works, but Unity doesn't realize it I have an animation which plays once, and it played once just fine. I want to Invoke a method as soon as the animation finishes. I have been researching and experimenting for over an hour now, but without the result I want. I try to get the animation from the Animator, but Unity says my animation is not attached. The thing is, I don't care if it's attached...I just want to know how long it is, not actually do anything with it. How can I achieve this? Here is the code which results in the error CODE using UnityEngine using System.Collections RequireComponent(typeof(PolygonCollider2D)) RequireComponent(typeof(Animator)) public class Construction MonoBehaviour Use this for initialization void Start() Invoke("EnableObstacleState", GetComponent lt Animator gt ().animation.clip.length) private void EnableObstacleState() GetComponent lt PolygonCollider2D gt ().enabled true ERROR MissingComponentException There is no 'Animation' attached to the "Barricade(Clone)" game object, but a script is trying to access it. You probably need to add a Animation to the game object "Barricade(Clone)". Or your script needs to check if the component is attached before using it. Construction.Start () (at Assets Scripts Construction.cs 11)


How to solve the ground check problem? I noticed a problem in Unity's third person controller's ground check. The ground check should detect whether or not the player is standing on the ground. It does so by sending out a ray beneath the player. However, if the player stands on top and in middle of two boxes and there is a space between these boxes, then the ray shoots into the gap and the player thinks he is not in contact with the ground, which looks like this I am unable to move. You can clearly see that the ray is in the gap and thus the player animator airborne blend tree is active. What is the best way to solve this problem? I was thinking of shooting multiple rays, from the same origin but with different angles. And OnGround should only be true, if X of these rays hit the "ground". Or is there a better way?


FPS horizontal smooth camera rotation I have a problem, my camera is parented to the FPS Controller prefab, then there is a script I wrote for the rotation of the player horizontally by mouse movement, it all works but the rotation is very choppy and not smooth. How can I have the camera rotating smoothly or should I not parent my camera to the FPS Controller at all and make the rotation through scripting if so then how? here's the script of character rotation void Update () float rotationY Input.GetAxis ("Mouse X") 50f transform.Rotate (0, rotationY, 0)


Changing color for each element in linerenderer not working I want to change color for each line (element) just like in color switch. But my code is not working. What I wanted is that the right line should turn blue then the down line should turn color red. What is wrong with my code? void Start() lineGeneratorPrefab new GameObject() DrawLine() private void DrawLine() GameObject myLine new GameObject() myLine.transform.position start myLine.AddComponent lt LineRenderer gt () LineRenderer lr myLine.GetComponent lt LineRenderer gt () lr.positionCount 4 lr.SetPosition(0, new Vector3( 2, 0, 0)) lr.SetPosition(1, new Vector3(2, 0, 0)) lr.SetPosition(2, new Vector3(2, 2, 0)) lr.SetPosition(3, new Vector3( 2, 2, 0)) lr.materials 2 .color Color.blue lr.materials 3 .color Color.red


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


is unity DOTS mature enough to build a whole project on it? maybe you assume this question opinion based but its not. please read the whole question. the question has 2 aspects. are all features implemented? just better say, can i do everything or any gameplay i did on monobehaviours, on the DOTS? all are needed features implemented? including Ai, navigation, physics, animations and... the bigger problem about DOTS and ECS is software engineering. DOTS gives us much better performance in memory and performance and parallel processing but it takes all good OOP practices from us. as you may know, DOTS is not OO and uses its own architectures. most of references values are gone in dots to make data more compact. so there is no solid principles. dependency injections and all those OO design patterns. instead we have a hardly coupled code and entities. the question is does DOTS and ECS really lacks software engineering or its just we dont know enough about it and there are standards about it? many people say that you should make all project on old monobehaviours and you can migrate section that are expensive to DOTS. im not really sure what is the right approach for using with new technology.


Left Hand and Right Hand Coordinate Systems In Blender and other 3D modeling tools, the coordinate system is right handed, while in Unity 3D and Orbiter Space Flight Simulator, they are left handed, why this could happen? Why they don't simply use the right hand coordinate system all the time to make things easier? Why don't all programs that deal with 3D graphics use Z as up? Y Z ZX YX RIGHT HAND LEFT HAND TOP VIEW TOP VIEW (fortunately, Unity3D converts from Blender coordinate system to Unity3D coordinate system)


Gyroscope Parallax Effect In Unity I want to make a parallax effect in Unity 3D with gyroscope like the one on this site http matthew.wagerfield.com parallax I found an asset, but it is too expensive. So I need a script which I can set to the GameObject, so it would move depending phone's gyroscope.


Rotate arrow without using Unity3d physics engine I have this code that simulates the movement of a projectile without using the unity physics engine IEnumerator LaunchProjectile(int angle, float speed) Move projectile to the position of throwing object add some offset if needed. Projectile.position transform.position new Vector3(0, 0f, 0) Projectile.rotation transform.root.rotation Debug.Log(transform.root.eulerAngles) Calculate distance to target float target Distance speed (Mathf.Sin(2 firingAngle Mathf.Deg2Rad) gravity) Extract the X Y componenent of the velocity float Vx Mathf.Sqrt(speed) Mathf.Cos(firingAngle Mathf.Deg2Rad) float Vy Mathf.Sqrt(speed) Mathf.Sin(firingAngle Mathf.Deg2Rad) Calculate flight time. float flightDuration target Distance Vx this.arrowSimulationScript Projectile.gameObject.GetComponentInChildren lt ArrowSimulation gt () float elapse time 0 while (!arrowSimulationScript.Collided()) Projectile.Translate(0, (Vy (gravity elapse time)) Time.deltaTime, Vx Time.deltaTime) Projectile.LookAt(Projectile.position new Vector3(0, (Vy (gravity elapse time)) Time.deltaTime, Vx Time.deltaTime)) arrowSimulationScript.Velocity new Vector3(0, (Vy (gravity elapse time)) Time.deltaTime, Vx Time.deltaTime).magnitude elapse time Time.deltaTime yield return null The arrow is fired in the direction of the object which has this script attached. To make the arrow rotate I use this line of code Projectile.LookAt(Projectile.position new Vector3(0, (Vy (gravity elapse time)) Time.deltaTime, Vx Time.deltaTime)) The arrow moves towards the right direction but with the tip facing the z axis direction, instead of the direction of the bow. Here is a video of the problem https www.youtube.com watch?v cyK6DXxTw E If I comment out that line of code the arrow fly with the tip facing the direction of the bow, but it doesn't rotate.


uNet Client cant see server spawned objects I'm facing a problem where when I connect with the host, all the towers spawn. After I connect with a client only to find out there are no towers visible and I can walk through them when looking at the host screen. My tower spawn script ( GameManager.cs ) public int numberOfDestroyedTopTowers 0 public int numberOfDestroyedMidTowers 0 public int numberOfDestroyedBotTowers 0 public GameObject topTowerSpawns public GameObject midTowerSpawns public GameObject botTowerSpawns public GameObject towerPrefab void Start() CmdSpawnTowers() Command void CmdSpawnTowers() for (int i 0 i lt midTowerSpawns.Length i ) GameObject currTower (GameObject)Instantiate(towerPrefab) currTower.transform.position midTowerSpawns i .transform.position currTower.name "Tower MID " i NetworkServer.Spawn(currTower) for (int i 0 i lt topTowerSpawns.Length i ) GameObject currTower (GameObject)Instantiate(towerPrefab) currTower.transform.position topTowerSpawns i .transform.position currTower.name "Tower TOP " i NetworkServer.Spawn(currTower) for (int i 0 i lt botTowerSpawns.Length i ) GameObject currTower (GameObject)Instantiate(towerPrefab) currTower.transform.position botTowerSpawns i .transform.position currTower.name "Tower BOT " i NetworkServer.Spawn(currTower) The script is derived from NetworkBehaviour and it does have a Network Identity on it (Server Only checked). Also on my towerPrefab I also have a network identity with server only checked. I have added my tower prefab under the network manager "Registered Spawnable Prefabs".


How can non CG shader code in Unity be included? In Unity shaders, include, define, and other preprocessor commands seem to not be able to be used outside the CGPROGRAM section of the shader. Since these are required for compiling multiple shader variants, and a large portion of the shader is non CG, this would be incredibly useful to reduce shader duplication. Do these commands exist outside CG?


Unity Rendering Pass Before Refraction not showing In the documentation it states Before Refraction Draws the GameObject before the refraction pass. This means that HDRP includes this Material when it processes refraction. To expose this option, select Transparent from the Surface Type drop down. I have selected the Transparent option for surface type but the Before refraction rendering pass is not in the drop down list for rendering pass. How can I get it to be there? Are there some other option that might be disabling it?


How can I make item interactable for action? In this script when there is a detection I'm setting the flag detect to true and using in with other scripts. And using the clickForDescription flag and OnGui to display text description for each interactable item if there is a text for it. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class DetectInteractable MonoBehaviour public Camera cam public float distanceToSee public string objectHit public bool interactableObject false public Transform parentToSearch public static bool detected false private RaycastHit whatObjectHit private bool clickForDescription false private bool clickForAction false private int layerMask 1 lt lt 8 private void Start() private void Update() if (Input.GetMouseButtonDown(0)) clickForDescription true clickForAction true Debug.DrawRay(cam.transform.position, cam.transform.forward distanceToSee, Color.magenta) if (Physics.Raycast(cam.transform.position, cam.transform.forward, out whatObjectHit, distanceToSee, layerMask)) detected true objectHit whatObjectHit.collider.gameObject.name interactableObject true print("Hit ! " whatObjectHit.collider.gameObject.name) else detected false clickForDescription false print("Not Hit !") private void OnGUI() if (clickForDescription true) ProcessOnGUI(parentToSearch) void ProcessOnGUI(Transform parent, int level 0) foreach (Transform child in parent) if (child.GetComponent lt ItemInformation gt () ! null) ItemInformation iteminformation child.GetComponent lt ItemInformation gt () if (child.name objectHit) var centeredStyle GUI.skin.GetStyle("Label") centeredStyle.alignment TextAnchor.UpperCenter GUI.Box(new Rect( Screen.width 2 50 20 level, lt INDENTATION Screen.height 2 25, 100, 50), iteminformation.description, centeredStyle) Process next deeper level ProcessOnGUI(child, level 1) public class ViewableObject MonoBehaviour public string displayText public bool isInteractable This is the ItemInformation using System.Collections using System.Collections.Generic using UnityEngine public class ItemInformation MonoBehaviour TextArea public string description Once object is tagged for Interactable and the ItemInformation is attached to it it will display some description for the item. Now I want to do something for action. For example if the item is Interactable and a script name ItemAction is attached to it do some action, For example move the object from side to side or rotate the object. The logic should be like the Information. It's just with the Action there might be many options then just displaying text. I'm not sure how to make some logic and how to work with the ItemAction. using System.Collections using System.Collections.Generic using UnityEngine public class ItemAction MonoBehaviour


How to apply a force to a wheeled veichle and make wheel rotate ? I've a veichle with 4 wheel and 4 wheel collider. My veichle is a toy.. so i would like to apply an impulse force (veichle rigidbody.addforce) to that veichle, move it and make wheel rotate... How can i do ? Thanks


Unity3d vector and matrix operations I have the following three vectors posA (1,2,3) normal (0,1,0) offset (2,3,1) I want to get the vector representing the position which is offset in the direction of the normal from posA. I know how to do this by cheating (not using matrix operations) Vector3 result new Vector3(posA.x normal.x offset.x posA.y normal.y offset.y, posA.z normal.z offset.z) I know how to do this mathematically Note indicates a column vector, indicates a row vector result 1,2,3 2,3,1 0,0,0 , 0,1,0 , 0,0,0 What I don't know is which is better to use and if it's the latter how do I do this in unity? I only know of 4x4 matrices in unity. I don't like the first option because you are instantiating a new vector instead of just modifying the original. Suggestions? Note by asking which is better, I am asking for a quantifiable reason, not just a preference.


Unity using Animation and Ragdoll The question is simple, but I can't resolve it for a couple of days. I have an enemy model with ragdoll attached and also a couple of animations(e.g. idle, walk, run). It seems that ragdoll work only when animator is stopped and vice versa. What I want is when the animation is playing all the forces are applied too, e.g. when I shoot enemy he still walking by animation and and ragdoll corresponds with AddForce(). I tried to find appropriate tutorial for that, watched ton of youtube videos and read a lot of unity forums, but no success. Any help is appreciated. Thanks in advance.


Issue picking the closest vector in a unique circumstance I have a list of targets that can be picked depending on the magnitude from the vector created using for(int i 0 i lt targetQueue.Count i ) 2 loops to cycle through targets for(int j 0 j lt targetQueue.Count j ) if two targets are the same, then skip them if(targetQueue i ! targetQueue j ) getting the direction using the source and destination vectors Vector3 iDir targetQueue i .transform.position transform.position Vector3 jDir targetQueue j .transform.position transform.position comparing i with j, if i is less than target at j then match found if(iDir.magnitude lt jDir.magnitude) LockedTarget is a gameobject to show what target the turret is locked on to LockedTarget targetQueue i if match found then set locked target to target at i break This code compares every target to each other, however it does this twice, once on each side( target i becomes target j ). When the magnitude is compared, if the target i is smaller, then this is now the locked target as this target is closer to the turret. This works every time except for one instance and I can't figure out why its happening here When both targets are inside the collider, the target on the right should still be highlighted, yet I get the target that is farther away being selected, this also occurs with more than two targets, with even stranger results. These being that the original target chosen for 'DEADLOCK' what i'm calling it, stays locked. Even when I move the other targets above, below, left and to the right of it. This only occurs with this target, i've tried with 2 other targets (south of the turret) and it works as intended by properly switching based on size of magnitude of the direction vector between the target and the source. I have ruled out the possibility being that it is an issue to do with adding target's to the gameobject list as it works everywhere else. When measuring the lengths of the magnitudes, the wrong target is chosen as the locked target. It does show that the closest target on the images does actually have the smallest vector magnitude. UPDATE the magnitudes of the vectors are increasing and decreasing by tiny amounts, 1 to 2 for a major movement. this makes sense as its worldPos. What doesn't make sense is the target on the right having a magnitude of 49 and the target above having a magnitude of 82, when according to world space they are pretty close to eachother. Can anyone help me with this issue? its been driving me nuts for days. It must be to do with the magnitudes of the direction vectors not being calculated properly.


How to create pixel perfect text in TextMeshPro with a shadow? Problem Making the font asset of type Raster creates a pixel perfect font, but it doesn't have the underlay option inside its material to give it a shadow. Making it of type SDF (or one of the variants) does, but it's blurred in game view. See the image for a visual example. The top text uses the SDF variant, whereas the bottom is of Raster type. This is Game View, zoomed in. Attempted Solution I considered using Unity's own Text component, which, strangely enough, doesn't blur in Game View (but does in Scene View). However, to give it a shadow, I need to create a 2nd, black Text object to place behind it with a small offset. This is fine, but then I need to match its value to the main Text's, and I can't seem to do that without checking every frame inside Update(), which is wasteful.


Virtual World Plaforms and Unity3d I'm moving in the direction metaverse developing. A few years back I wandered around in Second Life and found it entertaining for a New York minute. Now, I'm set to plunge into the Virtual World MMO enviroment. ReactionGrid's Jibe seems to be wonderfully paired with Unity3d. I've been a Unity developer for 5 6 years now. Is there a open source Virtual World Platform that integrates with Unity like Jibe? I've read an article on platforms like OGRE, Open Colbalt, OpenSimulator, Project Wonderland and Sirikata but none seem to mention working with Unity3d.


Moving camera vertically only after player is too high or too low In my 2D platformer game, I find it very exhausting for the player if the camera follows the player all the time. So, I looked up for some tricks to make camera movement feel more natural. The first trick is from James Doyle, where the camera follows a target instead of the player itself. Thus, I can safely use Mathf.Lerp for the target, and avoid having jitters. The second thing I want to do is to limit the vertical movement of the camera. That is, I don't want the camera to move up and down whenever the player jumps. It is dizzying. Instead, I want camera to follow the player only if player is vertically too high or too low. Here is roughly what I do PlayerController.cs public Transform cameraTarget private void FixedUpdate() if(Mathf.Abs(transform.position.y cameraTarget.position.y) gt verticalLimit ) cameraTarget.position new Vector3(cameraTarget.position.x, Mathf.Lerp(cameraTarget.position.y, transform.position.y, Time.fixedDeltaTime), cameraTarget.position.z) if (Input.GetAxisRaw("Horizontal") ! 0) cameraTarget.localPosition new Vector3(Mathf.Lerp(cameraTarget.localPosition.x, Input.GetAxisRaw("Horizontal") cameraAheadAmount, 0.8f Time.fixedDeltaTime), cameraTarget.localPosition.y, cameraTarget.localPosition.z) The problem for this approach is that whenever the vertical distance between the player and the camera target is less than the limit, the camera does not follow the player anymore. So, what I get is basically a camera following the player from down below, again, all the times. I thought of using a boolean flag to tell the camera follow the player when vertical limit is exceeded, but then when do I set and unset the flag? I am new to Unity's Update() and FixedUpdate() logic, so I cannot somehow design a workaround. Is there a simple way to do this?


Game is darker on build I've been recently doing test builds of my game. In Unity, I worked on baking the lighting to ensure everything looked fine. However, upon building, the game level becomes far darker and much of the lighting and baking is ineffective. Here is how the scene looks in the editor And here is how it looks in the built game It's much darker than intended. Here are my lighting settings which I've baked in Unity's Editor. These settings and lightmap parameters were designed to, at least in the editor, provide decent quality while making light bake times relatively quick. However, I've noticed that newer Unity's Lighting settings are way different now, so perhaps something is amiss here? I've been at my wits end trying to figure this out for the past while, but I can't figure out why this is happening or how to fix it. Any ideas?


Why the Render texture is not working when trying to preview a camera on a object? In the editor in Assets right click Create Render Texture Then changed the Render Texture name to SecurityCameraTexture Dimension 2D size 480 x 256 Then created a new material Assets right click Create Material Then changed the material name to SecurityFootage Then changed the material shader from Standard to Mobile Diffuse Then dragged the render texture(SecurityCameraTexture) to the top right image place of the SecurityFootage(material) Next I have a tv object in the scene. In the tv screen I dragged the new material The SecurityCamera. On the SecurityCamera I attached the script that rotate the camera from side to side And the script using UnityEngine using System.Collections public class scr camera MonoBehaviour public float rotate amount Use this for initialization void Start () Update is called once per frame void Update () transform.rotation Quaternion.Euler(transform.eulerAngles.x, (Mathf.Sin(Time.realtimeSinceStartup) rotate amount) transform.eulerAngles.y, transform.eulerAngles.z) Last step I did was to drag the render texture(SecurityCameraTexture) to the camera Target Texture. When running the game and watching the tv I don't see the camera preview in the tv. It should the show the camera preview the camera moving from side to side and what the camera is showing. The camera preview was working fine before I started working with the render texture. But it's not showing the preview in the tv.


Unity General Prefab I have 2 questions about how i should approach this. I want to make a 2D game, with alot of different creatures. Question one If i have alot of monsters and i'm using ScriptableObjects, since they have very similar variables. How can i make one Enemy prefab which will load the right ScriptableObject information? For example i have an Enemy Prefab, then it will load random monster between Dragon, Frog, Wolf. How can i achive this without creating 3 new Prefabs for each one and instead load just the right ScriptableObject. Question two Should i create new prefab for each monster? Or is approach 1 the right way to do it, if you plan to expand over 100 creatures. Thanks


Formatting Unity data for communication with a REST API I am pretty new to unity but I am not new to programming. I am building a Hololens application in Unity 2017.2 and it communicates with a REST api that I built. I am using Unity as a front end more or less and it manages my state. Coming from the web developement world, I have my server converting my models into JSON and I am sending that as a response. For the most part, it works well but since Unity works on an older version of C , I am having issues working with the JSON data, mainly if the data type is not a string, int, float, or double. For example, if my model contains a date data type I am having issues converting it back into a c model or even arrays are proving to be a pain. I don t want to rely on unity packages too much as most I have tried don t do what I need but I am open to any good ones if you know of any. My question is, what is the best way to send data from my API to Unity? Should I send xml or a csv instead? Or even a more C native approach? (If that makes sense)


Continous repeatable object image moving horizontally unity3d I want to move objects on the screen horizontally. And the user has to pop the object by touching it. When user touch it, it gets destroyed and new object comes randomly. For experimenting, I used Unity's Scroll Rect to move them. What can be the best solution for this.


Loading texture from Resources folder not working C So I want to load different textures for my game object when different conditions are met. There are no errors when I compile this code. The colours change according to the condition, that part does work. The textures do not load though. The textures are stores in a Resources folder in Unity. The first code works but the second does not. Why is this the case? Below is my code using System.Collections using System.Collections.Generic using UnityEngine public class Level4 MonoBehaviour Material mat GameObject Sphere Use this for initialization void Start() Sphere GameObject.FindWithTag("Player") Material mat GameObject.FindWithTag("Player").GetComponent lt Renderer gt ().material Update is called once per frame void Update() try if (Input.GetKeyDown(KeyCode.UpArrow)) Renderer rend GetComponent lt Renderer gt () Material mat rend.material rend.material.mainTexture Resources.Load("face1") as Texture mat.color Color.red catch (System.Exception) this is the second code that does not work using System.Collections using System.Collections.Generic using UnityEngine using System.IO.Ports public class arduino MonoBehaviour SerialPort sp new SerialPort(" . COM6", 9600) Com port and the baud rate of the arduino Material m Material GameObject Sphere void Awake() Sphere GameObject.FindWithTag("Player") m Material GameObject.FindWithTag("Player").GetComponent lt Renderer gt ().material void Start() if (!sp.IsOpen) If the erial port is not open sp.Open() Open sp.ReadTimeout 250 Timeout for reading Update is called once per frame void Update() if (sp.IsOpen) Check to see if the serial port is open try string portreading sp.ReadLine() get the string output of the serial port float amount int.Parse(portreading) if ((amount gt 251f)) Renderer rend GetComponent lt Renderer gt () m Material rend.material rend.material.mainTexture Resources.Load("face1") as Texture m Material.color Color.red catch (System.Exception)


How can this method to make a text mesh always face the camera be simplified? (Unity c ) Despite a fairly heafty new years I am back trying to learn a bit more coding D This latest feature I am trying to add is a TextMesh that floats above a gameobject when the player is looking at it. I does all work fine (except it kinda shakes a little but I'll look into that another time). But as I wrote the method to make the textMeshObject look at my camera, I just had a niggling feeling it could be written in less lines of code. I actually get this a lot where I write several lines and think it must be able to be simplified, and after the code having several parts like this it can look pretty messed up. Anyways, I thought i'd ask you experts on here if it was possible to do this an simpler (NOTE I only want it to rotate on Y Axis) void FaceTextMeshToCamera() Vector3 origRot textMeshObject.transform.eulerAngles textMeshObject.transform.LookAt(textLookTargetTransform) Vector3 desiredRot textMeshObject.transform.eulerAngles desiredRot.x origRot.x desiredRot.z origRot.z textMeshObject.transform.eulerAngles desiredRot


How can i use StartCoroutine to set the speed for each scaling step of the walls? using System.Collections using System.Collections.Generic using UnityEngine public class WallsTest MonoBehaviour using a GameObject rather than a transform public GameObject prefab public Vector3 wallsStartPosition public float width 0 public float height 1 public float length 2 public Camera wallsCamera void Start() wallsCamera.transform.position new Vector3(wallsStartPosition.x, wallsStartPosition.y 100, wallsStartPosition.z 235) StartCoroutine(BuildWalls()) IEnumerator BuildWalls() for (int i 2 i lt 2 i ) GameObject go Instantiate(prefab) go.transform.parent transform Vector3 scale Vector3.one Vector3 adjustedPosition wallsStartPosition float sign Mathf.Sign(i) if ((i sign) 2 0) adjustedPosition.x (length sign) 2 yield return new WaitForSeconds(0.1f) scale.x width scale.y height scale.z length width else adjustedPosition.z (length sign) 2 scale.x length width scale.y height scale.z width adjustedPosition.y height 2 go.transform.localScale scale go.transform.localPosition adjustedPosition What it does now it's creating two walls at once it's just waiting 0.1 millisecond before creating them. But instead i want it to show the scaling of the walls how they scaling and moving same for the else part for the adjustedPosition.z and not only the adjustedPosition.x The problem is it's just waiting until it's placing the walls at once. I want to see the walls being building step by step like it's placing cube after cube.


Global variables in a multiplayer environment I would like to know what's the best approach to solve this problem. In a racing game, i need to create the final result chart. In a single environment i've tought something like private string arrivalOrder void playerArrived(string playerName) arrivalOrder arrivalOrder.getLength() 1 playerName I would like to know how to do in a multiplayer environment. How the client can communicate to server "my player finishes the racing"? Thanks


Delay in connecting to server in Unity I have a button, when I press the connect button, it gets connected to the server. When I press the connect button again, it's getting delay in connecting to the server. Below is the code to connect to the server public void setupSocket() try socket new Client(Host, Port) theStream socket.GetStream() theWriter new StreamWriter(theStream) theReader new StreamReader(theStream) socketConnect true catch (Exception e) Debug.Log("Socket error " e) And I have one more issue. When I take the desktop build of the app and opened the app, clicked button, it's getting connected to the server, but when I click the button again it's not getting connected. But when I close the app, it displays the connection message and also close message on the server. Is there anything to be set when taking the desktop build? Can anybody help out what will be the problem?


Make a 2d top down game with round map Currently, I am making a top down game using Unity. Here is the problem that I m trying to solve The player in my game is always centered on the screen, and the since the map is rounded, the agents controlled by AI must acts and be shown base on the distance of the round map. Here is the sketch for the better explanation. I want to ask for a good way to design and implementing the above task. And here is my approach for this task I split the map into 4 areas (could be smaller and more in number). Each of the 4 areas will have its corresponding area outside of the map area (The outside map areas are trigger boxes). When the area that is covered by the main camera has its parts out of the map area, these outside parts will active the trigger boxes that are overlapped by them. When a trigger box is activated, all the agents in its corresponding area inside the map will be moved temporally to the trigger box area. This can be done just by adding the difference between the trigger area position and the inside map area that the agent is staying to the agent s position. When the area that is covered by the main camera no longer overlap the trigger box, all the agent will move back to its corresponding position inside the map. This process is done by reversing the moving out process. Here is the sketch for this. And the flawless come when there are agents with the flocking or forming formation behavior that requires the agents to have connections with others. When an agent is moved out of it actual position, the other agents in the formation will lose their connection with the moved agent (Like the distance between them suddenly becomes large). I think that this could be somehow solved by storing the actual position of the agent and marking it as moved, but it may be too computational cost, or having too many cases. I tried to think of a different approach, that the map border is a circle, and to show the round view is just needed to take the symmetric through the center of the map. However, the circular border shows a bad animation when the agents try to move through the border. (I don't have enough reputation attach image about the flocking behavior problem and the circular approach, so you have to imagine it) If you can solve the problems that I mentioned above or have a different approach, please show me. Thank you.


Saving Unity Custom Inspector state to a text save file? For the basic values I know how to do it like Item name (Simple string value) Amount (Simple int value) isNormalDrop (Simple bool value) The problem is saving the Reflection variable (The script part near the bottom) which is of type 'UnityEngine.Object' and the GameObject variable how would I do this?


2D UI Image with 1px border randomly gets different thickness I created a test image that is 60 x 60 px, which has a 1px border. I then drop that into Unity as a UI sprite image set to the same size, however the 1px border on a few sides can appear to be thicker, and this ruins the look I am going for especially when there are multiple of them. I've tested in the editor and creating builds (testing resolutions), and the same issue in all cases. It's easier to explain this with images. The left screen shot is the actual size of the image in the game view. The zoomed in image is another case where the borders change thickness, but zoomed in to make it more clearer. I've tried various settings, always the same issue. How can I get the image to appear exactly as it should with no changes to the borders?


Unity polymorphism in editor through a list So I have an ItemDatabase class which basically only has a list of Item public class ItemDatabase MonoBehaviour public List lt Item gt Items new List lt Item gt () The Item class looks as follows System.Serializable public class Item public string Name public int Id public string Description public Texture2D Icon Now I have some item types deriving from the Item class, for example Consumable System.Serializable public class Consumable Item public int Resore I next created a gameobject (empty) in my editor and hooked up my ItemDatabase to that object, providing a number of items in the list is no problem but I would like to make sure that from my editor I can choose a type of Item to put into the list, as of now, it only lets my add Item and not Consumable because it is a list of Item. Can I also force the editor not to accept just Item by making it an abstract class?


How to calculate FPS and what factors affect FPS? In this case, FPS means Frames Per Second and that means the number of frames that graphic hardware render in one second. I'm wondering what kind of stuffs could affect FPS? So, for some tests I created a simple scene in Unity with some cubes and capsules and then create a empty game object and then add this c code to it public class FPSReport MonoBehaviour public double Fps void Update () Fps 1.0 Time.deltaTime I think it can tell me the FPS. When I played it it worked but it wasn't more than 30. I was saw a lot of games that their fps was normally on 150. Is this fps rate ok? If I add more objects, textures, animations , etc ... to my scene. What happen to my fps? Could it attain zero? and If it attain zero, what is the meaning of a zero FPS (the hardware stopped working?!)?


Tab between input fields I am new to working with Unity3d, I need to navigate between several inputField, for this I have looked at the solution that is in tab between input fields, but always the FindSelectableOnUp() or FindSelectableOnDown() returns null, so my next is always null and always ends in next Selectable.allSelectables 0


In unity, some part of mesh doesn't show only in play mode This is screenshot of not playing mode. You can see the the speedloader and bullets inside of the revolver. And this is when playing mode. As you can see, I can see the speedloader and bullets in scene view, but not player's camera. Sometimes, it disappears in scene view either! I made this model same as other weapons, but others are working fine. Only this weapon causes this problem. All weapons that I made are based on same model and rigs, and I kept the weapon's scale fit as same as possible. I tried move the camera and scale down a little bit, but still couldn't saw. Why this is happening? How do I solve this? Any advice will very appreciate it.


Unity Shader Graph randomly tiled sprite Lets say I have a shader with a clean white tile. Then I use it on a wall and tile it a few times. I also have a sprite with numbers. Now, is it possible and if yes how. To put a random sprite number ontop of the already tiled texture. Example I am pretty sure this can be achieved with shadergraph, but I am hardly an expert and I really dont want to spend a month or more try erroring my way through...


Multipurpose buttons As in the title, I am trying to figure out how to use a button for multiple purposes in Unity. In my specific case for instance, I am currently using the joystick button 0 (the A button) to perform a simple melee attack if (Input.GetButtonDown( quot Fire1 quot ) amp amp currentState ! PlayerState.attack amp amp currentState ! PlayerState.stagger) second clause because I do not want to indefinitely attack every frame StartCoroutine(GetComponent lt Player Melee gt ().FirstAttack()) In the conditions I make sure that I am pressing the right button and determining in which state my player is (the state is then changed in the attack coroutine). In order to interact with a given object, I created a trigger to check that the player is within range to inspect the object if (Input.GetButtonDown( quot Interact Alt quot ) amp amp playerInRange) if (dialogueBox.activeInHierarchy) dialogueBox.SetActive(false) else dialogueBox.SetActive(true) dialText.text dialogue In the Input manager settings in unity, I set the 'Interact Alt' button to be the same as the 'Fire1' used in the attack script. The scripts actually work, however whenever I check an object I also perform an attack. How can i make so that when I want to inspect an object I do not attack? I was considering create a new finite state similarly to the one I use to attack e.g. 'PlayerState.interact', but then I was wondering, how would unity give the priority to which command to use? Another alternative would be to check if I am in the range of some object when I want to attack and if within range it inspects the object instead, but it seems to me a much more convoluted solutions. How should I solve this?


Unity stats framerate vs Time.deltaTime Googling around, a way for calculating framerate and displaying it as text ingame is using 1 Time.deltaTime. However, comparing this against unity stats FPS shows 2 different FPS. Which of it is incorrect? If 1 Time.deltaTime is incorrect, how does one go about calculating FPS? Below is a screenshot of the FPS difference, as seen in the profiler, fps is well below 100 FPS whereas calculated FPS stays around 60.


Help with modifying a geometry grass shader to allow removing areas? So I have this geometry grass shader from a roystan tutorial I followed but it applies the grass effect to the entire mesh at once. I need to find a way to only apply grass to set areas much like how the unity painting vegetation tools work. I had an idea of using a quot guiding quot texture that the shader would follow which would only apply grass onto set areas on the texture e.g areas that are green but I'm not sure how to implement it. I would appreciate any advice!


How can I generate spheres equal between the waypoints? public void duplicateObject(UnityEngine.GameObject original, int howmany) howmany for (int i 0 i lt waypoints.Count 1 i ) for (int j 1 j lt howmany j ) Vector3 position waypoints i .transform.position j (waypoints i 1 .transform.position waypoints i .transform.position) howmany UnityEngine.GameObject go Instantiate(original, new Vector3(position.x, 0, position.z), Quaternion.identity) go.transform.localScale lightsScale objects.Add(go) For example howmany value is 21. If I have two waypoints it's fine it will create 21 spheres between the two waypoints. But if I have 3 waypoints it's creating 42 spheres but it should create 21 since howmany is still 21. And it also position the spheres between waypoint 1 and 2 and then from waypoint 2 to 3. But I want that it will create 7 spheres between waypoints 1 and 2 and 7 spheres between waypoints 2 and 3 and last 7 spheres between waypoints 3 and 1.


How can I use GPL software like Stockfish Chess Engine in my Unity game? I am working on a 3D Chess game and I want to implement an A.I bot to play with the player. I found a chess engine called Stockfish which serves this purpose, and I would like to implement that engine in my project. Is it as simple as including the Stockfish code in my project or importing a binary as a plugin, or do I have to do something more complex because of the GPL licence?


How best to structure manage hundreds of 'in game' characters I've been making a simple RTS game, which contains hundreds of characters like Crusader Kings 2, in Unity. For storing them the easiest option would be to use scriptable objects, but that isn't a good solution as you cannot create new ones at runtime. So I created a C class called "Character" which contains all data. Everything is working fine, but as the game simulates it constantly creates new characters and kill some characters (as in game events happen). As the game continuously simulates it creates 1000s of characters. I added a simple check to make sure a character is "Alive" while processing its function. So it helps performance, but I can't remove "Character" if he she is dead, because I need his her information while creating the family tree. Is a list is the best way to save data for my game? Or it will give problems once there are 10000s of a character created? One possible solution is to make another list once the list reaches a certain amount and move all dead characters in them.


One Android app, dynamic load several Unity games I'm a newbie in this unity world, exciting about everything in it. Days ago I came up with this idea One day someone finds this android app, naming "Blahblah Game Engine" or anything else. This app has to be very small, containing only some simple activity and Unity runtime, without further resources related to any specific game. He installs it and sees an android activity, maybe a webview, showing a list of unity games the server currently hosting, produced by the very same Blahblah company. Then he clicks on one and this "Blahblah Game Engine" loads the game build via network, starts an Unity activity, without prompting an installing dialog. He can exit the current game whenever he likes, returns to the previous game list, and plays another, all working well in one app's lifetime. In a word, the user experience is very much like how we play games on www.kongregate.com with pc browsers light weight app, mutiple games in one list, all loads via network, playing right away and installing less. Any game that listed in this app should not be installed as a standalone android app, it should be part of the "Blahblah Game Engine", stored as a file inside data folder of "Blahblah Game Engine", run as an activity of "Blahblah Game Engine". Is it possible with Unity 5, both technically and legally? If I were to start this "Blahblah Game Engine" project, should I choose Unity 5 personal or pro licence?


Health Bar is always 100 full I have this GUI to graphically display a variable similar to the health in a game. The variable 'test' goes up and down during gameplay. To show this I have the following onGUI () public GUISkin btnskin1 public Texture2D emptyTex public Texture2D fullTex public Vector2 pos new Vector2(20,40) public Vector2 size new Vector2(60,20) void OnGUI() float test GUI.skin btnskin1 if (LoadDiagram.diagramaCarga.TryGetValue (TimeManager.gametime, out test)) GUI.BeginGroup (new Rect (pos.x, pos.y, size.x, size.y)) GUI.Box (new Rect (0, 0, size.x, size.y), emptyTex) draw the filled in part GUI.BeginGroup (new Rect (0, 0, size.x test, size.y)) GUI.Box (new Rect (0, 0, size.x, size.y), fullTex) GUI.EndGroup () GUI.EndGroup () In the game scene I attached the empty bar to the emptyTex texture, and the full bar to the fullTex texture. When I play the game, he bar is always full. I have not inserted the minimum and maximum of the variable test because I don't know where, but I guess that may be necessary. Any hints?


How can I start the game with a random formation? public class SquadFormation MonoBehaviour enum Formation Square, Circle, Triangle Header("Main Settings") public Transform squadMemeberPrefab public int columns 4 Range(4, 100) public int numberOfSquadMembers 20 public float yOffset 0 Range(1, 20) public int numberOfSquads 1 Space(5) Header("Formations") public int squareSpace 10 public int circleSpace 40 Range(3,50) public float moveSpeed 3 public bool randomSpeed false Range(3, 50) public float rotateSpeed 1 public float threshold 0.1f public bool destroySquad false public string currentFormation public bool startRandomFormation false private Formation formation private List lt Quaternion gt quaternions new List lt Quaternion gt () private List lt Vector3 gt newpositions new List lt Vector3 gt () private bool move false private bool squareFormation false private List lt GameObject gt squadMembers new List lt GameObject gt () private float step private int randomSpeeds private int index 0 private int numofobjects 0 Use this for initialization void Start() numofobjects numberOfSquadMembers if (startRandomFormation) formation UnityEngine.Random.Range(1, 3) In this case I have 3 formations. But it might later more or less formations. Making this line is has no sense formation UnityEngine.Random.Range(1, 3) The idea is to start randomly with one of the 3 formations. How can I get the number of formations ? The count in the enum ? And how can I select randomly one formation ?


Is there a way to make GUI.SelectionGrid expand horizontally I am working on an inventory system, And I want to be able to make a Selection Gird that expands horizontally rather than vertically, is there an easy way to do this? Or will I have to create my own version of SelectionGrid?


score and high score system for multiple levels I'm trying to create a scoring system for a game with multiple levels. For this I'm using the binary formatter instead of playerprefs (I read online that playerprefs are not that secure). I have created the system but whats happening is that the score is not resetting to 0 when I load a new level. If in one level the score was 10 and I start some other level, the score in this level starts from 10 instead of 0. This is the code I have so far public class ScoreIncrease MonoBehaviour public Text scoreTxt public int score void Start() LoadScore() void Update() if (Input.GetKeyDown(KeyCode.Space)) Save() public void Save() score scoreTxt.text "Score" score BinaryFormatter bf new BinaryFormatter() FileStream file File.Open(Application.persistentDataPath " scoreContainer.dat", FileMode.Create) ScoreContainer scoreContainer new ScoreContainer() scoreContainer.score score bf.Serialize(file, scoreContainer) file.Close() public void LoadScore() if(File.Exists(Application.persistentDataPath " scoreContainer.dat")) BinaryFormatter bf new BinaryFormatter() FileStream file File.Open(Application.persistentDataPath " scoreContainer.dat", FileMode.Open) ScoreContainer scoreContainer (ScoreContainer)bf.Deserialize(file) file.Close() score scoreContainer.score scoreTxt.text "Score" score Serializable public class ScoreContainer public int score How can I change this so that each level has a separate highscore and all levels have a start score of 0?


How can i detect if the player is inside an explosion radius? I'm making a driving game, there are enemies which spawn on the side of road and when my player car gets close, they fire a rocket in front of the player. I need to detect if the car is within a certain radius of the explosion center. So when I can detect that I'm assuming I can then use rb.AddExplosiveForce to make the car fly a bit or something. What is the recommended way to get the blast radius collider (or equivalent) and detect if the player is inside it?


Screen transition effect like subway surfers I would like to know how can I achieve this kind of screen transition effect ? The effect is screen independent. https www.youtube.com watch?v Muh7QFisCfE t 01m57s


import text strings into Unity editor 3D text objects so that Scene View displays them I am having trouble finding a solution to this problem. I want to generate the text for TextMesh.text in a custom application and import into the Unity editor so that I can then scale the text to fit. If anyone could point me in the right direction to simply edit a 3D Text game objects' text mesh.text property from a script so that it is reflected in the scene view in Unity's editor, I would greatly appreciate it! Best Regards, Ben


Select specific tile in Tilemap I am following this video tutorial on how to implement drag to select behavior like in an RTS. The only difference is, I'm using a tilemap. The selection area is a square which I can drag to make it as big as I want, like in any top down RTS. CodeMonkey in his video uses Physics2D.OverlapAreaAll to get a list of all colliders in the selected area. I want to use this to specifically see which quot vegetation quot tiles I've selected. However, no matter which vegetation tile I select, or how many, I always get one result the vegetation tilemap itself. You can clearly see from this picture that every grass tile and every tree tile have a collider around them, which is why this works, but how can I get exactly those that I selected? Other than vegetation from the tilemap, I also want this to work with GameObjects that have Box2DColliders on them, and that works out of the box. I also made those MonoBehaviors inherit an interface called ISelectable, so I can only add to the selected list entities that have that inherit that interface. I tried to do the same with vegetation like so public class Vegetation Tile, ISelectable but it doesn't work. What am I missing? Can this even work on a specific tile basis?