Problem with the Layer System Tilemap Layer from Unity This is my first time using Unity (and my third time creating a game in general), so I hope I can provide the needed information to solve this problem. My character overlaps with the upper wall, but doesnt with the lower wall. This is the right behaviour given the layers (seen in the picture). But I want him to be behind the lower wall AND in front of the upper wall. Side Information The Wall Tile is one piece, which covers two tiles. Movement is depended on the existents of a ground tile. The reason behind this is, that I wanted the character to always move one tile at a time. And since this is my first time with unity, that was the easiest way of doing it. So there is no actual interaction with the wall. No collsions or anything. There are three Layers (Ground, Creature, Wall) and two tilemap layers (Ground and Wall) (see picture) and the character doesnt interact with the tilemaps at all, he just gets drawn above the ground tilemap layer. What I see as answers Split the wall tile into two tiles and let the wall part be on another layer, then the roof part. Split the character into two parts and do the same thing. Both seem like a good way of solving it, but I dont even know where do start there. I think I can split the walls into two tiles, but I dont know if this is a good way to solve this issue. The other option, to split my character, there I really dont know where to start. What I tried Trying around with layers and order in layers. Trying around with the tile atlas (adding the sprite, removing tiles)


Vuforia AR VR sample with Google Cardboard SDK I cannot switch from augmented reality to virtual reality I have followed the Integrating Cardboard to the AR VR Sample latest tutorial. I have configured the provided scene sample according to that tutorial. I have compiled it to Android without any problem. The game load an AR scene with a yellow pointer in the center. If I understood well, if a glaze at the ImageTargetStones GameObject, it will switch to VR. Unfortunately I cannot find that GameObject anywhere. I only see the AR scene with nothing than the yellow pointer. I don't find what I'm missing. Why is not that ImageTargetStones GameObject in the AR scene? UPDATE 1 I think I want to use Vuforia for an uncommon use. I think that's a reason of a possible misunderstanding. I don't want to use its image recognition possibilities. I want to switch between AR to VR when glazing to a button. I have tried to duplicate the VRButton to move it to an independent place of the scene with no parent. I have checked its IsTrigger checkbox. I have added a PointerEnter EventTrigger that set Focused to true. I have added a PhysicsRaycaster to both AR Camera and MainCamera (child of CardboardMain Head). Nothing happens when I gaze at the button. I have to compile everytime I want to try it by the way. I did not manage to make it work in the editor. UPDATE 2 I haven't been able to do it with vuforia yet. I have done it with WebCamTexture. Specifically, I have used the scripts of this answer http answers.unity3d.com answers 687987 view.html . The result is not nice because the image from camera seems closer than it actually is (with Vuforia, there is not that problem)


How Can Create Line Renderer Runtime When Player in Gravity I want to Create functionality Like Rock Runner Game.when player into the gravity and hold the button then generate line and player hold the line and move forward. After So many Research i couldn't find anything in google and also in YouTube then i post the question. I put some snippets to very well understand what i want actually. if any one have idea how to do this then tell me. thanks in advance


How to Animate a Mechanical Model to work with Unity's Mechanim? I made a relatively simple model in 3D Studio Max to be used in a game. It's a simple stationary laser turret with an openable maintenance hatch. I want to use Mechanim to handle the animation states. The parts of the model are parented in a way that it's easy to just make it move from code but I rather have it use Mechanim and animation files to make it easier to add details like idle animations. I tried animating it with Unity's build in animation editor which looked nice enough but I couldn't get the animation created with that in Mechanim for some reason. If I have to use an external editor to add animations, I can't seem to find any. Google only gives results on how to animate character models or how to make an animation just to be exported to video. How would I animate this model to work with mechanim, what programs should I use and what should I pay attention to?


Why do not Easy Mobile Pro scripts know about each other? I am getting this error when I try to build the project Assets EasyMobile Scripts Modules NativeAPIs NativeUI Nati veUI AlertPopup.cs(68,17) error CS0103 The name 'AndroidNativeAlert' does not exist in the current context I tried adding this to my NativeUI AlertPopup.cs if UNITY ANDROID using EasyMobile.Internal.StoreReview.Android endif Hint says unnecessary using. Googling, searching Unity EMP forum and thread did not bring any results. Unity version 2019.2 .net 4.x EMP 2.5 If I try adding a breakpoint it says The breakpoint will not currently be hit. Unable to find a corresponding location. AndroidNativeAlert is a static class, have have no clue why it can't been seen from the other one.


Unity3D Multiple OnTriggerEnters are called before the first one could finish and destroy the object I'm working on a projectile which explodes when it reaches a destructible object and damages its voxels. (The projectile is a trigger) But the problem is that I use raycasting in OnTriggerEnter which makes it slow to finish. Which lets multiple OnTriggerEnter to be called before it could be finally destroyed. I fixed it by having a flag which lets only one call to be executed. But it feels a bit hacky, so I decided to ask you, maybe you have some better solutions. void OnTriggerEnter(Collider collider) if (!hit amp amp LayerMask.LayerToName(collider.gameObject.layer) "Destructible") hit true DoImpact() Destroy(gameObject) void DoImpact() Do 1 SphereCast RaycastHit hits Physics.SphereCastAll(transform.position, ExplosionRange, transform.forward, 0.0001f, 1 lt lt LayerMask.NameToLayer("Destructible")) Iterate through voxels foreach(var hit in hits) the parent object which manages its voxels var destructible FindDestructibleParent(hit.transform) Make some damage to that voxel based on the projectile, the voxel, and some "whole container parent object properties" destructible.TakeDamage(this, hit.transform.gameObject)


Rigidbody slows down when its going up a slope. What can I do? I am using unity and I am creating a 3d topdown game. There is no jump feature. The input handling supports only x and z axis player movement. Climbing slopes or falling from gaps is something I want to happen without certain input. So, I have a rigidbody which I move by directly setting its velocity. When it goes up a slope it slows down. I would like it to keep the same speed. Now I do it like this void Update() moveInput new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical")) void FixedUpdate() MyRB.velocity moveInput.normalized runSpeed I am using a capsule collider on the rigidbody and a box collider for the slope. The physics materials of the colliders are the default none (not changed).


Trying to get reference to Button in Javascript Unity3d I've this simple script in Unity3d pragma strict public var topLeft UnityEngine.UI.Button public var topCenter UnityEngine.UI.Button public var topRight UnityEngine.UI.Button public var midLeft UnityEngine.UI.Button public var midCenter UnityEngine.UI.Button public var midpRight UnityEngine.UI.Button public var bottomLeft UnityEngine.UI.Button public var bottomCenter UnityEngine.UI.Button public var bottomRight UnityEngine.UI.Button private var x "X" private var o "O" function Start () var board topLeft, topCenter, topRight , midLeft, midCenter, midpRight , bottomLeft, bottomCenter, bottomRight for (var i 0 i lt board.length i) var row board i for (var j 0 j lt row.length j ) var button row j button.onClick.AddListener(function() onTileClicked(button) ) function onTileClicked(tile UnityEngine.UI.Button) Debug.Log("Click click!") Here is how I reference the buttons Why are all the buttons in 'board' variable null even if I referenced them through the GUI (the red rectangle in the image)?


Help to Code Bowling Like Feature in Unity for Mobile I need Code or Guidelines for Touch Feature. When We Drag ball back and Send it Forward. I am Making feature like bowling, and I need Player to add force while dragging back and also curve the path of the Ball Anybody, Please Help


How to change transform.position.x after a state is changed? When I press attack button, player will change to Normal Attack state to perform Normal Attack animation and you will notice the player seem like step back a little bit as the width of sprite for Normal Attack animation is longer than Idle animation. http youtu.be hnPXt kprqQ To solve this issue. I need to change the transform.position.x 0.5 to move a bit further to match the position of Idle animation stands and transform.position.x 0.5 when Normal Attack state done its animation and back to Idle state. How can I perform transform.position.x 0.5 when when Normal Attack state done its animation and back to Idle state?


Ridiculous Error on Unity 5.6.4p4 Method Name doesn't exists I am facing a strange issue on Unity version 5.6.4p4 The code compiles and runs just perfectly fine in editor but when I build it for android I see an error message saying that my method doesn't exists. I have checked many times but there is no such issue. I am not doing anything wrong. Can anyone suggest what could be wrong ?


Move around the object using head tracking movement in Unity I am developing an app for Samsung Gear VR with unity.I have added a cube and made the cube move forward on the terrain. Now I need to move around the cube using head tracking movement.I have referred the below link(Flyer VR movement) .But I am not able to understand the code used in it. https unity3d.com learn tutorials topics virtual reality movement vr Can anybody help me doing this in a simple way to move around the cube by head tracking


Why does Avatar Mask not work as expected? I have 2 layers The base layer, and an upper body layer. On the upper body layer, I have an avatar mask because I only want to affect the upper body. However, this mask doesn't work as expected. Here is what it looks like This is what is looks like when the upper body layer has a weight of 0 And this is with the upper body layer with a weight of 1 and with the Avatar Mask As one can see, the lower body is affected. The avatar mask doesn't seem to have an effect. Is that a bug in Unity, or is there anything I could still check? Thank you!


Can I set multiple animations to run at the same time with Unity's animator (some animated properties would overlap) I am creating a vehicle in Unity and I am currently trying to set up lights for it. I need to be able to press one button to turn on the parking lights. But the parking lights share the same bulb as the turn signals. So when a turn signal is turned on, I need that parking light bulb to now flash, while the others remain on. This is just one example of several I am coming across. Now, I could create an animation for every single scenario, but I believe there should be a simpler way to do this. I thought perhaps using the layers would handle it, but I'm fairly new to animations and I'm not sure I'm understanding them right. I put each animation on a different layer, and then ordered them in a way that made sense to me, and set them to additive. The right turn signal is on top and it works, but the left turn signal right below it does not. Is there something else I can do to make this work? Or a tweak I can do to fix what I have now, something I'm missing maybe? Thanks for the help!


