Can't refer mesh size after using .BakeMesh() in Unity I can't figure out how to refer to the size of a particular mesh. The mesh is created through .BakeMesh(), then a box collider is added. Unfortunately the box collider has a scale of 1 by 1 by 1, regardless of how big the mesh I'm adding it to seems to be. This doesn't match my understanding of how creating a box collider should work, so I've set up a Debug.Log that outputs the mesh size. Here the plot thickens. The mesh's size just comes back at 0, 0, 0. My attempts at getting the size of the object are as follows objectToMeasure.GetComponent lt Renderer gt ().bounds.size objectToMeasure.GetComponent lt MeshFilter gt ().mesh.bounds.size objectToMeasure.GetComponent lt MeshFilter gt ().sharedMesh.bounds.size Assuming I'm referring to the size of the object in the correct way, this seems like it must be an issue created by baking the object. Do I need to wait a frame (via starting a coroutine) before trying to access the size of the object, or am I referring to the wrong component of the object, or is the BoxCollider setting it's size based on objectToMeasure's scale rather than it's size in the world? I feel sure that objectToMeasure.GetComponent().mesh.bounds.size should be right, since the script I use to bake to the mesh is meshToBake.BakeMesh(meshToMeasure.GetComponent().sharedMesh) I've been driving myself to the edge of sanity for 24 hours with this script not working, so advice is greatly appreciated.


How can I grab the script component of a collided object without knowing what script it is? CalculateDamage() is an animation event called at a point during the character's animation in my 2D game. The commented out code is before I realized that not all of my pirates will be of class MeleePirateUnit, so I'm trying to do things more generically here. My order of inheritance is like so MonoBehaviour Unit MeleePirateUnit, RangedPirateUnit. So sometimes, the collidedobj is a MeleePirateUnit, sometimes it's a RangedPirateUnit, etc etc. How do I set pirateUnit to the correct type of the script component of my gameObject? I thought just getting component of type monobehaviour would work since RangedPirateUnit and MeleePirateUnit both derive from monobehaviour but I'm getting an error of Assets Scripts Combat Scene RangedPirateUnit.cs(72,56) error CS1061 Type UnityEngine.MonoBehaviour' does not contain a definition forhealth' and no extension method health' of typeUnityEngine.MonoBehaviour' could be found (are you missing a using directive or an assembly reference?) public void CalculateDamage() if (!isDestroyed) var pirateUnit collidedObj.GetComponent lt MonoBehaviour gt () MeleePirateUnit pirateUnit collidedObj.GetComponent lt MeleePirateUnit gt () pirateUnit.health pirateUnit.health (damage pirateUnit.defence) if (pirateUnit.health lt 0) Destroy(pirateUnit.gameObject) isDestroyed true didAttack false


Unity WebPlayer WWW GET Requests fail in webplayer only, not in editor My question is about my game requesting data from my server side cloud based storage (I have the option of free public Dropbox or Amazon S3) via GET and the WWW class, and it not working only in the WebPlayer (works fine in the Editor). By not working, I mean that the request is sent successfully, authorized and responded to by the cloud service, but that WWW shows an error in the logs. In the case of using Amazon S3, the Web Player even crashes, otherwise it just fails gracefully and the user is unable to move forward. The Error log left by the webplayer says the following WWW Error Error when creating request. GET request with custom headers is not supported. for URL https my storage.s3.amazonaws.com myDir myFile.json Here's when I use a similar request to a public directory on Dropbox. There is no crash, but the request also fails. WWW Error Failed downloading dl.dropboxusercontent.com u 7782207 spare change weapons 0.json for URL dl.dropboxusercontent.com u 7782207 spare change weapons 0.json Try it for yourself http webroleplay.appspot.com (currently using Dropbox, so not crashing the player) username test1 password t


Unity Display array of Objects in inspector I have an array of ScritableObject's, which should only be displayed in the inspector if a boolean is true. How would I do this? With my current code, I get an error saying Cannot implicitly convert type Tile to Tile This is my current code using System.Collections using System.Collections.Generic using UnityEditor using UnityEngine CreateAssetMenu (fileName "Data", menuName "Tiles Map", order 1) public class Tile ScriptableObject public ETile eTile public Sprite sprite Space(5), Header("Variety") public bool variety Range(0f, 1f) public float varietyChance public Tile varietyTiles lt This should be hidden if variety is true public enum ETile Water, Grass CustomEditor(typeof(Tile)) public class MyScriptEditor Editor override public void OnInspectorGUI() var tile target as Tile tile.variety EditorGUILayout.Toggle("Hide Fields", tile.variety) if (tile.variety) tile.varietyTiles (Tile)EditorGUILayout.ObjectField("Tile", tile, typeof(Tile), allowSceneObjects true)


Why does my ship look like it's going backwards instead of fowards? I'm making an Asteroids clone based on this tutorial. I'm stuck on the 5th part of the tutorial. For some reason my ship is going backwards instead of forward or it looks like its going forward, but in the tutorial the ship gos toward the asteroid. In the debug log, the z axis increments in a positive value. so I assume it is going forward but for some reason the ship it self doesnt go towards the asteroid like it does in the tutorial. The ship itself is an fbx export from Maya 2014. Here's an annotated screenshot Full size version It's probably something really stupid, but I just can't figure out why this is happening.


Is it better to have object components in a variable than using GetComponent everytime? (Unity c ) Is this Rigidbody2D rb GetComponent lt Rigidbody2D gt () void Update() rb.AddForce(transform.up 20 Time.deltaTime) Better than this? void Update() GetComponent lt Rigidbody2D gt ().AddForce(transform.up 20 Time.deltaTime) And can you please tell me why?


Why is my custom Texture2D blurry? Have some WWW object downloading a .PNG image. ((SpriteRenderer)renderer).sprite Sprite.Create(request.texture, new Rect(0,0,100,100)) My sprite looks fine. Now, let's be a bit redundant and create a Texture2D out of the bytes from the download Texture2D t new Texture2D(100,100) t.LoadImage(request.bytes) ((SpriteRenderer)renderer).sprite Sprite.Create(t, new Rect(0,0,t.width,t.height)) Technically, this should produce something identical to the above snippet. However, the sprite is blurry (as in, low quality). I suppose it is when calling LoadImage. What may be causing this?


How do I determine distance of a point within a ProBuilder mesh? As in the title, I have an effect prepped for my game which applies certain derived parameters to a post processing effect after the player enters a boundary I created with ProBuilder. Finding how far inside the bound the player is that is, how far the player would have to travel, at minimum, to leave it would help me scale this effect. It is not an axis aligned boundary, and its sloped shape is fairly important. Having the effect go full on on crossing the boundary would be jarring to the player. I'm tempted to resort to traditional edge testing with this, but I would like to highlight that it will be done at least once per frame on multiple objects, so I would like to keep it as simple, and non home rolled, as possible. The other possibility would be to keep track of time exposed and scale it by that but this isn't ideal and I'm seriously curious as to whether a penetration depth testing method exists out of box. A requested image of my setup It is laterally symmetric, and that is unlikely to ever need to change. However, future volumes are likely to have varying angles and heights. Depth is more or less irrelevant, as while I'm using 3D, this game has the physics of a 2D platformer so you can consider it to have infinite depth if you need to. As you can see on the right, I've added almost nothing to it, other than the MagneticField.cs custom script (which does not even reference the mesh, only whether it's been crossed) and a debug class, TriangleReport.cs, that I'm working on right now. One thought I had was to get triangles for the top, bottom, left, and right edges, use them to define planes, and then determine the distance from those planes but if you've got something better I am all ears!


My script to play the intro scene the first time the player hits play from the main menu wont work The script I am using determines if it is the players first time hitting the play button and if it is it will load the intro scene, but if they have played before it will take them strait to the game scene. The problem is that it just takes them strait to the game scene. public class SeenBefore MonoBehaviour public string SceneName AsyncOperation preload Start is called before the first frame update void Start() preload SceneManager.LoadSceneAsync(SceneName) preload.allowSceneActivation false Update is called once per frame void Update() public void before() if (PlayerPrefs.HasKey("HasSeenIntro")) preload.allowSceneActivation true else PlayerPrefs.SetInt("HasSeenIntro", 1) SceneManager.LoadScene("Intro")


Duplicate a Prefab as a separate asset in Unity 5.2 I have a Asset which is a collectable object Pickup and I currently have eight in my scene, I'd like to duplicate this asset and use it to harm the player Bad Pickup . I decided to duplicate the asset because I wanted both assets to have the same components (Animation script, rigid body, mesh colider, etc...). However, when I edit the texture of my new asset Bad Pickup , it changes the texture used for the original asset Pickup as well. I've tried GameObject Break Prefab Instance on the object with the new asset but it doesn't appear to make a difference. Is there a way to break this instance so that I don't have to make a completely new GameObject and add the same components manually?


How to make player stay on a moving object I've made an obstacle course with various moving parts to test out movement of a player. In the obstacle course there is a section where there are multiple cubes moves from side to side, and you have to jump from one to the other. But regardless of their speed, I can't seem to get the player to stay on top of any of the moving cubes. I have no clue how to fix this my only guess would be to use materials, but I can't apply any to the character controller. I appreciate any suggestion that you can give. Also the movement is done as an animation that I created in unity in the animation window. Thanks, Nova


How to efficiently keep the player from moving outside the gameobject he is colliding with? I am developing a game with Unity 2017. The game mechanics are as follow Classic top down RPG Movements are UP, DOWN, LEFT and RIGHT Player evolves in a 16 16 map He can dig in the direction he wants to make his way through the map one tile at a time At first I was using a very classical approach using tilemaps, RigidBody2D and BoxCollider2D on tiles and the player GameObjects. Collision detections went fine and my tilemap looked pretty much like that (red being the walls and white the empty spaces) The problem with this approach is that I have to keep in memory the state of 256 tiles in a List lt Vector2f gt and to create the 256 expected GameObjects representing either my walls (which a totally black), or my floor (the empty space). Creating a black GameObject with its own BoxCollider2D for each of the tile seems a little bit overkill. And this brings me to the second iteration of my game to keep in memory only the tiles the player digged. What I would like to achieve efficiently, is to let the player evolve as long as he is colliding with an underlying tile, but stop moving as soon as he doesn't. This is ok This isn't, and player should be placed to previous state. I could take advantage of OnTriggerEnter2d and handle custom collision and response, but I have the feeling that something more simple and more optimized may exists somehwhere in the wild! Thanks to any help provided!


