How can i keep the spawned cubes to be inside the given area? In this case the 4 walls and objects I spawn inside the 'wall area' are all cubes. This situation could change to where the walls will be spheres and the other objects can be cylinders or cubes (its not limited to cubes only). What I'm trying to do is to spawn the objects in random positions but within the 'wall area'. The problem is when some cubes (objects) are spawning too close to the walls, part of the cubes will inside the area and some will be outside. In the screenshot example on the right, a cube is going out of the wall area. In this case the walls area is sized according to the terrain (500x500) but it could be any size like 45x23 or 100x100. In the script below I'm getting the 4 walls objects in array. walls GameObject.FindGameObjectsWithTag("Wall") Now I wonder how can I use a ray cast to detect if each cube is spawning too close to one of the walls and if so then re position the cube randomly, over and over again until it's inside the walls area. I'm not sure if using ray cast is the best way but that's what I had in mind. using System using System.Collections using System.Collections.Generic using System.IO using UnityEngine public class SpawnObjects MonoBehaviour public int numberOfObjects public GameObject objectToPlace public Vector3 newObjectsSize public float spawnSpeed 0.1f private int wallsLengthX private int wallsLengthZ private int wallsPosX private int wallsPosZ private int currentObjects private GameObject walls private List lt GameObject gt objects new List lt GameObject gt () private GameObject spawnedObjects void Start() var wi GetComponent lt Walls gt () wallsLengthX (int)wi.lengthX wallsLengthZ (int)wi.lengthZ wallsPosX (int)wi.wallsStartPosition.x wallsPosZ (int)wi.wallsStartPosition.z walls GameObject.FindGameObjectsWithTag("Wall") spawnedObjects GameObject.Find("Spawned Objects") StartCoroutine(Spawn()) IEnumerator Spawn() for (int i 0 i lt numberOfObjects i ) GameObject newObject (GameObject)Instantiate(objectToPlace) newObject.transform.localScale GenerateRandomScale(newObject) newObject.transform.localPosition new Vector3(GenerateRandomPositions(newObject).x , GenerateRandomPositions(newObject).y newObject.transform.localScale.y 2.0f, GenerateRandomPositions(newObject).z) newObject.name "Spawned Object" newObject.tag "Spawned Object" newObject.transform.parent spawnedObjects.transform objects.Add(newObject) yield return new WaitForSeconds(spawnSpeed) currentObjects 1 var wp GetComponent lt WayPoints gt () wp.FindMyObjects() private Vector3 GenerateRandomScale(GameObject newObject) Vector3 newScale new Vector3(UnityEngine.Random.Range(5, 100), UnityEngine.Random.Range(5, 100), UnityEngine.Random.Range(5, 10)) return newScale private Vector3 GenerateRandomPositions(GameObject newObject) float paddingX Mathf.Clamp(newObject.transform.localScale.x, 0, wallsLengthX) 2f float paddingZ Mathf.Clamp(newObject.transform.localScale.z, 0, wallsLengthZ) 2f float originX wallsPosX paddingX wallsLengthX 2f float originZ wallsPosZ paddingZ wallsLengthZ 2f float posx UnityEngine.Random.Range(originX, originX wallsLengthX paddingX) float posz UnityEngine.Random.Range(originZ, originZ wallsLengthZ paddingZ) float posy Terrain.activeTerrain.SampleHeight(new Vector3(posx, 0, posz)) return new Vector3(posx, posy, posz)


Materials aren't loading correctly from SketchUp into Unity I imported a SketchUp COLLADA (.dae) file from 2017 SketchUp Make, and imported it into Unity. I then clicked quot Use External Materials quot and the colors began to load. But I noticed quickly that one of the wings of my imported B 29 was Dark Gray, while the other way a proper color. Random parts, such as the front engine housing piece, were also dark gray. Parts of my advanced dials were also dark gray, and I immediately decided that there is now ay that I am going to manually go in and fix every single dark gray material, but at the moment, I found no alternative. I began with the wing. I went to assign the material that I used for the other wing, which was white, to the dark gray wing, but I found out that the other wing already had that material in use. And when I went to assign a different white color, absolutely nothing changed, aside from the fact that the wing now claimed that it had that color in use. Is there a fix for this problem? I could try importing as a .SKP file, if the reason for the issue is something to do with the COLLADA (.dae) file. What I had was 2 wings. they were both components in SketchUp, so whatever I did to one applied to the other, Then I made them unique before importing to Unity. The Wing that won't work right is the one wing that had the USAF Insignia on it. But I doubt this is the problem, because all engines on that wing were also not colored correctly, whereas the other wing was fine. Those engines were also components, but were also made unique before the import. Each wing has 9 groups inside of it. The other wing is identical in this sense. I imported the file from file explorer by dragging the file from file explorer and dropping it into unity. This is what the plane looks like in Unity My apologies for the crude handwriting, it is difficult to draw with a touchpad. In the image, I numbered the incorrectly colored parts visible in the image (Right Left references are perspective to image) 1. Left Wing. Color Dark gray. Color intended White. 2. Propeller blade hub. This is the part that all propeller blades are connected to. Both hubs on the two propellers on the Left Wing are colored incorrectly. Color white. Color Intended Grey. 3. Pistons. All piston components, such as the pistons, securing poles, and piston heads are not colored correctly same on the other engine on the Left Wing. Color White. Color Intended Grey pistons, darkish grey piston heads, and copper orange securing poles. 4. Cowl Flaps. In the image, this appears to be a stripe in the engine. Same with the other cowl flaps on the other engine on the Left Wing. Color Dark gray. Color Intended White. 5. Propeller blades. All 4 propeller blades on both engines on the left wing are not colored correctly. Color White. Color Intended Black, with yellow tips. 6. Right Wing Pistons. Most piston components, such as the pistons heads and securing poles are not colored correctly. Same with the other engine on the Right Wing. Color White Piston Heads, Grey Pistons, Almost Black Gray in the lines on the pistons, white securing poles. Color Intended Grey pistons, darkish grey piston heads, and copper orange securing poles. 7. Front Engine Casing. The same error is in the other engine's front engine casing on the Right Wing. Color Dark Gray, with an apparent shine coming from beneath the part, which shouldn't be happening (the directional light is above the engine part). Color Intended White. 8. Rear Engine Casing. The same error is in the other engine's rear engine casing on the Right Wing. Color Dark Gray, with an apparent shine coming from beneath the part, which shouldn't be happening (the directional light is above the engine part). Color Intended White.


Why is there a discrepancy between these two transform.up vectors? I was trying to implement a feature which required transform.up, the result didn't match the green axis gizmo displayed in the editor so I assumed it was being put off by the rotation of the object despite expecting the gizmo to adapt to that. I then modified the prefab such that everything was now child to an empty object and the secondary objects were child to that instead of the rotating model, and wrote a script that simply copies the transform so that it tracks. This still didn't show the values expected from what the gizmo in the editor showed. I then did a Debug.LogError in the track script and this time the result was as expected. Why is transform.up showing the value expected from the local y axis gizmo but when passing a reference to the original script and checking tracked.transform.up gives off results? To reproduce in a simpler environment I set up a simple test scene. Simple default cube with the hierarchy structure shown in the screenshot. The transform values are as follows parent zeroed x 0, y 90, z 0 for cube x 0, y 90, z 90 for TrackPoint Scripts are as follows test.cs attached to trackpoint private void Update() Debug.LogError(transform.up) Track.cs attached to tracker public Transform transformToTrack private void Update() transform.position transformToTrack.position transform.rotation transformToTrack.rotation Debug.LogError(transform.up) byref.cs attached to cube public GameObject refObj private void Update() Debug.LogError(refObj.transform.up) When run, if you clear the console then click pause you'll see that one of them differs from the others. I don't understand why. My project and this sample scene differ in which it is that is giving unexpected results but the results are inconsistent with what I would expect. But wouldn't they all give the same result?


Apparently, Unity decided to import a bunch of things I already had I am getting lots of errors ever since Unity decided to reimport plugins and Unity assemblies that were already present in my project. I am not sure what I can now do, what folders to delete to fix this issue, etc. Is there any simple solution to fixing all of these problems? I cannot even click play in the Unity Editor now.


Object Touch Drag Problem Object moving to next finger My Code is as follows foreach (Touch touch in Input.touches) switch (touch.phase) case TouchPhase.Began touchPosition Camera.main.ScreenToWorldPoint (Input.mousePosition) offset touchPosition GOCenter break case TouchPhase.Moved touchPosition Camera.main.ScreenToWorldPoint (Input.mousePosition) newGOCenter touchPosition offset newGOCenter.y 0.0f newGOCenter.z 0.0f gameObject.transform.position newGOCenter gameObject.transform.position new Vector3 ( Mathf.Clamp (gameObject.transform.position.x, boundary.xMinMax, boundary.xMinMax), 0.0f, 0.0f ) break default break What i am doing is i am moving the player left and right along x axis by dragging in the screen. When i drag move the player with one finger then it works as expected. But when i keep another finger in the screen and take out the first finger from the screen the player comes of the second finger. I want the player to be moved from the place where it was left instead of coming to the second finger. I have done disabled multiTouch but it does not worked. user fingerIndex


How can I properly display the distance with the unit in a string on the UI? I wrote a script for distance of car and I don t know how to make distance like this Distance 156Km. I wrote this code distanceText.text ((int)distance).ToString() "Km" It works only from 1 to 9 when it goes to 10 Km, it disappears but if I write it like this distanceText.text ((int)distance).ToString() " Km" It show like this from 1 to 9 "5 Km" and from 10 to 99 "99Km" but when it goes to 100 Km and above, it disappears. What code should I write for this to show always Km after the distance. And I have one more question. I have a gameover canvas and I'd like in gameover canvas to show the final distance I make with PlayerPrefs but it doesn't work. Here it shows how it does not work


How to integrate images into text lines in Unity? Here are two screenshots from Stellaris, where images are seamlessly integrated into the text. How can I achieve this in Unity?