How do I set up the microphone for an Android device in Unity? I'm developing a simple android app that needs to use the microphone. I'm able to load my app on my Android phone using developer mode, but I do not understand how to enable the mic. How can I enable the microphone and use the input? I started with a brand new Unity 2D project. I created a TextMeshPro Text object to display logs and set this reference on the script via the inspector. I have attached the following script to the Main Camera. using UnityEngine using UnityEngine.Android using TMPro public class RequestPermissionScript MonoBehaviour public TextMeshProUGUI logs void Start() if (Permission.HasUserAuthorizedPermission(Permission.Microphone)) The user authorized use of the microphone. logs.text "has authorized" else We do not have permission to use the microphone. Ask for permission or proceed without the functionality enabled. logs.text "has not authorized" Permission.RequestUserPermission(Permission.Microphone) I then Build and Run this as Android and the app is loading on my Android phone attached via USB. I expect a pop up to appear asking for permissions to the mic, but this does not happen and the logs says "has not authorized". What am I missing or doing wrong?


Unity Particle System Shuriken Setting particles in code with random row in texture animation? Good day, I'm attempting to randomly generate a space scene (quite large actually) in Unity through C code mainly. So far, I've gotten stunning results up to what image 2 will show you. However, now I'm looking to expand the look with more random particles. So, I've made a texture atlas of 8 in a vertical row, which works on the random setting if you have an emitter and the particle system is called with PS.Play() Assigning different materials would only work on a per particle system basis(which would be new texture PER cloud, so to speak) which is not what I want. So, my question How can I use the Shuriken Particle System's Texture Sheet Animation functionality through code, without having an "active" particle system? More precisely, I wish to use the 'Random Row' feature of it to assign random textures to each particle. Since I can't share my code (due to policies), here is a bit more info on how I do it I create an array with coordinates for each cloud. Assign a particle system to that cloud. Randomly generate all the particles for the cloud with relative offsets. Use PS.setParticles(particlesArray) Using a Texture Atlas consisting of the letters A to H to test, only B showing on all particles. Using a Texture Atlas consisting of the fog particles to test, only 2nd showing on all particles. Thank you DMGregory for the help, I've tested it multiple times and it works perfectly now, I've also went ahead and tweaked a few of my settings just to get a more "clear" space


How to access the currently touched instance of the Prefab? I have a prefab which is instantiated in the Scene and what I am trying to do is to disable with a touch or timeCounter but sometimes it disables all the instances of the prefab and sometimes 2 or 3 of them. I want to disable particular object which I have touched currently. when i am passing the collider in Destroy(hit.collider) it works perfect but how to handle it null is passed as parameter. Here is my code void Update () blastingTimeCounter Time.deltaTime if (blastingTimeCounter lt 0) DestroySquare (null) for (int i 0 i lt Input.touchCount i ) if (Input.GetTouch (i).phase TouchPhase.Stationary) hit Physics2D.Raycast (Camera.main.ScreenToWorldPoint ( Input.GetTouch (i).position), Vector2.zero) if (hit.collider ! null) DestroySquare (hit.collider) void DestroySquare(Collider2D collider) if(collider null) else collider.gameObject.SetActive (false) blastingTimeCounter blastingTime


How can I change the rotatearound radius in real time when the game is running? using System.Collections using System.Collections.Generic using UnityEngine public class TargetBehaviour MonoBehaviour Add this script to Cube(2) Header("Add your turret") public GameObject Turret to get the position in worldspace to which this gameObject will rotate around. Header("The axis by which it will rotate around") public Vector3 axis by which axis it will rotate. x,y or z. Header("Angle covered per update") public float angle or the speed of rotation. public float upperLimit, lowerLimit, delay upperLimit amp lowerLimit heighest amp lowest height private float height, prevHeight, time height height it is trying to reach(randomly generated) prevHeight stores last value of height delay in radomness Range(0, 50) public float xradius 5 Range(0, 50) public float yradius 5 private void Start() Update is called once per frame void Update() Gets the position of your 'Turret' and rotates this gameObject around it by the 'axis' provided at speed 'angle' in degrees per update transform.RotateAround(Turret.transform.position, axis.normalized, angle) time Time.deltaTime Sets value of 'height' randomly within 'upperLimit' amp 'lowerLimit' after delay if (time gt delay) prevHeight height height Random.Range(lowerLimit, upperLimit) time 0 Mathf.Lerp changes height from 'prevHeight' to 'height' gradually (smooth transition) transform.position new Vector3(transform.position.x, Mathf.Lerp(prevHeight, height, time), transform.position.z) Using the xradius and yradius sliders I want to change the transform.RotateAround radius in real time. UPDATE I added this to the Update if (radius gt 0) var newPos (transform.position Turret.transform.position).normalized radius newPos Turret.transform.position transform.position newPos The problem is now that some times when the radius the distance from the Turret is small for example 20 or less some times the transform is getting right above the turret not sure why. I want it to rotate around the turret at the fixed set distance(radius) but not to be above the turret. Can't figure out why sometimes it's moving right above the turret then after some time it's getting back to the set distance.


Coding style about collisions with geometry Let's say I'm writing 3D Pacman. I have "Dot" objects throughout my maze, that are structured as follows in the Inspector Dot (GameObject) Sphere w Collider When I run into the sphere trigger, I can trivially say "Get me your parent and check if it's a Dot" However, I hate baking in the knowledge that some spheres have parents that are Dot objects. If the trigger were on the Dot itself that problem would solve itself, as I could just call GetComponent(). What's a good programmatic style approach to finding out what logical Game Object actually owns the geometry you've collided with? I could add a Tag of "Dot" to the sphere but that's just a level of confirmation, I still would have to walk up to it's parent and check.


How to set an EditorGUI foreground color for the light Unity skin? Writing an asset management GUI as part of our editor tools, I am in some places colouring LabelFields. Working mostly in the dark Pro skin, this seems to work just fine GUI.color Color.green EditorGUILayout.LabelField("Name", GUILayout.Width(75f)) GUI.color Color.white When switching to the light default skin however, this colouring is no longer visible. The usual GUI.backgroundColor still functions fine there as it does in the dark skin. Is this "foreground" colour something specific to the dark Pro skin? If so, is there perhaps another way to achieve a similar effect?


Rotate a Polygon node in Shader Graph I have a hexagon in the Polygon node I would like to rotate so the pointy side is upwards. Applying the rotation nodes, however, simply changes the color of the hexagon from white to a color in the rainbow. What does the Vector1 of the Polygon output represent and is there a way I can rotate it as if it were a texture?


Unity Shader Graph and GPU Instancing? Unity Version 2019.4.1f1 Render Pipeline URP I created a shader using Unity's ShaderGraph, and i want to apply GPU Instancing on this shader, but there is no way to declare per instance properties inside the shader graph. Is there a way to make GPU Instancing work on shader graphs' materials?


Make a child sprite match the layer ordering of its parent I have my project settings set up to order the sprites' visual layering based on their y position. If I add a sword as a child to my character, the sword won't have the same order as the parent so things can look like Sword gt enemy gt player instead of enemy gt sword gt player (because I want the sword to be in front of the character) I thought of setting the pivot point of the sword sprite so when nested inside the parent sprite, it would be around the same height as the player's pivot point so they would have the same order. I feel like this wouldn't be the best solution because when I will animate the sword to attack, I wont be able to rotate it around the position I want.....unless I make it the child of an empty object? How can I solve this issue?


Remove hidden values within string I tried removing the Unicode Whitespaces in the string using words len .Trim() but still there's still an extra character. Every letter represents the coordinate of where the letter is. As you can see there's an extra coordinate value and it is always located at the end of the string. (dont mind the ' tries') Can you help me Identify what is the extra invisible unicode and what to do in order for it to be removed? private string FisherShuffle(string words) int len words.Length while(len gt 0) float index Mathf.Floor(Random.Range(0f, 1f) len) len var temp words len .Trim() words len words (int)index words (int)index temp return words UPDATE I have found out that the ASCII value is 13. I also have tried using TrimEnd(' n',' n') amp words len .TrimEnd(System.Environment.NewLine.ToCharArray()) to no avail private string FisherShuffle(string words) int len words.Length int index string temp while(len gt 0) index (int) Mathf.Floor(Random.Range(0f, len)) len temp words len .TrimEnd(' n',' r') temp words len .TrimEnd(System.Environment.NewLine.ToCharArray()) words len words index words index temp return words


Civilization Style Borders With Sprites I am making a civilization style game in Unity. The game uses square tiles and has a 2d sprite style. I am currently implementing a border system like in civ4 where a line is drawn around you civilization's borders, but I cannot find a way to create the correct sprites to draw the border. My first thought was to have a sprite corresponding to each neighbor, the sprite would toggle on if the tile it is over is in the bordered area and the corresponding neighbor is not. This would work but It would require 8 (one for each neighbor) sprite renderers per tile and I assume that would be pretty inefficient. I thought of making a separate sprite for each configuration to cut it down to one sprite renderer per tile but that would require 2 8 sprites which just is not feasible. I also thought that maybe I should stick to the first idea but only instantiate or move sprite renderers to where they are needed which would greatly reduce the amount of sprite renderers used at once. This seems like my best option but it seems unnesicarily complicated and still pretty inefficient. I do not know of any simple way to dynamicaly draw sprites to fit a pattern, so it seems I am stuck with one of these solutions. Does anyone know of a better way to handle this?


Blur shader without render textures? Is it possible to append a blur shader to a standard (diffuse) shader ? I am looking for a way to do this as Unity indie doesn't allow render textures.


Using 10 materials for one Model? I made more than 10 robots. all of them had not less than 4 materials, and some had 12 materials. I can't go back and fix this. How this will effect on the game performance later ?


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


Unity3D filling visible camera area with objects I'm developing an isometric tile based game using Unity 3D. I'm using an orthographic camera looking down yaw 45 and pitch 45 . The game has an infinite world, which is loaded from a remote server. Because it is impossible to load everything at once, the game should only load visible areas of world. But I don't know how to determine which tiles should be requested from server in order to fill up all the visible space on the screen. I tried loading tiles by chunks e.g. 16x16 tiles chunk around camera. But this looks hacky to me and sometimes leaves blank edges visible on the screen. Is there better solution to simulate a continuous world on the client side?