Path solving for a game with a similiar pathing mechanic to Anno I cant quite wrap my head around how to solve pathing in my game. The basic premise is you will place buildings and roads on a 2d field and then you will be able to create routes from one building to another where the pathing alghorithm should figure out the shortest path between them (if there is one). Something to keep in mind is that the game is going to be quazi infinite scale (think factorio) and i cant think of a performant enough solution. Currently what i am working with is that i have every straight Path segment saved as two (startPoint, endPoint) Vector2Int points in a list. And everytime a new road gets added or some road segment deleted i update this list depending on what happened, example situation I have this road This would be represented in my Roads list as 0 startPoint(0, 0) gt endPoint(5, 0) 1 startPoint(5, 0) gt endPoint(5, 3) 2 startPoint(5, 3) gt endPoint(10, 3) I now add another road so we have something like this Which would change the road list to something like 0 startPoint(0, 0) gt endPoint(5, 0) 1 startPoint(5, 0) gt endPoint(5, 2) 2 startPoint(5, 2) gt endPoint(5, 3) 3 startPoint(1, 2) gt endPoint(5, 2) 4 startPoint(5, 3) gt endPoint(10, 3) What i am doing currently when a new route is to be calculated is that i create a 2d bool array which i am feeding into a A solver to get the shortest path so the above road gets transformed into 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 With some starting and endpoint. This works fine for now but when the player will build on a huge size 10kx10k, i cant imagine generating 10kx10k bool array everytime will be a good solution. Anybody knows how to optimize this?


How to figure out what's moving my GameObject? I have a GameObject as part of a complex scene with a handful of interconnected parts, that's moving when it shouldn't be. I've tried running under the debugger and setting breakpoints on all of the script points that are supposed to move its Transform, and ensured that none of them are firing. There seems to be some "spooky action at a distance" going on, some rogue script doing something I don't want it to be doing, but I can't for the life of me figure out where it is. What I'd really like is some way to set a "breakpoint" on the object's Transform that will break me into the debugger when it gets moved by any script, but that doesn't appear to be supported. Is there any way to figure out exactly what it is that's moving my object around when it shouldn't be? (And before anyone says "trial and error, disable components and see when it stops moving," I already know exactly which component to disable to make it stop moving. Unfortunately, that isn't helping track down the problem because the movement isn't coming directly from that component's MonoBehaviour script.)


Step by step 3D Game Design in Unity My main question is related to 3D game design for Unity, but please let me introduce my idea so that you can understand what I really mean. I am very eager to develop an adventurous travel 3D game (Unity), where the main character is given some kind of task in country A and if he deals with it, he goes to the upper level, which is in another country and so on. I have never developed a computer game before. I have knowledge of c and a bit of java (for the programming part of the game). But I really don t know where to start with the design. I have to think of a main character, episodic characters, environment and distinctive buildings for each country in 3D (for e.g. The Eiffel Tower in Paris, The Colloseum in Rome, The Great wall of China etc. ). My question is where to begin with the 3D design of the characters, the cities and the buildings? Can you please give me step by step instructions so that I can do something good and meaningful? I know that Blender is a good option for 3D modeling, but is it the only thing needed for the 3D game design? I have experience with Adobe Illustrator, so can I use it to some extent in this case (for 3D game elements)? Can I use Illustrator then import it in Blender and finally import the Blender product in Unity? I accept every advice given. I really need someone to explain these things to me because for now I am really puzzled and not orientated from where to begin. Thank you!


Playing an animation relative to current Transform in unity? I have an animation created with the built in dope sheet. It plays correctly but I would like it to be played relative to current object transformation. For example I have a palm tree that moves its leaves. If I rotate the palmtree and then start the animation leaves does not play animation relative to its new position orientation. I know it is playing this way because of the animation being absolute. Is there any way to make it realtive to current transformation?. Thanks in advance.


Profiling unity games on Android devices I would like to profile our Unity mobile game on Android devices in a way similar to profiling Unity games on iOS with Instruments. I am aware of how to do this using Unity's profiler, I would however like to use a third party profiler for the following reasons to validate Unity's profiling data to have more visibility into how the app is running, including Unity's functions, etc. the largest lag spikes cause unity's profiler to run out of samples. I'm however very interested in precisely these spikes I'd like to have profile data for longer periods than unity records for I'd like to do analysis over time (not just detailed data for each frame, but also aggregated over a time span) Essentially I'd like as much visibility as possible to make Android on device profiling as comprehensive as possible. As close to Instruments on iOS as possible. So far I've tried with DDMS, but could only get visibility into Andoid OS functions and seeminly nothing in the actual apk at least nothing I recognised. I tried with mono2x and il2cpp, with all debug features that I'm aware of in build and player settings enabled. The game is developed with Unity 5,4 with Mono2x. All help is appreciated. I've listed my intents above, so even if profiling on device is not possible in this way on Andoid, alternate solutions to the listed intents are still very appreciated. Thanks!


Unity How to add a shader to a material via c script? I found already some things but those seem not quite what I need. (perhaps outdated functions?) https docs.unity3d.com ScriptReference Material shader.html here, it seems you can add a shader to a renderer using UnityEngine using System.Collections public class ExampleClass MonoBehaviour public Shader shader1 public Shader shader2 public Renderer rend void Start() rend GetComponent lt Renderer gt () shader1 Shader.Find("Diffuse") shader2 Shader.Find("Transparent Diffuse") void Update() if (Input.GetButtonDown("Jump")) if (rend.material.shader shader1) rend.material.shader shader2 else rend.material.shader shader1 well i dont have a renderer. i only have a material. and there is no "material.setShader" , only a material.setTexture" sooo can anyone solve this mystery of how to add a shader to a material via script?


Export Spriter animations to Unity I want to use bone animations in my 2D game for Unity (5.0 beta). I am trying Spriter. Apparently, it has no official Unity support. There was some guy, back in 2014, who posted a plugin to convert Spriter files to Unity prefabs here http brashmonkey.com forum index.php? topic 3365 spriter for unity 43 updated integrated . However, the plugin does not seem to work (perhaps it is because I am using 5.0 beta). There are deprecated lines, like AnimationUtility.SetAnimationType(animClip, ModelImporterAnimationType.Generic) Or UnityEditor.Animations.AnimatorController.AddAnimationClipToController(controller, animationClip) If you remove them, of course it won't be able to properly export your files. So my question is is there a reasonable to use Spriter animations in Unity? I know I could just export to a spritesheet, but I was hoping to use bones for super fluid animations (I have several characters so I don't really want to make lots of spritesheets). Or perhaps there is a better bone based solution for 2D animation in Unity?


How do I storing a Score in each level? I have a problem when I store the DistanceScore to text, the problem is why the DistanceScore always storing at text number 1, this happens when I play at level 2 which is the DistanceScore could be store in text number 2and so on, FYI I have 3 levels here. here the preview as you can see on the top of level 2 gameplay is distance so when i dead the distance saved and storing to text each level. and when I go to the main menu the Level 1text updated instead of Level 2. this is my script public Item item public int mapIndex public enum ITEM TYPE LEVEL public ITEM TYPE type private void Start() loadItemInformation() public void loadItemInformation() for (int i 0 i lt item.Length i ) if ( type ITEM TYPE.LEVEL) item i .bestScore.enabled true item i .distance.enabled true float distanceUi PlayerPrefs.GetFloat( quot distance quot i.ToString()) float value PlayerPrefs.GetFloat( quot Time quot i.ToString()) float minutes Mathf.FloorToInt(value 60) float seconds Mathf.FloorToInt(value 60) if (value 0) item i .bestScore.text quot No Record Yet quot else item i .distance.text quot Unstopable quot item i .bestScore.text quot Best Time quot string.Format( quot 0 00 1 00 quot , minutes, seconds) item i .distance.text quot Long distance quot distanceUi.ToString() System.Serializable public class Item public TextMeshProUGUI bestScore public TextMeshProUGUI distance here the distance script region Distance Header( quot Distance quot ) public Transform checkPoint public TextMeshProUGUI distanceText M GameManager GameManager private float distance private float highDistance float index endregion private void Start() GameManager FindObjectOfType lt M GameManager gt () checkPoint GameObject.FindGameObjectWithTag( quot Finish quot ).transform distanceText GameObject.FindGameObjectWithTag( quot DistanceTxt quot ).GetComponent lt TextMeshProUGUI gt () index (float)(PlayerPrefs.GetInt( quot Level quot )) typo here i call it set and now I've fix it index PlayerPrefs.GetFloat( quot Level quot ) distance (checkPoint.transform.position.x transform.position.x) if (transform.position.x gt checkPoint.transform.position.x) distance 0 PlayerPrefs.SetFloat( quot distance quot index, distance) if ( GameManager.isDead GameManager.isTimeout GameManager.fuelFinished) PlayerPrefs.SetFloat( quot distance quot index, distance) PlayerPrefs.Save() distanceText.text distance.ToString( quot F1 quot ) quot m quot and for item i .bestScore.text this work to storing each level but why for the distance not working.


How to smooth terrain to lower polygon count? I'm using Unity. I've created a simple Beach using Terrain editor. The problem is that Stats show me already a lot of Triangles only for Terrain renderer 40K . So my question is how can I create a Unity Terrain suitable for Mobile game ? How can I smooth terrain edge ? Thanks