Raycast not hitting a collider I have the following simple raycast from a capsule on a cube bool hit Physics.Raycast (transform.position, Vector3.down, jumpSettings.groundJumpDistanceCheck, jumpSettings.layerMask) print(hit) When my layerMask is 8 (terrain), I have set my layer on my cube and my groundJumpDistanceCheck is 2. Then my hit is false. When my groundJumpDistanceCheck is set to Infinity. Then my hit is still false. However when I remove the distance parameter bool hit Physics.Raycast (transform.position, Vector3.down, jumpSettings.groundJumpDistanceCheck, jumpSettings.layerMask) print(hit) Then hit returns true. This is odd for me, as far as I know when you exclude the distance parameter it's supposed to be Infinity by default. But when I explicitly give Infinity as the distance, it returns false. I have also used the following code in an attempt to debug my issue, using the desired distance 2f Debug.DrawRay(transform.position, Vector3.down jumpSettings.groundJumpDistanceCheck, Color.red, 60f) As you can see, the ray does intercept the cube. I need the reycast to return true with a distance of 2f.


Unity Shader Graph, set blackboard properties from code I have a Shader Graph shader with a blackboard property that I want to change from within my code. The property is called Highlight here are the things I have tried Color myColor new Color(1f,0,0,1f) material.Color myColor throws error (as I expected) material.SetVector("Highlight", myColor) Name in blackboard window material.SetVector("HighlightColour", myColor) Name in material property material.SetVector("Color 8C3A526", myColor) Name in the shader inspector None of these work. Here's the shader set up


SetIKHintPosition and SetIKHintPositionWeight seems to have no impact I have recently been exploring Unity's inverse kinematics, to further polish the interaction between our rigged avatars and props. I have made a sample project, using PuppetMaster's basic humanoid for the model, rig, and idle animation, but without Final IK meaning this is Unity's inverse kinematics. Inside our OnAnimatorIK method, we set the right elbow's SetIKHintPosition and SetIKHintPositionWeight like we did with the hand IK animator.SetIKHintPosition(avatarIKHint, hintPosition) animator.SetIKHintPositionWeight(avatarIKHint, hintBlendValue) animator.SetIKPosition(sourceIKGoal, targetPosition) animator.SetIKPositionWeight(sourceIKGoal, blendValue) You can see the left and right hand correctly move to where we set it. However, it seems like the right elbow is ignoring the hint position entirely. You can see the white debug line connecting the elbow to the hint position in the picture above. It seems like the elbow ONLY bends if it absolutely must for the hand to reach the target position, regardless of where the hint is set, and the weight value given. I have fiddled with this on and off for days and still haven't found a solution. Others have asked the same question here and on other sites, but no one has posted an answer.


Is it ok to commit to git while my Unity project is still open? I tend to have big commits and it is related to me being tool lazy to close Rider and Unity, commit changes and then start both programms back up to make changes and repeat. I just assumed that this is the correct way of doing it, but is this even the case? Thanks in advance!


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


Elegantly exposing properties in Unity inspector There are various game objects in my scene that share some common characteristics, so I created an interface, like so public interface IHasLimitedRangeOfMotionAlongZAxis float MinimumZ get float MaximumZ get For certain types that implement this interface, I would like MinimumZ and MaximumZ to be publicly assignable in the Unity inspector. Therefore, I would like to be able to expose these properties in Unity. I am aware that one approach is to write C scripts in the Editor folder to implement an ExposePropertyAttribute (see here). However, this approach is unsatisfactory for two reasons My solution is not co located with my Assets folder. I write my code in a separate solution, and then use pdb2mdb.exe to import my scripts into my Unity scenes. (The reason for doing this is to avail myself of C language features introduced beyond C 4.0, which nonetheless target .NET Framework 3.5.) I shall have to create a custom editor for every single type that implements the interface with publicly assignable properties. This leads to a lot of boilerplate code. Is there a more elegant approach than adding private backing fields with the SerializeField attribute for all of my public properties?


Is it a good idea and a logic to create adventure game with one scene? I mean instead messing with loading scenes and passing variables between the scenes to make one scene and using in the hierarchy empty game objects for each part in the game for example empty game object name main menu and all the childs of it will be main menu objects. Or instead making a new scene to make one empty gameobject and all it's childs will be like scenes.


How do I set up a dedicated server for my multiplayer Unity game? I've made a multiplayer game with Unity and Mirror networking, and it all works perfectly when just running it on my own computer. However, I am trying to host on a dedicated server so that I can put the project on my portfolio and not have to worry about whether players can log in and test play the game or not. I tried a AWS Free server and I see that the Tanks example from Mirror is working just fine (although laggy), but my own project doesn't. I think this has something to do with the RAM limit of the free server but I'm not sure. I can see the task manager going up to 95 memory usage. When I remove some particle effects and geometry and enemies, it works. I'm not sure if this is my code that is so cloggy or the server or both. In any case I would need a solution for this but I don't know what my options are. Would be great if anyone can point me in the right direction. Thanks!


Companion AI with NavMeshAgent causing jittery movement on the X Axis I'm trying to do a companion AI that follows around my player but with a certain distance. I first tried to self program the movement behavior. but realized quickly that a NavMeshAgent offers more simple solutions to what I'm trying to achieve. Now the problem is that my AI doesn't follow around smoothly. It's surely not because of the camera, since my player and my enemy AIs do not have these jittery movement. My script is as simple as it can get private Transform target private NavMeshAgent agent public Animator partnerAnim public GameObject player private void Start() set target to player transform target GameManager.GM.playerMachine.transform agent GetComponent lt NavMeshAgent gt () private void Update() Determining wether to play the walk animation or not partnerAnim.SetFloat( quot normalizedSpeed quot , Mathf.Clamp01(agent.velocity.magnitude)) agent.SetDestination(target.position) My stopping distance is at 2 and my speed is at 3.5. No matter how I change these values, the jittery movement won't change. I also have a rigidbody attached to my NavMeshAgent, and I made sure to turn on isKinematic, and I also removed it to check if that solves the problem, but it didn't. The weird thing is that it only seems to be a problem when moving along the X Axis. When I move on the Z Axis only, my partner is following my player smoothly (I'm guessing this is because I increase the speed of my player on the Z Axis, but I don't really see the connection with my problem here. If it would be a speed problem, then lowering the speed on my AI would've fixed this, but it didn't.) Here are the full NavMeshAgent settings


Unity importing Blender models with different orientations All the models apart from 'Jungle Tree' are facing right which is not a problem, because they still seem to work with my game. But how can I change the 'Jungle Tree' to face right like the other models instead of left? I haven't made the Jungle Tree drastically different to the other models so I don't see why it is doing this


Unity, shader, vertexID I'm writing a shader and I just wanna ask if it's possible to get the ID of the vertex that is currently being manipulated. I read something about gl vertexID, but I couldn't find out if that is something I can use.


How to create an animation clip that changes whatever color a RawImage has to a certain destination color? I created an animation clip that turns a certain RawImage's color from white to red. I'd like to know how I could change that clip to turn any color that the RawImage might have into red with other words, I don't want to have a specific starting color. Instead the current color shall be used and faded to red.


Unity How to make grass details look good from top down I have an issue with the terrain details. Since it only draws a single plane per texture, it looks quite crappy with a angled top down camera, for example for an RTS camera. Is there some way around this, I know one solution people use is to angle the grass towards the camera a bit, but that isnt possible with the terrain details painter. The issue is circled in red If there is no solution to this, are there some techniques I can use to make some interesting looking grass for an RTS camera?


When an animation involves movement, where is the movement better to implement? For context, I am using Blender and Unity. Regarding the question, as an example, in some games, when you get hit, your character tucks a bit and gets knocked back a few distance. The tucking animation I want to implement in Blender but how about the knockback distance? Do you move your model in Blender (tuck and knockback), or do you do the tuck animation only (tuck in place) and then handle the knockback in Unity (basically triggering the tuck animation and then moving the model backwards a bit). My question basically is, what's commonly done and if there's any specific reason, why?


Shooting weapons Unity I'm trying to create a falling word game like z type (code here). Once the game starts a few words are displayed on the screen. When the user types a letter and if that matches with the first letter of any of the words displayed, an "activeWord" tag is added to the word. I have also created a laser script that checks if the tag is active and when that happens, it shoots the laser. What's happening right now is that the laser is shot only once i.e when the first letter matches but doesn't shoot a laser when the remaining words are typed. Can someone please have a look at the code and tell me where I'm making a mistake. this is the word display script where the active word is assigned public void RemoveLetter() remove the first letter if its correct and so on for the remaining letters. change the color of the word to red and add the "activeddWord" tag. text.text text.text.Remove(0, 1) text.color Color.red text.gameObject.tag "activeWord" public void RemoveWord() Destroy(gameObject) removes the word from display here is the input manager script public class WordInput MonoBehaviour public WordManager wordManager void Update () foreach (char letter in Input.inputString) wordManager.TypeLetter(letter) EDIT This is the player script where the laser is instantiated public class Player MonoBehaviour public GameObject laserPrefab void Start () transform.position new Vector3(0.0f, 3.92f, 0) player position void Update () Instantiate(laserPrefab, transform.position, Quaternion.identity) This is the updated laser script public class Laser MonoBehaviour public float speed 10.0f private Vector3 laserTarget private void Start() GameObject activeWord GameObject.FindGameObjectWithTag("activeWord") if (activeWord ! null amp amp activeWord.GetComponent lt Text gt ().text.Length gt 0) laserTarget activeWord.transform.position find position of word transform.Translate(laserTarget speed Time.deltaTime) for (int i 0 i lt Input.inputString.Length i ) Debug.Log("Character from input string " Input.inputString i " n" "Character from word displayed " activeWord.GetComponent lt Text gt ().text 0 ) if (Input.inputString i activeWord.GetComponent lt Text gt ().text 0 ) laserTarget activeWord.transform.position find position of word transform.Translate(laserTarget speed Time.deltaTime) shoot the laser After I do this, there are two major errors that I get As soon as I hit play, the laser fires continuously without stopping. The laser still shoots only once after the word is typed...This is the message I get in the console (screenshot attached). There is a difference of one word between the input string and whats displayed on the screen...Can someone please tell me how to rectify these.....


There any way to insert images inside the code (just for comprehesion) in any IDE compatible with Game Engine Unity3D (Monodevelop for example)? My code has a lot of geometry codes, thinks that shouldn't be represented just by comments I don't know if it exists, but should be fine to insert images like png in the middle of codes explaning that math behind, just in case I forget what any classes method lines do in future. Thanks.