Best Practices for Random Enemy Animations? For various animations for NPCs (getting hit with projectiles, shooting, dying) I've been creating 2 4 animations each in blender before exporting. Should I be doing this inside Unity with Animation Controllers instead? Either way what would be the best practices to actually randomizing the animations?


How can I switch between cinemachine free look cameras by script? using System.Collections using System.Collections.Generic using UnityEngine using Cinemachine public class CamerasManager MonoBehaviour public CinemachineFreeLook freeLookCameras public float timeBeforeSwitching Start is called before the first frame update void Start() StartCoroutine(SwitchCameras(timeBeforeSwitching)) Update is called once per frame void Update() IEnumerator SwitchCameras(float TimeBeforeSwitching) yield return new WaitForSeconds(TimeBeforeSwitching) for(int i 0 i lt freeLookCameras.Length i ) freeLookCameras i .en If I have two or more cameras I want that after X seconds start switching between all the cameras in the array by disabling enable the cameras. disable the first enable the second then disable the second enable the third and so on.


How to get time since frame start in Unity for loading purposes I am building a big world (1000 game objects). It takes 2s on the device. I am doing it in the background (the world is hidden until fully loaded). I have figured out that I can maintain the FPS of the active scene by switching to coroutines and making yield return null . The main issue is when to fire yield return null . If I do it too often, then it will slow down the loading. If I do it too rarely, it will reduce FPS on low end devices. My idea is simple to detect how much milliseconds have passed since the start of the frame and fire yield return null just after I have spent for example 12ms (to leave some time to render everything else and maintain something near 60FPS). However, I can not find an efficient way of getting the time since frame start? Unity should have something as the async loading of assets seems to consume just right time to maintain stable FPS.


Load a second app in background and launch behind a loading screen there is a way to preload an application in android from Unity? I mean.. I'm developing a launcher and every click in icon, should be launch a different game.. so, the time between show a loading animation and open the second app, in android, It's posible to make.. when the loading's animation is fadeout and behind the loading screen, the second app is loaded? P D I have to said that, the launcher is a different application from the game that should be launch.


How to cut a desired shape out of a mesh? I want the player to be able to cut a hole through a wall, similar to what's shown in this video I know for the fact that it's really difficult to achieve, so I was wondering how I can cut a shape out of a simple mesh at run time (or even cut a shape out of a 2D sprite).


simple 2d car AI unity I have a top down Car Game. how can I implement AI for the Cars? how the car follow the way points? I want AI cars also rotate itself along the path. I tried this solution using System.Collections using System.Collections.Generic using UnityEngine public class waypoint MonoBehaviour public List lt Transform gt waypoints private Transform currentWaypoint public float speed 5f private float closeEnouth 0.5f int point 0 void Start() currentWaypoint waypoints point Update is called once per frame void Update() Quaternion rotation Quaternion.LookRotation(waypoints point .position transform.position, transform.TransformDirection(Vector3.forward)) transform.rotation new Quaternion(0, 0, rotation.z, rotation.w) float dist Vector3.Distance(waypoints point .position, transform.position) transform.position Vector3.MoveTowards(transform.position, waypoints point .position, Time.deltaTime speed) if (Vector3.Distance(this.transform.position, waypoints point .position) lt closeEnouth) if (point 1 lt waypoints.Count) point and the car moved in the path but it moves reversed and if arrives the final node it stops and corrects its direction and console displays "Look rotation viewing vector is zero" error. Thanks in advance


Voxel clouds rendering in Unity I would like to have realistic voxel clouds in Unity game I found a very promising article on fast fluid simulations, however the the output of the algorithm itself is 3D grid of cloud densities ( 3D texture). My question is how can I render such 3D texture into clouds? My research so far The original article suggest two pass rendering of particles for each voxel, in first pass reading output after each particle(!) is rendered. This approach is both slow and outdated not leveraging modern shader pipeline in addition to being overly complicated. Searching for voxel clouds in Unity suggests using ray marching while the actual implementations does not seem to do any ray marching, but rather using Fractal Brownian Motion to same 2D noise texture. This approach gives decently looking results (with some problems addressed in horizon zero dawn slides), but would not make use of my realistic simulation. The most promising source I could find was this answer, namely last paragraphs. However the answer itself rather vague on actual algorithm and links it provides are either broken or inacessible.


What does pressing CTRL do when editing a sprite sheet? I have a multi sprite sprite sheet. When I have a blue box selected, and I hold CTRL, the box turns green. I have played with it, but cannot figure out what it does. I checked the documentation, but I don't see anything about turning the boxes green. What does holding CTRL when editing a sprite within a multi sprite sprite sheet do?


Can't go above max speed with RigidBody2D.AddForce() I'm having trouble making a character move faster than a certain limit using RigidBody2D.AddForce(). My game is a top down 2D game (constrained to the x y plane). I'm using a float 'MovementSpeed' to scale a normalized vector passed to RigidBody2D.AddForce(), however, when I increase MovementSpeed past 1000, there's almost no noticeable difference in the object's "speed" going from 100 to 1000 is a drastic difference, but there's almost no noticeable difference going from 1000 to 1000000. Here's my WASDMovement() function (called during FixedUpdate() ) private void WASDMovement() Vector3 translationVector Vector3.zero if (Input.GetKey(KeyCode.W)) translationVector new Vector3(0.0f, 1.0f, 0.0f) if (Input.GetKey(KeyCode.A)) translationVector new Vector3( 1.0f, 0.0f, 0.0f) if (Input.GetKey(KeyCode.S)) translationVector new Vector3(0.0f, 1.0f, 0.0f) if (Input.GetKey(KeyCode.D)) translationVector new Vector3(1.0f, 0.0f, 0.0f) translationVector.Normalize() rigidbody2D.AddForce(translationVector MovementSpeed) Here's a video demonstrating my problem to make it easier to see what I'm doing wrong http youtu.be 9kwKvfDOYoo


How to simulate car drivetrain (in Unity)? One of my hobby projects involves cars. Up until now I had a quick and dirty "one class" implementation of engine gearbox wheels, but I thought that this is ugly, and I want to go a bit more realistic. Sadly I couldn't find much on Google (either wrong search terms or there really isn't anything that is what I want). It seems like Setup in scene Four wheelcolliders attached to a big boxcollider. Things that I want in the system Separate classes for engine, clutch, gearbox, differential and wheels (and whatever else does stuff with torque). Throttlecontrol with revlimiter (works!), steering (works too!), brakes (not yet made, but also not very complex and will likely work). First thing I tried Mainly this rotates around how I tell the engine that the wheels are actually using or giving (engine braking) power to the system. so first I created all the classes each with their own updatemethod (not called directly by mainloop, but from a fixedupdate of a controllerclass). updatemethod of engine calculates engine torque from throttle, torque curve (animation curve) and engine friction. This is then used to speed up the virtual crankshaft which has its own inertia. But before speeding up the shaft, I decided to put some feedback torques on the engine torque, so if the wheels can't keep up, the engine can't speed up, or even slows down. Such a feedback torque is added for example by the gearbox, which in turn also has feedback forces from the differential and with that the wheels. The wheels calculate the torque needed to spin up to the speed of the shaft coming out of the gearbox and then it propagates all back to the engine over a few updates. Problem was, the torque feedback didn't really do engine braking, but catapulted it to several million RPM in a split second. Dividing the feedback torque by 1000 did work, but then the car didn't move at all. So this is fail number 1. Fail number 2 Okay screw this, I thought, and tidied up all the stuff. This doesn't use several updatemethod anymore, but recursive updating. Basically I call update on the engine, which in turn then calculates what torque it has available. With that it tells the transmission that it has t torques at r RPMs. The gearbox changes the values according to the current gear and then again puts the values into the differential. The differential SHOULD split the torque between its outputs. To do this I calculate how much torque the output (in this case wheels) would need to speed up to r RPMs. I do this for each output and make a list of it for each output. I also save the sum of these values. With this I can get a value of 0...1 for each output, that determines how much torque each output gets in its updatemethod. Its basically an intelligent differential that gives the output which needs more torque, more torque. I guess modeling a real differential would involve some more complex stuff. Now the torque is at the wheels and gets put into the motorTorque property of the wheelcollider. Up until here it works. If I throttle up and then let go of it the wheels start turning backwards. It's basically another feedbackloop just like with the first try. So also fail And fail 3 Instead of returning the torque that's left, I tried backpropagating the RPMs to the engine instead. So I apply torque, and get RPMs back. But again everything tries to move the car in the opposite direction that I want it to go. Here is where I'm out of ideas. I want a relatively realistic drivetrain, that is modular and can do enginebraking. A bought asset will most probably not solve my problem, and I also want to understand how it works, and not just use it. Does anybody have experience with how to properly model a drivetrain? If I forgot to mention something, please ask.


Armature's bone can't be rotated in Unity when I'm trying to rotate its chest toward its looking direction? I want to rotate my character's chest, so its looking direction will be visualised correctly. But I think that the animation controller doesn't let me. I logged its rotation before and after I set it, and after setting, it's correct, but next frame before I would set it, it's always snapped back. How could I make my character's animation transformed, based on its looking direction? This is the code Debug.Log(Chest.localRotation.eulerAngles) Chest.localRotation Quaternion.Euler(90, 90, 0) Debug.Log(Chest.localRotation.eulerAngles)