Scaling Uma Character Unity 3d My room is bigger than my UMA character so on spawn my character looks tiny. I have found this link http answers.unity3d.com questions 988134 uma how to increase npc avatar scale.html but everywhere I put my code, it does not change my avatars features. Here is my code using UnityEngine using System.Collections using UMA public class UMACreator1 MonoBehaviour public UMAGeneratorBase generator public SlotLibrary slotLibrary public OverlayLibrary overlayLibrary public RaceLibrary raceLibrary public RuntimeAnimatorController animator Range(0.0f, 1.0f) public float bodyMass 0.5f private UMADynamicAvatar umaDynamicAvatar private UMAData umaData private UMADnaHumanoid umaDnaHuman private UMADnaTutorial umaDnaTutor private int numberOfSlots 20 void GenerateUMA() GameObject go new GameObject("MyUMA") umaDynamicAvatar go.AddComponent lt UMADynamicAvatar gt () umaDynamicAvatar.Initialize() umaData umaDynamicAvatar.umaData umaDynamicAvatar.umaGenerator generator umaData.umaGenerator generator umaData.umaRecipe.slotDataList new SlotData numberOfSlots umaDnaHuman new UMADnaHumanoid() umaDnaTutor new UMADnaTutorial() umaData.umaRecipe.AddDna(umaDnaHuman) umaData.umaRecipe.AddDna(umaDnaTutor) CreateMale() umaDynamicAvatar.animationController animator umaDynamicAvatar.UpdateNewRace() go.transform.parent this.gameObject.transform go.transform.localPosition Vector3.zero go.transform.localRotation Quaternion.identity void CreateMale() var umaRecipe umaDynamicAvatar.umaData.umaRecipe umaRecipe.SetRace(raceLibrary.GetRace("HumanMale")) umaData.umaRecipe.slotDataList 0 slotLibrary.InstantiateSlot("MaleFace") umaData.umaRecipe.slotDataList 0 .AddOverlay(overlayLibrary.InstantiateOverlay("MaleHead02")) umaData.umaRecipe.slotDataList 1 slotLibrary.InstantiateSlot("MaleEyes") umaData.umaRecipe.slotDataList 1 .AddOverlay(overlayLibrary.InstantiateOverlay("EyeOverlay")) umaData.umaRecipe.slotDataList 2 slotLibrary.InstantiateSlot("MaleInnerMouth") umaData.umaRecipe.slotDataList 2 .AddOverlay(overlayLibrary.InstantiateOverlay("InnerMouth")) umaData.umaRecipe.slotDataList 3 slotLibrary.InstantiateSlot("MaleTorso") umaData.umaRecipe.slotDataList 3 .AddOverlay(overlayLibrary.InstantiateOverlay("MaleBody02")) umaData.umaRecipe.slotDataList 4 slotLibrary.InstantiateSlot("MaleHands") umaData.umaRecipe.slotDataList 4 .SetOverlayList(umaData.umaRecipe.slotDataList 3 .GetOverlayList()) umaData.umaRecipe.slotDataList 5 slotLibrary.InstantiateSlot("MaleLegs") umaData.umaRecipe.slotDataList 5 .SetOverlayList(umaData.umaRecipe.slotDataList 3 .GetOverlayList()) umaData.umaRecipe.slotDataList 6 slotLibrary.InstantiateSlot("MaleFeet") umaData.umaRecipe.slotDataList 6 .SetOverlayList(umaData.umaRecipe.slotDataList 3 .GetOverlayList()) umaData.umaRecipe.slotDataList 3 .AddOverlay(overlayLibrary.InstantiateOverlay("MaleUnderwear01")) umaData.umaRecipe.slotDataList 5 .AddOverlay(overlayLibrary.InstantiateOverlay("MaleUnderwear01")) umaData.umaRecipe.slotDataList 0 .AddOverlay(overlayLibrary.InstantiateOverlay("MaleEyebrow01",Color.black)) Use this for initialization void Start () GenerateUMA() Update is called once per frame void Update () if(bodyMass! umaDnaHuman.upperMuscle) SetBodyMass(bodyMass) umaData.isShapeDirty true umaData.Dirty() void SetBodyMass(float mass) umaDnaHuman.upperMuscle mass umaDnaHuman.upperWeight mass umaDnaHuman.lowerMuscle mass umaDnaHuman.lowerWeight mass umaDnaHuman.armWidth mass umaDnaHuman.forearmWidth mass And here's the image. I want him to be as big as the chair


Unity3d iOS build where are the textures? First time building and running my Unity3D app on my iPhone and it appears that all the textures are missing. Everything is just a solid block of whatever color I made it. When running in Unity I see everything correctly. See images below. To complicate things I'm using custom shaders, and all the objects are custom procedural meshes. Quads that I build in script. If I switch the paper backplate shader to a built in shader I still only see white on the iPhone. So I suspect that somehow the textures just aren't making it to the iOS project. When I look in the iOS project I can't find any textures. Where would they be in the iOS project? For example in Xcode under Build Phases Copy Bundle Resources the only thing there is the Images.xcassets, which only contains the splash screens and icons. Surely I'm missing something simple. I tried renaming the folder where I keep my textures to "Textures". Also my textures are not built in to the shader but added programmatically like this void Awake () meshFilterComponent GetComponent lt MeshFilter gt () Material material GetComponent lt MeshRenderer gt ().material material.SetTexture(0, paperTexture) material.color new Vector4(1f, 1f, 1f, 1f) Where paperTexture is set up in the GameObject to point to the correct texture. Is there any way to force a texture to be part of a build? Let's say that you swap out textures in code, like swapping themes, how would you make sure they're all there to be loaded as needed? Running On iPhone Running In Unity3D


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 you use playerprefs to save an array in javascript on unity As I stated I can't find a working answer anywhere else. I have a game where you are to draw out your own weapon and I'm storing that information in an array. How?


Emissive material from white texture I have texture with black and white shapes. I would like that white parts are emissive and black parts are transparent glass. How to make such material ?


How to develop custom Unity graphics? Processing is a Java library for working with computer graphics, providing methods by which to draw primitive objects, custom meshes, etc., as well as mathematical methods (such as Simple Harmonic Motion) by which to animate and control them. p5.js is an equivalent library for JavaScript and working with graphics on the web. You also have openFramworks which is similar but for C . How can you achieve similar graphics capabilities in the Unity Game Engine? Suppose, for example, I wanted to build a game like Duet. I can imagine how I might go about creating those graphics in Processing or p5.js, but not in Unity and C . How can you have that kind of creative freedom to build and draw in Unity? Thanks.


How to create a puzzle where the player needs to rotate hexagons to connect to the neighbors? I was researching different puzzle ideas and came across a game called Warframe that requires the player to hack a console to progress further into the level. The player has to spin around the hexagons (randomly generated, and get more difficult later on) to link up the connections to other hexagon neighbors. It's simple for the player to do, but also quite fun from my research. How can I create something similar to this? Edit To be more specific I would like to know how to generate a puzzle like below and how to check for successful connections. The graphics, animations, and player input I can handle. I suppose it's more about the algorithms to create the puzzle and then check the conditions. I couldn't figure out good search terms to find something similar. So even if someone can point me in the right direction, that would be helpful. I will be doing this in Unity C . Example of doing a puzzle.


Does it make sense to export and use skeletal animation as sprites? As tools like Dragonbones, Spine lets you export animations as both sprite atlas and skeleton data (JSON binary), I'm not sure which format to use when importing to Unity. I have few concerns Will there be any differences between the quality of the animations, when imported as atlas vs skeleton data? Any other pros and cons, using one over the other? If I use a sprite atlas, I don't have to depend on a third party runtime though. It is for mobile, so performance is also a concern.


Unity Deactivating Keyboard Input Interpolation I'm working on a game in Unity, and it is a little jarring to use with keyboard controls. I'm using the built in Input Manager, where I have a set of axes mapped to the left and right keys. When the player is using the keyboard instead of a joystick, I'd like it to simply be 1 when hitting left, 1 when hitting right, and 0 otherwise, but this isn't the case. I've found that for the first few frames of the button being held, Unity automatically builds up to the value for example, if I'm holding right, the value wouldn't go straight from 0 to 1, but rather from 0, to 0.25, to 0.5 and so on, continuously up to 1. Can I deactivate this? If so, how? Thanks in advance.


Manipulating an animation towards a target object (ie. The hand and arm lean towards the target) I am trying to make a boxing game just for fun (I dont expect the end product to be anything decent lol) . I have my boxers in the ring and they are animated quite well so far, with Idle, and punch Left and Right. They also rotate so they are always looking at each other. What I want to do is give the punch some aim towards the head. I will give the punch a set amount which it can move from the standard animation and move the hand bone in the direction of the targets head object. But I don't know how to do this S So far i have used dragged the 3 animation files into Mecanim and coded it to do the animations when a button is pressed. Is there a way to manipulate the animation in this way? (ie. actually make the arm reach towards the target object )


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


Keeping a Character Controller grounded? I've got a character that makes use of isGrounded() to determine whether I can jump, whether my air jump is reset, and the amount of friction to be applied. I've run into a common problem, isGrounded() is fluctuating every frame returning true and false randomly resulting in jagged movement. The standard suggestion is to constantly apply gravity. Unfortunately, aside from any other more nuanced issues that this could result in, this only works for me if I apply so much gravity that I am no longer able to climb up slopes. I need a way to keep the character grounded without applying large amounts of gravity every frame.


Agents going to the same position So more often than not I have a case where two agents get the same destination vector3. This causes some hiccups because they won't be able to get to their target because they block for one another. I was thinking that I am not the only one who has faced this issue and was wondering what you guys do to fix such an issue? An example of this could be if I want my agents to go to the nearest tree and chop it down. Since both agents have the destination which is the trees transform they will go to the same position.


How to set "useGravity" for Rigidbody to entities in Unity For the position you can use this Inject private ComponentDataFromEntity lt Position gt position But cant use it for Rigidbody. How to access the parameters for Rigidbody for entities?