How do I calculate a line segment that is a certain number of degrees from another line segment? I have a line segment that is at an arbitrary angle in 3D space. I want to (in code) draw another line that shares an end point with the first line and has an angle of arbitrary degrees between them. The second line will partially overlap the first in the XZ plane.


How can I programmatically add a Controller to an Animator during runtime? I am trying to set the Controller of an Animator during runtime using a script. When I click on the dot in the inspector manually, I can choose one called quot Standard Walk quot , but have not found a way to automate it.


Can I export a model and texture from a terrain file built in Unity3D? I am mostly familiar with building my level maps within unity, and have become quite use to its inbuilt terrain creator, in both generating my terrain, and spraying a texture on to it. I am making a game using MonoGame XNA, and would like to use a terrain map I built with Unity. I would have to recover the file, however, and have not been able to find anything to support being able to, in the first place. Can I export my terrain file with its texture, in any way, to use in XNA MonoGame?


Allow player to restart animation after it plays fully I have this code that plays an animation when the player touches the screen. The animation lasts 3 seconds. public class canCDanim MonoBehaviour public Animator anim private void Start() anim GetComponent lt Animator gt () void Update() Touch touch Input.GetTouch(0) if (touch.phase TouchPhase.Began) anim.Play( quot CanReload quot ) The trouble is that if the player touches the screen again, the animation will not play again. How can I make it so that I can restart the animation, but only after it's finished playing?


Generate platforms and move them with same speed I'm building an infinite runner and have to generate pillars on which the player jumps. There's a minimum and maximum value for how much gap can exist between two pillars. In addition to this, i want the pillars to move to the left with increasing velocity. All pillars need to have same velocity. So, i made a pillarHolder object which would have velocity that increases with time. The instantiated pillars would be made children of this pillarHolder. Code is if ((Vector3.Distance (go.transform.position,transform.position) lt 25f)) t rand.Next(13,35) t t 10 Debug.Log(t) tempx t pos new Vector2(tempx, 2.22f) go Instantiate(pillar,pos,Quaternion.identity) as GameObject go.GetComponent lt Transform gt ().parent holder holder.GetComponent lt Rigidbody2D gt ().velocity new Vector2( 10f,0) The problem is, the pillarHolder keeps moving in the negative x direction and after a while, the pillars are not positioned properly. The gap between them exceeds the maxGap. I tried to solve the problem by resetting the pillarHolder's position once it went beyond position.x 20f. But when it's position resets, child objects are reset too. Any help please?


Load 3D model from external directory I am developing a desktop application that want to load the 3D model from desktop. Using file explorer user wants to choose the 3d model then it want to show in the application scene.I tried to find the object, the path is detecting but if i tried to Instantiate it on unity it showing this error. ArgumentException The Object you want to instantiate is null. here the code is used public class ReadData MonoBehaviour string path GameObject go public void OpenExplorer() path EditorUtility.OpenFilePanel("Overright with model", "", "dae") Debug.Log(path) GetObj() void GetObj() if(path! null) UpdateObject() void UpdateObject() WWW www new WWW("file " path) go GameObject.Find(path) Instantiate(go) Anybody please help me to do this. Thanks in Advance.


Update method from script doesn't called After experiments with Unity versions, I have reproduced Mandelbrot example from scratch and got C script doesn't called. If I set breakpoint, it says it is not reacheable I think I set up all links. As it seem from IDE hint, inheritance is correct. Simultaneously, shader is working, i.e. image is displayed, but not updated by controller.


What design pattern should be used when there are a lot of different possible jobs? Some background information on what I am trying to accomplish. I am creating the game in Unity using C . Basically, I am trying to create an RPG type of game where it really harps on the idea of a lot of different possible classes jobs(I will call them jobs so not to confuse anyone). Basically, every job will have its own unique set of skills and can only do certain tasks, not dissimilar to a lot of games out there. However, the way I see most of the advice given down this path is simple inheritance, mostly because the user is only trying to implement 2 or 3 unique jobs. I feel as though this is just the easy answer that ends up causing a lot more headaches in the long run when you have lots of different jobs to implement. So my main question is, what design patterns would someone use when there are a lot of different jobs that the programmer needs to implement?


Unity crossplatform native plugins I need to create a c native plugin for my game. If I want to support macOS and Windows, do I need to write my plugin twice one in XCode with a bundle project and another in VS for windows or is there a way to support both with one codebase?


Discoordinated Chromatic Aberration Effect The game Teleglitch heavily utilizes the CA effect with screen distortion. I am trying to achieve this effect. Issue 1. How to not apply the effect onto the floor? (solved) They render the screen then apply the CA effect. However, the floor is not rendered with the post processing effect. Issue 2. How to have discoordinated position for each rendered CA effect? Currently I have three offsets for each channel red, green, and blue. However, I cannot assign different offsets for the channels for certain areas only. What would be a way to have discoordinated positions?


How do I create a sphere by script? I want to add a sphere at runtime via script. I have the following code which compiles fine. At runtime however, no sphere is added to the scene. I have attached the debugger to the script, and I have set breakpoints at each line. After the line Material nMat new Material(Shader.Find("Lit")) I'm using the URP the debugger "blanks" out, it doesn't hit the next line. What am I doing wrong? Thank you! using System.Collections using System.Collections.Generic using UnityEngine public class SphereMaker MonoBehaviour private GameObject Sphere void Start() Sphere GameObject.CreatePrimitive(PrimitiveType.Sphere) Sphere.AddComponent lt MeshFilter gt () MeshRenderer nRenderer Sphere.AddComponent lt MeshRenderer gt () Material nMat new Material(Shader.Find("Lit")) I'm using the URP if (nMat null) Debug.LogError("no mat!! n") nMat.color Color.red nRenderer.material nMat Sphere.transform.localScale new Vector3(0.4f, 0.4f, 0.4f) Sphere.transform.position new Vector3(0, 0, 0)


How do I create a HUD that appears to occupy 3D space can animate? I'm working with a group to try and make a first person space platformer in Unity, and was wondering if there would be anyway to create a HUD that moves and reacts to player actions, specifically looking around similar to the way the HUD moves in Metroid Prime. I'd also like it appear projected onto the inside of a helmet. I'm not entirely sure what best practice would be in this situation. Should we just attach the GUI elements to transparent objects in 3D space, then parent them to the main camera, essentially building our HUD with actual objects or is there another way that would be more efficient? I'm still very new to game development, but this is something we'd really like to have in our game if at all possible.


Speed dependent arc question I'm currenlty working on an assignment and would appreciate any sort of help on the following implementation The question follows We are tasked to implement some heuristics but one of them is really confusing to me. The following are a set of heuristics widely used by game developers for the movement of human characters while trying to reach a target A. If the character is stationary or moving very slowly If it is a very small distance from its target, it will step there directly, even if this involves moving backward or sidestepping Else if the target is farther away, the character will first turn on the spot to face its target and then move forward to reach it. B. Else if the character is moving with some speed If the target is within a speed dependent arc (like a narrow perception zone, or a cone of perception) in front of it, then it will continue to move forward but add a rotational component to incrementally turn toward the target Else if the target is outside its arc, then it will stop moving and change direction on the spot before setting off once more. B2 I'm not entirely sure what a speed dependent arc is. I googled it and it bring it back to the textbook( Artificial Intelligence for video games). My question is what is a speed dependent arc?


How can I make Matrix Rain? I want to make 3d Matrix rain like this shader that you can rotate camera.I tried to convert this shader but It have many calculations that it's expensive inside game engine.then I tried to make this effect by trail Renderer but I couldn't make random letters inside trail renderer.finally I tried by Instantiating quads but It hadn't fade like trail. so my question is how can I make this effect In efficient way?


Wall checking not working correctly Basically I am working on side scrolling 2d game. For that I want to check whether player is collided with wall. I have written some code for it but can't able to decide where I have done stupid mistake. So please guide me in this. If you need any more details then I am always available. Code for detecting wall RaycastHit2D hit Physics2D.Raycast (wallCheck.position, Vector2.right, wallCheckDistance) if (Physics2D.Raycast (wallCheck.position, Vector2.right, wallCheckDistance)) Debug.Log ("collider name " hit.collider.name) isDead true Debug.DrawRay (wallCheck.position, Vector3.right wallCheckDistance, Color.red) Following image gives you all idea about situation. In that I have allocated player with groundCheck and wallCheck flag. At present in wallCheck section, I am detecting ground as collider response after execution of above code. Above code I have placed in Update method for continuous checking. For this game, I want to do game over if wallCheck object detect any object in collision. Why wallCheck object detecting collision of ground object (stage1a)? That is big question of mine.


Everything black except where there's a light I have a camera in my scene with a map created at runtime As you can see everything can be seen. Now I want the map to be invisible (black as the background) except where there are lights. How can this be achieved in Unity3D?


is there any method to simply ignore some files in unity build? as im trying to build my new app on unity android specially when i want to use gradle, there is always some conflict with manifest or libraries and ..... for debug and problem exploration i need to ignore some folders to check for those bugs instead of need to move them somewhere else. i just thought about git branching but it can cause lots of branches and maybe not efficient


Play animation state's clip from particular time or fram I have a controller where i have a animation state. I want to play that animation clip from specified frame to specifed end frame. is this possible? here is the snap shot of the controller currently i am simply switching tow application using bool. I want to transition to paritcualr state but want to play its particular frame or time duration as a clip. public Animator talkingAvatarAnimator public bool isPlayHandGesture void Update () talkingAvatarAnimator.SetBool("isPlayHandGesture", isPlayHandGesture)


using Playerprefs on Android Mobile Platform I have a question about playerprefs on my android mobile game not initializing properly. I have already pre set my playerprefs data on a variable with a value of 3. In my play mode on unity the value is showing 3 through the textmesh that I have it scripted on. But when I install and test it on my android mobile device it is 0. can someone help how to properly initialize my playerprefs data to the right value on android platform? public static Game GM int maxAntiBody public TextMeshProUGUI antibodyTexMesh void Start () if (GM null) GM this maxAntiBody PlayerPrefs.GetInt("MaxAntiBody") antibodyTexMesh.text maxAntibody.toString() void Update () debugging() I use this method for setting or resetting my desired value for the playerprefs data I'm working with. In this case I choose 3 as a value. void debugging() if (Input.GetKeyDown(KeyCode.M)) PlayerPrefs.SetInt("MaxAntiBody", plus ) Debug.Log("max anti body value is " PlayerPrefs.GetInt("MaxAntiBody")) else if (Input.GetKeyDown(KeyCode.R)) plus 0 PlayerPrefs.SetInt("MaxAntiBody", plus) Debug.Log("max anti body is now reseted to " PlayerPrefs.GetInt("MaxAntiBody"))