How to reset the score to 0 when reloading the game? My scoring system uses DontDestroyOnLoad to persist between scenes public class ScoringSystem MonoBehaviour private int score 0 public void Correct(int number) If correct add score score score number void Start () score 0 void Awake() DontDestroyOnLoad(transform.gameObject) public int GetScore() return score Here is another script that I should include a description about public void iniTag() jawab true Time.timeScale 0 GameObject objek1 GameObject.FindGameObjectWithTag("Benar1") GameObject objek2 GameObject.FindGameObjectWithTag("Benar2") GameObject objek3 GameObject.FindGameObjectWithTag("Benar3") GameObject objek4 GameObject.FindGameObjectWithTag("Benar4") if (objek1.transform.parent.tag "Jawab4" amp amp objek2.transform.parent.tag "Jawab3" amp amp objek3.transform.parent.tag "Jawab2" amp amp objek4.transform.parent.tag "Jawab1") PanelBenar.SetActive(true) buttonNext.SetActive(true) GameObject.Find("QuizManager").SendMessage("Correct", playerScore) void Start () if (GameObject.Find ("QuizManager") ! null) ScoringSystem scoringSystem GameObject.Find ("QuizManager").GetComponent lt ScoringSystem gt () gameObject.GetComponent lt Text gt ().text scoringSystem.GetScore().ToString () else Debug.Log("No Scoring system found. To test scoring system start from the front page scene")


Unity Behavior Designer get gameobject I am trying to create my own action in Behavior Designer. However i cannot seem to get the game object that designer is attached to. if i attempt to do protected Combatant enemyCombatantObject public override void OnAwake() enemyCombatantObject GameObject.GetComponent lt Combatant gt () base.OnAwake() It gives me an error the property or indexer 'Task.GameObject' cannot be used in this context because it lacks the get accessor Can anyone tell me how to get the GameObject that the script is attached to?


How can I unify the collision handling of melee spell attacks in a networked environment? I am trying to figure a good way to create the battle system of a game. The game is fast paced and the gameplay needs to be precise (think hack n slash) What I would like to achieve is a simple and unified system that could manage any type of attacks, that could be tweaked. My first idea is to use physics shape For example an arrow will just be a little capsule moving forward, an explosion would be a growing sphere collider, and melee combat could be done by spawning a box in front of the player. One problem I have with this is that I'd like to have an authoritative server for multiplayer, which means I shouldn't use too much actual physics. So, is there any standard way people program these sort of systems, do you know any good starting point better than just using physics?


How can I make the space craft takeoff landing by code with logic? The code so far using System.Collections using System.Collections.Generic using UnityEngine public class AnimFlyertransportationController MonoBehaviour public Transform transformToMove public GameObject JetFlame public float speed public bool takeOffLand false private Animator animators private void Start() TurnAllAnimtorsOff(transform, false) private void Update() if(takeOffLand) TakeOff() else Land() private void TakeOff() float step speed Time.deltaTime var v3 new Vector3(transformToMove.localPosition.x, 7, transformToMove.localPosition.z) transformToMove.localPosition Vector3.MoveTowards(transformToMove.localPosition, v3, step) private void Land() float step speed Time.deltaTime var v3 new Vector3(transformToMove.localPosition.x, 0, transformToMove.localPosition.z) transformToMove.localPosition Vector3.MoveTowards(transformToMove.localPosition, v3, step) private void TurnAllAnimtorsOff(Transform root, bool onOff) animators root.GetComponentsInChildren lt Animator gt (true) foreach (Animator a in animators) if (onOff) a.enabled true else a.enabled false The problem I need to call the function TurnAllAnimtorsOff but each time only once when taking off and when landing. When taking off it should first turning all animators and flame to true turn them on then taking off and when landing first to land when reaching height target when landing finished then call the function again and turn off all the animators and the flame. I added this flag bool variable takeoffland as helper but now the object is taking off and engine and animators turning on but now it's not landing anymore using System.Collections using System.Collections.Generic using UnityEngine public class AnimFlyertransportationController MonoBehaviour public Transform transformToMove public GameObject JetFlame public float speed public bool takeOffLand false private Animator animators private bool takeoffland false private void Start() TurnAllAnimtorsOff(transform, false) private void Update() if(takeOffLand) if(takeoffland false) TurnAllAnimtorsOff(transform, true) JetFlame.SetActive(true) takeoffland true TakeOff() else Land() private void TakeOff() takeoffland false float step speed Time.deltaTime var v3 new Vector3(transformToMove.localPosition.x, 7, transformToMove.localPosition.z) transformToMove.localPosition Vector3.MoveTowards(transformToMove.localPosition, v3, step) private void Land() float step speed Time.deltaTime var v3 new Vector3(transformToMove.localPosition.x, 0, transformToMove.localPosition.z) transformToMove.localPosition Vector3.MoveTowards(transformToMove.localPosition, v3, step) if(takeoffland) TurnAllAnimtorsOff(transform, true) JetFlame.SetActive(true) private void TurnAllAnimtorsOff(Transform root, bool onOff) animators root.GetComponentsInChildren lt Animator gt (true) foreach (Animator a in animators) if (onOff) a.enabled true else a.enabled false


Stop animation from playing while waiting to destroy object I'm working on functionality in Unity where if a game object's health is zero, it does and the object is destroyed. This works fine as is, I reduce the health to zero, the die animation plays and the game object is destroyed. I want to have the script wait a certain amount of time and then run the destroy method. I thought using WaitForSeconds() would do the trick, and technically, it does, but the death animation continues to play until the object is destroyed. My question is, how do I get the animation to stop playing as the script waits to destroy the object? C void Die() GetComponent lt Animation gt ().CrossFade(die.name) If the current animation time is greater than 90 of the entire animation length, destroy the object. if(GetComponent lt Animation gt () die.name .time gt GetComponent lt Animation gt () die.name .length 0.9) StartCoroutine(RemoveBody()) IEnumerator RemoveBody() yield return new WaitForSeconds(5) Destroy(gameObject)


How to initiate manually an animation in Unity? I have a prefab and I want to control when an animation is initiated. I can't seem to figure out how to do that. I have already created the animation clip, the animator component for the prefab, and the animator controller. The animation works, when I enter play mode in the unity editor (it plays automatically), but I want to control when the animation occurs when providing input (such as pressing on the space bar or clicking on the prefab). How would I go about doing that?


Make objects stack in unity? I have two kinematic rigidbody cubes from the standard 3D objects, I have also enabled contact pairs mode to quot all contact pairs quot , how do I make it so that no matter what angle they collide in they perserve the same angle but just get out of each others space making it look like they're in contact e.g. collided? Here is my attempt at doing that using System.Collections using System.Collections.Generic using UnityEngine public class Physics MonoBehaviour private Collider collider1 private bool grounded false used to determine if the collider hit something so it doesnt keep going down Start is called before the first frame update void Start() collider1 GetComponent lt Collider gt () Update is called once per frame void Update() if (!grounded) if the collider hit something, stop going down collider1.transform.Translate(0f, .1f,0f,Space.World) private void OnCollisionEnter(Collision collision) grounded true the collider hit something if(collider1.transform.position.y ! collider1.bounds.extents.y) if this is true, it means it is at the floor so dont move it transform.position new Vector3(collider1.transform.position.x, collision.collider.bounds.size.y collider1.bounds.extents.y, collider1.transform.position.z) attempts to put the collider on top of whatever it get This works if the cubes are right on top of each other with no angle It also works if one of the cubes collides at a angle to the other cube, when they collide the bottom cube perverse its angle of collision and and the top cube just gets out of the space of the other collider making it look like they have collided What doesn't seem to work is if both cubes collide with each other at a angle, although they preserve their angle of collision, and also get out of each others space, they do not remain in contact with each other which if they did would make it look like they have collided. Instead there is a gap between them, how do I get rid of the gap e.g. make it so that no matter what angle the objects are at they get out of each others space, preserve the angle, and remain in contact with each other to give the illusion that they have collided?


How do I make sprites overlap eachother based on a layering system? In Unity, I am building a 2D puzzle game, however I need to make sure that certain sprites are rendered on top of other sprites when they are above them. Here is an example switch (left) and block (right). I wanted to make sure that the green block appears on top of the green switch when it passes over it, so how do I avoid a situation like this happening?


Problem with Raycasting in a 2D Game I'm new to using unity and came across a problem when I was following a tutorial. The game is in two dimensional space, and when my player walks over a certain tile the detection never goes off. Here's the code that I have, function calculateWalk() yield WaitForSeconds(0.3) var hit RaycastHit if(Physics.Raycast (transform.position, Vector3.down, 100.0)) Never evaluates to being true var distanceToGround hit.distance Debug.Log("Hit") if(hit.collider.gameObject.tag "tallGrass") walkCounter Debug.Log("Tall Grass") END if END if END calculateWalk() I've made sure to attach the script to my player, as well as tag the tiles that I want with "tallGrass". I've followed what was done in the tutorial, but for some reason it's not working out for me, not sure if this is all the code needed to help solve this problem, if more information is needed let me know, I also set my player 1 unit above the tiles.


Unity Player Movement Problem I want to make a little game in Unity, where the player (a ball) jumps up and down and you have to maneuver it through (flappy bird like) obstacles. My problem is, after I added a simple movement script float speed 10f Vector3 move new Vector3(Input.GetAxis ("Horizontal"), Input.GetAxis ("Vertical"), 0) transform.position move speed time.deltatime The ball is stuck and can only be moved a little,before returning to its start position. My question is how i can fix that? I didnt find any solution


NavMesh moving is not smooth I have two car in game one of them is cop that chase player, i put a NavMesh on cop with these values when the cop get close to player (player speed is 10 ) , movement will go jittery and not smooth. Note cop will not collide with player because i have changed stopping distance in script instead of editor. Note 2 this jittery movement is not only in camera its also on scene view. now how i must make movement smoother? where is the problem?


Can UNet do Rigidbody2D prediction? (i.e. using gravity) Having a NetworkTransform with transformSyncMode set to SyncRigidbody2D (as opposite to a plain SyncTransform) I assumed it would try to sync all physics, hence handling gracefully forces, especially gravity. What I got instead, is a very simple linear interpolation, which smooths out the gravity, so that jumping up and down looks incredibly unnatural I would have expected this wish a SyncTransform of course, but, given the name I would have expected SyncRigidbody2D to solve this sort of problem So, am I missing something and might I have some value set wrong, or what?