Issues with Flashlight Handle position with player rotation I want the flashlight to look same while looking up and down as when looking straight. Normal Position for Hand and flashlight Looking up and down, position is completely off More images for character camera prefab rotation Basically the position of the Hand held flashlight changes when I look up or down, as well as the arm stretches. How do I fix this? Code for character rotation private void CharacterRotation() float posX Input.GetAxis(mouseX) ((StructsInitializers.Sensitivity 5) StructsInitializers.Sensitivity 50) Time.deltaTime float posY Input.GetAxis(mouseY) ((StructsInitializers.Sensitivity 5) StructsInitializers.Sensitivity 50) Time.deltaTime yAxisClamp posY if(yAxisClamp gt 90.0f) yAxisClamp 90.0f posY 0.0f ClampYAxisRotation(270.0f) else if(yAxisClamp lt 90) yAxisClamp 90.0f posY 0.0f ClampYAxisRotation(90.0f) transform.Rotate(Vector3.left posY) PlayerBody.Rotate(Vector3.up posX) private void ClampYAxisRotation(float value) Vector3 eulerRotation transform.eulerAngles eulerRotation.x value transform.eulerAngles eulerRotation PS I am new to game developing. I have lack of experience.


How unity works on Web How Unity can work on Web if the code is written in C ? I understand that you can compile the C code to a shared library and use it in Java (for Android) in ObjectiveC (for iOS) to enable Unity on multiple platforms, but you cant use shared library on JS. Does Unity do language to language translation from C to JS to enable Unity on Web? As I understand now starting from Unity 5.0 it even doesn't use Unity Web Player.


How to generate mesh at runtime using raycast points? I'm trying to make a clone of the trail line renderer with the difference that everything is perfectly flat, i.e. the faces are not designed to face the camera. I'm using two raycasts to get the position of the edges of where I want those faces but now I'm struggling to generate the mesh...I've gone through the mesh docs but I don't really understand it. Could someone help me do this? Here is my code so far public Transform probes public float probeDistance public Vector3 newVertices public Vector2 newUV public int newTriangles void Update () Generating the mesh Mesh mesh new Mesh() GetComponent lt MeshFilter gt ().mesh mesh mesh.vertices newVertices mesh.uv newUV mesh.triangles newTriangles Defining the rays Ray l ray new Ray(probes 0 .position, probes 0 .forward probeDistance) Ray r ray new Ray(probes 1 .position, probes 1 .forward probeDistance) RaycastHit l hit RaycastHit r hit Debug.DrawRay(probes 0 .position, probes 0 .forward probeDistance, Color.blue) Debug.DrawRay(probes 1 .position, probes 1 .forward probeDistance, Color.red) Getting the position of the left ray point if(Physics.Raycast(l ray, out l hit)) print (l hit.point) Getting the position of the right ray point if(Physics.Raycast(r ray, out r hit)) print (r hit.point)


How to give a Jerk Effect when the player is moving left of right float amttomove Input.GetAxis("Horizontal") playerspeed Time.deltaTime transform.Translate (Vector3.right amttomove) Currently, I have above script in Update function to move the object to left or right.But this movement is way smoother.To give it more realistic feel, I want it to have a slight jerk when it stops moving to left or right and not just stop right there and then. What exactly needs to be done to have that effect?


Getting array of points shaping curve from 2 vector3 points What I want is to get path for DoTween method DoPath(), which as a parameter expects array of vectors shaping the direction of the path. I googled some stuff and found out nothing. Just think bezier curve is good idea but i dont even know how it works. Here is an ilustration of my problem The movement must be curved, don't need linear one. Thanks in advance


How to create a searchlight in Unity ? I'm trying to create a WW2 simple game and I'm experience issue creating the light emitted from a Flak Searchlight. The final lighting effect will be something like this http s1115.photobucket.com user k4kittycrew media K4KITTY3 Slide2 zpsfccf1590.jpg.html I know that it is called "volumetric light" and this is not supported by Unity. Thanks


Placing a gameobject with restrictions I am newbie in programming and I am making a tower defense game 2d. My problem is I want to make a restriction to place a tower only, if the mother tower is in place or within its range. I'm sorry if my explanation is a bit confusing. For example, you can oly place a certain tower within the range of the mother tower and only if that mother tower is placed. I don't exctly know if I have to create a function for this or create a range game object for the placement attached to the mother tower. Any help and tips would be appreciated, thank you. This is by the way unity C .


SpriteRenderer batching issue, with Z Position and Order in Layer I have two sprites (they look the same but with different colors) I want them to be positioned like on the image above, so there's a feel like blue is standing on the green one. There are two ways to achieve that Blue block with Order in layer 1, Green block with Order in layer 0 Blue block with lower Z coordinate, so it's physically in front of the green one. Both of the concepts appear to break batching between these two objects. They're on the same atlas (I've tested it by setting the same Z position and Sorting Order and batching works). How can I achieve batching here?