Need insight on item system I have made an item database that takes keyed values from a database script then assigns them to an item class, then stores that item class in a List variable. This works fine but I have come across something that I see as potentially troublesome. For every unique effect, I have to make another keyed value and apply it to all the existing collections in the database. I want to make it such that an item can hold only 6 special values(physical damage, magical damage, armor, heal, etc) but with this method, I don't know how to tell the script which value goes to which special effect. Below is a template item from the database file. I use GRFON for this. See how I have written down all the possible damage types but for special values, I made 7 only with 6 of them being generic. The damage types can easily be assigned but when it comes to the special values, I have a hard time assigning magnitudes to special effects. iD 0 name Template category Null type Null subtype Null values physical 0, magical 0, hot 0, cold 0, electric 0, dark 0 specialvals spMag1 0, spMag2 0, spMag3 0, spMag4 0, spMag5 0, spMag6 0, spDuration 0 special none . properties mass 0, durability 0, maxdurability 0, charge 0, maxcharge 0, accuracy 0, useRate 0, reloadRate 0, range 0 description This is a template item. equippable 0 usable 0 stackable 0 maxStacks 1 count 0 rarity 0 price 0 uID template


Unity random.range value not same as last value Quick one, Currently using Unity Random.Range to set a var with the value of an enum state. State has 4 possible values, up, down, left,right. I call it like currentState (StateType)Random.Range(0, 3) This gets set at certain conditions. My issue is though I don't want the new setting to be the same as the current one. I have taken a look at the random.range on the API but haven't found anything useful. Is there an easy way to basically say "randomize but not the same as the current state" EDIT Currently im using a while loop. while (currentState LastState) currentState (StateType)Random.Range(0, 3) Is there anything i can do to remove the while loop?


How to make local keyboard input move only the local player, not everyone in networked multiplayer? I am working on Unity Networking and following this Tanks Networking tutorial https www.youtube.com watch?v V6wEvT6G92M Problem is that the keyboard inputs move all the tanks in the scene. It is not detecting the local tank. And when I run the game all tanks shows the same movement but it is not giving any error. I have followed all steps in the tutorial and searched all solutions on the google. This step in Tutorial is at 11 48. Implemented Code is using System.Collections using System.Collections.Generic using UnityEngine using UnityStandardAssets.CrossPlatformInput using UnityEngine.Networking public class TankController NetworkBehaviour Use this for initialization Header("Movement Variables") SerializeField float movementSpeed 5.0f SerializeField float turnSpeed 45.0f Header("Camera Position Variables") SerializeField float cameraDistance 16f SerializeField float cameraHeight 16f Rigidbody localRigidBody Transform mainCamera Vector3 cameraOffset void Start () if (!isLocalPlayer) Destroy(this) return localRigidBody GetComponent lt Rigidbody gt () cameraOffset new Vector3(0f, cameraHeight, cameraDistance) mainCamera Camera.main.transform MoveCamera() Update is called once per frame void FixedUpdate () float turnAmount CrossPlatformInputManager.GetAxis("HorizontalUI") float moveAmount CrossPlatformInputManager.GetAxis("VerticalUI") Vector3 deltaTranslation transform.position transform.forward movementSpeed moveAmount Time.deltaTime localRigidBody.MovePosition(deltaTranslation) Quaternion deltaRotation Quaternion.Euler(turnSpeed new Vector3(0, turnAmount, 0) Time.deltaTime) localRigidBody.MoveRotation(localRigidBody.rotation deltaRotation) MoveCamera() void MoveCamera() mainCamera.position transform.position mainCamera.rotation transform.rotation mainCamera.Translate(cameraOffset) mainCamera.LookAt(transform) I have also checked the auto create player in the spawn info as suggested in some solutions.


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


Is it possible to tile box colliders without causing "false" collisions in Unity3D? This is in regards to something like a sidescroller where you have a tiled map where each tile uses a 2d box collider. If you use a 2d circular collider as an example for your character, as it rolls across a series of tiled 2d box colliders, it will occasionally collide with the seams between tiles rather than rolling smoothly across them. In my scenario here, the tiles are 1x1 units snapped directly adjacent to each other. When rolling a 2d circular collider across a row of tiles, it goes mostly smooth but the more force applied, the greater chance of the circle flying up into the air rather than it's y staying the same as it rolls across them. The obvious conclusion I had was to use edge colliders instead which works fine, but I'm hoping to find a way to completely eliminate this problem even with just 2d box colliders. Thanks, Tim


Unity3d wheelcollider falling through terrain I have created simple project with 3D car and terrain. I have added 4 Wheel Colliders on model wheels. But when I run project wheels falling through terrain. Before run After run I am sure that at start wheel colliders above the terrain and not intersect it. Configuration is In what problem is? I have tried a lot of different things but I can't find a solution.


Why are parts of this Unity scrollrect not being bound to the mask? I'm setting up a system for people to load up extra levels. Since I don't know how many levels are going to be loaded I have a UI prefab that gets added to the main Level Load UI. However, the Text components of the prefab are not being bound by the scrollrect mask. The panel, images and button all are, and they are all children of the panel getting added to the panel that is the scrollrect's content. Another related problem, each of the prefabs also has a button on it. I've given it some alpha because I find that once it's in the scrollrect only the top half is clickable. You can see below that it only highlights (as red) if your on the top half of the button. The exception is that the final button will work if your mouse is anywhere on the button. This isn't an issue for the buttons if they're just placed in the scene. It only happens inside the scrollrect. I have a smaller version of the project right here for download. The 'main' gameobject starts a script that instantiates the main 'Load Level Screen' prefab and populates it with the 'LoadLevel Single' prefabs. I've been banging my head against the wall for over a week now, so any help would be appreciated!


save a particular area of the scene as screenshot in unity I need to save a particular part of the scene as screenshot. I have done a sample to show the particular part of the scene. When I click on the rectangular area the selected area will being shown on the screen on a texture (marked in red rectangle) But when I save, the whole scene is getting saved but not the selected part Here is code Texture2D screencap Texture2D border bool shot false public string path void Start () screencap new Texture2D(300,200,TextureFormat.RGB24,false) border new Texture2D(2,2,TextureFormat.ARGB32,false) border.Apply() Update is called once per frame void Update () if(Input.GetKeyUp(KeyCode.Mouse0)) StartCoroutine("Capture") string fileName(int width, int height) return string.Format("screen 0 x 1 2 .png", width, height, System.DateTime.Now.ToString("yyyy MM dd HH mm ss")) void OnGUI() GUI.DrawTexture(new Rect(200,100,300,2),border,ScaleMode.StretchToFill) GUI.DrawTexture(new Rect(200,300,300,2),border,ScaleMode.StretchToFill) GUI.DrawTexture(new Rect(195,100,2,200),border,ScaleMode.StretchToFill) GUI.DrawTexture(new Rect(500,100,2,201),border,ScaleMode.StretchToFill) if(shot) GUI.DrawTexture(new Rect(50,10,60,40),screencap,ScaleMode.StretchToFill) Application.CaptureScreenshot(myFolderLocation myFilename) IEnumerator Capture() yield return new WaitForEndOfFrame() screencap.ReadPixels(new Rect(198,98,298,198),0,0) screencap.Apply() shot true byte bytes border.EncodeToPNG() string filename fileName(Convert.ToInt32(screencap.width), Convert.ToInt32(screencap.height)) Application.CaptureScreenshot("D " filename) How can I save only the particular part in unity,can anybody please help me out.


Building meshes conforming to terrain deformation I have an uneven terrain on which the player is supposed to build buildings. For most structures I can just fudge the foundations, have them extend through the terrain. For roads, pipes, tracks and such I do have however the problem how to make them line up. What techniques can I best use to make the meshes of adjacent pieces line up, making it conform to the terrain?


How to Enable canvas with Event during a animation clip I want to enable a canvas while an animation clip is playing, I used animation Event and call the following script to enable the canvas, but the editor does not recognize any game object. How a canvas can be enabled? public void SetActiveTrue(GameObject game object) game object.SetActive(true)


How make circle with multiples holes In Unity, how can I programmatically make a shape like The gaps in the shape will all be the same size but their number may vary.


How can I implement foot pedal of a car in unity? I trying to create 2 D car game in unity for mobile where player controls acceleration by sliding the pedal in touch screen.Mine idea of implementation is using UI slider. Is there any other good I can use? Please suggest me any other implementation if any available.I'm new to this field.


Speedup Dev process for bug fixing and debugging in Unity? We're using Unity 2017 for a big Indie game. at the moment We have some issues with our development speed In order to fix issues and bugs, We used the visual studio and attach the process to Unity and go through the code step by step. every time we change something (even just a line of code) we back to unity and wait for all scripts to recompile which takes up to 1 minutes sometimes. after that, we run the game and go to the place that bug happened which takes us about two minutes. I was wondering if there was a Best practice for fixing issues and debugging in Unity which brings us speedup on script compiles and also helps us to get to bug location faster.