Causing Update loop with Coroutine Unity Total Noob Alert! lt 7 days with C and Unity My Win Game screen becomes SetActive and my Player is SetActive false when you are standing in a trigger and crouch. That all works fine except you cant see the crouch animation because he is IMMEDIATELY SetActive false. I tried to delay this by creating a coroutine. The problem with that is this is all happening in the Update function (or whatever it's called) because of the getkeydown for crouch. That gets called once per frame so my coroutine is trying to go off once per frame. I tried creating a bool called isCoroutineStarted and set it to false and then set it to true in the Coroutine to break the loop but that didn't work either. Don't know what to do so I reverted it back to before where it doesn't show my crouch animation. Here's my script (It's attached to a Game Object with the trigger) using System.Collections using System.Collections.Generic using UnityEngine public class xxxxxx MonoBehaviour public bool xxx false SerializeField private GameObject youWinUI SerializeField private GameObject player Determines whether or not the player is standing on the xxxxx void OnTriggerEnter2D (Collider2D other) xxx true void OnTriggerExit2D (Collider2D other) xxx false Turns on Win screen and makes player disappear when crouch on xxx void Update () if (Input.GetKeyDown (KeyCode.S) amp amp xxx true) youWinUI.SetActive (true) player.SetActive (false) P.S. ignore the x's no stealsies lol. Also this piece of script works as intended I just want a delay so you can see the crouch animation.


Make my Random.range not repeat same position So I want to make my array Gameobject transform to transform array points position but it will be randomized position when start only without repeating a position so make some script like this public GameObject collectibleAyatGO public Transform transformPoint public List lt int gt TakeList new List lt int gt () private int randomNumber public void RandomTransformPosition() TakeList new List lt int gt (new int transformPoint.Length ) for (int i 0 i lt transformPoint.Length i ) randomNumber Random.Range(0, transformPoint.Length) while (TakeList.Contains(randomNumber)) randomNumber Random.Range(0, transformPoint.Length) TakeList i randomNumber collectibleAyatGO i .transform.position transformPoint TakeList i 1 .position it seem not working or make my unity notresponding maybe due to while loop, Am I doing right here ?


Unity 3D Rotate (smoothly) towards a target I wanted to know if there is a method on which I can rotate an object with an angle given (a float to be precise), I use trigonometry to calculate the angle between the two objects in a (x, z) plane perspective (using y as the height coordinates). This is the code I use to calculate the angle, but I want to know if a float would be anough data (then pass a Vector3 with that angle calculation as the Y parameter, since I want to rotate the Y axis). Makes the player heads to the direction the ball is... public float headOnBall() Vector3 playerPos this.transform.position Vector3 ballPos ball.transform.position float angle float x (playerPos.x ballPos.x) float z (playerPos.z ballPos.z) if(playerPos.z lt ballPos.z playerPos.x lt ballPos.x amp amp playerPos.z lt ballPos.z) angle (Mathf.Atan2(z, x) (Mathf.PI 2)) Mathf.Rad2Deg else angle Mathf.Atan2(z, x) Mathf.Rad2Deg return angle Thanks in advance.


Unity Custom aspect ratio in build I have made a game that was supposed to be for mobile but now I need to build it for PC. I want the aspect ratio to be 2 3 but as you can see on the image that doesn't exist. How do I add a custom aspect ratio for the build?