It lags when it collides. Help? ( I am trying (and believing) to make a game of pong. I have got a slightly decent working game. I haven't implemented the scoreboard or AI yet because I want the physics to work first. I am trying to reverse the direction of the ball when it hits either paddle just to make it work cleanly and am having the issue where it changes direction twice, it bounces off the paddle as expected and then goes in the opposite direction to when it hit the paddle . If anyone could help me, it would be much appreciated. using System.Collections using System.Collections.Generic using UnityEngine public class BallController MonoBehaviour private float randomNumber private float range private float pointOfContact private float paddleTop private float paddleBottom private float limits private int speed private int caseNumber private Vector2 direction private Rigidbody2D ballRigidbody void Start () Getcomponent finds the rigidbody of the attached object. ballRigidbody GetComponent lt Rigidbody2D gt () speed 5 caseNumber Random.Range (0, 2) range PickARange (caseNumber) ballDirection (speed, range) void FixedUpdate() void OnCollisionEnter2D (Collision2D coll) if (coll.gameObject.tag "Player" coll.gameObject.tag "Computer") pointOfContact ballRigidbody.position.y print (pointOfContact) ballRigidbody.velocity new Vector2 (ballRigidbody.velocity.x, ballRigidbody.velocity.y 1) void ballDirection (int ballSpeed, float yDirection) randomNumber (Random.Range (0, 100)) if (randomNumber lt 49) direction new Vector2(Random.Range ( 1.0f, 0.5f), yDirection) ballRigidbody.velocity (direction ballSpeed) else direction new Vector2(Random.Range (0.5f, 1.0f), yDirection) ballRigidbody.velocity (direction ballSpeed) float PickARange (int number) switch (number) case(0) range Random.Range (0.5f, 1.0f) return range case(1) range Random.Range ( 1.0f, 0.5f) return range default range 1.0f return range I thought to multiply the whole velocity by 1 but that just caused a loop because of the lag. Even though that's the right way to reverse the direction. I think. Thanks Peeps!


2D active ragdoll physics based procedural animation I'm trying to make a 2D quadraped robot stand and walk via physics. My robot looks like this. (art is not mine. Source is vapgames) It's rigged via Unity's 2D animation package and each joint bone has it's own collider rigidbody with the legs also having hingejoints connecting the lower part to the upper part and the upper part to the main body of the robot. I've also set up IK for both legs using the 2D IK package with the IK target being attached to their respective leg via fixedjoint and can be moved programmatically to move the legs with respect to IK. I want it to stand up, as at the moment is just falls and acts as a generic limp ragdoll. I've tried these methods Adding downward force to the legs via the IK targets Adding upward force to the torso Animating the IK targets to try and get the bot to stand up with animatePhysics enabled. All of these failed (downard force to legs did pretty much nothing, upward force to torso just made it float if there was no ground, animating the IK targets was too glitchy). I'm out of ideas on how to actually do this now. I've looked around for guides but there seems to be nothing good (I keep getting this suggested to me but it doesn't help. It's in 3D and the only thing that could help, spider legs, isn't finished and probably never will be) There's very little information on how to do this sort of stuff and even when I find people who know about active ragdolls they just say add force to the head (for a 3D active ragdoll), which I've already tried (see 2. on the list of what I've already tried) and don't explain anyt further. If anyone could help, that'd be great!


Oculus Rift DK1 and DK2 compatability issues For a project I need to make a multiplayer game using Unity and the Oculus Rift. My project works fine with the DK2 but it turns out the second rift is a DK1 and it won t work with Unity. I was thinking the best way forward would be to use an older version of the Oculus Runtime and Unity. Does anyone know what versions of Unity and the Runtime I need to have both the DK1 and DK2 work with Unity?


Getting "Non invocable member 'items.item' cannot be used like a method." when invoking a class I have my item class (items.cs) not attached to any gameObjects, I want to use items for all items in my game so I can use arrays as inventories. I have Stone.cs which is attached to a gameObject. On the line inv items.item(100f, "Stone", "Rock used for building") I get a compiler error Non invocable member 'items.item' cannot be used like a method. I am confused by this as I copied it from the Unity class tutorial, just splitting creating the item to another script. items.cs using System.Collections using System.Collections.Generic using UnityEngine public class items MonoBehaviour public class item public float iQuan public string iName public string iDesc public item(float iQ, string iN, string iD) iQuan iQ iName iN iDesc iD Stone.cs using System.Collections using System.Collections.Generic using UnityEngine public class Stone MonoBehaviour Use this for initialization public items.item inv public float iMax public float iCur void Start () inv items.item(100f, "Stone", "Rock used for building") Update is called once per frame void Update ()


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?


Component based programming with child objects I am presently working on a game in Unity3d and have come to a cross road regarding scripting for repetitive child objects. Should these child objects handle its own scripting for best practice? For example, I have a parent game object, Game Board, that spawns repetitive child objects, Tiles, on the board. Right now, I let these child objects handle its own position on the board and its own animation when the tiles move. However, I can just as easily do this with the parent object's scripting class. The reason I chose to let the child object do so is because I believe that child objects should be as independent to the parent object as much as possible. But since these are repetitive child objects, I start to wonder if it is just as easy to do all the scripting in the parent object. This way I decrease the number of class instances in the child objects. According the component based programming, which method is recommended?


Seams between tiled textured cubes I've created a textured cube in Blender, which I have uv mapped like this The tiles are 256x256, and I've mapped the coordinates exactly at the edges (e.g. x 256, y 512). I then export my model as an fbx file to Unity. In Unity, if I put many cubes adjacent to each other, seams appear between the cubes, like this I think I understand why this happens, because the uv coordinates are exactly on the edges, and thus two faces sample from the same points along an edge. I could solve this in some ways By making the uv tiles smaller, but it would look ugly with patterns. By adding some space between the tiles in the texture, and aligning the uv coordinates to them. My question is there a better proper way for achieving this? UPDATE So, about half a year later I still have issues with the seams. I've tried many things Start uv coordinates at 256.5 instead of 256, and so on... Turned of mipmapping. Set wrap mode to clamp. Set filter mode to point filter. Edge padded the texture atlas with first 4px, 8px, 16px, 32px. But still bleeding occurs at certain angles. Also updated the uv coordinates accordingly. Changed my atlas to be of Power of 2 instead, i.e. 1024x1024 instead of 1024x768. Set quot Non Power of 2 quot in Unity to None so Unity doesn't rescale my texture to nearest Power of 2. Set texture format to Automatic Truecolor instead of Compressed. With 32px edge padding it actually gets a lot better, but it still isn't perfect, I guess I could go on and try even more padding, but my textures will get bigger and bigger. I understand now that it is the mip levels that are causing the bleeding. At far distances I don't think this is a problem, but I can see this occuring just about 5 7 units away from the player, if the player is looking down. I believe there is something trivial about this that I'm missing. This is really a showstopper for me, forever grateful to the one who helps me solve this. Thanks in advance! This is how I have edge padded my texture (lines not visible on real texture), the problem does not only occur when the faces has such extremes distinct difference in colors as this one. It also occurs when the faces have patterns.


Unity I need to edit my prefab but I can't move anything inside it! I imported a character into Unity and turned him into a prefab. I couldn't get my custom "Look At" script to work for the eyes, which are children of the prefab I imported. So I opened the prefab and discovered (to my HORROR) that I am unable to transform his eyes AT ALL, even in the prefab view. It's like his body parts are made of stone, or something! I checked his eyes in the Blender scene and don't see any animation data attached to them. So how could this happen? How can I fix it? The eyes ARE children of a bone called "root", which I don't think has any keyframes in any animation. Further, all my bones imported as empties.


How to change AddForce code to MovePosition or SetVelocity? Vector2 vec new Vector2(horizontal, vertical) vec Vector2.ClampMagnitude(vec, 1f) Vector3 camF cam.transform.forward Vector3 camR cam.transform.right camF.y 0 camR.y 0 camF camF.normalized camR camR.normalized targetPosition (camF vec.y camR vec.x) MoveSpeed Vector2 targetVelocity (targetPosition transform.position) Time.deltaTime rb.AddForce(targetPosition rb.velocity, ForceMode.VelocityChange) My problem is my character doesn't affects by the gravity when i changed my code from transform.position to rb.AddForce. I searched online and even asked here how to calculate gravity and add it to my character, nobody knew, so i think if i can change this code to rb.MovePosition or rb.SetVelocity maybe it does affects by the gravity?


How can I highlight words in a word search puzzle? For days I am struggling to implement the highlighting functionality in game as there is not much tutorial also for this. I did how ever make the cell of the grid change the material color but it looks ugly that's why I prefer to choose this method (see pic). How can I implement a highlighting method that will work the same on link. My try private bool first sel false private void Update() if (Input.GetMouseButton(0)) ray Camera.main.ScreenPointToRay(Input.mousePosition) if (Physics.Raycast(ray, out pressed)) if (pressed.transform.tag "cell") if (!first sel) GameObject sel Instantiate(sel cell, new Vector3(pressed.transform.position.x, pressed.transform.position.y, pressed.transform.position.z 0.55f), Quaternion.identity)


Why is Vector3.MoveTowards only working on a single frame? I have three laptops in my scene and I am trying to bring them to front when I click on them. I am able to recognize which laptop is clicked by using the code below, but it doesn't move to the focus position in a single click it moves only one frame so I have to keep clicking it. void Update () if (Input.GetMouseButtonDown (0)) RaycastHit hit Ray ray Camera.main.ScreenPointToRay (Input.mousePosition) if (Physics.Raycast (ray, out hit)) if (hit.transform.name "Laptop 1") Debug.Log("Laptop 1 is clicked") Laptop1Trans.position Vector3.MoveTowards (Laptop1Trans.position, FocusPointTrans.position, moveSpeed) else if (hit.transform.name "Laptop 2") Debug.Log("Laptop 2 is clicked") else if (hit.transform.name "Laptop 3") Debug.Log("Laptop 3 is clicked") else I tried moving the move part to a method but still same behaviour. Are there any workaround?


Why one colorKey in ParticleSystem cannot be changed without a new Gradient? My question is partly a continuation of this question. So, why I can't change just one GradientColorKey this way (without replacing the whole Gradient instance) ColorOverLifetimeModule colorOverLifetime particle.colorOverLifetime MinMaxGradient color colorOverLifetime.color color.gradient.colorKeys 1 new GradientColorKey(new Color(1, 0, 0), 0.5f) colorOverLifetime.color color colorOverLifetime.color is MinMaxGradient struct, so I copy its value in a variable color. The colorOverLifetime.color.gradient property is Gradient class and there is no need to copy it. The colorKeys property is just an array of GradientColorKey struct. So, I assign a new GradientColorKey value to the array element that already exists. Why shouldn't this work?


Get all the gameobjects for a SceneManager scene in Unity I'm using the new SceneManager to load multiple scenes in the same structure adopting the Additive method. I find it extremely useful but I wonder if there is a way to get all the GameObjects for a specific scene. When multiple scenes are loaded I see the GameObjects clearly separated by scene in the hierarchy but I cannot find a way to access the specific hierarchy of a single scene via script. Is that possible? The findGameObject method I think returns the GameObjects for all the scenes..


Unity Lerping Following Camera is too slow I'm using this script to follow a game object in 2D public class CameraFollow MonoBehaviour ... void LateUpdate() Vector3 position target transform.position float targetX position.x float targetY position.y targetX Mathf.Lerp(transform.position.x, targetX, 1 m DampTime Time.deltaTime) targetY Mathf.Lerp(transform.position.y, targetY, m DampTime Time.deltaTime) transform.position new Vector3(targetX, targetY, initial z) I've set damping time to 2. But with this when the object's speed gets higher it can't follow anymore, it lags. Any suggestions or solutions ? Here is the current situation


Code Logic's execution with respect to time Events I have to show complete 24 hours cycle in Unity3d Scene. Where different kind of task will be executed in different Times. Suppose at 2pm I have to move a car, at 6pm An Aeroplane will land on airport at 07 07pm I have to open the door of Market's Buildings and so on different task works execution at different timing. Now, I have some basic animation e.g., car, Aeroplane and door etc.,. Now I am confuse that how to play and stop my animation according to the time. And time can also be changed manually using GUI. If currently 6pm (animation working) then user can switch to 8am to view 8am time's animation (or code execution). And User can also fast the timing to view complete hours in a single minutes or in an hour. I can use if else in Update Events but I guess this is not the right way to do and will be very difficult if I require to show significant number of works in different time duration (which means significant number of if else statements). Just like below void Update() if(time 1) logic if(time 2) logic if(time 3) logic ... so on, tedious way ... and also not possible if time require between the hours, suppose 06 06pm What to do ? How to handle this?


Why does the script stop working after respawning? I have a flying enemy that follows the player public class MoveTowardsPlayer MonoBehaviour public float moveSpeed, sightDistance public Rigidbody2D theRB public Transform target private void Start() theRB GetComponent lt Rigidbody2D gt () private void Update() Vector3 targetDir target.position transform.position targetDir targetDir.normalized float dist Vector3.Distance(target.position, transform.position) if (dist lt sightDistance) theRB.velocity targetDir moveSpeed And here is what happens when the enemy dies, and then respawns public void Die() Instantiate(enemyDieEffect, transform.position, transform.rotation) gameObject.SetActive(false) public void Respawn() gameObject.transform.position initialPosition gameObject.SetActive(true) currentHealth maxHealth The enemy respawns if the player dies and goes back to the last checkpoint. Interestingly, if the player dies before reaching any checkpoint, the MoveTowardsPlayer scripts still works after respawning. It only stops working after any of the checkpoints are reached. For the sake of completeness, here is the Checkpoint script, which has absolutely nothing to do with the enemies public class Checkpoint MonoBehaviour private Animator animator public bool isReached Start is called before the first frame update void Start() isReached false animator GetComponent lt Animator gt () private void OnTriggerEnter2D(Collider2D other) if (other.CompareTag( quot Player quot )) CheckpointController.instance.DeactivateCheckpoints() animator.SetBool( quot isActive quot , true) CheckpointController.instance.SetSpawnPoint(transform.position) public void ResetCheckpoint() animator.SetBool( quot isActive quot , false)


How to sample from six cubemap images for a skybox in Shader Graph? I'm trying to update a skybox shader to URP and reimplement it in Shader Graph. The shader code itself is pretty straightforward, but I don't know enough about Shader Graph yet to set up the basic skybox. It's a standard cubemap skybox made up of six textures for x, x, y, y, z, and z. Trying to Google different variants of "unity shader graph cubemap skybox" turns up tons of noise and nothing actually useful that I can see. Does anyone know what the basic node setup is I would need to input six images and output a skybox?


2D 3D Soft body physics in Unity I want to implement soft bodies in my game similar to this link. I tried using this Soft body simulation plugin but it has the following problems Only works with box colliders. Doesn t work with Unity s physics engine i.e. the bodies don t react to the forces applied. For my game, The soft bodies should be able to collide and interact with any types of colliders (including mesh collider). The bodies should work with Unity s physics engine i.e. the bodies should react to the forces and gravity applied. I am flexible in implementing soft bodies in 2D or 3D. I would appreciate any suggestions and thoughts on this topic.


Best way to create a Chromadepth shader for unity? I'm trying to create a chromadepth environment in unity3D. So the camera sees close objects colored as red, and then farthest objects as blue. And everything in between falls down the color spectrum (Red orange yellow green blue) I've looked into a few things such as z depth or even using fog for this kind of thing. But I'm not sure what the best way to approach this is or maybe it's already been done before but I couldn't find it in the asset store. I Thanks in advance for your thoughts and time, it is much appreciated.


How to import character package in Unity I recently made a game in Unity 3D and I tried to import the FPS Controller package as the tutorial I was following said, but when I clicked Assets Import Package the only thing I saw was a button saying 'Custom Package' How do I get the character option when I click 'Import Package'?


Unable to save player data in a binary file within Update() method I'm trying to save player life within a binary file in Application.persistenceDataPath. I've written a method to store the player life public void SaveLife() BinaryFormatter bf new BinaryFormatter () FileStream file File.Open (Application.persistentDataPath " playerInfo.dat", FileMode.Open) PlayerData data new PlayerData () data.savedLife life bf.Serialize (file, data) file.Close () The problem is that when the SaveLife() is called OnApplicationQuit it works. Instead, if I call it within an Update() method of a class, it doesn't work. The Update() method is called when a certain event is triggered void Update() if (life lt 20) if ( certain event is triggered) SaveLife() lifeTimer Time.deltaTime if (lifeTimer lt 0) ResetLife () The container class for the data is Serializable class PlayerData public int savedLife What could be the problem?


is there a way to alternate between two state machines? I'm programming an enemy on Unity that has two state machines, one controlling the quot normal quot behaviour of the enemy (that consists in three states idle, patrol and chase) and another one controlling the battle behaviour of the enemy (that consists in three more states attack, dodge and run away). I'm doing these state machines by using enums, like the following code public enum StateMachines NORMAL, BATTLE public enum NormalStates IDLE, PATROL, CHASE public enum BattleStates ATTACK, DODGE, RUNAWAY I want to loop between the Normal and Battle state machines but I have one problem that is they always get executed at the same time. Is there a way I can alternate between state machines through code in a single script (by conditions)? Thank you!


NavMesh Changing Mesh by Jumping upwards I have been playing around with the NavMesh and I have seen that there are different situations where an agent has to change meshes. When it works Everything seems to work alright with links, if I try to make the agent jump from a mesh to another one, tweaking the "Jump distance" paramenter Another scenario is when the agent needs to fall to another mesh to reach the target. This one also works, when I tweak the "Drop height" parameter. When it does NOT work But there are 2 different scenarios, where the agent cant reach the target. The first one is when the agent must jump upwards instead of dropping. And the other scenario is when the agent needs to fall to another mesh that is not directly below the one he is standing on. How could I do so that the agent jumps either to move upwards, or to land in a lower mesh?


How to stop car from slipping backwards on a slope? I am trying to simulate a car in Unity, the slope of the road is high so the car slips backwards. Is there any physics property which can stop this from happening? Thanks in advance.


Simple Line Formation I'm working on the first formation for my game's troops. These should simply stand on land, facing the same direction. To achieve this, I tried to create offsets towards a pivot unit, that is approximately the unit in the center of the formation. The units are (temporary) elements of a squad list withing the Squad class. I divide the List by 2 and get the closest integer, that should be the pivot point of the formation. Now I generate offsets for all units on the left side (Unit 1 to pivot 1) and right (pivot 1 to last unit) based on the distance gaps. This is the code for the line formation. Sadly, the units are only forming a very stange line with no visually detectable system int count (int)(squadMembers.Count 2) pivot squadMembers count center pivot.transform.position switch (type) case FormationType.Line int space 5 for (int i 0 i lt squadMembers.Count i ) Unit tmp squadMembers i int dist 0 if (i gt count) dist (count 1) space center.x dist if (i lt count) dist (count 1) space center.x dist tmp.StartMove(center) break It also appears that this only works along the x axis, any idea how i can realize this with the walking facing direction ov the pivot? Is there any (obvious) error? How can I improve this script? PS Any idea, how I can transform this into a double line (2 Lines behind with half spacing)


How do I fix "Invalid character '' in input string at LitJson.Lexer.NextToken ()" when trying to use JSON from URL? When trying to use a Json file served by a url I am getting the error JsonException Invalid character '' in input string it happens when I use this method IEnumerator GetText() UnityWebRequest webjson UnityWebRequest.Get("http awebsite.com Art .json") yield return webjson.SendWebRequest() if (webjson.isNetworkError webjson.isHttpError) Debug.Log(webjson.error) else The following line is giving me the error ItemDatabase lt GetText gt d 3.MoveNext () (at Assets Version2.0 Scripts ItemDatabase .cs 38) itemData JsonMapper.ToObject(webjson.downloadHandler.text) Debug.Log(itemData) ConstructItemDatabase() I have tried to use Trim() itemData JsonMapper.ToObject(webjson.downloadHandler.text.Trim()) But still have the same result. I have tried what is suggested in this question answer, but it seems to not fix the issue I have.


Can I reset the DisallowMultipleComponent attribute in child classes in Unity somehow? Can I reset the DisallowMultipleComponent attribute in child classes in Unity somehow? I want to create my base class DisallowMultipleComponent public class MyCompanyClass Monobehaviour I want all my component scripts to inherit from the MyCompanyClass. So, I will be able to add only one instance of my component script to a game object at a time. I need it for most of my classes. But for some classes I still want to preserve the ability to add a few class instances to a game object, while still inheriting from the MyCompanyClass (because I am going to put some custom behavior into it, which is going to be used by all my component scripts). So, I was trying to search for something like AllowMultipleComponent , but found nothing. Is there maybe another way to achieve what I want?


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


How can I combine sprites and attach them to a GameObject? I have the following sprites Background Foreground Combined they should look like this The first problem is Unity can only show one sprite with its Sprite Renderer, so I can't combine them with it. The second problem is the bomb sprite should not be rotating along with the background, like so How can I do this?


How to replicate Unity's Rigidbody.AddForceAtPosition in C ? I am trying to replicate the function Rigidbody.AddForceAtPosition of Unity in C , it means, to apply force to a body offset from its center. How could I achieve that in C ?


How to construct a propeller clock in Unity? I am considering the possibility of using Unity to construct a propeller clock https www.youtube.com watch?v 6JnAxTXApw . It's an array of LEDs on a PCB board connected to motor that spins at a high RPM. The LEDS flash on and off such that it generates the appearance of a clock face. So far, I've tried turning a red pointer in a circular path with high RPM in Unity, but I don't get an image of a circular red disc. Instead I see a pointer showing random discrete movement in a circular path. Is there any suggestion to rectify this issue?


Reloading scene in Unity gives weird result I am making an infinite racing game where you fly an airplane while trying to avoid obstacles. I recently finished my menu that comes up when you die. When I press the restart button that simply reloads the current scene like this SceneManager.LoadScene(1) it gives me a weird result. The obstacles starts generating at about the same position as you died previously. I never get this problem when I start the game with the Unity play button. The only thing I could think off was player prefs. It should not affect the generation of obstacles but tried anyway to use PlayerPrefs.DeleteAll() before reloading the scene, but that did not work. What could be causing this strange problem?


How to make a 2D neon like trail effect in Unity Recently I've been toying around with neon ish effects for a game I'm making and wanted to share my results with you. If you guys have any other methods of achieving this result, please be sure to share.


Additive scene loading to UNet I have a main scene where my player is loading as I start or join the server. On some player action, I want to load additive scenes in to my main scene. It is loading fine on the client, but not across the network. My other clients are unable to watch it. I checked different links, and found a forum post and a Unity Suggestions page. It seems, to me, that this "Additive scene loading to UNet" feature is not available in Unity. If additive scene loading in UNet is not available, then what are the alternatives? I am able to load scene through ClientRpc . Is this the correct way to do this? ClientRpc public void RpcLoadLevelAcrossNetwork() SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive)