How can I move an object over linerenderer lines positions? I have 4 cubes the first 3 cubes connected with two lines one of the lines is curved. The fourth cube I want to move over the lines. The lines is built using linerenderer and in the linerenderer there are 397 positions. I created a small script that move an object over the positions. I checked and I have in the array 397 positions and the loop get to 397 but the object (Cube (3)) never moving all the positions only some. Or maybe the positions I get are not the same in the linerenderer ? This screenshot show some of the positions in the linerenderer this is the positions I want the object to move on Why the object is not moving over all the positions , only on some ? And this is the script I created that should move it using System.Collections using System.Collections.Generic using UnityEngine public class MoveOnCurvedLine MonoBehaviour public LineRenderer lineRenderer public GameObject objectToMove public float speed private Vector3 positions new Vector3 397 private Vector3 pos private int index 0 Start is called before the first frame update void Start() pos GetLinePointsInWorldSpace() Vector3 GetLinePointsInWorldSpace() Get the positions which are shown in the inspector var numberOfPositions lineRenderer.GetPositions(positions) Iterate through all points, and transform them to world space for (var i 0 i lt numberOfPositions i 1) positions i transform.TransformPoint(positions i ) the points returned are in world space return positions Update is called once per frame void Update() if(index lt pos.Length 1) objectToMove.transform.position pos index Time.deltaTime speed index Now I checked using a breakpoint the first position in the linerender at index 0 is X 30.57, Y 6.467235, Z 4.98 But in my script in the pos array I see that in index 0 the position is X 30.6, Y 6.5, Z 5.0 And the result is that the object that move Cube(3) is moving only some of the way and also it's not exactly on the line Why the object is not moving over all the positions , only on some ? Something is wrong in my script with getting the right positions from the linerenderer and maybe also the loop and the move is wrong. I can't figure out ho to do it.


Unity2D wait for coroutine to finish to activate it again is there a way to start another coroutine once the last coroutine is finish. I have a button that activates a coroutine, the button can be pressed any time you want, when pressed you activate a coroutine. However I notice that when you press the button twice the coroutine happens twice, which is not want I want. Is there a way to make sure that once my Boomerangeffect(coroutine) is activate the coroutine can't start (if button is pressed) until the present coroutine is finished. public GameObject BoomerangOn, BoomerangOff public static int buttonCount 4 static int timesActivated 0 void Start() if (PlayerPrefs.HasKey ("boomerangbutton")) buttonCount PlayerPrefs.GetInt ("boomerangbutton") void Update() PlayerPrefs.SetInt("boomerangbutton", buttonCount) public void Activated () if(timesActivated lt buttonCount) timesActivated StartCoroutine(BoomerangEffect()) IEnumerator BoomerangEffect() BoomerangOn.SetActive (true) yield return null yield return new WaitForSeconds (10.0f) yield return null BoomerangOn.SetActive (false) yield return null BoomerangOff.SetActive (true) yield return null yield return new WaitForSeconds (1f) yield return null BoomerangOff.SetActive (false) yield return null


Why do I keep getting an exception about "an element with the same key already exists" in this code? I'm trying to follow this tutorial about object pooling in Unity I got to minute 17 22. But when I run the game I get this exception ArgumentException An element with the same key already exists in the dictionary. System.Collections.Generic.Dictionary 2 System.String,System.Collections.Generic.Queue 1 UnityEngine.GameObject .Add (System.String key, System.Collections.Generic.Queue 1 value) (at Users builduser buildslave mono build mcs class corlib System.Collections.Generic Dictionary.cs 404) ObjectPooler.Start () (at Assets Scripts ObjectPooler.cs 31) This script is attached to a new empty GameObject using System.Collections.Generic using UnityEngine public class ObjectPooler MonoBehaviour System.Serializable public class Pool public string tag public GameObject prefab public int size public List lt Pool gt pools public Dictionary lt string, Queue lt GameObject gt gt poolDictionary private void Start() poolDictionary new Dictionary lt string, Queue lt GameObject gt gt () foreach(Pool pool in pools) Queue lt GameObject gt objectPool new Queue lt GameObject gt () for (int i 0 i lt pool.size i ) GameObject obj Instantiate(pool.prefab) obj.SetActive(false) objectPool.Enqueue(obj) poolDictionary.Add(pool.tag, objectPool) Like in the tutorial I'm making size of 1 of the Pools in the Inspector then giving as tag name Cube then drag a cube prefab to the Prefab then set the size to 150. But I'm getting this exception when running the game.


Creating color texture from greyscale heightmap in shader I'm trying to create a shader that takes a grayscale map as input, and returns a colored albedo that I want to use as texture for my PCG planets, I think that the code below should work, but it only produces flatly white objects. I'm a total shader noob, so I'm terribly sorry if I'm missing something obvious here. Shader "Custom Planet" Properties height("HeightMap", 2D) "white" SubShader Tags "RenderType" "Opaque" LOD 200 CGPROGRAM Physically based Standard lighting model, and enable shadows on all light types pragma surface surf Standard fullforwardshadows Use shader model 3.0 target, to get nicer looking lighting pragma target 3.0 struct Input float2 heightMap float minHeight 0 float maxHeight 1 float inverseLerp(float a, float b, float v) return saturate((v a) (b a)) UNITY INSTANCING CBUFFER START(Props) UNITY INSTANCING CBUFFER END void surf (Input IN, inout SurfaceOutputStandard o) float hv inverseLerp(minHeight, maxHeight, IN. heightMap) o.Albedo hv ENDCG FallBack "Diffuse"


Sprite always starts flipped Everytime I start the game, or I swap animator controllers in the inspector (in runtime), the character is flipped in X axis until I start moving him. How do I prevent this to happen? This happens to me everytime I start a new project and I grow tired of this. Update 8 animations which are all idle ones of just 1 frame Down DownRight Right UpRight Up The last 3 have the Sprite Renderer's flipX enabled within their animations UpLeft Left DownLeft In the middle of the transitions, sprite remains flipped until it reaches 1 or 1. I recorded recently a video to display the issue. https www.youtube.com watch?v dC09snKvHAM Same as above but in 1080p and showing entire Unity window. https www.youtube.com watch?v Ww3GkUvb7bc 2nd update PlayerControls.cs using UnityEngine using System.Collections public class PlayerControls MonoBehaviour Rigidbody2D rb PlayerStats pStats Animator anim void Awake () rb GetComponent lt Rigidbody2D gt () pStats GetComponent lt PlayerStats gt () anim GetComponent lt Animator gt () void Update () if (Input.GetAxisRaw("Vertical") gt 0) rb.velocity new Vector3(rb.velocity.x, pStats.pMoveSpeed, 0) if (Input.GetAxisRaw("Vertical") lt 0) rb.velocity new Vector3(rb.velocity.x, pStats.pMoveSpeed, 0) if (Input.GetAxisRaw("Horizontal") lt 0) rb.velocity new Vector3( pStats.pMoveSpeed, rb.velocity.y, 0) if (Input.GetAxisRaw("Horizontal") gt 0) rb.velocity new Vector3(pStats.pMoveSpeed, rb.velocity.y, 0) if (Input.GetButton("Vertical") Input.GetButton("Horizontal")) anim.SetFloat("OrientationY", Input.GetAxisRaw("Vertical")) anim.SetFloat("OrientationX", Input.GetAxisRaw("Horizontal")) PlayerStats.cs using UnityEngine using System.Collections public class PlayerStats MonoBehaviour public string pName public string pClass public int pLevel public float pExperience public float pBasicDamage public float pMoveSpeed public string pClassList Animator anim public RuntimeAnimatorController animCtrl void Awake() anim GetComponent lt Animator gt () void Update() pLevel 1 (int)pExperience 240 if (!CheckAssignedClass()) pClass "Warrior" Debug.LogWarning("Player class not found. Using 'Warrior' as default.") if (Input.GetKeyDown(KeyCode.J)) SetClass(pClass) bool CheckAssignedClass() bool found false var i 0 for (i 0 i lt pClassList.Length i ) if (pClassList i pClass) found true break else found false return found void SetClass(string className) switch (className) case "Warrior" anim.runtimeAnimatorController animCtrl 0 break case "Archer" anim.runtimeAnimatorController animCtrl 1 break case "Mage" anim.runtimeAnimatorController animCtrl 2 break default anim.runtimeAnimatorController animCtrl 0 break


How do I know the data has arrived at server without requesting every frame of the game? I have a game where I have to get data from the server but the problem is I don't know when the data will become available on server. So I decided to use co routine and hit server at after specific time or on every frame. But certainly this is not the right, scale able and efficient approach. Now my question is that how do I know that data has arrived at server so that I can use this data to run my game. Or how should I direct the back end team to design the server in an efficient way that it responds efficiently. Our back end team currently uses REST Web services with JSON with Python. And they want to push data to my unity player without my frequent requests.


How to create a normal map for my dice texture? I have this simple dice texture and would like to create a normal map for it where the black dots are are dents and the edges are trimmed(like on a actual dice) I'm using unity5. I need a explanation on how to create the normal map in PhotoShop CS5 or a code solution. Thanks in advance. Here is the dice texture I'm using.


C Script file is not showing in Onclick Event in Unity 5.0.4f1? I uploaded the levelLoader file to the gameobject. Still, when I drag the script file onClick Event, the no function is null. Why? Can anybody help me? C code using UnityEngine using System.Collections public class LevelLoader MonoBehaviour Use this for initialization void Start () Update is called once per frame public void LoadLevel(int a) Application.LoadLevel(a) public void Quit() Application.Quit() Correct me where I am wrong. I am following this racing car game tutorial. At 7 58 he added this event. Please help me!!!


Fade a texture effect as it nears the end of a cylinder mesh In my game I have a laser beam that travels for about 15m, but abruptly stops due to the mesh the texture is attached to. How can I setup my shader graph so that the end of the texture fades away? I can't find anything similar to this anywhere online, and have tried multiple things (gradient colors with lerp attached to alpha) but just can't figure it out as I'm too new to the whole shader graph thing. Anything helps, thank you. Note The texture is 'animated' and scrolls along the path of the beam using the shader graph


Good way to establish an inventory system? Fairly new to Unity as a whole, and while making a prototype game I came across the issue of setting up an inventory system. So far, I've been stuck on what sort of structure it should have, given Each quot Mob quot (player, enemy, NPC, etc.) has its own inventory Objects can have children attached, which should be saved (e.g. Gun gt Attachment Manager gt Magazine Rail etc.) Simpler items (ammunition, etc.) are stackable An inventory has quot pouches quot which are available only for certain objects (magazines, health items, etc.) and have a certain volume At first, I simply made a Mob gt Inventory Manager gt Pouch gt Item system where everything was a child of its respective parent, but obviously even with colliders sprites disabled that's possibly hundreds of transforms per mob being shifted around each update. Right now, I'm just parenting each mob's inventory system to a static quot Inventories quot object to get past the issue of that many transforms, but is there a better long term solution that takes into account saving loading and scene transitions? Right now, I'm considering Turning each item with children (guns with attachments) into a prefab and saving it (not ideal) Using an ID system to instantiate objects on load by loading the root object (gun), then the children (attachments) given certain parameters (but the variables, like the rounds loaded into a magazine, would be tricky to load) Having different prefabs for items depending on whether or not they're equipped, on the ground, or in an inventory, and switching between them as needed