How do I display the next speaker image in my dialogue? I am working on a dialogue system and while the text part works, the UI for the Dialogue Boxes does not. When I click on the Continue button, I want the script to go down the Elements and use the Image that I have selected there, similar to what the sentences feature does. This is my script using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI using TMPro public class TextDialogueScript MonoBehaviour public TextMeshProUGUI textDisplay public TextMeshProUGUI ContinueDialogue public Image UIDisplay public string sentences public Image CharacterNames public Sprite CharacterDialogueBox public Image CharNames public List lt Image gt DialogueBoxes new List lt Image gt () public List lt Image gt CharacterName new List lt Image gt () private int index private int DBindex public float typingSpeed public GameObject DialogueTrigger public GameObject DialogueEventController public GameObject NormalEeventController Start is called before the first frame update void Start() NormalEeventController.SetActive(true) DialogueEventController.SetActive(false) UIDisplay.enabled false ContinueDialogue.enabled false Update is called once per frame void Update() if(textDisplay.text sentences index ) ContinueDialogue.enabled true public void OnTriggerEnter(Collider other) if(other.CompareTag("Player")) NormalEeventController.SetActive(false) DialogueEventController.SetActive(true) StartCoroutine(Type()) ContinueDialogue.enabled true UIDisplay.enabled true UIDisplay.sprite CharacterDialogueBox DBindex public void OnTriggerStay(Collider other) if (ContinueDialogue true) public void OnTriggerExit(Collider other) NormalEeventController.SetActive(true) DialogueEventController.SetActive(false) ContinueDialogue.enabled false UIDisplay.enabled false IEnumerator Type() foreach(char letter in sentences index .ToCharArray()) textDisplay.text letter yield return new WaitForSeconds(typingSpeed) public void NextSentence() ContinueDialogue.enabled false if(index lt sentences.Length 1) index textDisplay.text "" StartCoroutine(Type()) else textDisplay.text "" if (DBindex lt CharacterDialogueBox.Length 1) DBindex I was using a List that grabbed sprites, but the problem is, it would only use Sprites from the Assets and not the Hierarchy. This is a problem because I have messed with the colours using Unity and played around with the Alpha to get the exact effect I want that cannot be replicated with my image program. (I do not know what the term is for adding on the end of items to add elements that can be expanded. I have been stuck on this dialogue system for a very long time and I am very tired yet excited because I am so close to getting this to work, that it's painful)


(Why) Should I choose Unity 3 or Cocos2d (or something third) for my app? My colleague and me made an HTML 5 iPad game ( http braille.gandzo.com ) and we would like to upgrade it, and our framweork is not enoguh, for what we want. Some of the things we would change are graphics update, animations "effects", multi player, achievements and so on. The game would stay 2d. Now, as far as I understand, both Unity and Cocos would be good for this task, with Unity having the advantage of being multi platform. What I want to know is are there unknown qualites "flaws" to these two programs which would influence my decision (maybe even by choosing something else). Examples that come to mind are "Unity is too complicated has too much unneeded options hoops because it's made with 3d in mind" or "Cocos is significantly more suited for 2d games".


Recursive Unity Coroutine I have a co routine which is heavily reliant on calling itself to get the task done. I have tested it and the code works fine, the problem is that the co routine will return every time that it enters itself recursively. IEnumerator test(arg1, arg2) I want to pause here yield return null I don't want to pause on any of these yield return test(arg1, arg2) yield return test(arg1, arg2) yield return test(arg1, arg2) yield return test(arg1, arg2) In the example above I have a yield return at the top that is hit and pauses the co routine, thats fine. Then there are the calls to itself below which also pause the co routine. How do I avoid pausing the co routine on the recurcive calls?


Rigidbody Ray alternative or optimization I am creating an AI that moves around to certain points, but should interact with ais or objects seen. The ai should find other ai to comunicate or look for objects on the ground. It works with all those solutions with a low number. But when I have 300 ais the fps drops a lot, caused by Physics2D.FixedUpdate or something related with physics. How would you deal with this? I have tried those solutions Solution 1 AI Rigidbody2D Kinematic SphereCollider2D Trigger OnTriggerEnter amp Exit Script. Objects Rigidbody2D Kinematic SphereCollider2D Trigger Solution 2 AI Rigidbody2D Kinematic SphereCollider2D Trigger OnTriggerStay Script executed each 120 frames amp a Coroutine to simulate OnTriggerExit. Objects Rigidbody2D Kinematic SphereCollider2D Trigger Solution 3 AI No RigidBody SphereCollider2D Trigger Cone of Rays executed each 2 second to detect colliders at certain layers. Objects No RigidBody SphereCollider2D Trigger EDIT In solution 1 and 2, all AI have an quot eyes quot children GameObject with a TriggerCircleCollider2D and no RigidBody2D, to detect near AIs and GroundObjects.


Client side prediction buffer size considerations for jitter I am currently having a FPS game with client side prediction. Every 20ms, the client sends it's input to the server. The server buffers 5 ticks worth of input (100ms) and starts consuming the inputs each tick and sends a world snapshot to the client. The client then validates the predictions and corrects the simulations if there is a misprediction. The setup works fine under ideal network conditions. However when the latency suddenly spikes from say 50ms to 400ms, the client's tick packet is delayed which causes the server to eat through all of the available inputs in the buffer and resort to using the previous tick values to perform server simulation. When the client input finally arrives at the server late, the server discards the input because it has already processed the input for that particular tick (using old input values). How do I handle this edge case of latency increasing and decreasing? Sure I could use a larger buffer size for the inputs, but that will cause delays between client state and server state. Using a smaller buffer will cause the server to stall from inputs if there is a jitter that is more than the duration required by the server to process the inputs. I was under an impression that I would need some kind of dynamic buffer size that expands and contracts. However, I am out of ideas to implement something like this. Does anyone have a solution?


Using CNN's in Unity via Tensorflow and TensorFlowSharp I have a project that tracks hands made in python, shown here https github.com timctho convolutional pose machines tensorflow I want to effectively import this into Unity. I have generates the .bytes file from the model, but have no idea how to do anything further than this. If anyone has worked with ML Agents or TensorflowSharp in Unity and or would be willing to have a look, this would be great. The image processing stuff would be done probably in a C file beforehand, I just want to know how to run the network. Thanks.


Make UI Button Image Size Independent of Screen size Unity I have two UI Buttons with image sprites in Panel (inside canvas). I have set their sizes to 40 in the inspector. If I run game in maximize mode, buttons retain constant assigned size of the inspector, instead of adjusting themselves with screen size. I have already added Canvas Scalar component with value Scale with Screen Size. Text fonts are able to adjust with screen size present in same canvas, but button with image does not. Any guide on this? Thanks.


Character not collecting animated coins I am trying to make a simple game where the player jumps and collects animated coins. After collecting all the coins, the scene is supposed to change. For some reason, my character collects the coins but the scene doesn't change. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class Coins MonoBehaviour SerializeField private string newLevel public int coinAmount int coins void OnTriggerEnter2D(Collider2D other) if (other.CompareTag("Player")) coins 1 Destroy(gameObject) addCoins() void addCoins() coins if (coins coinAmount) SceneManager.LoadScene(newLevel) This is a screenshot of the game


Creating a planet out of an existing terrain I am creating a game that I have created a terrain for. I really like the terrain so I am wanting to keep it but I want to have the game take place on a full planet. Avoiding paying 200 for an asset already made, how would I develop something to allow me to "tile" this terrain to make a full planet and to make it round instead of flat? I know this has to be somewhat possible with the expensive assets on the asset store that are for round terrains. I just need to figure out how and I can't find anything online that is much help.


Efficient way to implement a lot of singletons I just came upon programming patterns and learned about singleton. I'm in the process of creating my first game and it contains several managers I wanted to implement singleton on each of the managers,but the only way I can think is copy pasting the singleton pattern on each awake method script attached to each manager. Is there a more efficient way to do it rather than pasting the pattern on each awake method?


Unity Rigidbody2D to act on certain gameobject only I am creating a 2D game and the player object has a rigidbody2D attached to it. The game works fine until the player collides with a power up. The rigidbody physics get all messed up. So I was wondering is there a way so that rigidbody will only act on enemies and be disabled for power ups?


Understanding Physics Materials I have been reading the documentation about Physics materials, and it really seems very incomplete to me. When I try to work with it, I get so many questions... Maybe can someone help me wrap my head around how it works? Why is there a physics material field for the Rigidbody2D, but also another in the BoxCollider2D? Do they work differently, depending on which you put it? What happens if you put different materials, one on the RB and one in the collider with different settings? If a player is standing in a platform, and you want it to bounce, or slide... do you set that on the player? Or in the platform? Update As suggested in the comments, I did some experimenting and this is what I saw When I put contradicting materials in the RigidBody2D and the Collider2D, the one in the collider seems to take precedence. Not sure what is the purpose of the one in the Rigidbody. If both are the same, well, they just behave like one of them alone. The value isn't added


How do I snap the Unity camera to a 2D, tile based map? I have a 2D, tile based map. I want to be able to control the number of visible tiles on the screen vertically and horizontally, regardless of resolution. I want the player to be able to move the camera one tile width at a time until it hits the edge. I do not understand how to manipulate the Unity camera in order to accomplish this. I have read the documentation, and Googled, but there is just something that is not clicking for me. So, let's say I have a 100x100 map. A 32x24 portion of the map is shown at a resolution of 1024x768, each tile has a size of 1x1 Unity unit. The bottom left of the visible area of the map starts at the bottom left of the map (0, 0). The player then clicks the right arrow key and the map moves one tile to the right (1, 0). How do I accomplish this, given that I am using the latest version of Unity in 2D mode?


Unity Adding more functionality to a List Inspector Let's say I have the following code public List lt Armor gt armors new List lt Armor gt new Armor() name "Black set", folder "black set" , new Armor() name "Conquistador", folder "conquistador" , new Armor() name "Crusader", folder "crusader" , new Armor() name "Gothic Plate", folder "gothic plate" , new Armor() name "K.D.", folder "kd" , new Armor() name "Lorica segmentata", folder "lorica segmentata" , new Armor() name "Rusty", folder "rusty" , new Armor() name "Spartan", folder "spartan" This appears in the editor like this While this is acceptable, there are a couple features I am missing Lets take for instance the Sorting Layer list Here there are 2 features that I would like The ability to reorder elements on the editor The ability to add more elements using or Is there any way to add this functionality into my List?


Scale one object to be cover multiple other objects I have placed and aligned several objects next to each other. For the sake of understanding, lets just say I placed 10 cubes next to each other. I snapped them all together (Move V Click amp Drag). The cubes look great so far. Now I want to make a plane in front of the cubes, that has exactly the width of the cubes altogether. Now, I can place a new plane in front of the, no problem. I can snap a single edge to the cube on the most right, also no problem. But now, how can I make the size exactly the same as all the cubes together? Sure, I could eyeball it from top view, an kind of make it about the same size, but chances are, it's a little bit too short or too long. Isn't there a possibility to snap one edge, lock it, and snap another edge making the object scale automatically to the desired width?


How do I move an object towards a moving object? I am trying to make an AI that tries to move towards the player but I don't know how. I tried using Vector2.MoveTowards() but it just mimics my movements instead of moving towards the player. I tried everything i could think of (which was not a lot D) but i couldn't make it move towards and touch the player! Help please D. Also my original code pragma strict var speed float 100 var targetX Transform var targetY Transform var mex Transform var meY Transdorm function Update () var targetX transform.position.x var targetY transform.position.y var meX transform.position.x var meY transform.position.y Vector2.MoveTowards(Vector2(meX, meY), Vector2(targetX, targetY), speed)


How do you deal with transparent fonts that you want to be white? I'm a bit of a total amateur, but I thought I would learn how to make a simple game during quarantine. However, I stumbled into a problem with fonts. I'm thinking about using the free font quot Pixelmania quot to show a score at the top of the screen. But the font is transparent! How do I make the inner part of the font white? Do I have to manually edit the font file myself? Or is there an easier way?


I added a terrain in Unity, but can't see it In Unity I added a terrain through Create rarr 3D Object rarr Terrain. It didn't show up and I can't see it. I tried to press F to focus on it, but I still don't see it. What am I doing wrong? Here is a screenshot


Can't rotate object after using transform.forward I'm using above code to rotate object pointing where it moves transform.forward m Rigidbody.velocity It works fine, however the problem is that I can't rotate this object anymore after set direction. transform.forward m Rigidbody.velocity transform.Rotate(0, 0, m RotateSpeed Time.deltaTime 500) Not Working Code is simple, first rotate the object to point where it goes and then rotate z axis. But when I ran the game, it just shaking little bit and didn't rotate at all. Why it doesn't work even rotating code after the transform.forward? Any advice will very appreciate it.


Why are these unity UI buttons only responding to the top half? I'm instantiating UI objects with buttons on them into a scrollrect. For some reason, all of the buttons will ignore their bottom half with the exception of the last prefab instantiated. Below is a gif to show the problem. I have it set to turn red when the button is highlighted. When the mouse isn't in a highlight position clicking will do nothing so I know it's not just a highlighting issue. Here is the code that I'm using to instantiate the scene. Instantiate the parent UI MyLoadGUI (GameObject)Instantiate(LoadGUI) Get the RectTransform of the scroll rect so I can add each level to the right thing. RectTransform rt MyLoadGUI.GetComponentsInChildren lt RectTransform gt () RectTransform myRt new RectTransform() for (int i 0 i lt rt.Length i ) if (rt i .name "Scroll Panel") myRt rt i break We're going to make 6 fake levels int levelCount 6 int levelSize 88 How tall the levels are int height Mathf.Max(levelSize levelCount, 252) myRt.sizeDelta new Vector2(myRt.sizeDelta.x, height) myRt.anchoredPosition new Vector2(myRt.anchoredPosition.x, height) for (int i 0 i lt levelCount i ) GameObject lsl (GameObject)Instantiate(LoadSingleGUI) RectTransform rect lsl.GetComponent lt RectTransform gt () rect.SetParent(myRt, false) rect.anchoredPosition new Vector2(0, 37 (i levelSize)) Fill in fake details. Doesn't run anything related to the button. lsl.GetComponent lt LoadLevelBar gt ().BuildRandom() So, nothing that should be affecting the button that I can see. I thought that the button was getting resized, but when checking in the scene the button is stretched all the way across the prefab. Any ideas why the button isn't working properly?


Unity Movement Questions I have recently been trying to learn how to make Unity games through Lynda.com using the tutorials provided by Jesse Freeman. But I have one issue, he doesn't explain any of the coding. This bit has me confused. Body2D.AddForce (new Vector2 (forceX, forceY)) 1.) Why is Body2D (this is a variable) separated by AddForce with a .? 2.) Why does a new vector2 have to be created? 3.) My last question isn't quite in the code itself but why must we add a () to methods? (Full Code) using System.Collections using System.Collections.Generic using UnityEngine public class Player MonoBehaviour public float Speed 2.5f public Vector2 MaxVelocity new Vector2 (5, 10) private Rigidbody2D Body2D private SpriteRenderer Renderer2D Use this for initialization void Start () Body2D GetComponent lt Rigidbody2D gt () Renderer2D GetComponent lt SpriteRenderer gt () Update is called once per frame void Update () var absValX Mathf.Abs (Body2D.velocity.x) var forceX 0f var forceY 0f if (Input.GetKey("right")) if (absValX lt MaxVelocity.x) forceX Speed else if (Input.GetKey("left")) if (absValX lt MaxVelocity.x) forceX Speed Body2D.AddForce (new Vector2 (forceX, forceY))


Call code on interrupting Unity animator sub FSM I'm trying to find a way to execute a code when one of two outcomes happens in Unity animator controller When animator's sub FSM finishes or When animator's sub FSM is "interrupted" by a transition originating from "Any state" node at the parent FSM. The concrete setup is next (but that is probably not super important) The parent FSM have a transition from "Any state" to Damaged state and that can "interrupt" an attack sub FSM Parent FSM The attack sub FSM consists of three states that run in succession PreAttack Attack PostAttack Attack sub FSM At the end of the attack sub FSM a method is called. It can be through Animation even at the end of PostAttack animation in the sub FSM, or StateMachineBehaviour.OnStateExit() at the PostAttack state , or StateMachineBehaviour.OnStateMachineExit() at the sub FSM. The problem is that none of these 3 is called when the sub FSM is "interrupted" by the "Any state" transition in the parent. Is there any way to call code when a sub FSM is "interrupted" by "Any state" transition in the parent FSM?


Why would the same script attached to multiple scenes not work the same way in some of the scenes? I have 4 scenes in my Unity Project. And in each scene I have identical sliders, what I want to do when Advance Trial is called via a button press, the sliders' value resets to 0. However, this only works for two of the scenes. For remaining two it doesnt work, I checked if Advance Trial is attached to the button gameobject which calls it and it is (in all scenes). There are no errors messages in the console either. How do I correct it? Also, when the else portion is executed the sliders are not inactive meaning, the sliders are still visible. This happens for the same two scenes for which the sliders do not reset. Am I missing something? Or do I need to check something in individual scenes? Please see my code below. public Slider sliders public void Start() sliders FindObjectsOfType lt Slider gt () as Slider for (int s 0 s lt sliders.Length s ) Resets the sliders sliders s .gameObject.SetActive(false) public void Advance Trial() for (int s 0 s lt sliders.Length s ) sliders s .value 0 int stimIndex UnityEngine.Random.Range(0, signals.Count 1) string text stimIndex.ToString() byte data5 Encoding.ASCII.GetBytes(text) client.Send(data5, data5.Length, remoteEndPoint) Debug.Log( quot lt color yellow gt Signal played is lt color gt quot stimIndex) Debug.Log( quot lt color magenta gt NUMBER sent to MAX is lt color gt quot text) Debug.Log( quot lt color magenta gt Index removed was lt color gt quot signals stimIndex ) signals.RemoveAt(stimIndex) if (signals.Count gt index) Debug.Log( quot lt color orange gt Yay! Keep Listening! lt color gt quot ) index else Debug.Log( quot lt color green gt All Trials finished lt color gt quot ) for (int s 0 s lt sliders.Length s ) sliders s .gameObject.SetActive(false) EndSessionPanel.gameObject.SetActive(true)


Display object at different position Id' like to create impression of shaking holographic image of NPC in Unity 2018, but moving it with transform will cause unnecesary transform rigidbody syncing, and using Rigodbody.position isn't an option for other reasons (too long to explain). I could write custom shader for moving vertices by given vector, but I'd like to keep flexibility of Standard Shader. Is there any way to properly render object at different position than it's transform.position? I was thinking about passing custom matrix to shader, but not sure which matrix should I overwrite and if it's not gonna complicate things (like break shadows or something).


How do I link a GameObject activated state to a UI button being held? How do I go about this functionality When a user taps and still holds onto a UI button, a GameObject will be set active, when they release the UI button, the GameObject will be deactivated.


How to design prefabs in Entity Component Systems In Unity (and I presume other game engines) you can create "prefabs" which are blueprints for game objects. They contain a list of components, and default values for those components. Prefabs can be instantiated many times, which is an efficient way of creating many objects of the same kind. One feature in particular of prefabs is that you can modify an attribute on a single instance of a prefab, without modifying the prefab itself. Similarly, you can modify the prefab, which will propagate the change to all instances. I've been working on an implementation of the Entity Component System (for a high level description of ECS see this question How to implement n body in an Entity Component System), and I got stuck on how to implement prefabs efficiently in ECS. I think it's a powerful capability of EC design, and implementing this on native ECS would be awesome. I can come up with a few approaches Create archetypes, which are predefined lists of components (Unity approach). This does not let me set initial values for the components, nor override them (there is nothing to override). Easy to implement, but doesn't really do what I want it to do. Create a "prototype" entity from which other entities are cloned, including component values. With this design I can override individual attributes, but when I update the prototype, the clones don't get updated. Create entities with a reference to a "base" entity. When getting a component from an entity, first look in its component list, then try the base entity. This way when I update a base component, base instances change as well. To override a base component I can simply add it to the instance entity. Of these three approaches the third approach comes closest, but I don't see a straightforward way to extend it so I can override a single attribute. How can I make this work?


How to make a script work when clicked only on the given prefab? I am very new to unity but not to C . I am working in Unity 2D I made this prefab called LongLane. Its basically a collection of sprites of road, put together into a Gameobject. Now I wanted objects to spawn on the road when I ONLY click on the road, I can spawn the object on the road but they spawn regardless of where I click. I have written some code but they aren't clear and readable. So how do I make a script work only when clicked on that specific prefab


How do I handle loads of (prefab?) objects in Unity2D 3D? I have been looking around for information regarding this process but I was unable to come across anything that would help me out. Basically, in a game where you may have many items or enemies or player objects, how would one go about creating these objects? Am I supposed to be creating every single one of these objects as a prefab and then load them into the game when needed? Or is it possible to create one object that has references to the different variables needed to create the above objects and then load in from an external source all the necessary information? And then during run time, depending on what object I am looking at, the script will 'create' the object with the information from the external source. Meaning, if I decide to have 50 different enemies in my game, do I need to make 50 prefabs, one for each enemy? Or just one prefab that loads in data pertaining to the 50 different enemies and then build upon that information? Thank you!


Why does the Debug.DrawRay return these weird lines I am working on a small feature of a 2D mobile game where a indicator points towards a object in 2D space. I am trying to make the indicator turn towards the object, however the vector I am trying to construct that points towards the object is off a bit. When I decided to draw a debug ray from the indicator position to the objects position it was also off a bit. I then decided to draw the debug ray the other way around which gave me a different line. If my understanding is correct, if you switch the starting point and the end point of a ray the line should stay exactly the same right? using UnityEngine using System.Collections.Generic public class Tracker MonoBehaviour public GameObject goToTrack private List lt Renderer gt renderers new List lt Renderer gt () void Start() foreach (Transform child in transform) renderers.Add (child.gameObject.GetComponent lt Renderer gt ()) void Update () void OnGUI() Vector3 v3Screen Camera.main.WorldToViewportPoint(goToTrack.transform.position) if the target is within the viewable screen the indicator shouldn't be rendered) if (v3Screen.x gt 0.01f amp amp v3Screen.x lt 1.01f amp amp v3Screen.y gt 0.01f amp amp v3Screen.y lt 1.01f) foreach (Renderer renderableObject in renderers) renderableObject.enabled false else foreach (Renderer renderableObject in renderers) renderableObject.enabled false v3Screen.x Mathf.Clamp (v3Screen.x, 0.01f, 0.99f) 0.04f v3Screen.y Mathf.Clamp (v3Screen.y, 0.01f, 0.99f) 0.04f transform.position Camera.main.ViewportToWorldPoint (v3Screen) Debug.Log ("Target planet position " goToTrack.transform.position.ToString()) Debug.DrawRay(Camera.main.ViewportToWorldPoint (v3Screen), goToTrack.transform.position, Color.red, 5.0f) Debug.DrawRay(goToTrack.transform.position, Camera.main.ViewportToWorldPoint (v3Screen), Color.green, 5.0f) Debug.Log ("Tracker angle " angle) transform.Rotate(0,0, angle, Space.Self) Output UPDATE I have noticed that when i substract the second vector with the first vector of the Debug.DrawRay it draws the ray like i want it to. From this I am taking that the Debug.DrawRay function draws the second vector on top of the first vector. (kind of like the the first vector is Vector(0,0,0) and the second vector is the actual ray you want to draw)


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


How to stop jumping again when character is in air (double jump)? I'm using touch inputs in my game to control the character. I would like to know how to disable my character from jumping again in the air. if (FingerTouchy.phase TouchPhase.Ended) charcter.transform.Translate(Vector2.up speed Time.deltaTime) float jumpForce 250 charcter.GetComponent lt Rigidbody2D gt ().AddForce(new Vector2(0, jumpForce)) Update Im using Collision Detection void OnCollisionEnter (Collision col) if(col.gameObject.tag "Ground") grounded true And checking if charcter is grounded if(FingerTouchy.phase TouchPhase.Ended) float jumpForce 250 if (grounded) continue charcter.transform.Translate(Vector2.up speed Time.deltaTime) charcter.GetComponent lt Rigidbody2D gt ().AddForce(new Vector2(0,jumpForce)) grounded false using collision collision2d doesn't work too.


How do I wait to execute code? I'm trying to make a relatively simple elevator (which essentially teleports the player), but I don't want it to instantly teleport them. I want the player to enter the collider, wait 2 3 seconds, and then do it to take make it seem somewhat more natural. My code thus far using UnityEngine using System.Collections public class Teleporter MonoBehaviour public GameObject TeleportTo public Material NewSkybox void TimerInvoke() void OnTriggerEnter(Collider other) Vector3 displacement other.transform.position this.transform.position other.transform.position TeleportTo.transform.position other.transform.position displacement RenderSettings.skybox NewSkybox Also if possible I'd like to stray away from coroutines. How should I do this?


Difference between GUILayout and EditorGUILayout? Is it matter if I use GUILayout or EditorGUILayout for my custom editor? I need to use one of them in the OnInspectorGUI function. which one should I use? What are the differences between the two? Thank you in advance.


How to implement efficient Fog of War? I've asked a question how to implement Fog Of War(FOW) with shaders. Well I've got this working. I use the vertex color to identify the alpha of a single vertex. I guess the most of you know what the FOW of Age of Empires was like, anyway I'll shortly explain it You have a map. Everything is unexplored(solid black 100 transparency) at the beginning. When your NPC's other game units explore the world (by moving around mostly) they unshadow the map. That means. Everything in a specific radius (viewrange) around a NPC is visible (0 transparency). Anything that is out of viewrange but already explored is visible but shadowed (50 transparency). So yeah, AoE had relatively huge maps. Requirements was something around 100mhz etc. So it should be relatively easy to implement something to solve this problem actually. Okay. I'm currently adding planes above my world and set the color per vertex. Why do I use many planes ? Unity has a vertex limit of 65.000 per mesh. According to the size of my tiles and the size of my map I need more than one plane. So I actually need a lot of planes. This is obviously pita for my FPS. Well so my question is, what are simple (in sense of performance) techniques to implement a FOW shader? Okay some simplified code what I'm doin so far Setup for (int x 0 x lt (Map.Dimension planeSize) x ) for (int z 0 z lt (Map.Dimension planeSize) z ) CreateMeshAt(x planeSize, 3, z planeSize) Explore (is called from NPCs when walking for example) for (int x ((int) from.x radius) x lt from.x radius x ) for (int z ((int) from.z radius) z lt from.z radius z ) if (from.Distance(x, 1, z) gt radius) continue transparency x tileSize, z tileSize 0.5f Update foreach(GameObject plane in planes) foreach(Vector3 vertex in vertices) Vector3 worldPos GetWorldPos(vertex) vertex.Color new Color(0,0,0, transparency worldPos.x tileSize, worldPos.z tileSize ) My shader just sets the transparency of the vertex now, which comes from the vertex color channel


Can't Transform.SetParent in Unity i have a problem that i don't understand why is happenning and it's driving me mad. I'm trying to code a script to put the player in the car by disabling the third person controller and then Transform.SetParent. Here's the code public ThirdPersonCharacterControl Controller public GameObject Player public GameObject Car public void PutWheel() if(isInteractive) if(isCar) PlacePlaceables() Controller.enabled false Player.transform.SetParent(Car) The error is Assets Scripts Player Interactible.cs(361,34) error CS1502 The best overloaded method match for UnityEngine.Transform.SetParent(UnityEngine.Transform)' has some invalid arguments Assets Scripts Player Interactible.cs(361,44) error CS1503 Argument 1' cannot convert UnityEngine.GameObject' expression to type UnityEngine.Transform' Why is that happening? It doesn't make sense to me because everything seems correct.


Cursor is locked and hidden, and can't click UI I have a player with a third person character controller component. I have a problem with the cursor lock it hides the cursor so I cannot click UI buttons. protected virtual void CharacterInit() cc GetComponent lt vThirdPersonController gt () if (cc ! null) cc.Init() tpCamera FindObjectOfType lt vThirdPersonCamera gt () if (tpCamera) tpCamera.SetMainTarget(this.transform) Cursor.visible false Cursor.lockState CursorLockMode.Locked


Unity NodeJS Projectile synchronization I am working on a MOBA game similar to League of Legends. I am building the game server system in NodeJS Socket.IO but I'm running into issues on figuring out the best way to handle projectiles (aka player skill shot abilities) on the server side. The Main goal is to be able to spawn a projectile (or projectiles) on the server side and update the position in a certain direction (all on the server side separate from Unity) until I specify the projectile to be destroyed. This way, each time the projectile moves I can check with every single players current position and see if the projectile hit (thus allowing me to damage the player on the server side). How could I achieve this effect, or something similar?


Process Purchase Event get called on each App launch iOS At present when I launch the app, each time ProcessPurchase event get called in iPhone device. Though upto now I have not pressed any purchase related buttons. Yes I have setup subscription purchase within my app and before I have purchased subscription in sandbox environment two to three times but now their time period is expired. Here you have debug log for actual event happening As per my past experience, ProcessPurchase event require to call only two times when a user purchase something or at restore purchase time. So why its get called each application launch that I can't able to understand!!! Please give some help in this so I can complete my Unity IAP related thing. Source Code https pastebin.com bNpXsjHg


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


Why does my terrain turn white when I get close to it? When I zoom in on my terrain it goes white The further in I zoom, the greater the whiteness becomes. Is this normal? Is this to speed up rendering or something? Can I turn it off? I'm also getting these error messages in the console over and over again rc.right ! m GfxWindow GetWidth() rc.bottom ! m GfxWindow GetHeight() and GUI Window tries to begin rendering while something else has not finished rendering! Either you have a recursive OnGUI rendering, or previous OnGUI did not clean up properly. Does this bear any correlation on the issue? Update I create virtual desktops to flit between using the program Deskpot. Turning this program off and restarting has stopped the above errors appearing in the console. However, I still get white terrain when I zoom in. Not a single error message. I've restarted my computer to no avail. I have an Asus NVidia GeForce GTX 760 2GB DDR5 Direct CU II OC Edition Graphics Card. Any known issues? Update I don't think it's fog...


What is the difference of target frameworks for unity3d? In Visual Studio in properties I can change target framefork. I cannot find anywhere what means all of these magic titles. What does it all mean (full, micro base, subset, web base)? And...Can I use functionality of .NET 4.6.1 ?


How to synchronize a parent and child position? When watching this video of Unity development, I was following along trying to learn Unity and for the most part understood everything conceptually. Where I got lost was when I tried using some of the same code and setup in Unity. I got the code working fine, but I got in trouble when I tried to implement the parent child behavior seen in the video at around 7 minutes regarding the Enemy objects. The solution described is set up as follows (someone correct me if I didn't understand it properly from the video). Parent Object Contains the script which drives behavior and movement Is located at the origin of the scene (reset the transform in other words) Child Object Contains the graphics renderer which draws the actual sprite or 3D object Is located at the enemy spawn point For me to get this setup working, I had to run the Translate function explicitly against the child object transform.GetChild(0).Translate(dir.normalized distThisTurn) However, in the video, it appears to work just fine with only transform.Translate(dir.normalized distThisTurn) Once he fixes the rotation issue, at about 7 minutes in, this works beautifully, and the enemy travels the path exactly as expected. When I tried this exact same approach, my enemy sprite jumps all over the place. It took me several hours to figure out that I needed to add the .GetChild(0) part. The behavior I saw with the setup from the video is that the invisible parent object moved correctly along the path, and the child went crazy and followed some alternate version of the same path, as if the origin was different or offset, or the path was reflected across some axis. My question is what did I do wrong? Can anyone spot how my setup is different than the one used in the video? Did I miss some detail of how he set up his parent child objects, particularly for the enemies? Or could this be some different behavior due to the version of Unity he is using (I believe mine is newer as I installed it just this week). I think it could also be some small gizmo or feature he neglects to mention that allows you to synchronize the movement of a parent object with its children. The reason for this setup (at least as given in the video) is it allows you to easily swap out the graphics. The scripting is tied to the parent, so all you have to do is exchange the child for one with different graphics and you're done. That part makes sense, I just don't understand why the exact same code he uses did not work for me. I'm talking only about the Enemy object here the creeps that move along the path (it's a tower defense game). I just want to know because I may have to use this extra GetChild call quite a bit, and I feel like it shouldn't be necessary, especially after seeing it work so well in the video. Doing this would also make my scene design a little easier. I have already read the comments on that video for additional info, as well as looked through Unity forum posts, other posts here on Game Dev.SE, and Google results. It would seem as if this is either old behavior, or there is some small detail neglected to explain in the video of how to synchronize movement of parent and child objects.


How do you Draw a path and have a GameObject follow it? How would you go about creating a path that a gameobject would follow? I'm looking to create similar functionality that you see in some RTS games. most notability the Total War series does this well. here are a few screen shots for reference. https imgur.com a Zhi6pQu Goal. Click a Unit Hold the mouse button down and drag to draw a line Release the mouse button. unit follows path drawn


Can't Get .enabled to Work for Children Sprites. What Gives? So I have an object with a few children. I want to be able to disable enable 2 of their SpriteRenderers via one of my scripts. I feel like I'm doing things right, but apparently I'm not. And yes, my game objects have the appropriate tags that are being searched for in my code. I'll paste the relevant bits of code below public bool isAiming false Animator playerAnim GameObject arm GameObject weapon SpriteRenderer armRenderer SpriteRenderer weaponRenderer void Start() playerAnim gameObject.GetComponent lt Animator gt () arm GameObject.FindGameObjectWithTag("Arm") weapon GameObject.FindGameObjectWithTag("EquippedWeapon") armRenderer arm.GetComponent lt SpriteRenderer gt () weaponRenderer weapon.GetComponent lt SpriteRenderer gt () void Update() CheckIfAiming() void CheckIfAiming() if (Input.GetButton("Fire2")) Holding right click isAiming true armRenderer.enabled true weaponRenderer.enabled true playerAnim.SetBool("isAiming", isAiming) else isAiming false armRenderer.enabled false weaponRenderer.enabled false playerAnim.SetBool("isAiming", isAiming) What gives? I want to just enable the sprite rendering when I hold down the right mouse click. SetActive(false true) is not an option as I still want code to affect them while they're not visible. Am I just trying to access the SpriteRenderers incorrectly?


How to change the geometry of the scene in Unity? I'm trying to experiment with 3D spherical geometry in Unity, but it seems like Unity objects are inherently set in flat space. My first idea was to create a class inheriting from Transform that would override most of the methods, but I discovered that the transform member of a game object is read only so I cannot replace it with my custom class. I know this sort of thing is possible because the game Hyperbolica is being built in Unity using curved space. I have the math all figured out, I'm just not experienced with Unity. Anyone have other ideas for things I could try?


Recursively find neighbors I'm making a Bubble Shooter game in Unity. I came to the point where I can hit another bubble and it destroys all of its neighbors. Now I'm trying to use recursion to destroy all of its neighbors neighbors and it causes a stack overflow. private List lt Bubble gt FindAllRecursiveNeighbors(Vector2Int originPosition) List lt Bubble gt allNeighbors FindNeighbors(originPosition) List lt Bubble gt result new List lt Bubble gt () foreach (Bubble bubble in allNeighbors) if (result.Contains(bubble)) continue result.Add(bubble) Recursion starts here. foreach (Bubble bubble in result) List lt Bubble gt neighbors FindAllRecursiveNeighbors(FindPositionOfBubble(bubble)) foreach (Bubble neighbor in neighbors) if (result.Contains(neighbor)) continue result.Add(neighbor) return result


Can an iOS application have an explicit quit button? I've heard a rumor that you cannot have an explicit quit button on your app when it goes to the Apple App Store, can anyone verify this? It seems that most applications do not have one, and there is no explicit quit. How to developers handle quitting in general on iOS applications? Note I am using Unity, C , and Xcode to develop my game for the iPad.


Are lightmaps also considered textures? I want my game to support phones with max texture size of 1024 so my texture atlases are 1024. My question is are lightmaps also considered textures and their max size must be 1024? Or they can have higher dimensions like 4096?