Which GameObject should I put the animator on? I have a GameObject. One of its children is an empty GameObject, whose children are the body parts which need to be animated. Character (root) gt Body gt gt Body Parts Should I put the animator on the root GameObject ("Character")? Or on the empty child ("Body")? Does it matter? What benefits would one way offer over the other? Or is there another approach I should be taking? This is for 2D sprites animations. I am trying to figure this out before making all of the animations to avoid redoing them.


Move an object with other objects connected (via joints) the right way What is the best way to move an object with other objects connected to it via joints? Let's assume we have the following setup A player that can move on the x and the z axis "Normally configured" RigidBody Moving like this void FixedUpdate() Vector3 movement new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical")) movement movement.normalized 2f Time.deltaTime m rb is the RigidBody of the player m rb.MovePosition(transform.position movement) Another object that should be moving with the player as it were its child Connected to the player via a fixed joint "Normally configured" RigidBody When moving the player without any object connected the movement looks as expected Now moving the player with the object connected results in some kind of dragging effect as seen here One way to solve this behaviour would be to also move the connected object m otherRb is the RigidBody of the connected object (m other) m otherRb.MovePosition(m other.transform.position movement) Is there a better way to solve this? Shouldn't the joint handle the movement of the other object? Moving the connected object like this results in many problems like to high impulse forces when colliding with something as both elements get pushed towards the collider. Also handling the rotation of the connected object isn't as easy as the position.


How to Replace two object by rotating in center I created Find Rock game but I have problem In replacing two object by rotating in center and when rotating finish stop rotating how can I do this? using UnityEngine using System.Collections public class example MonoBehaviour public GameObject obj public int Randomize new int 2 void Start() StartCoroutine (Delay ()) IEnumerator Delay() Randomize 0 Random.Range (0, obj.Length) Randomize 1 Random.Range (0, obj.Length) while (Randomize 0 Randomize 1 ) Randomize 0 Random.Range (0, obj.Length) yield return new WaitForSeconds (2) obj Randomize 0 .transform.rotation Quaternion.Euler (new Vector3 (0, 0, 0)) obj Randomize 1 .transform.rotation Quaternion.Euler (new Vector3 (0, 0, 0)) StartCoroutine (Delay ()) void Update() if (obj Randomize 0 .transform.rotation.eulerAngles.y lt 90 obj Randomize 1 .transform.rotation.eulerAngles.y lt 90) obj Randomize 0 .transform.RotateAround (obj Randomize 1 .transform.position, Vector3.up, Time.deltaTime 100) obj Randomize 1 .transform.RotateAround (obj Randomize 0 .transform.position, Vector3.up, Time.deltaTime 100) I can make this game but when rotating finish they aren't Directed. this video link describe my problem and this is unity package of my game. how can I use mathf clamp RotateAround for stopping rotation?!