How to force a translation to go through an exact point? I have a camera object with a script that will whether translate it with a set speed, or stop it. I also have 7 "checkpoints", where there are 7 different quads, who will stop the camera whenever the camera reaches them. The problem here is that in my code void Update() if (scoreholder.CheckScore() lt scoretimer) if the current score is less than set X score if (killcam.transform.position.y quadholder.y) and if the camera's position equals the position of the generic quad PROBLEM HERE killcam.GetComponent lt cameraUp gt ().SetCam (true) stop the cam while (scoreholder.CheckScore () lt scoretimer) do stuff offset mr.material.mainTextureOffset offset.y offsetSpeed 0.1f mr.material.mainTextureOffset offset break else once the score is not less than the desired X score, move the cam killcam.GetComponent lt cameraUp gt ().SetCam (false) So my problem here is that this line of code if (killcam.transform.position.y quadholder.y) never happens, the translation skips some values, and the camera doesn't hit the exact quad spot. I tried to use gt instead of , but I ran into another problem, is that after the 3rd quad, since my camera speed increases in time, the code apparently doesn't get processed fast enough, and my camera goes beyond the 4th,5th,6th, and 7th quad without stopping. I have already tried Vector3.Lerp, and it gives me almost the same result, if I lerp between the beginning and the end of the track, I have to do it with an extremely small fraction, and I can't have my camera move at that speed.


Process for converting unity asset to scenekit scene resource Has anyone successfully figured out a method for converting a unity3d asset to a 3d SceneKit model scene? I imagine it would require exporting the asset into some third party file type, and then importing into scene kit. If you have any knowledge that can help me, would you kindly explain the process? Unity3d has a fantastic asset store, and I want to import some of these things to a project that requires scenekit (unfortunately, "just use unity" is not really an answer to my problem set).


Unity Assigning a key to perform an action in the inspector I am trying to write a simple piece of code in JavaScript where a button toggles the activation of a shield, by dragging a prefab with Resources.load("ActivateShieldPreFab") and destroying it again (Haven't implemented that yet). I wish to assign this button through the inspector, so I have created a string variable which appears as intended in the inspector. Though it doesn't seem to register the inspector input, even though I changed the value through the inspector. It only provides the error "Input Key named is unknown" When the button name is assigned within the code, there is no issues. Code as follows var ShieldOn false var stringbutton String function Start() function Update () if(Input.GetKey(stringbutton) amp amp ShieldOn ! true) Instantiate(Resources.load("ActivateShieldPreFab"), Vector3 (0, 0, 0), Quaternion.identity) ShieldOn true


Can Cloud Functions be used for a multiplayer game server? I'm building a turn based online multiplayer game with Unity for both desktop and mobile. Traditionally, I would build a Java socket server, host it in Google Compute Engine or similar, and have players connect to it. Since this works with sockets I can easily notify players of relevant events, such as matchmaking, chat, enemy turn, etc. I've been curious about Serverless Functions for a while, such as Google Cloud or Amazon Lambda. However, at first glance it doesn't seem to me like that would work for my game because there ins't a constant connection (with sockets), I can't notify players of relevant events in realtime or can I? For mobile I realize I could probably use something akin to push notifications (so the serverless code may push messages to the relevant player's phone). But that doesn't seem as simple for desktop games. Well, what if the players poll for messages? Like every second, call a Cloud function and ask them if there's anything for them. I'd image that would work, but that seems rather overkill with as little as a couple thousand players, calling the same function every second for prolonged times (the game's matches are long) sounds like it would easily increase expenses. Is there something I am missing? A coding practice that would make serverless code feasible for a cross platform online multiplayer game? I want to make it work, but it would seem like a socket server is still my only option.


Resize from one side of the object in runtime Unity For now I managed to resize my object but it resizes always from the center. I have the same problem like this question here. I've been thinking like adjusting the position and stuff, but nothing works for my code. Here's my code if (isMouseDragging) tracking mouse position. Vector3 currentScreenSpace new Vector3(Input.mousePosition.x, Input.mousePosition.y, positionOfScreen.z) converting screen position to world position with offset changes. Vector3 currentPosition Camera.main.ScreenToWorldPoint(currentScreenSpace) offsetValue if(getTarget.CompareTag("LeftRightWall")) currentPosition.y getTarget.transform.position.y currentPosition.z getTarget.transform.position.z if(getTarget.CompareTag("FrontWall")) currentPosition.x getTarget.transform.position.x currentPosition.y getTarget.transform.position.y It will update target gameobject's current postion. Vector3 v3Scale getTarget.transform.localScale getTarget.transform.localScale new Vector3(v3Scale.x 0.1f , v3Scale.y , v3Scale.z) getTarget.transform.position new Vector3(mfX getTarget.transform.localScale.x 2.0f, 0 , 0) getTarget.transform.position currentPosition My idea is I want to make the gameobject tagged LeftRightWall will be resized whenever the FrontWall is dragged and vice versa, like adjsuting the room size but I want to know how to resize them first. Any ideas?


Unity editor, horizontal line in inspector How to draw a horizontal line in the inspector like on the reference image? Kind of separation line.


Detect collision with static collider only Is this possible to detect collision with static colliders only I check it is not working. I dont want to use rigidbody or character controller with my box collider.


Can I pause Unity Setup download and continue it whenever possible as per convenience(using Unity Hub)? Actually I get only 1.5GB data daily. So it's not possible for me to download the whole Unity setup in a day. So I wanted to know if I can pause and resume download process as per convenience. I am downloading using Unity Hub.


Unity How to make input field respond to only double taps in Android? I am using Unity in my Android project. There are input fields in my app. As soon as I click on the field the keyboard pops up. I want the keyboard to only show up when there is a double tap on the field. But I am not able to get it to work and I have tried several ways. Requirement 1 Single tap shouldn't open keyboard Requirement 2 Double tap should open keyboard I tried OnPointerClick method of IPointerClickHandler but this doesn't seem to work. I used this code in one of the scripts attached to input field with IPointerClickHandler. public void OnPointerClick(PointerEventData eventData) if (eventData.clickCount 2) Debug.Log("UNITY Double click") else if (eventData.clickCount 1) Debug.Log("UNITY Single click") Then there is also the question of how to hide the keyboard or prevent it from opening on single tap. This also I am not able to solve. I started with clicking the Hide Soft Keyboard in control setting of InputField in Unity editor. But surprisingly this starts opening a keyboard which has mobile input. Can someone help? I have been stuck on this for some time I can't seem to be getting anywhere.


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?


MissingComponentException There is no 'TextMesh' attached to the "Can" game object, but a script is trying to access it When I run my program I keep getting MissingComponentException There is no 'TextMesh' attached to the "Can" game object, but a script is trying to access it.Even though I have attached it as you can see In the script I am trying to edit the text of the Text Mesh like this private int count public TextMesh countText Use this for initialization void Start () count 0 counterText gameObject.GetComponent lt TextMesh gt () counterText.text "Count " count.ToString() What I want is to count the cans that have been shot, so what I do next is void OnCollisionEnter(Collider other) if (other.gameObject.CompareTag("Can")) other.gameObject.SetActive(false) count count 1 counterText.text "Count " count.ToString()


Best practice for 4x game management in Unity? I'm trying my hand at creating a turn based 4x game in Unity, with a galaxy map and 2D hexagon grid maps for each individual planet. The planet grid hexes would be gameobjects, with the overall grid being around 30x40 in size. The number of planets would be under 50. What would be the best way to set this up? I'm looking for a solid approach regarding performance here, but one that also caters to easier design programming would be a plus. Some approaches I've come up with Load all of the grids for the individual planets at the start into a single scene, with each being under a "planet gameobject", and then set those gameobjects to inactive. The galaxy map would be its own scene that is loaded additively when needed clicking on a planet to view it would set its associated gameobject to active and then unload the galaxy map scene. Instantiate the gameobjects for planets as they're called up the grid data for the planet is dynamically loaded as part of this. The planet gameobject is destroyed when no longer needed. Galaxy map would function the same as approach 1. Individual scenes for each planet, loaded unloaded additively when needed. A separate, single scene would be used for loading procedurally generated planets. Seems to have serious challenges for managing units resources across planets scenes. Approach 1 seems to be the most straightforward, as the core of the game would be managed in a single scene, but I am concerned about performance. I'm setting up some test projects to stress test the approaches, but it'd be great to get feedback from someone with more experience. Any help is appreciated!


Character rotation according to camera causes rapid flipping when game starts When I load my scene, my character rotates 90 and 90 on the X axis very fast about 4 or 5 times, and then he stops at 90 on X axis (lays back down). When I move the character, the rotations are just the way I want them, but I need to fix that weird bug at the beginning of the game. Here's my character's movement logic. It's based on the rotation of the camera, which is a child of my character object. void Update() Vector2 vec new Vector2(horizontal, vertical) vec Vector2.ClampMagnitude(vec, 1) Vector3 camF cam.transform.forward Vector3 camR cam.transform.right camF.y 0 camR.y 0 camF camF.normalized camR camR.normalized transform.position (camF vec.y camR vec.x) Time.deltaTime MoveSpeed Vector3 deltaPosition transform.position prevPosition if (deltaPosition ! Vector3.zero) transform.forward deltaPosition prevPosition transform.position


How to restrict the players movement win relation to screen bounds in Unity? (Without colliders) I am really enjoying making the switch to Unity. But here I have found one of those rare moments where it appears to make things more difficult (at least it is for me as I am crap at understanding the actual manual) Basically my 'player' is a space ship. It starts life at 0,0,0 world coordinates and I have been doing all the movement based off of that. (ie. Add force X to move left or right, and there is a constant Z speed which is done via rb.transform.Translate().) I want to restrict the movement on the X Axis, so in Libgdx id use something like if (player.position.x lt 0) player.position.x 0 if (player.position.x gt viewport.getX()) player.position.x viewport.getX() The thing is that wont work for me in Unity for several reasons (1. I dont know much about the viewport as I didnt create it. 2. the player.position is being affected by the rigidbody forces. AND i am working in world coordinates with the players position). As I said, the player is constantly moving forward on Z axis, so making colliders doesnt seem like the right choice for me. I'm pretty sure Unity devs would of put this in Unity v0.001 but I just cannot for the life of me find how to actually do it. (Any info I can find seems from like 2011 and also is pretty badly written code making this simple matter takes dozens of lines of code and some methods I'm hoping there is a Unity method already made, like player.transform.ScreenPosition or something but yeah I cannot find it!? Any help would be massively appreciated as always.


Unity Quaternion Rotate Unrotate Error I'm trying to un rotate a quaternion, aligning it with the axis, and then rotate it back to where it was originally. But with every iteration it seems to lose precision and just after 20 iterations the rotation disappears. Here is an example, which is a simplification of my code Quaternion rotation Quaternion.Euler (0f, 90f, 0f) Debug.Log ("Before " rotation.ToString ("F7") " Euler " rotation.eulerAngles.ToString()) int iterations 1 for (int i 0 i lt iterations i ) var currentRotation rotation rotation Quaternion.Inverse (currentRotation) rotation rotation currentRotation rotation Debug.Log ("After " rotation.ToString ("F7") " Euler " rotation.eulerAngles.ToString()) With 1 iteration the output is Before (0.0000000, 0.7071068, 0.0000000, 0.7071068) Euler (0.0, 90.0, 0.0) After (0.0000000, 0.7071067, 0.0000000, 0.7071067) Euler (0.0, 90.0, 0.0) With 5 iterations Before (0.0000000, 0.7071068, 0.0000000, 0.7071068) Euler (0.0, 90.0, 0.0) After (0.0000000, 0.7071019, 0.0000000, 0.7071019) Euler (0.0, 90.0, 0.0) With 10 iterations Before (0.0000000, 0.7071068, 0.0000000, 0.7071068) Euler (0.0, 90.0, 0.0) After (0.0000000, 0.7059279, 0.0000000, 0.7059279) Euler (0.0, 90.0, 0.0) With 15 iterations Before (0.0000000, 0.7071068, 0.0000000, 0.7071068) Euler (0.0, 90.0, 0.0) After (0.0000000, 0.4714038, 0.0000000, 0.4714038) Euler (0.0, 90.0, 0.0) And finally with 19 iterations Before (0.0000000, 0.7071068, 0.0000000, 0.7071068) Euler (0.0, 90.0, 0.0) After (0.0000000, 0.0000000, 0.0000000, 0.0000000) Euler (0.0, 0.0, 0.0) At the 19th iteration the euler angles becomes zero, and at previous iterations altough the euler angles are still correct, if I rotate a vector with the quaternion its magnitude is changed. I hope you can help me and sorry for my bad english!


How can I check if the text string is not equal and then to do something? using UnityEngine public class DrawLines MonoBehaviour public LineRenderer lineRenderer public string text private Vector3 positions private string oldText private void Start() if (lineRenderer null) lineRenderer GetComponent lt LineRenderer gt () lineRenderer.startWidth 0.3f lineRenderer.endWidth 0.3f 0, 0, 0 5, 0, 0 5, 5, 0 0, 5, 0 positions new Vector3 5 new Vector3(0, 0, 0), new Vector3(5, 0, 0), new Vector3(5, 5, 0), new Vector3(0, 5, 0), new Vector3(0, 0, 0) DrawLine(positions, Color.red, 0.2f) void DrawLine(Vector3 positions, Color color, float duration 0.2f) GameObject myLine new GameObject() myLine.transform.position positions 0 myLine.AddComponent lt LineRenderer gt () LineRenderer lr myLine.GetComponent lt LineRenderer gt () lr.positionCount positions.Length lr.startColor color lr.endColor color lr.startWidth 0.1f lr.endWidth 0.1f lr.useWorldSpace false lr.SetPositions(positions) void DrawText() for (int i 0 i lt positions.Length i ) if (oldText ! text) var pos Camera.main.WorldToScreenPoint(positions i ) text positions i .ToString() var textSize GUI.skin.label.CalcSize(new GUIContent(text)) GUI.contentColor Color.red GUI.Label(new Rect(pos.x, Screen.height pos.y, textSize.x, textSize.y), text) GUI.contentColor Color.green GUI.Label(new Rect(pos.x, Screen.height pos.y 20, textSize.x, textSize.y), i.ToString()) private void OnGUI() if (positions ! null) if (positions.Length gt 0) DrawText() I added oldText variable but not sure how use it more then I did so far. I want that if the text is the same in the loop then don't show this text not in red not in green. Each time show the text once if it's not equal. When the square is closed


How do I properly light characters in a Unity scene? I made a game prototype and want to improve some of rendering the visuals through light baking (which I'm new to). While I was mostly able to do this in my environiments, I'm having issues doing this for my characters in Unity. Previously, they came out with odd ish dark shadows in places as they were affected by light and dull colors. After I begin light baking though and adding Light probes in areas that my characters would be extremely light, especailly on the skin areas. It doesn't look good at all. Alternatively, without using light probes, it looks like this. I'm genuinely confused on how to properly light these characters if I can't get a middle ground of proper lighting. Can anyone help me try to understand this and solve this problem?


Support multiple gamepad layouts (Unity 2017.3) My game supports touchscreen, keyboard mouse and the Xbox One controller and the input so far works properly. Now I also want to add a second layout for the gamepad the player can then pick in the settings, e.g. Layout 1 Fly up with "A", fly down with "B" (so two buttons) Layout 2 Fly up with "LB", fly down with "LT" (LT uses an axis, not a button!) With keyboard touchscreen and gamepad input I was able to create two different inputs in Unity's InputManager for the same thing and they would then trigger depending on which input device you're using. I thought about adding a bool for the layouts and checking it every time a button is pressed but that sounds more like a quick and dirty solution. Descriptions of InputManagers I've found so far make it sound like they're used for rebinding keys or to support different gamepads (e.g. Xbox One and PS4), which I don't want need (plus, these InputManagers are usually pretty expensive). How do you handle actual different layouts that use the same buttons axis for different things, especially with something using a button in the first layout and an axis in the second?


Unity How to add bones to procedural mesh Basically this is the set up An N amount of prefabs are bundled together into a new GameObject. This is then merged into a single main mesh composited of M amount of material submeshes. The shape is standing upwards on the Y axis and is a bunch of arms. The goal is to move these by adding bones. I wasn't able to find many examples on how to properly assign bones to a procedural mesh which isn't a simple cube. The problem is assignment of vertices to the boneweights. I'd like for the transform Y 0 vertices to have no weight and the Y furthest vertices have full weight. I am not sure how the assignment should be done.. Any pointers? ) So far the Lower and Upper bone transforms are in the right place, but when moving them the mesh isn't bending as I hoped it would in a nice curve, half of the vertices are simply moved uniformly with a thin mesh line connecting the two halves. private void AddBones() if(m SkinnedRenderer ! null) Make bone weight for vertices BoneWeight weights new BoneWeight m MainMesh.vertexCount int halfway (weights.Length 2) for (int i 0 i lt weights.Length i ) if(i lt halfway) weights i .boneIndex0 0 weights i .weight0 1 else weights i .boneIndex0 1 weights i .weight0 1 m MainMesh.boneWeights weights Make bones and bind poses Transform bones new Transform 2 Matrix4x4 bindPoses new Matrix4x4 2 bones 0 new GameObject("Lower Bone").transform bones 0 .parent m MergedRoot.transform bones 0 .localRotation Quaternion.identity bones 0 .localPosition Vector3.zero bindPoses 0 bones 0 .worldToLocalMatrix m MergedRoot.transform.localToWorldMatrix bones 1 new GameObject("Upper Bone").transform bones 1 .parent m MergedRoot.transform bones 1 .localRotation Quaternion.identity bones 1 .localPosition new Vector3(0, 1.5f, 0) bindPoses 1 bones 1 .worldToLocalMatrix m MergedRoot.transform.localToWorldMatrix m MainMesh.bindposes bindPoses m SkinnedRenderer.bones bones m SkinnedRenderer.sharedMesh m MainMesh m SkinnedRenderer.rootBone bones 0


Lightmapping runtime combine children Is it possible to have lightmapping on runtime generated combine children in Unity? It is possible to bake combined meshes when they are done in the editor, but the .apk .ipa size increases too much.


How to animate material change to get a status bard effect, in unity Imagine a long cube, like a bar, that has a dark material, and you want to animate changing its material to a light material, but do it gradually from one end to the other, like filling up a tube, or like a progress bar that fills from one end to the other. Is there a way to achieve this in Unity? Or do you need to generate the animations in Blender or similar and control them in unity?


how to make turret only shoot when pressing in specific location? im using this code to shoot bullets from turrets, it is working perfectly but what i want to do is that, if i ll click mouse at the bottom of it it will still shoot i want it to only shoot if i will click on those positions i ll attach image to explain what i want to do here is my code using System.Collections using System.Collections.Generic using UnityEngine public class shoot MonoBehaviour public Rigidbody2D projectile public Transform fireTransform public GameObject missilePrefab public float fireForce 90000 public Transform projectileSpawnPoint public float projectileVelocity public float timeBetweenShots private float timeBetweenShotsCounter private bool canShoot protected Animation Animation void Awake() Animation GetComponent lt Animation gt () void Start () canShoot false timeBetweenShotsCounter timeBetweenShots void Update () if (Input.GetMouseButton(0) amp amp canShoot) GameObject missile Instantiate(missilePrefab, fireTransform.position, transform.rotation) Animation.Play () Rigidbody2D missileBody missile.GetComponent lt Rigidbody2D gt () AudioSource audio gameObject.AddComponent lt AudioSource gt () audio.PlayOneShot ((AudioClip)Resources.Load ("sh")) missileBody.AddForce(transform.forward fireForce) canShoot false if (!canShoot) timeBetweenShotsCounter Time.deltaTime if(timeBetweenShotsCounter lt 0) Animation.Stop () canShoot true timeBetweenShotsCounter timeBetweenShots


Placing units on isometric map (2D) I'm making a map editor for further RTS game (2D), something like the first StarCraft Editor. Terrain tiles will be a rhombuses. So I'll probably just make an 2D array with intigers, that corresponds proper tiles. Then, after creating the terrain, you'd probably like to add some units and structures to map (especially if you're making a scenario). I'm not sure how do I check if the unit can be placed somewhere. I decided to make units almost independent from terrain tiles like in StarCraft (1), so the units are not placed in any grid. I'll give a simple image As you can see, those green tiles represent a passable area (grass, let's say), and a blue one impassable (for example water). That stickman in a box is our unit. You can place it only in green area. That means the box can't go outside the green rhombuses. I have some ideas how to achieve this, but I'm not sure which one would be the most optimal. 1) Since I work in Unity, I could add a collider to every tile. That will be very simple to do and will probably have terrible optimalisation in maps 256x256. 2) Math. I can calculate if any of those boxes crosses tile's borders. If so, I'll have to check if all those tiles are passable. It won't be that easy to programme (well, for me at least) and... yeah, here comes my dillema. Am I right that it would have much better optimalisation? Is it worth the effort? What about saving this map? I can easily save the array with tiles, but how can I do it with units? Just save their positions or is there a better way to do it? EDIT I've tested the first idea (I've written script to create 256x256 map that will be probably the biggest, and to move a camera). The map generates quite long (comparing to tiles without collider), but after that there isn't much difference in performance (it doesn't mean it won't cause problems when I add more features than moving a camera )). I can also attach colliders only to impassable tiles, not all. This should improve the performance even more. Still not sure if that's a good idea. EDIT 2 I've just realised how bad my idea was. Let me visualise this So if you consider not the whole rectangle, but only a circle, it's not only easier to implement, but also more reasonable. You can now convert rhombus' vertices' position from isometric to cartesian like B lint said CartX ( 2 IsoY IsoX) 2 CartY ( 2 IsoY IsoX) 2 You can also do it with circle's center point. Radius is equal to half of square (rhombus) side length OR sqrt(2) square side length (when square is inscribed in circle). So now I have a square grid and a circle. How can I check if all squares that this circle lays on are passable? What's the most optimal way to do it?