Check whether a vector is to the left or right of another position I don't know how to decide if my point is on the left or right side of another object. My first thought was to check if x axis of object1 is bigger or smaller than object2's, but if my objects rotate then that isn't working. In the picture above we have two states where object2 is on the left side of object1. In one case its x coordinate is greater, in the other, its x coordinate is less.


How to implement Vector3.MoveTowards follow with random movement I want to implement an AI behavior where an enemy runs towards the player while sidestepping randomly and aggressively (like in this video https www.youtube.com watch?v 35Ut C4eL40) Currently I am just using Vector3.MoveTowards but that results in smooth movement which isn't exactly what I need. I've tried adding an offset to the target using Random.insideUnitCircle but it just doesn't work. If anyone could give me an algorithm to implement it'll be great. Thanks


Rotating a button in Unity UI by 180 on the Y and it stops working If I rotate my button by 180 on the Y axis I can't even click on it. If for example I rotate it 180 on the Z axis everything is fine. Why does this happen and how can I fix it ?


Conditional Variables in Scriptable Objects While using ScriptableObjects, how can I make some variables conditional? Example Code System.Serializable public class Test ScriptableObject public bool testbool public string teststring public int testint Goal When testbool true then teststring is available to edit, when testbool false then testint is available to edit while the other one is "grayed out".


Corgi Engine Character glitches with "jump" animation on top of a ladder I'm new to Corgi Engine and Unity in general. I have an issue that I could find a way to resolve. I'm using CorgiEngine's quot RetroLadder quot prefab and extended quot Rectangle quot character with custom animations from quot MinimalLevel quot The problem is that when character finishes climbing the ladder, for a very short amount of time, jump animation appears. As in my case jump animation is very different from idle animation, this feels like an unpleasant glitch to me, so that's why I want to fix it. You can see it on the GIF below (at first I jump near the ladder to show how animation looks and then start climbing the ladder and on the top jump glitches) I checked some other demos (e.g. RetroVania, which uses some ladders there) and they also have this quot glitch quot with Corgi demo character, but as the character's idle and jump animations are not very different, it doesn't seem wrong (GIF below) I suspect that this glitch happens because quot CharacterLadder.cs quot script disables gravity during ladder climbing and then enables it back which triggers fall of the character Do you think it's possible to workaround it somehow? Thanks!


Why do these textures tile rather than just overlap? It might help to provide all the details, so here is the YouTube tutorial which sparked my question. There's a prefab of the background tile called "Tile Background." This prefab has the default settings, except that Pixels Per Unit is set to 512, and that it has a script attached to it called BackgroundTile which hasn't even been opened. It's just there for the other script to reference. An empty object was created called Board, which has Tile Background as its tile prefab. It also has a script, Board.cs, the contents of which are here using System.Collections using System.Collections.Generic using UnityEngine public class Board MonoBehaviour public int width public int height public GameObject tilePrefab private Backgroundtile , allTiles Start is called before the first frame update void Start() allTiles new Backgroundtile width,height Setup() private void Setup() for(int i 0 i lt width i ) for(int j 0 j lt height j ) Vector2 tempPosition new Vector2(i, j) Instantiate(tilePrefab, tempPosition, Quaternion.identity) Width is set to 4. Height is set to 7. Other than that, the camera position is X 1.5,Y 3 and the aspect ratio is 9 16. My question is this why, when this is run, does Vector2(i,j) get interpreted as tiling the sprites, rather than placing the sources of the sprites in a 4x7 pixel grid, where they overlap almost entirely? There's no place where their positions get multiplied by the size of the tiles, right? Halving the pixels per unit doesn't even just halve the height of the board it stays a constant size and looks really weird, despite the board not having set dimension attributes. What's going on here?


Loading encounters and collisions questions within 2D I had three basic questions regarding the creation of a 2D sandbox openworld game much like Terreria. Only looking for a general overview opinion, nothing too detailed. Any links to literature that would help answer the questions below would also be helpful. First off Keeping track of the map using regions chunks, lets say 512 x 512 chunks. Is it recommended to pre load the surrounding chunks of the 'chunk in focus', so if the character enters either one there is no load time? Or do you simply load smaller slices of the chunk next door, in the direction of movement? Secondly. Do I need to add a collision box to every tile that is preloaded so any NPCs that are off screen but 'next door' can interact with the environment? Or is this going to be massively CPU intensive ? (512 x 512 x 9 tiles alone) Third and last question. Off screen RANDOMDLY GENERATED NPCs monsters I assume dont load and render as they enter the viewable area on the active chunk but are loaded and activated sometime before they are seen. What are the general strategies use to handle this? For Reference Using c with Unity, no third party frameworks plugins. Many thanks John


Unity PoolingSystem failing to instantiate I am wanting to spawn monsters into my scene in Unity. I was told to use a Pooling System, so I got the free one Unity offers in the Asset store. I have followed the little documentation that there is, and am encountering an error. I do not know if I am just missing something but I am getting an object reference not set error. NullReferenceException Object reference not set to an instance of an object PoolingSystem.InstantiateAPS (System.String itemType) (at Assets Advanced Pooling System PoolingSystem.cs 104) MobSpawner.Start () (at Assets Scripts MobSpawner.cs 16) It throws this on the following code private PoolingSystem poolingSystem Use this for initialization void Start () poolingSystem PoolingSystem.Instance poolingSystem.InstantiateAPS("Resources EnemyPrefabs Skeleton") Could someone please guide me in the right direction or tell me what is wrong here?


Visual studio alternatives for unity as intellisense not working I am new to unity and unity tools for game dev are unavailable in vs community,i also tried vs code.So what are some alternatives for vs for unity scripts for a beginner?


One side of every object is black I'm trying to make a driving game in Unity, but recently have been having lighting issues. When I was first building it, the lighting worked fine. However, recently, one side of everything (the indirect lighting side) has turned black. Here's an image of the issue. I've tried changing my lighting settings, but can't seem to fix it. Here are my lighting settings. What can I do to fix this? (I am using Unity 2017.2.0f3)


Getting Image From Android to Unity3D I am trying to get an image from the user gallery and import it in unity. I have written a native plugin in Android Studio and exported JAR as it s needed for the native stuff to get working. I am successful in opening gallery but I don t have an idea how do I get that image retrieved from OnActivityResult in Java File and use it in C for Unity. Any help and ideas will be highly appreciated.


How to "amplify" a force and physic using AddForceAtPosition? I have the object in the image. The red box is kinematic when an object hit it , i set kinematic to false, so Unity apply normal physic. But I would like to apply also a force to the point indicated by the violet cross. So I'm using Rigidbody.AddForceAtPosition rb.AddForceAtPosition (ForceDirection ForcePower, PointForcePosition.transform.position, ForceType) PointForcePosition is an empty GameObject child of the red box object, placed where violet cross is pointing. My question are Force Position can I use that approach (an empty gameObject placed where i want to apply force ) ? Force Direction is it corret a Vector3 ( 0 , 1 , 0 ) to indicate a down force Which ForceMode is the best for my purpose ? Impulse ? Force ? Thanks


Downsides of using a 8192 x 8192 texture? So I am using Unity to build a 2D game and one thing that I needed is to be able to render a lot (talking about 10s of thousands) of sprite to the screen so I have a custom solution that basically is a single game object with a script that uses Graphics.DrawMesh() with pretty good results right now. Now I know another way to reduce draw calls is to have a few materials as possible (as I believe a single mesh can only use 1 material) so I was think about using a 8192 x 8192 texture as basically my main (maybe only texture) as with 64 x 64 sprites, I can fit a bit over 16000 sprites which should be more than enough for all the sprites in the game world). My question is whether or not there is any major downside of using a texture of this size? I am sure there are decides and video cards that would not support this but I am curious as to what those are. Would current gen next gen consoles support this? At what point would video card not support this? For the game I am working on mobile VR is not a concern. If this texture size would restrict support too much, what about 4096 x 4096?


Spawning random objects at random positions in the 3D world My main character can move horizontally and not vertically. It can move from x 4 to 4 and z 4 to 4 (a square area). I don't want objects to spawn where my character can move but every where else. I wrote the following script. According to me it should have worked perfectly fine. But, I can't figure out why the objects are still spawning in the perimeter where the main character is present. public class SpawnGameObjects MonoBehaviour public float secondsBetweenSpawning 0.1f public float xMinRange 25.0f public float xMaxRange 25.0f public float yMinRange 5.0f public float yMaxRange 0.0f public float zMinRange 25.0f public float zMaxRange 25.0f public GameObject spawnObjects what prefabs to spawn private float nextSpawnTime void Start () determine when to spawn the next object nextSpawnTime Time.time secondsBetweenSpawning void Update () exit if there is a game manager and the game is over if (GameManager.gm) if (GameManager.gm.gameIsOver) return if time to spawn a new game object if (Time.time gt nextSpawnTime) Spawn the game object through function below MakeThingToSpawn () determine the next time to spawn the object nextSpawnTime Time.time secondsBetweenSpawning void MakeThingToSpawn () Vector3 spawnPosition get a random position between the specified ranges spawnPosition.x Random.Range (xMinRange, xMaxRange) spawnPosition.y Random.Range (yMinRange, yMaxRange) spawnPosition.z Random.Range (zMinRange, zMaxRange) if ((spawnPosition.z lt 4 amp amp spawnPosition.z gt 4) (spawnPosition.x lt 4 amp amp spawnPosition.x gt 4)) MakeThingToSpawn () determine which object to spawn int objectToSpawn Random.Range (0, spawnObjects.Length) actually spawn the game object GameObject spawnedObject Instantiate (spawnObjects objectToSpawn , spawnPosition, transform.rotation) as GameObject make the parent the spawner so hierarchy doesn't get super messy spawnedObject.transform.parent gameObject.transform


How can I convert an html5 web game to an android app? I have already made an html5 game and it is in service. I want to service this at Android app too. I know little about Java or Kotlin, so I think the least risky way is to use a webview. There is already a function to save game data with Oauth authentication. I thought this part should be replaced with google play Oauth. However, there is a problem that the app does not run when the player is offline. (Run the app fails to load any html document) However, if you load a local html file, it will be rejected from the existing firebase SDK because there is no domain. In fact, I know very little about native app development, so I don't know that what I don't know, what I need. What should I do in this situation? Do I need to rebuild my app in Kotlin or Java from scratch? Do I have to use the same engine as Unity? Do I have to rebuild with a framework like cordova? The question may not fit here, but I need help. Please.


What's the "right way" to open a websocket connection inside WebGL? The official Unity documentation says that, to run websockets in the WebGL player, you should use this plugin on the Asset Store. Unfortunately, following that link leads to a notice that this asset has been deprecated and is no longer available, with no explanation as to why or what should be done to replace it. With that unavailable, how should I implement WebGL websockets in my game?


Are all referenced sprites loaded into memory for each object? I'm trying to understand how Unity works behind the scenes. Let's say I have a GameObject that has a large number of sprites attached to it in an array (think a deck of cards). Each GameObject represents 1 card. For simplicity, each card has all the sprites for all the card faces. So it has 52 sprites 1 for the card back (all in a sprite sheet of course). If I have all 52 cards placed in the world. Does this mean I have 53 52 2756 sprites, or is there only one instance of each sprite that's being displayed (ie does it only use the resources of 52 active sprites)? I guess what i'm asking is if I have a bunch of sprites attached to a GameObject, are they all instantiated when the object is created, or are they only created when they are actually attached to the sprite renderer? Would it be more efficient to only attach the current cards value sprite (ie just the back and the face for the cards value)?


How Client send info to Host in Unity Multiplayer I want to send player name and other details from client to host device. I have setup game for maximum two players connection. Here is the code that I have tried multiple times with different changes void Start () spriteRenderer GetComponent lt SpriteRenderer gt () circleCollder GetComponent lt CircleCollider2D gt () StartCoroutine (ColorSwitcher ()) InitialTasks () private void InitialTasks () isAlive true GameManager.Instance.IsPlayerWin false int selectedTheme Random.Range (0, ballSprites.Length) spriteRenderer.sprite ballSprites selectedTheme trailRenderer.material trailMaterials selectedTheme destroyParticleObj.GetComponent lt ParticleSystemRenderer gt ().material trailMaterials selectedTheme hidePlayerName OnTouchHidePlayerName if (!isLocalPlayer) remote player gameObject.tag GameConstants.TAG REMOTE PLAYER else local player Debug.Log ("locally set player name " DataCollection.localPlayer.PlayerName) playerNameText.text DataCollection.localPlayer.PlayerName StartCoroutine (SomeDelayForSendingPlayerDetails ()) if (isServer) RpcSetRemotePlayerName (DataCollection.localPlayer.PlayerName) else CmdSetRemotePlayerName (DataCollection.localPlayer.PlayerName) public override void OnStartLocalPlayer () base.OnStartLocalPlayer () CmdSetRemotePlayerName (DataCollection.localPlayer.PlayerName) ClientRpc private void RpcSetRemotePlayerName (string remotePlayerName) playerNameText.text remotePlayerName Debug.Log ("rpc remote player name " remotePlayerName) Command private void CmdSetRemotePlayerName (string remotePlayerName) RpcSetRemotePlayerName (remotePlayerName) Debug.Log ("cmd remote player name " remotePlayerName) Basically I want to interchange names of both players in 2 players multiplayer game. So please give me some advice into this.


How to stop jumping again when 3D character is in air (double jump)? I'm working on simple rpg and having some trouble with player jumping. I'm trying to use unity's raycast to check colliders under the player before jumping again. The problem appears that no matter how many tweaks I make to the distance or the validation of the canJump function, the raycast the player seems to at max jump twice. At lower levels the player can even hover if timed correctly. Could someone overlook my code since it appears that I might have a noob glitch somewhere? using System.Collections using System.Collections.Generic using UnityEngine public class Player MonoBehaviour public float speed public float jumpForce public float turningSpeed private bool canJump void Start() void Update() RaycastHit hit if (Physics.Raycast(transform.position, Vector3.down, out hit, 1.01f)) canJump true ProcessInput() void ProcessInput() if (Input.GetKey("right") Input.GetKey("d")) transform.position Vector3.right speed Time.deltaTime if (Input.GetKey("left") Input.GetKey("a")) transform.position Vector3.left speed Time.deltaTime if (Input.GetKey("up") Input.GetKey("w")) transform.position Vector3.forward speed Time.deltaTime if (Input.GetKey("down") Input.GetKey("s")) transform.position Vector3.back speed Time.deltaTime if (Input.GetKeyDown("space") amp amp canJump) canJump false GetComponent lt Rigidbody gt ().AddForce(0, jumpForce, 0)


How can I optimize the size of my .apk? I noticed that the Flappy Bird .apk is only around 900 KB. I'd like to know how I can achieve a similar optimization in .apk file size for my own games, which use Unity. A small single scene game developed with Unity will have an .apk size of nearly 10 MB, in comparison.


how to reset etsa function GetJoystickNames in unity? the problem is that if I connect a command the array GetJoystickNames increases an index but if you disconnect it does not reduce the index and continues counting as if it were connected


Why doesn't my C 6 code compile in Unity? Why can't Unity work with C 6 code? It always gives me compiler errors. Here are some code examples using static System.Convert using static System.Environment " punten NewLine Money NewLine KilledEnemies NewLine bonus NewLine total " I use Visual Studio as my code editor and build with no errors. If I press play in Unity it won't build.


Unable to add asset sprite, not sure why I'm using Unity and have a 2D project. I'm trying to add a background image to my project scene, but I'm unable to. Adding smaller .png files to the project work fine, by simply dragging them onto the Hierarchy tab. My background image, and larger images, do not work though. Below is the image in question It's a 66kb png. Nothing weird about it. How should I be adding it as a background if I'm unable to add it as a sprite? Below is the assets settings under Import Settings


How to stop several coroutines running on array of game objects In the code below, I am running a coroutine on each element of an array of game objects. How can I stop running the FadeToForEnemy coroutine on each game object? IEnumerator EnemyCycle() while (isRepeating) for (int j 0 j lt enemies.Length j ) Enemy currentEnemy enemies j var myMaterial currentEnemy.GetComponent lt Renderer gt ().material var currentFade StartCoroutine(FadeToForEnemy( myMaterial, 0f, 1f, currentEnemy.gameObject, false)) yield return new WaitForSeconds (hdTime) for (int j 0 j lt enemies.Length j ) Enemy currentEnemy enemies j var myMaterial currentEnemy.GetComponent lt Renderer gt ().material var currentFade StartCoroutine(FadeToForEnemy( myMaterial, 1f, 1f, currentEnemy.gameObject, true)) yield return new WaitForSeconds (srTime) UPDATE I tried stopping the coroutines in the following but the cycle of fading in and out just continued. public void StopEnemyCycles () for (int i 0 i lt enemies.Length i ) enemies i .StopAllCoroutines () StopCoroutine ("EnemyCycle") Also below is FadeToForEnemy IEnumerator FadeToForEnemy(Material material, float targetOpacity, float duration, GameObject gameObj, bool isEnabled) Cache the current color of the material, and its initiql opacity. Color color material.color float startOpacity color.a Track how many seconds we've been fading. float t 0 if (isEnabled) gameObj.GetComponent lt BoxCollider2D gt ().enabled isEnabled while(t lt duration) Step the fade forward one frame. t Time.deltaTime Turn the time into an interpolation factor between 0 and 1. float blend Mathf.Clamp01(t duration) Blend to the corresponding opacity between start amp target. color.a Mathf.Lerp(startOpacity, targetOpacity, blend) Apply the resulting color to the material. material.color color Wait one frame, and repeat. yield return null if (!isEnabled) gameObj.GetComponent lt BoxCollider2D gt ().enabled isEnabled I have several groups of enemies, each group fades in and out at the same time.


Why isn't my tilemap collider appearing? I am trying to make a 2d game but my player falls through the tilemap every time. My tilemap collider doesn't seem to show up. What is going on and how do I fix this? The first image is rigidbody currently falling through the tilemap and the tilemap. The second image is rigidbody currently falling through the tilemap and the rigidbody.


How can I turn off the sound from another scene? I attached music file to my first scene and thanks to following javascipt code, sound continues without stopping in other scenes. public static var object SingletonMusic null function Awake() if( object null ) object this DontDestroyOnLoad(this) else if( this ! object ) Destroy( gameObject ) My problem is that I want to turn off the sound from the button in the another scene (setting scene) so that I added a new button to my setting scene and attached the following javascript code to the button that I have created. Javascript code var objects AudioSource SingletonMusic.object.GetComponent(AudioSource) if( objects.isPlaying ) objects.Pause() else objects.Play() However, it gives following errors If I start the game from Setting scene I get this error If I start the game from first scene and then, go to Setting scene I get this error


Camera is centered on character, but doesn't show character in game window I'm using Unity 4.6.3. I create an animation from sprite. When I press Play button, I see animation plays on scene window, but on Game Window, I don't see anything. Here is Inspector for main camera Here is Inspector for Player I have checked that both z 0 when execute. Please tell me which part I config wrong ?


ForceMode in AddTorque in Unity game development In UNITY game development platform while programming in C I came across a method to add torque to component public void AddTorque(float x, float y, float z, ForceMode mode ForceMode.Force) In this Function what is meant by ForceMode?