objects disappear before time I created a little pool in order to better manage my enemies, to which, an enemySpawner object calls to retrieve a clone and show it on screen public class ObjectPool MonoBehaviour public static ObjectPool current public GameObject objectForPool public int poolAmmount 20 public bool growth true List lt GameObject gt objectsForPool void Awake() current this Use this for initialization void Start () objectsForPool new List lt GameObject gt () for (int i 0 i lt poolAmmount i ) GameObject obj Instantiate(objectForPool) obj.SetActive(false) objectsForPool.Add(obj) public GameObject GetPooledObject() for (int i 0 i lt objectsForPool.Count i ) if (!objectsForPool i .activeInHierarchy) return objectsForPool i if (growth) GameObject obj Instantiate(objectForPool) objectsForPool.Add(obj) return obj return null Update is called once per frame void Update () The call(EnemySpawner update) void Update () transform.position new Vector3(transform.position.x (speed Time.deltaTime), 0, transform.position.z) if (transform.position.x lt boundary.xMin transform.position.x gt boundary.xMax) speed 1 if (Time.time gt nextSpawn) nextSpawn Time.time spawnRate GameObject clone GetComponent lt ObjectPool gt ().GetPooledObject() if (clone null clone.activeInHierarchy) return clone.GetComponent lt EnemyMovement gt ().SetPlayerShip(playerShip) clone.transform.position transform.position clone.transform.rotation transform.rotation clone.GetComponent lt Health gt ().RestoreHealth() clone.SetActive(true) The problem here is, that my enemies are being deactivated on mid trajectory https youtu.be ZGHC6wwGX1E I know my issue is in my pooling, but I can't figure out what I'm doing wrong


Set Layer of UI Object being Dragged In my game, I have an inventory system with slots and images in those slots. The images are by default disabled, but when an item is added to the slot, the image component becomes enabled. I have implemented a very simple drag and drop system for moving objects around in the inventory using IBeginDragHandler, IDragHandler, and IEndDragHandler. As I am dragging an item from one slot to another, I want the item image to be rendered in front of the slots and the rest of the inventory. Currently, when dragging an item image, it renders behind the empty slots. I don't want to use hierarchy order to organize the layers of these slots because moving items around is very dynamic and the hierarchy order of the slots changes seemingly randomly when I press play. Is there another way to ensure that the item image being dragged is "closer to the camera" or in front of the rest of the inventory? Thanks.


Making Scene at editor mode On Button click at editor mode I am trying to make a scene of selected Hierarchy game object but the problem is as i click the button new scene become upon and I lost the scene where i were selected the Game object. My code given below if (GUILayout.Button("Generate Scene")) Scene newScene EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects) SceneManager.MoveGameObjectToScene(Selection.activeGameObject, newScene) EditorApplication.SaveScene("Assets RegionScene " gameObjectSelected gameObjectSelected.Count 1 .name ".unity") newScene


How to create a Spawn Area that can be visualized in the Unity Scene Editor? Consider a Spawn Area for GameObjects. We define a Spawn Area to be a boundary consisting of 3 or more points such that an object can spawn at any coordinate that is within the boundary of the Spawn Area. Contrast this with a Spawn Point, where objects can only be spawned at that specific coordinate. In Unity, one method of creating such a Spawn Area is to place an Empty Game Object at a point, and then use Random.Range around that point. Vector3 emptyGameObjectCoordinate emptyGameObject.transform.position Vector3 randomSpawn emptyGameObjectCoordinate new Vector3(Random.Range( 1, 2), 0, 0) My issue with this approach is that it is very difficult to visualize this area through the scene editor. It would look like a simple cube no matter what the area actually is. I have considered possibly using a box collider as the area. This is can easily be visualized. However, Unity Lacks a method to select points within a collider. It would be ideal if we had a method such as Random.insideCollider. BoxCollider collider GetComponent lt BoxCollider gt () Ideally. But sadly, does not exist. Vector3 randomSpawn Random.insideCollider(collider) So my question is, what is the Unity way of creating a Spawn Area such that it can be visualized through the scene editor? As a bonus, how can we create areas that consists of arbitrary points, as opposed to just being rectangles or cubes? It would still need to be possible to visualize it, and it should be easy to select random points within it.


My array loads in the wrong order I have a load all chapters script which loads up all the Chapter items in an array and instantiates the buttons in the Viewport so you can select which chapter you would like to play. The problem is the chapters load up in the wrong order, they load up as Chapter 4, Chapter 0, Chapter 1, Chapter 2, Chapter 3. Below is the code I am using. void Start() menuManager GetComponentInParent lt MainMenuManager gt () levelManager GetComponentInParent lt LevelManager gt () chapterArray Resources.LoadAll lt GameObject gt ("Chapters").OrderBy(go gt go.name).ToArray() txtStatus.text "" if (chapterArray null) txtStatus.text "Could not find Chapters" return else txtStatus.text "Loading..." FillChapterList() txtStatus.enabled false void FillChapterList() foreach (GameObject chapter in chapterArray) GameObject listChapter Instantiate(chapterListItemPrefab) listChapter.transform.SetParent(chapterListParent, false) ChapterListItem chapterListItem chapterListItemPrefab.GetComponent lt ChapterListItem gt () chapDetails chapter.GetComponentInChildren lt ChapterDetails gt () chapterListItem.Setup(chapDetails.chapterNumber,chapDetails.chapterName) This is not only happening with the Chapter Select, it has been happening with all the arrays I load up in this fashion. Below is the visual side of the problem where you can see it loads the last object First. I have been struggling with this for a while and I think its stopping me from progressing forward. Thank you for reading this and taking the time out of your day to help.


Stop 2D platformer character from sliding down slope I'm making a 2D platformer game with the default Unity 2D physics. I am implementing slopes, but my player slips down the slope because of the physics. Here is the code I use for the player movement MoveInput Input.GetAxisRaw( quot Horizontal quot ) rbd2.velocity new Vector2(MoveInput speed, rbd2.velocity.y) rotacion de personaje if (MoveInput gt 0) transform.localScale new Vector3(1f, transform.localScale.y, transform.localScale.z) if (MoveInput lt 0) transform.localScale new Vector3( 1f, transform.localScale.y, transform.localScale.z)


How can I access a method via a string in Unity? I myself am new to unity and I would like to know how it is possible to access a method via a string, something like this public string PlayerPrefsName public GameObject Button public string GadgetForSkin private void Start() GadgetChanged PlayerPrefs.GetInt(PlayerPrefsName) if (GadgetChanged 0) Button.SetActive(false) GadgetForSkin quot GadgetForSkin quot GadgetChanged public void GadgetChecker() GadgetForSkin() public void GadgetForSkin1() If it's not possible, how can I achieve something similar?


Issue with dark .PNG files in Unity I made sprite assets in Krita and I exported them as .PNG files. When I import the files into Unity assets, however, they become a lot darker than the original colors. So far, I haven't found the issue, and I was wondering what's going on?


GTA style camera Unity I am wanting to make a 3d RPG with unity, and I'm in the planning phase. For the camera I decided to make it GTA style. I want the camera to be rotated around the player without effecting the movement of the player. If anyone can give any pointers on this, I would be very grateful.


How can the fluid stream be stuck to the top of flask? I created a flask and added a fluid stream to the top of the flask. When I translate the flask, the fluid stream goes along with the top of the flask. How do I achieve this when rotation occurs. void Start () aa.transform.position new Vector3(bb.transform.position.x, bb.transform.position.y 4, bb.transform.position.z) aa.SetActive(false) aa.SetActive(true) void Update () aa.transform.position new Vector3(bb.transform.position.x, bb.transform.position.y 4, bb.transform.position.z) aa is the fluid stream and bb is the flask cc.transform.position new Vector3(bb.transform.position.x, bb.transform.position.y 4, bb.transform.position.z) The traslation works. But you can see the gap between top of flask and rotation here. How do I close that gap?


How to see the surface arc in Unity? How to see the surface arc in Unity? There is the tutorial and in this tutorial we can see the arc in editor While I can not see it. I checked that all my gizmos are enabled. How can I enable the arc?