How do you make a object that always follow another object? I'm trying to make a game object follow another game object and switch to another when a button is pressed. But right now it just seems to change the position when the button is pressed but it doesn't follow the object. How can I make it follow the other object? public Transform PosObjOne public Transform PosObjTwo public Transform PosObjThree void Update () if (Input.GetButtonDown("UseVr")) PosObjThree.position PosObjTwo.position if (Input.GetButtonDown("NoVr")) PosObjThree.position (PosObjOne.position)


Using Smaller Textures in Unity on Older Smaller devices In Unity, when you have MipMapping selected, will this cause the full size texture to always be brought into memory? I have a game which runs on high end mobile devices with ultra high resolution textures, but I have complaints of it crashing on smaller old devices. Will this fix it, or is there a more fitting way to address this problem?


How can I extend the FindObjectsByTag to filter multiple parents of the found objects? private List lt GameObject gt FindDoors(string parents) GameObject doorsLeft GameObject.FindGameObjectsWithTag(c doorLeft) GameObject doorsRight GameObject.FindGameObjectsWithTag(c doorRight) List lt GameObject gt allDoors doorsLeft.Union(doorsRight).ToList() List lt GameObject gt toRemove new List lt GameObject gt () for (int i 0 i lt allDoors.Count i ) for (int x 0 x lt parents.Length x ) if (allDoors i .transform.parent.name ! parents x ) toRemove.Add(allDoors i ) foreach (var it in toRemove) allDoors.Remove(it) foreach (GameObject door in allDoors) Debug.Log("Door Parent " door.transform.parent) return allDoors Usage var allDoors FindDoors(new string "Wall Door Long 01", "Wall Door Long 02" ) But in the function FindDoors the return allDoors is empty. I think the problem is at this IF if (allDoors i .transform.parent.name ! parents x ) Once it's Wall Door Long 01 so if it's Wall Door Long 01 it will not remove the item but next it's Wall Door Long 02 so now the it's true and will remove the even if the parent name is Wall Door Long 01 and same if it's Wall Door Long 02 And then in the end it will remove all the items. But I want it to remove only doors that the parents of them is not Wall Door Long 01 and not Wall Door Long 02


Refactoring fighting game Movement class responsibilities I'm a web developer, new to C and trying to learn Unity. I've learned the C syntax, I understand how to write working code, although I'm having a hard time understanding when and to what classes should I split my code. At the moment I'm doing a simple 2D fighting game, similar to Mortal Kombat, I've started out with creating some basic sprites and basic scripts for the environment, like clouds spawning and moving (the action takes places on a rooftop), created a fighter character with animations and started with writing the movement script. At this point, the Movement script deals with moving, jumping, animations (also triggers for punches and kicks) and player input (I'm using the new Input System), also I want to make the game a two player game, so the Movement script also checks if the the fighter is controlled by player 1 or player 2 and everything is crammed in this little Movement script, not that it's too large, it's just funny that a Movement script is doing so much and furthermore I'll need to add health and attacks (not just animations). I think it's about time I refactor, my questions are Should I create a Character, CharacterController, CharacterManager or whatever script that inherits from MonoBehaviour and other scripts as simple C scripts, or should all of my scripts inherit from MonoBehaviour and be attached as components to my GameObject with references to each other? Should I have a separate script for my animations or should they be at their respective scripts as in Attack, Movement, maybe Jumping or Death, whatsoever? What would be the best way or what would be the ways of managing my Fighter GameObject to determine if it is controlled by player 1 or player 2 and if I'll plan to add an AI for example? Should I have a PlayerController AIController inherit from Character script, or have a separate AI class, or just have some variable to check against? My problem with various tutorials is that most of them don't give a larger overview of the whole picture, most of them just focus on a single subject movement, animations, spawning, pathfinding or some other concrete thing or term, etc. and don't show how they are intertwined together.


What are the advantages and disadvantages of exporting spritesheets instead of models from Spriter into Unity? I'm working on a simple 2D platformer in Unity and have been using the Spriter2Unity tool to import my Spriter animations directly into Unity. I have noticed that this creates large hierarchies of gameobjects within the imported prefabs, basically 1 per image piece. Since the animations are fairly simple, I am thinking it would be cleaner to import each of them as a spritesheet and hook them up with a spriterenderer on the player object rather than using the importer tool. Would this actually result in any performance benefit at runtime or are the impacts of animating a lot of game objects at once negligible?


How to make a cartoon like trail particle system? I'm currently working on an little Android game, it's a reaction casual game. Because the user needs to tap some balls flying around at the right moment, I want to add some new effects to them. So I looked at some other games and found this cool looking cartoon like effect. As you can see the ball there has an cool tail. So my question is, does anyone know how to recreate such a trail with the Unity particle effects or some other tools?


How can I add an IsTrigger propriety from code? Unity I made an gameobject in my script and i made it a rigidbody, and added it a boxcollider, but I dont know how to tell the program to make it a trigger. Here's my code until now multi new GameObject() multi.AddComponent lt Transform gt () multi.transform.position new Vector2(1f, 1f) multi.AddComponent lt Rigidbody2D gt () multi.AddComponent lt BoxCollider2D gt ()


How to make player move only along the line I am using Line Renderer to draw a line on 2D scene using a path of multiple Transforms. And I want player to move along the line without the ability to get off it, like if he was on a rail. The simplest method I can see is setting a number of invisible walls along the line, so the player couldn't physically move away from the line. But maybe there's better method?


3rd person game with rigid body Im making a 3rd person 3D game. I have a little capsule shaped player controlled drone at the moment that moves on a flat surface. Y axis is locked. The Game object contains a script and then the child objects which are the actual body parts. If i attach a rigidbidy to the root object i get crazy results. The drone collides with something and starts to spin and then forward becomes some upward direction. Somehow i would like to be able to use the pysics collision and ragdoll effects but still be able to maintain the keyboard movement. I guess that id have to animate the drone getting back up again when fallen. Movement code void CheckForKeys () if (Input.GetKey(KeyCode.W)) transform.Translate(Vector3.forward Time.deltaTime walkingSpeed) if (Input.GetKey(KeyCode.S)) transform.Translate(Vector3.back Time.deltaTime walkingSpeed) if (Input.GetKey(KeyCode.A)) transform.Rotate(Vector3.up Time.deltaTime rotatingSpeed) if (Input.GetKey(KeyCode.D)) transform.Rotate(Vector3.down Time.deltaTime rotatingSpeed)


Unity using "as" vs "GetComponent()" Hello im new to unity and im learning raycast right now , after checking the documentation here https docs.unity3d.com ScriptReference RaycastHit triangleIndex.html , i got something that's confusing me , what is the difference between MeshCollider themeshhit thehit.collider as MeshCollider if (themeshhit null) Debug.Log (" themeshhit null ! ") and MeshCollider themeshhittwo thehit.collider.gameObject.GetComponent lt MeshCollider gt () if (themeshhittwo null) Debug.Log (" themeshhittwo null ! ") Both method is working correctly , but i want to know what is the difference between them , and i also want to know which one is better if comparing against speed , compatibility , and ability . Edit variable thehit is look similar to this RaycastHit thehit


Keeping score server side to prevent cheating For my Unity WebGL game, I'm looking into storing the score of users in a database to make a highscore table (it's not a multiplayer game). Because client side code can always be "hacked", the advice most people give is "keep the score server side so you can validate it". But I don't quite understand how that would work. I could of course publish the score to the server using an Ajax call, and even hash it, but even then the cheater could just simply look at the hash method and use the same Ajax to upload a different score. I'm assuming I should get a game server or something then? But again no idea on how to start... I'm really just scratching the surface here. So I'm basically looking for any sort of information on how to change my "regular", client side, WebGL Unity game to a game where I keep the score securely at server side so that the highscore table is valid. I don't mind spending some money on both a server assets that simplify the task. As I said, I'm just interested in implementing this feature, I don't need to become a game server wizard. Note even with server side scores, there's probably a way to cheat. There most likely always is, but at least it would be more secure than just inserting the final score into the database...


What happens to my already published game when I upgrade to Unity Pro? I made a game with Unity's Standard liscense, and published it (version 1.0) on Google Play. If I buy a Unity Pro license can I publish an update to my game (version 2.0) with it on Google Play, or must I create a new game on Google Play for the updated version?


How to change the virtual joystick Input direction depending on camera rotation so the player moves to its current forward direction? I have a scene set up where the player moves and rotates with Virtual Joystick Input. I have button which rotates the camera to the back of my player at that point I want to change the joystick input direction so it moves my player to towards its current forward direction. The joystick Scripts 1) script to handle events public class joystickEvents extends EventSystems.EventTrigger var position Vector2 Vector2.zero public var joyStickHolder Transform private var pointerUp boolean false function Update() if(position! Vector3.zero amp amp pointerUp) position Vector3.Lerp(position,Vector3.zero,5 Time.deltaTime) public function OnDrag(data EventSystems.PointerEventData) position data.position joyStickHolder.position public function OnPointerUp(data EventSystems.PointerEventData) pointerUp true public function OnPointerDown(data EventSystems.PointerEventData) pointerUp false 2) script for joystick movement public class joystick extends MonoBehaviour var joystickEvents joystickEvents var joystickHolder RectTransform var dir Vector3 private var maxDist float private var direction Vector3 private var magnitude float function Start() maxDist joystickHolder.sizeDelta.x maxDist maxDist 2.5 function OnGUI () if(joystickEvents.position.magnitude gt (maxDist)) magnitude maxDist else magnitude joystickEvents.position.magnitude direction joystickEvents.position.normalized transform.localPosition direction magnitude dir direction (magnitude maxDist) The player controller script takes the variable dir to move around the world. I think this value must changed somehow to so that move the player moves towards its current forward based on joystick input when camera is rotated. Here some part of playerController responsible for player movement public class charcterController extends MonoBehaviour private var controller CharacterController private var moveDirection Vector3 Vector3.zero var speed float 6.0 var joystick joystick reference to the joystick script function Start() controller GetComponent. lt CharacterController gt () function Update() var joyInput Vector3 joystick.dir the dir in joystick script dir Vector3(joyInput.x,0,joyInput.y) if (controller.isGrounded) moveDirection dir moveDirection speed controller.Move(moveDirection Time.deltaTime) rotate() function rotate() if(dir! Vector3.zero) transform.rotation Quaternion.LookRotation(dir)


Unity Oculus Rift Setting field of view or rendering part of display I need to render a small portion of the display to a texture. I found a script to simulate a scissor rect by modifying the projection matrix Unity 5 doesn't seem to provide any out of the box scissor functionality. However, modifying the matrix in this way causes my scene to render monoscopic. Suggestions? There used to be an OVRCameraController class that provided a SetVerticalFOV() method, but that appears to have been removed from the SDK.


Singleton pattern Class attached to multiple GameObjects still only 1 instance? I'm currently working on an Inventory Equipment System and so far have been using a Singleton Pattern to instantiate my Inventory and Equipment classes. I was wondering if i attach this Script to multiple gameObjects, whether they each have a seperate instance or whether they share it? This would be important for the Equipment classes as each GameObject should obviously have different Items equipped. My current Singleton pattern looks like this public static Inventory Instance get return instance void Awake() if(instance ! null amp amp instance ! this) Destroy(this.gameObject) Debug.LogWarning("More than one instance of Inventory found!") return instance this


Handling accelerate in different devices I am adding tilt controls to my game. The sensor values I get are different in different android devices which results in random behavior. Anyone knows how can I tackle this situation? I tried normalizing acceleration but it is still the same.


Move player in a circular manner i'm creating a pong game for learning purpose and decided to have the Paddle moving freely but with a slight change in its control. When pressing LEFT OR RIGHT it should move in polar coordinates facing the ball. And UP OR DOWN moves the paddle towards or backwards the ball. I've spent the whole day trying out a few solutions but didn't make it. var ball Vector3.zero target var d ball translation.Value.ToVector3() var radius d.magnitude var dir d.normalized data.speed deltaTime var angle Vector3.Angle(ball, translation.Value) var nextPos translation.Value if (data.input.x gt 0) nextPos.x dir.x 15 math.sin(angle) data.speed deltaTime nextPos.z dir.z 15 math.cos(angle) data.speed deltaTime if (data.input.x lt 0) nextPos.x dir.x 15 math.sin(angle) data.speed deltaTime nextPos.z dir.z 15 math.cos(angle) data.speed deltaTime translation.Value nextPos


Unity Ajax and json data sending once again i need your help! with help from here i managed to make a function that sends a formated json text to a subscription service.the format is this quot profiles quot quot email quot quot example example.com quot that works fine and great from my pc but once i upload the game it gets blocked by cors. Now i have cors enabled so i contacted klaviyo which handles the data and they told me their api does not accept data from the front end and i could use ajax to make it happer, an example of which is this var settings quot async quot true, quot crossDomain quot true, quot url quot quot https manage.kmail lists.com ajax subscriptions subscribe quot , quot method quot quot POST quot , quot headers quot quot content type quot quot application x www form urlencoded quot , quot cache control quot quot no cache quot , quot data quot quot g quot quot LIST ID quot , quot email quot quot email address.com quot , pass in additional fields (optional) quot fields quot quot source, first name, last name quot , quot source quot quot Account Creation quot , quot first name quot firstname, quot last name quot lastname .ajax(settings).done(function(response) console.log(response) ) now my code which is working from my pc is this public class testing MonoBehaviour public InputField field private string URL quot https a.klaviyo.com api v2 list YeXzKp members?api key pk ec448e1bdab7504c143466ca5eeabc5e95 amp profiles quot public void SaveData() string data JsonUtility.ToJson( new EmailApiData() profiles new EmailApiProfileData new EmailApiProfileData() email field.text ) StartCoroutine(SaveIntoJson(URL , data)) IEnumerator SaveIntoJson(string url, string data) var request new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST) request.SetRequestHeader( quot Content Type quot , quot application json quot ) request.SetRequestHeader( quot Access Control Allow Origin quot , quot quot ) request.SetRequestHeader( quot Access Control Allow Credentials quot , quot true quot ) var jsonBytes Encoding.UTF8.GetBytes(data) request.uploadHandler new UploadHandlerRaw(jsonBytes) request.downloadHandler new DownloadHandlerBuffer() yield return request.SendWebRequest() if (request.isNetworkError request.isHttpError) Debug.Log(request.error) Debug.Log(request.downloadHandler.text) else Debug.Log( quot Form upload complete! quot ) Debug.Log(data) Serializable public class EmailApiProfileData public string email Serializable public class EmailApiData public EmailApiProfileData profiles how can i put those two together?? i know im way out of my waters here but i want to learn it!Thank you once more!


Object Composition in the Unity Editor I'm trying to learn how to use Unity for my class composition, and I was wondering if you could help me. I'm trying to create a simple game where the player is trying to pop a bunch of balloons. However, any given balloon can only be popped if all of its conditions are met. Example conditions are The player color must match the balloon color The balloon must be popped in sequence (balloon A must be popped before balloon C) The balloon is only pop able during a certain time window And I'm sure you could think of more. Balloons can have 0 to many conditions associated with them, but they follow the 80 20 principle where 80 will fall into a specific category (e.g. color match only, or color and sequence only). My Initial Solution I created a "Balloon" class that contains a list of "ICondition" interfaces. When a collision occurs, the balloon loops through each condition to determine whether the balloon is pop able or not. I populate this list within a "BalloonFactory" class. For 80 scenarios I can just pass in the name of the balloon type I want. For 20 scenarios I can pass a list of conditions. This solution works, except for each new combination I need to change the factory code to include the new condition. What I'd Like to Do Instead of storing the balloon definitions in code, I'd prefer to create prefabs in Unity and use the editor to assign condition implementations to each balloon. My problem so far is that the Unity editor doesn't seem to like displaying a list of interfaces or abstract classes. Is there some way to do what I'm trying to do here? Or is there a third option which you would recommend?


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


Instantiate works fine in Editor and does not work after building game Here is the situation, In my project everything works fine. After I build the game for windows, the prefab does not instantiate. I don't know which part I missed. This is how I load the prefab from Resources folder private void Awake() areaButtonPrefab Resources.Load lt GameObject gt ( quot Prefabs AreaButton1 quot ) And this is how I instantiate prefab for each data in a List public void SetAreaToUI() foreach (var j in areaList) cloneItem Instantiate(areaButtonPrefab, originalRect.position, new Quaternion(0, 0, 0, 0), rect) TMP Text text cloneItem.GetComponentInChildren lt TMP Text gt () AreaButtonData buttData cloneItem.GetComponent lt AreaButtonData gt () buttData.area j text.text j.areaName cloneItem.SetActive(true) cloneItems.Add(cloneItem)


Unity3d Box collider attached to animated FBX models through scripts at run time have wrong dimension I have several scripts attached to static and non static models of my scene. All models are instantiated at run time (and must be instantiated at run time because I'm procedural building the scene). I'd like to add a BoxCollider or SphereCollider to my FBX models at runtime. With non animated models it works simply requiring BoxCollider component from the script attached to my GameObject. BoxCollider is created of the right dimension. Something like RequireComponent(typeof(BoxCollider)) public class AScript MonoBehavior If I do the same thing with animated models, BoxCollider are created of the wrong dimension. For example if attach the script above to penelopeFBX model of the standard asset, BoxCollider is created smaller than the mesh itself. How can I solve this?


How to run code selectively only when a specific trigger collider has been hit I have 2 objects both with trigger colliders. The first object has only 1 trigger collider (imagine this to be a sword). The second object (a person) has multiple colliders. One is a non trigger collider (used for collision detection for walls, ground) and then multiple trigger colliders on different parts of the body (the purpose is for hurt box). Now when the sword hits the person, I want to only process code for those trigger colliders and to be able to detect which of those trigger colliders got hit (arm, leg, etc.). But the event only exposes a parameter hit for the other collider void OnTriggerEnter(Collider other) if (other.gameObject.layer LayerMask.NameToLayer(Constants.LAYER HITBOX PLAYER)) Run code here I want to run code only when certain trigger collider are hit, like for example, when the head is hit, or the body, etc. How do I get this info to be able to run conditional code on this method?


2D Rivers Lakes in infinite terrain I've been looking into generating lakes and rivers for a 2D infinite tilemap but I'm stuck with how to handle them for an infinite map. I can use noise heightmaps for determining the lakes and the starting points for rivers but for an infinite map I can't use the "flow downhill" or "carve out" technique because the player could come across the river at any point. If I have a river that's a max of 200 tiles long, I'd have to calculate noise map values for 33x33 chunks (my chunks are 6x6 tiles) around the player which feels excessive and very inefficient. I have not found a way to make noise alone work for this, rivers would always be too circular if I find a range narrow enough and they'd encircle lakes, not extend outward. Calculating voronoi cells and putting rivers at certain edges, with some extra noise to make the paths more natural, might work. I just can't seem to find any good examples where they aren't working with known dimension maps.


Need to boost the number of simultaneous players in single (existing) game with Unity3d I have created a turn based multiplayer game (with Unity3d) in which three teams battle to finish constructing a cake before one another. The game mostly targets on entertaining kids at certain venues. It is free and is only running from time to time (it isn't online and does not run 24 7 like what we normally see). The game consists of a few round that have two phases. Phase one asks for the joystick apps to enter their strategies (units to invest in construction and or defense and or attack) and send them to the server. This phase lasts for 30 seconds after which the second phase kicks in. Phase two is the MainGame talking to the server, getting all compiled strategies and rendering them on to the screen. The rounds follow one another until one of the teams finishes its cake. Kids love it! The setup is rather easy. Players use a joystick App that they install on their iOS device enabling them to send strategies to the server. The MainGame is responsible of rendering the compiled strategies on to the screen. In between the Joystick Apps and the MainGame App is the server that glues everything up and manages the states of the game. The server currently runs on a free PlayerIO account that supports 45 players to be connected at the same time (actually 44 since one of the instance is the MainGame who does the rendering). When the game reaches its full capacity, all 44 joystick apps and my 1 MainGame app are connected to one single room. Everything works fine! I now have this new client who wants me to boost the game so it can handle something between 1000 and 3000 players simultaneously. With you knowing this, here are my questions Should I stay with PlayerIO for my new and boosted version? Is it just a matter of getting a bigger server? Can I still have one single room with 3000 players joining it? If not, how should I handle the weight? How many players can normally connect to a single room (keeping in mind I am looking for a way to connect as many people in a single game at once Not many games at once)? What s the rules of thumb? Being that the game will only be running a third of the time every month (when my client s starts it), how much can I expect to pay in backend fees? (I really have a hard time knowing how much PlayerIO is going to charge me with its new pricing). Thanks in advance for your help!


why does my objects only spawn once or really slowly? public GameObject fallingRockPrefab public Vector2 spawnsMinMax float randX float randY void Update() if (Time.time gt nextSpawnTime) float SpawningInBetween Mathf.Lerp(spawnsMinMax.y, spawnsMinMax.x, Difficulty.GetDifficultyPercent()) print(SpawningInBetween) nextSpawnTime Time.time SpawningInBetween randX Random.Range( 5.6f, 5.6f) randY 5.57f SpawnPosition new Vector2(randX, randY) Instantiate(fallingRockPrefab, SpawnPosition, Quaternion.identity) I set the quot spawnsMinMax quot over at the inspector in Unity as high as I can like (25 or 30 etc) but it still spawns once or like 1 or 2 per second. Even I set the number as low it can go, it still spawn in the same way. How do I fix this?


Unity ads displaying only unity products i just implemented unity ads on my project and now its only showing a single unity product each times. Can anyone suggest why? Thanks.. Here is some screenshot of the ad 1 (https i.stack.imgur.com oG9vm.jpg) 2 (https i.stack.imgur.com ZrS7x.jpg) Can anyone tell me if this is even a real ad or just for testing?


Unity Is it possible to copy a rig from one model to another Lets say I have a model with a ready humanoid rig and a humanoid model with no rig. Can I somehow copy the bones from the rig to the model with no rig in unity?


How could I remove part of a Terrain Collider? After reading through this site, I began to think on how could I remove the colliders of vertexes with a transparent texture on it? I had read a suggestion (forgot where it was) to disable the whole terrain collider, but I also have NPC's, so having them plumet through the map wouldn't go over well.


How to set rotations to 0,0,0 in 3ds max for exporting in unity? I'm a modeler in 3ds max and the unity programmer ask me that the object must have pivot with Y up rotations at 0,0,0 but every object that I export in fbx he says don't have rotations at 0,0,0. I tryed different solutions as reset xform freeze rotation rotation to zero .rotation eulerangles 0 0 0 but in unity he have values like this 4.577637e 05, 1.525879e 05, 0 or 90, 1.525879e 05, 0 and so on It's a problem that can I fix in max or the programmer has to fix it in unity? Thanks


Problem connecting to Steamworks via Facepunch.Steamworks I'm using Facepunch.Steamworks (https github.com Facepunch Facepunch.Steamworks) to connect my Unity game to Steam. The login seems to work fine. The board object is an FP class, and AddScore is a call to the library to send the score to Steam. I have the boards set up on Steam, and they come out with IsValid true. Here are the output and the code. The boards currently have no data in them, so I don't think it's because the score isn't beating an existing one. xxxxxxxx Standard Normal True Fail public void SubmitScore(Globals.ApplicationMode mode, Globals.SkillLevels skillLevel, int score) int index GetLeaderboardIndex(mode, skillLevel) if(index 1 !IsSteamPlatform()) return Leaderboard board m leaderboards index Debug.Log("xxxxxxxx") Debug.Log(board.Name) Debug.Log(board.IsValid) board.AddScore(true, score, null, AddScoreSuccessCallback, AddScoreFailureCallback) private void AddScoreSuccessCallback(Leaderboard.AddScoreResult result) Debug.Log(result.Score) private void AddScoreFailureCallback(Facepunch.Steamworks.Callbacks.Result result) Debug.Log(result.ToString()) Here's a shot of the leaderboards on the Steam control panel. They seem in order their "Writes" attributes are false so that the client can submit to them directly.


How to make a proper release build Unity Android x86, ARM32, ARM64 I'm trying to create a release on Google Play. I currently have Build App Bundle checked in the build settings, and it helps decrease the build size. In player settings I've IL2CPP set as the scripting backend, and x86 ARM32 ARM64 checked as target architectures. Once built it creates symbols.zip in addition to just aab. My questions are, Do I need x86 ARM32 ARM64 all checked? (I want to comply with Google's new 64 bit requirement) Can I build split aab's similar to 'split APKs by target architecture'? If so can I have the same version code for aab's which targets different architectures? Is there any advantage of doing so?


Unity Fading mesh particles Is there any ways to fade mesh particles like color over lifetime method with addictive shader. I have little to no understandings of shader coding, and fade rendering issue kicks in even with vertex color shader. Any idea guys?


How to correctly implement custom tick system? I am making a custom tick system to suit my needs (calling normal ticks every 0.2 seconds, medium ticks every 5 seconds etc...) I followed the tutorial in this video CodeMonkey tick system tutorial In his tutorial, he implements the tick counting as shown private const float tickTimerMax 0.2f private void Update() tickTimer Time.deltaTime if (tickTimer gt tickTimerMax) tickTimer tickTimerMax Tick Happens every 0.2 seconds. OnTick?.Invoke(this, new OnTickEventArgs Tick Tick ) However, in other sources I have seen that instead of subtracting tickTimerMax from tickTimer, we just straight up set the tickTimer to 0, as shown if (tickTimer gt tickTimerMax) tickTimer 0 Tick It's hard to say if there's a big difference between these two methods, because at first glance they seem to do the same thing, but clearly they have their differences. So I'm wondering, which one I should use?


How could I do a 2d pixel design in game where you can see though the obstacles upper floors? Maybe the question didnt show much... but what I'm trying to do is e.g. if I'm in a train platform with two floors overlapped, or in a place where I'm blocked by some obstacle to see my char. from my view. I want to let my character be visible but have how should I say, have lines? of the obstacles overlapped a bit so i can have an impressing there is an obstacle but you're seeing your char. through, kinda like half visible, kinda like gradation. tl dr I want to see my character who is normally should be blocked the view from my POV to be visible, while also making the player to see that there's something between the character and the POV. is there a method I can check? using dots to create this via photoshop.


How do you allow joints in a character to fall freely based on gravity? I am building a game in Unity in which a character falls down on death. Is it possible to make the joints fall and bend based on gravity? That is to leave the joints fully dependent on gravity and colliders and not any skeletal animation.


Unity Outline each pixel on a texture So I have a 16x16 sprite. I would like to make each pixel on the sprite to have a border outline so you can distinguish each pixel from another, like shown in the picture below (ignore the colored boxes). How would I do so? Please note, I will be coloring those pixels, so those borders should be gone when colored


unity animation not starting I have written the following code public class TargetAnimation MonoBehaviour Animation anim public AnimationClip Open Use this for initialization void Start () anim GetComponent lt Animation gt () anim.AddClip (Open, "Open") anim.Play ("Open") I have the following script and animation settings I have put the animation type in legacy and the generation as store in root (Depricated) as suggested elsewhere, this did not work. The animation works in the import annimations view. The origenal comes from blender. And all f this is in unity 5.


How can i add a description of gameobject when click on the gameobject? I have this DetectInteractable working script attached to Player (FPSController). I'm using tag to detect interactable objects, each object i want to be interactable i change his tag in the editor to "Interactable". ( Maybe there is a better way to do it without using tag ? It's working but many told me not to use tag. ) I'm using Raycast to hit a gameobject detect if it's "Interactable" and if it does i display on the gameobject his name. For example "Security Door" or "Screen Monitor" or "Surveillance Camera" Now i want to do that if i hit a gameobject with the raycast and it's "Interactable" if i will click the mouse left button it will display a description text description about the gameobject. But this time i want to use some gui box so it will be in front of the screen in the middle and not on the gameobject. The problem is that i need to create a script for every "Interactable" gameobject and make that if i click on a button it will display a description. Then how do i make the script and how can i make that when i attach the script to each gameobject it will make in the inspector a box of text so i can enter and type there the description of the item(GameObject) ? using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class DetectInteractable MonoBehaviour public Camera cam public float distanceToSee public string objectHit public Image image public bool interactableObject false public Canvas canvas public Text interactableText private RaycastHit whatObjectHit private RotateObject rotateobj private void Start() rotateobj GetComponent lt RotateObject gt () private void Update() Debug.DrawRay(cam.transform.position, cam.transform.forward distanceToSee, Color.magenta) if (rotateobj.rotating false) if (Physics.Raycast(cam.transform.position, cam.transform.forward, out whatObjectHit, distanceToSee)) if (whatObjectHit.collider.gameObject.tag "Interactable") image.color Color.red objectHit whatObjectHit.collider.gameObject.name interactableObject true interactableText.gameObject.SetActive(true) interactableText.text whatObjectHit.collider.gameObject.name print("Hit ! " whatObjectHit.collider.gameObject.name) else image.color Color.white interactableText.gameObject.SetActive(false) print("Not Hit !") else image.color Color.white public class ViewableObject MonoBehaviour public string displayText public bool isInteractable


Getting mousemovement despite mouselock unity I have lockcursor so the cursor doesn't leave the screen, but now i have to rotate an object based on mouse movement (think garrys mod item rotation) but the mouse cursor is obviusly locked to the center, is there anyway of getting the input from the mouse? public void GetRotated() Debug.Log(Input.GetAxis("Mouse X").ToString() ", " Input.GetAxis("Mouse Y").ToString()) gameObject.transform.localRotation new Quaternion(Input.GetAxis("Mouse X") RotationSpeed Time.deltaTime, Input.GetAxis("Mouse Y") RotationSpeed Time.deltaTime, 0, 0)


Why my charchter fluctuate instead go down stairs? My player is a capsule with First person controller Charchter controller When my player go up stairs, it works well. When my player go down stairs, it fluctuate in air. What am i wrong ? Thanks


How do I access objects that are in the next scene I'm loading? using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class HouseExit MonoBehaviour public Transform player public void Houseexit() SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex 1) void OnCollisionEnter2D(Collision2D col) if (col.gameObject.CompareTag( quot Player quot )) Houseexit() GameObject.Find( quot Wizard quot ).transform.position GameObject.Find( quot SpawnPos quot ).transform.position This code belongs to the scene quot Goblin House 1 quot and I'm trying to find the wizard and the spawn position both from level 1.


How to get button component in Unity 2019.3 I have a simple class attached to a button in Unity Canvas using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UIElements public class AudioButtonPlay MonoBehaviour public Button button void Start() button gameObject.GetComponent lt Button gt () But on the line button gameObject.GetComponent lt Button gt () I get the following message GetComponent requires that the requested component 'Button' derives from MonoBehaviour or Component or is an interface How can I access the "Button" component?


Gameobject rotation around anchored pivot I'm looking for the best way to rotate the Camera(EYES) around a center of my character (Player Prototype) because if I turn around, the Camera enter inside the character. My FPS script is attached to Player Prototype, but the Camera isn't because i have to make particular rotation. So I don't know what I have to do. Have will I make the parent? If I will make it, Eyes will sum rotations to those of the parent. Or maybe I have to handle this in LateUpdate()? With RotationAround() I don't understand how to pass the second argument which is a Vector3, but I have a Quaternion.Euler. So at this point I accept all the advice or examples of what I can do to solve it.


How to do moving Rorschach using Perlin noise in c without shaders? I want to be able to make a moving Rorschach using Perlin noise like in this question but I know nothing about shaders. Is there a way to do it in just c ?


Why does Unity require an EventSystem component for input during a play test, where input works fine without it in a build? Please be aware that this was initially a question about how to get the input to work. A comment pointed me in the direction of a fix, but only left me with more questions in regards to understanding the problem I was originally having, so I have edited my question to include the initial solution and focus on the question I still have. The Problem Recently, I have moved from using GUIText and GUITexture objects to using the Canvas to display UI elements. In effort to set up a prototype, some external GUI elements were imported, and when the game is built and run from my phone, everything works as intended. However, if I simply run the game from inside Unity, input is completely ignored. I originally thought this may have been a response to grabbing touch screen input, and expecting it to work on a regular screen with mouse input, but I have since confirmed that it still does not work when using Unity Remote to test the game on my phone. It has since been pointed out that I was not using an EventSystem, along side my Event Trigger objects. After implementing an EventSystem component, and the default input module supplied by the EventSystem interface, the input works. However, this still leaves me confused. What is the point of enforcing the implementation of the EventSystem, if it only ensures functionality during play test? Why would I want this system in my end build, when I can confirm that the build version functions properly, without it? Below you will find my setup, contextual to the problem. Click for a zoomed in view, as I have included the component structure of my UICanvas and MainCamera objects, in case it is helpful. In this case, we have a button that increases the max speed, when pressed. Everything works in a build, but nothing works during a play test. Additional Information I have enabled 'show touch input' on my phone, to confirm that the phone is still registering touch input. I moved to using the Canvas object after the 'depreciated warning' for using GUIText and GUITexture turned into a 'depreciated error'. Even if there is a suitable way to still perform these actions with the GUIText and GUITexture objects, I still wish to persist with using the Canvas. I am also personally curious as to why this issue exists within the Canvas, as it seems lead to obvious cases of severe inefficiency, in a system that seems to have been put together with the sole point of being more efficient. I can create manual OnMouseDown buttons that will work during play test, however, some GUI elements are more complex and persisting with this sort of solution seems like an incredible waste of time. As previously mentioned, I do not have any input issues if I simply build and run the game from my phone. However, this takes considerably more time than a simply debug test, and even without the high efficiency cost, I do not have access inspector manipulation during my play test. I am using Unity version 5.3.5 personal. Any solution that does not include updating Unity will be well preferred. While I have no physical problems updating Unity, in some previous projects updating Unity versions has lead to massive issues that we would prefer to outright avoid, if possible. TL DR Unity will not accept input on my input canvas during debug. I literally have to build and run my project each time I want to test input, or create dodgy hacks to provide input from the Inspector. The addition of an EventSystem allows input during debug play testing, but is not needed for input post build. Why does Unity act this way, and why do I need an EventSystem entirely for play test input?


How to make a cube fall from the edge when part of it is outside in Unity Let's assume I have a 1x2x1 cube and it is balanced over an edge, since the weight of the cube is distributed perfectly, it doesn't fall, how to make it fall when part of the cube is over the edge? I have tried adding invisible objects to both ends of the cube and then adding another invisible object on the edge so when they collide I change the center of mass of the cube, this seems to work but I think it is overly complex since I have to add that invisible object around all edges of my scene.


Unity3d simple material color display correctly in windows built but yellow color turns to blue in android build? I have a simple roll a ball game as shown in unity 3d tutorials, and I have set the wall color as a shade of yellow using the standard shader and material. This runs flawlessly in windows application, however when running in android phone( Nexus 5 MM) the wall turns into a blue color. Can anyone tell me how to fix it?


Unity Camera Moving Vertical So I want to make a smooth transition with the camera from point A to point B while keeping direction and rotation. My current approach is using Vector3.Lerp using UnityEngine public class CameraMoveVertical MonoBehaviour public float cameraSpeed 0.125f public void moveCamera() Vector3 lerpPosition Vector3.Lerp(transform.position, new Vector3(transform.position.x, transform.position.y 50, transform.position.z), cameraSpeed) transform.position lerpPosition The camera does move but the movement is instant. Any way to make it a smooth transition?


Why won't character stay at the x axis rotation I set In the inspector? Here is a snippet of my Update function, which contains everything regarding my rotations for the character Higher the Z float, the LESS of a rotation when moving Vector3 v3 new Vector3 (Input.GetAxis ("Horizontal"), 0.0f, 1.5f) A Quaternion variable named "quaternion" that's equal to LookRotation class that takes the "v3" variable Quaternion quaternion Quaternion.LookRotation (v3) The actual rotation is done using the Slerp class transform.rotation Quaternion.Slerp ( transform.rotation, quaternion, Rotspeed Time.deltaTime) When Countdown timer is done, then the animator is enabled adventureAnimator.enabled true When I put "357" on the X Axis tab of Rotation, why does it go back to 0 whenever the game starts? After some debugging I know it is because of my logic contained in my "transform.rotation Quaternion.Slerp" line of code. What do I need to change? If you need more information or need me to elaborate, please let me know.


How to detect direction of rotation? I have a character with a camera behind him. The head of the character rotates with the LookAt function on the character's head rig. The LookAt is done towards targets that may be to the right or left of the entire body of the transform character. So I want to detect when the head rotates clockwise with respect to the controller body and when it rotates counterclockwise. How can I do this?


Automatically create C from manually created game objects I have created 2 gameobjects along with its properties in the Unity Inspector. I have attached a screenshot below. For prototyping, I like the Inspector very much, but for runtime I prefer doing everything by scripts. This way nothing can go wrong I don't have to carry so many files around, and I find it easier to understand everything. I would now like to change this so that these 2 components are created at runtime by script. Is there perhaps a way to automatically create the script that would create these game objects? I would appreciate it very much if I could save some time with such an automatic script creation. Thank you for any input.


Display Rich Text in a TextMeshProUGUI component I am rading a text to be displayed in a Text UI from an asset using the standard commands Resources.Load lt TextAsset gt ("nameOfMyTextAsset") The text is a .txt. The text contains richtext tags to format the text in bold or italics. The richtext tags are displayed as such. I am using TextMesh Pro and insert the text via the following cmd public TextAsset MainText MainText Resources.Load lt TextAsset gt ("nameOfMyTextAsset") this.GetComponentInChildren lt TextMeshProUGUI gt ().text MainText.text The text is displayed like this How can I read text with richtext tags from a text asset?


How do you write an unlit shader which supports Ambient Occlusion? For performance reasons, a scene might use Unlit shaders only. Is there an Unlit shader which supports Ambient Occlusion? What is the best way to achieve this look, for moving and static objects, while prioritising performance?


How to stop an animation from looping I want to make Unity play a squish animation when the player hits the ground, but only once, until the player jumps and hits the ground again, although Unity its constantly detecting that the player is on the ground and keeps playing the squish animation over and over again, only jumping stops it cause the condition to play the animation is if the player is on the ground. (loop already disabled) How I can possibly solve this? if (isGrounded true) anim.SetTrigger("EnterGround")


How to prevent collisions between instantiated prefabs I'm creating a virtual creature evolution system like here. This type of project requires to define creatures, which are made of some 3d boxes and simulate them over and over again, making little changes along the way, until the point where they are good enough at a certain task. Basically, I'm using Genetic algorithms. I'm going to be doing a lot of simulation (a few hundred creatures each generation, times X generations, where X could be in the thousands). In order to save time, I want to simulate multiple creatures at once, so I must run collision checks efficiently. Each creature exists on its own and therefore should not be bothered by other colliders except himself and the ground. I have a prefab of a creature. Each creature is made of multiple 3d boxes with colliders. The nodes in the same creature should collide with themselves but should not collide with nodes that are in other creatures (because it should learn to perform based on the environment as it is). What is the most efficient way I could do this? I thought about checking the root of the collision object but that just prevents the collision and doesn't eliminate the useless checks that are being made. I've also looked at solutions involving the "Layer Collision Matrix" but still could not find a way to make it work. Thanks in advance.


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


Rotating projectile in direction it is moving I am using a parabola curve to launch my arrows public static Vector3 Parabola(Vector3 start, Vector3 end, float height, float t) Func lt float, float gt f x gt 4 height x x 4 height x var mid Vector3.Lerp(start, end, t) return new Vector3(mid.x, f(t) Mathf.Lerp(start.y, end.y, t), mid.z) I have a projectile that is a simple capsule scaled down to be long and thin like an arrow. I've tried every way to rotate it I could find online, but there is always something off. In order to follow the curve I need the direction between the last position and the new position, so I have been trying things like void ParabolaMovement() Called in Update() parabolaAnim Time.deltaTime parabolaAnim parabolaAnim 5 Vector3 newPos MathParabola.Parabola(start, target, 5f, parabolaAnim 5) Vector3 dir newPos transform.position transform.LookAt(dir) transform.position newPos As for what is going wrong, it does not point AT the target, which I udnerstand it can't because nowhere do I specify target pos, which I should, but don't know where. I cannot simply tell it to lookat target, since I want it to lookat the direction it is currently going in the curve, but it also needs to face the target.


Getting ParticleSystemRenderer in inspector I have a component that manipulates the sorting order of a given renderer, for the sake of managing UI layering. It looks something like this public class ManipulateSortingOrder MonoBehaviour public Renderer Renderer public void DoManipulation () Renderer.sortingOrder some value Now I want to plug a ParticleSystemRenderer into the Renderer field via drag and drop. I know I can get it via script using GetComponent, but whenever possible I like to supply dependencies using the inspector for the sake of testability, looser coupling, and generally writing as little code as possible. That said, I can't seem to find the actual ParticleSystemRenderer component in any GameObject with a ParticleSystem. Dragging the quot renderer module quot (which I assume is some editor trickery disguising the actual underlying component?) doesn't seem to work. I've also tried looking at the ParticleSystem GameObject in debug mode in the inspector, but haven't seen a ParticleSystemRenderer component attached. Is there a way to grab the ParticleSystemRenderer using the inspector, or is GetComponent the only way to go?


Unable to instantiate objects Straight in unity I am creating a match card game in unity and I want to place cards in straight direction that is one below another and so on... But with my formula It's showing cards one after another.Please tell me whats wrong with my code. Following is my code void SpawnCards() int cardsinrow 4 int cardsincolumn cardslist.Count cardsinrow if(cardslist.Count cardsinrow gt 0) cardsincolumn 1 float spacebetweencards .2f for(int i 0 i lt cardslist.Count i ) GameObject mc Instantiate(memorycard, new Vector3((i cardsinrow (i cardsinrow spacebetweencards)) (cardsinrow 2f) spacebetweencards, 0, (i cardsinrow (i cardsinrow spacebetweencards)) (cardsincolumn 2f) spacebetweencards), memorycard.transform.rotation) as GameObject mc.GetComponentInChildren lt MemoryCard gt ().SetMemorycard(cardslist i .texture, cardslist i .number)


Momentum wise accurate player controls in Unity regarding collisions First post here. So I am a newbie to Unity and am willing to create a general character controller script to base my future characters. I understand a character's mechanics are pretty design (UX) dependent and I will need a few varients. What I want Momentum wise accurate physical simulation (as much as game performance allows). Some examples If a flying canon ball hits the player, it shall be crashed or flown away (some parameters would let us kill him in code hopefully) in accord with ball's momentum and player's mass. If the player hits a stationary canon ball the ball most probably wouldn't move (due to friction), yet if they push enough it gains some torque and rolls over. Rotational and kinetic energy would need equal energy provided. Multiple player's could act upon a bunch of pieces just for fun. Regular character capabilities such as stair ladder climbing, walking, etc. What I have read so far CharacterController needs to write code for desired physics, and apt when not so interactive characters (e.g. first person shooter) are at hand. Rigidbody is good for non agent dynamic items (e.g. falling boxes), and is hard to implement for agents (muscle powered humanoids, etc.), though possible. What I ask How can I implement such momentum wise accurate physics (regarding collisions) in Unity engine?


Should I use a database to store 10 000 names in a sports game? I'm working on a single player sports game for a year or so and this doubt came up how should I treat store big amounts of data, like player names. Let's take an arbitrary number as example 10000 names, 5000 first names and 5000 surnames. These names would be equally divided between 100 countries, which give us 50 first names and 50 surnames per country. Should I have a local database with these names (or even these countries) considering this data will be needed to generate new players names during the course of the game? Would that introduce limitations, considering I want to make my game moddable by players, as much as possible? These doubts can be extended to other, more complex game entities, such as Players each one with their own face, attributes, team etc... Teams each one with its own crest, kit, squad etc... In my previous research about that, the SQLite popped up as a seemingly viable solution. It happens that I have almost no experience with DB's (specially in games) and would like to know if this is a good direction before start to study and try to implement it.


Rotating a gameworld using quaternion I'm a hobbyist programmer at best and I had an idea I wanted to test in Unity, I wanted to rotate the game world around 90 degrees, to this end I've been learning a tiny bit about quaternions, in this simple test I have a empty game object at position 0,0,0 and 2 cubes placed so only one will be in the foreground at once (both children of the empty game object). I simply want to rotate the parent object on a mouse up like so. if (Input.GetMouseButtonUp(0)) Quaternion newrot Quaternion.Euler (0,90,0) transform.rotation Quaternion.Slerp (transform.rotation,newrot,0.05f) The problem I am having is that this does not do the rotation in a single click and never reaches 90 degrees, it only ever tends towards 90 (for fun I decided to click for 2 minutes and only got up to 89.99999 ... well you get the picture). Can someone tell me what I am doing wrong and if there is a better way of doing this?


How does one organize AI interactions with Local and Remote Players? Scenario In a first person multiplayer game, an AI monster grabs a player. (This would be first person player on the client's local machine, and a third person remote player on the master and other client machines) I'm trying to weigh the merits of different implementations of how these interactions could be organised. In this scenario, I can think of a couple different ways of implementing but I'm not sure what assumptions they might make which could result in a problem down the line The Monster could, in its grab function, have a test IsFirstPerson and then perform the FirstPerson specific or ThirdPerson specific grab mechanics, or The Monster could talk to an IGrabbable interface on the Player (remote or local), which would return whether it is FirstPerson or ThirdPerson and then perform the specific grab mechanics, or The Monster could talk to an IGrabbable interface on the Player (remote or local), which would return dictate the full details of how the Monster should grab. (And for clarity differences in implementation of FirstPerson or ThirdPerson would be where the hands are or headlook in first person it would look directly into the camera, but in third person it'd look at where the eyes are differing struggle animations, etc)


How can I prevent seams from showing up on objects using lower mipmap levels? Disclaimer kindly right click on the images and open them separately so that they're at full size, as there are fine details which don't show up otherwise. Thank you. I made a simple Blender model, it's a cylinder with the top cap removed I've exported the UVs Then imported them into Photoshop, and painted the inner area in yellow and the outer area in red. I made sure I cover well the UV lines I then save the image and load it as texture on the model in Blender. Actually, I just reload it as the image where the UVs are exported, and change the viewport view mode to textured. When I look at the mesh up close, there's yellow everywhere, everything seems fine However, if I start zooming out, I start seeing red (literally and metaphorically) where the texture edges are And the more I zoom, the more I see it Same thing happends in Unity, though the effect seems less pronounced. Up close is fine and yellow Zoom out and you see red at the seams Now, obviously, for this simple example a workaround is to spread the yellow well outside the UV margins, and its fine from all distances. However this is an issue when you try making a complex texture that should tile seamlessly at the edges. In this situation I either make a few lines of pixels overlap (in which case it looks bad from upclose and ok from far away), or I leave them seamless and then I have those seams when seeing it from far away. So my question is, is there something I'm missing, or some extra thing I must do to have my texture look seamless from all distances?


Why is the IntelliSense not working when I open a new script in Visual Studio? The strange thing is that opened scripts or newly opened ones are working fine. It's the new created C scripts that are not working. With not working, I mean the MonoBehaviour is not in light blue color it's in black color. In this screenshot I took, I marked it with a red circle. What have I tried so far? I have closed Visual Studio and started over again. Since it didn't solve it, I closed the unity editor and started it over again, to no avail. I pressed 'clean solution', I pressed 'rebuild solution', I pressed 'build solution'. What else can I do ? And why are the other scripts working fine? If I type gameo...it will auto complete it to GameObject but in this specific script it's just not working. This is a screenshot of the editor. I have in the Hierarchy a Ladder object. In the Assets I created a folder name Ladder and a script name Ladder. But this Ladder script is not working. This is the Ladder script and this script was working before but once I created another script inside the ladder folder name Raise empty script the Raise script didn't work and now the Ladder is not working either. But other scripts are working fine. using System.Collections using System.Collections.Generic using UnityEngine public class Ladder MonoBehaviour public Transform charcontroller private bool inside false private float heightFactor 3.2f private void OnTriggerEnter(Collider other) inside true private void OnTriggerExit(Collider other) inside false private void Update() if (inside true amp amp Input.GetKey("w")) charcontroller.transform.position Vector3.up heightFactor


How to move my character by itself but I can still move its direction or where it is going, using Mobile Joystick? So, I am making a 2D airplane game right now and I wanted to know how to move my player automatically but I can still control where it should go or the direction. How do I code this using Mobile joystick? CODE public float moveSpeed Rigidbody2D myBody protected Joystick joystick void Start() myBody GetComponent lt Rigidbody2D gt () joystick FindObjectOfType lt Joystick gt () Update is called once per frame void Update() myBody.velocity new Vector2( joystick.Horizontal moveSpeed, joystick.Vertical moveSpeed )


Convert the animation inside FBX into Unity Recently i bought a package with an fbx and lots of animations. Since I want full control and change a couple of details, I want to convert them into the regular Unities Animation System. I cant convert them into the normal Unity Animations though. They are "read only". I can load them, copy paste them into my own "not read only" animation file. But somehow i cant change the file anymore after I pasted something inside. What am I doing wrong? Is that something "impossible"? Can you guys help?


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 to implement the seek steering behavior in Unity3d? Following this tutorial Understanding Steering Behaviors Seek, I tried to add seek and steering behavior to my Unity prototype but it's not working this is my script. The cube does not steer it just follows the target. public GameObject target float maxForce 15 float maxSpeed 30 float maxVelocity 200 float mass 15 Vector3 velocity void Start() velocity Vector3.zero void Update() transform.LookAt(target.transform) var desiredVelocity target.transform.position transform.position desiredVelocity desiredVelocity.normalized maxVelocity Time.deltaTime var steering desiredVelocity velocity steering Vector3.ClampMagnitude(steering, maxForce) steering steering mass velocity Vector3.ClampMagnitude(velocity steering, maxSpeed) transform.position velocity Time.deltaTime What could be the problem??


How to refer to a object that has just been hit by a ray cast? I would like to use RigidbodyConstraints.FreezeRotation in order to freeze the rotation of an object that is picked up. The problem is I don't know how to refer (or call) the currently selected object. The script in it's currents state is below... public class PhysGun MonoBehaviour private GameObject Player void Start () Player GameObject.Find("Player") Update is called once per frame void Update () Vector3 fwd transform.forward Equivalent to the code you had. Ray ray new Ray(transform.position, transform.forward) RaycastHit hit if (Input.GetMouseButton(0) amp amp Physics.Raycast(ray, out hit, 10f)) hit.transform.SetParent(Player.transform) Debug.Log("We hit " hit.transform.name) hit.transform. RigidbodyConstraints.FreezeRotation So, how do I call (or refer to) the object that is hit by the ray cast exactly?


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


Unity look at rotation on one axis only problem Hey I would like an object to look at another object only at one axis, when I rotate the white cube all around the gray cube (gray has look at script), the gray cube flips as soon as the target passes the middle and is on the right side. How can I fix this, so that rotation is normal. Below is when the cube (target, white). Below is what happens when the cube (target) passes on the other side, as you can see by the texture the gray cube flips horizontally. Below is how it should be (texture shows difference) Code Quaternion lookAngle Quaternion.LookRotation(targetPos, Vector3.up) Thanks in advance!


Ocean visible through the island's lake in Unity3D? I'm working on a puzzle game featuring islands there is a plane with a water shader, and objects colliding with that plane. Now I'd like to make lakes on the islands, with different (higher) water levels than the ocean's. The problem is that if I put a water plane in a "hole", I can see the ocean below at best, or even worse, the upper water surface just glitches out and disappear. One option is that I move the lake's basin higher than the ocean's see level. This works, but I it doesn't look so good, because the lake becomes too shallow. Another option is that I cut holes in the ocean's plane, but that seems a bit overengineered, isn't it? Is there a better solution? Also having a water plane for every "lake tile" causes some problems but I want to have dynamic lakes, so having a 2x2 water plane for a 2x2 group of lake tiles isn't a walkable path.


Character controller passes through mesh collider I need a little help figuring out what's going on with an NPC's character controller. Here are the character controller settings for the NPC. The problem I'm running into is that the NPC isn't walking up a slight gradient as it should instead, it moves through the ground. Below are the settings for the ground. The NPC isn't on the ground it is a few units off. Any help is greatly appreciated. Thanks in advance...


Best way make static GameObject clickable 2D I've built a turn based battle combat game (like pokemon) but i'm stuck between a rock and a hard place. Asfar as i understod UI elements should be inside Canvas, while Players, Enemies, Items and etc... Should not be inside a canvas. Correct me if i'm wrong. I've tried different ways how to handle this situation. Such as make Enemy as a button, but seems not to fire. Since i think it has to be inside a canvas. Also make enemy which have animations as button, may not be a good idea? Update event, to check if the mouse is down and mouse position is converted with screentoworldpoint and see if the positions matches with the enemy position. Update event, to check if the mouse is down and rayCast see if we colide with something. But i dont feel like this is neccesary since the enemy does not move. So the position is always the same. Also if it's possible to take into consideration that every enemy is different size. But this is a minor detail, i would like firstly tackle the best way handle onClick event without the extra overhead. I would appericate any feedback on my dilemma.


One rock gameobject drops FPS heavily! Okay so this is really odd I have a game object (a rock) that even though is really high detail drops my fps from around 70 steady to 12! Now the object is divided into LOD's and the closer I get to the object the worse it gets! I have created a Material for each LOD of the object where i replace the normal map with a lower LOD (The other channels stay the same). The import settings for the different LODS looks like this Now as of the textures they are set to 2k (all of them) Can anyone tell me why this is happening? The object itself looks like this inside the game Even my scene view has framerate issues when looking at it.


Use arrow keys to navigate between specific toggles, not all UI elements I'm making a game where the player needs to select a object out of three and navigates between then with the arrows of the keyboard, and I'm using toggles to make this system. But the problem is that when I hit play, the navigation mixes the toggles with some other UI elements I dont want to include in the navigation, like sliders and buttons. How can I lock the navigation for just these three toggles? I also want to make the navigation switch between these toggles and another three toggles in the middle of the game. How would I change my navigation via script?


Unity how to set Off mesh link speed How can I set agent's speed on off mesh link? I want it to look like a jump, but now it looks like it was in slow motion.


Raycast Masks not working Unity3D I'm having a problem with filters masks when raycasting. I've created a LayerMask and then in the inspector selected the layer I want to ignore when Raycasting. however then I print out the name of the object hit by the raycast I am still getting hits on objects on the layer masked out, as well as on other layers. public LayerMask rayMask RaycastHit hit Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) if (Physics.Raycast (ray, out hit,rayMask)) Debug.Log (hit.collider.name) I have paused the Game and checked that the object I'm getting a hit on is indeed on the layer in the mask.


For creating a distant moon in a 3D game, is it better to use a model or texture? I'm working on my indie game and I want to create a moon (it's a 3D game) however I am unsure if I should create a model and put it far away, or if I should use a texture on a plane and have it constantly move so the face of the plane is facing the player. The problem I had last time I tried a model is the render view, as the model was really far away (as when I did it very small, you could sort of tell it was a tiny model rather then a far away moon) and with the texture I'm not sure if it comes across as tacky. I'd really like to hear the pros and cons of each, since I'm planning to use the 'render objects only when in view' method and basically want advice on which I should go with.


Prefabs moved to before position when zooming scene I have build some pipes for waterline drawing, like following screencast https youtu.be WnJb1JwOW78 As you can see, when I zoom in the scene, Pipes moved to lower position. When i zoom out, Pipes moved to higher position. Actually I have changed the position and moved down the pipe position before, the unexpected higher position was the pipe before position. So i guessing this problem might about cache clean. So I I try to clear the GI cache, but the problem still exist. And then I try to build a windows executable file and run game again, problem still. How to fix it? I am using Unity 2018.4


How can I efficiently make a solid Texture2D? I am trying to programmatically make an Image to cover the entire screen. I create the Texture2D, then create a Sprite from the Texture2D, then apply the Sprite to my Image. This works, but it is slow. I suspect the issue is that I am setting each pixel individually for my Texture2D private static Texture2D CreateSolidTexture2D(Color color) var texture new Texture2D(Screen.width, Screen.height) for (int y 0 y lt texture.height y ) for (int x 0 x lt texture.width x ) texture.SetPixel(x, y, color) texture.Apply() return texture I have tried creating the Texture2D by resizing a Texture2D of a single pixel, but the color comes out as a translucent white, instead of the color passed private static Texture2D CreateSolidTexture2D(Color color) var texture new Texture2D(1, 1) texture.SetPixel(0, 0, color) texture.Resize(Screen.width, Screen.height) texture.Apply() return texture Why doesn't my second approach work? How can I efficiently create a screen sized Texture2D of a solid color?


Unity3d zooming with orthogonal camera like in Google maps I am implementing 2d orthogonal zoom. As far as I know in Unity3d there are no translations like in OpenGL. Taking this into consideration, I work with camera size camera position (center) real world mouse position I have no issues implementing simple zoom in zoom out operations, combined with camera position changes ( drag'n'drop ) But I have some issues calculating camera zoom shift in this case camera size (4,4) camera position (0,0) real world mouse position (1,0) A double zoom in (2x) is applied, as a result camera size (2,2) camera position (0.5,0) real world mouse position (1,0) User shifts real mouse position to (1.5,0) and applies a double zoom out ( 0.5 ). In this case camera size is again (4,4) camera position ??????? real world mouse position (1.5,0) What should be the camera shift so the mouse doesn't visually move ? What is the formula for calculation in this case ? Thank you in advance. P.S. Any suggestion regarding current method of handling zoom are welcome Update So I resolved this issue with Blue's help. The basic idea about shifting is right. The main reason it didn't work was incorrect zoom factor. Example Initial camera size is 5. User zooms in by 1, camera size is now 4 ( it displays less content on the same 'screen'). User changes mouse position and zooms out by 1. Camera size is 5 again, but the amount of zoom is actually different initially the change was 20 ( 1 5 ) in the second time, the change was 25 ( 1 4 ) My fault was that, when zooming out, I tried to restore position by 20 , not 25 .


How can i check when Lerp has finished? private bool hitted false private Vector3 hitPosition private void Test() RaycastHit hit if (Physics.Raycast(start.position, Vector3.left, out hit, 1.5f) Physics.Raycast(start.position, Vector3.right, out hit, 1.5f) Physics.Raycast(start.position, Vector3.forward, out hit, 1.5f)) if (hit.transform.tag "Test") hitted true hitPosition hit.transform.localPosition private void Update() if (hitted true) player.localRotation Quaternion.Lerp(player.localRotation, Quaternion.LookRotation(hitPosition), 1 Time.deltaTime) What i want to detect is when the player finished rotating and then set back hitted to false.


Can I integrate Unity 5 with the 0.6.0 runtime for Oculus DK2? I am a new user and I am trying to get the Oculus running on an old PC. I had a few issues with the latest SDK so I am currently using the 0.6.0.1 beta version. I would like to integrate Oculus with Unity. My question is whether I can use Unity 5 with the SDK 0.6.0.1 beta and which kind of integration should I use or if I should download a previous release of Unity. Thank you!


GameObject transform with respect to local camera? I'd like to recycle objects as they pass behind the camera frustum i.e, the plane of the local Z axis, orthogonal to the camera vector Camera.main.transform.forward. Is there a nice method to test for the above case? That is, "if a GameObject's location lt local Z 0 plane", we can know that it is behind the camera.


Unity animation transition with 0 Exit Time doesn't transition immediately Question Why doesn't an animation transition with an Exit Time of 0 immediately transition to the next state? Minimal example Using Unity 2018.3, I set up an AnimatorController with two states Initial and Next. I wanted Initial to transition to Next immediately, so I tried setting an Exit Time of 0. However, this doesn't transition immediately As shown above, Initial state still runs instead of transitioning immediately to the Next state. (There is no Motion attached to the AnimationState, so perhaps it's using a default duration.) Below are screenshots of my animation transition settings. Strange behaviour with small non zero ExitTime I also tried using an Exit Time of 0.01 (i.e. transition after 1 of the animation has played), and it transitions almost immediately as I expect most of the time. However, occasionally it will still play the Initial state In this case, even though it transitions to Next immediately most of the time, it still occasionally waits for the Initial state to complete. (It happens much less frequently than the image above suggests, but the issue becomes more frequent if I set the ExitTime even lower, e.g. 0.003). Workaround From searching online, the recommended solution for immediate animation transitions seems to be to turn off Exit Time and use a condition (e.g. bool or trigger) to transition immediately instead. (Edit in my case, I've defined an animator bool parameter called ImmediateTransition and set it to true by default instead of using Exit Time 0.) This seems to work, but I would like to better understand how Exit Time works and why it's not working the way I expect.


Align spawned particle system I am working on a game in which tanks can shoot at each other. I intend to spawn a spark particle system (particles emit to Z) when a bullet hits a surface. I want to align the Z axis of the newly spawned particle system to be a) in a 90 degree angle to surface that has been hit b) in a reflective angle from the original trajectory I know that I can "fake it" by setting particle Z to World 90 degrees, however then it will do so on any angled surface, while I would like to have the particle system dynamically orient itself in a 90 degree angle away from the surface that has been hit or reflect into the direction away from the incoming bullet. hope you can help me, getting quite frustrated.


What is the most appropriate way to achieve synchronous Addressable asset loading? I am transitioning my project from Resources to Addressables. Some parts of my game just aren't worth doing asynchronously, and would just cause more problems but I still want to use Addressables for its other benefits. Anyway, it doesn't offer any synchronous methods in their API. Unity has an official repository with an example for "synchronous addressables" right here https github.com Unity Technologies Addressables Sample blob master Advanced Sync 20Addressables Assets SyncAddressables SyncAddressables.cs Although the code does appear to work in the few tests I've done The code below won't always work, and it doesn't make sense to me anyway. This is the relevant method public static TObject LoadAsset lt TObject gt (object key) if(!s Initialized) throw new Exception("Whoa there friend! We haven't init'd yet!") var op Addressables.LoadAssetAsync lt TObject gt (key) if(!op.IsDone) throw new Exception("Sync LoadAsset failed to load in a sync way! " key) if (op.Result null) var message "Sync LoadAsset has null result " key if (op.OperationException ! null) message " Exception " op.OperationException throw new Exception(message) return op.Result It will throw an exception if the asset didn't manage to load instantly (the !op.isDone part). Sure, that's technically synchronous, but it seems to ignore the elephant in the room if the asset is large I would expect it to need a bit more time (i.e. freeze the game), which is fine for my current needs but instead, the game will just end up crashing because it couldn't load immediately. What is the most appropriate way to achieve synchronous Addressable asset loading?


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.


Resize sprite to match camera width? I'm trying to resize my small background sprite to match the screen width of the user's device. This is what I'm trying Use this for initialization void Start () Set filterMode SpriteRenderer sr (SpriteRenderer) GetComponent("Renderer") sr.sprite.texture.filterMode FilterMode.Point Get scaling float multiplier Camera.main.rect.width sr.sprite.bounds.size.x Scale transform.localScale localScale multiplier It seems there is a problem with the measure I get from the Camera width, I also tried Screen.width but it seems it returns the value in pixels.


Animating 2d character which can wear items? In my game the player can control a character which can wear items. Now it is not visible but I would like to make it visible like for example in Terraria, Starbound, etc. In my game a player can only face right or left. (right is the mirrored version of left) Only the character's feet and arms are moving during the game. Is there a simple way in Unity to stick the sprite of the items to "bones"? (like in 3d modelling) Or how could I implement this "equipment on character" system? I found some assets but I dont have much money. Thanks in advance! )


Physics.CheckSphere never returning true despite being called to where a hitbox is I'm trying to create a random level generator where I have a load of rooms 16x10 and I generate them when the player enters the room. I want to check the space where I want to place a room, in this case up for if there's already a room there. I've written this code to do that but it doesn't appear to be working. Currently it should ALWAYS return true (and not run the code) because the object it is on has a hitbox. I want it to hit triggers because then I don't need a physical block in the centre of every room (hard when the rooms are even both ways) Can you see what's wrong here? The code does spawn a block in the correct place. if (!Physics.CheckSphere(new Vector2(transform.position.x, transform.position.y), 1f, 6, QueryTriggerInteraction.Collide)) Get list of open bottoms getList("Assets Room Lists bottom.txt") Make a random number from the list int newRoomIndex random.Next(0, prefabObjects.Count) Get that object GameObject newRoom prefabObjects newRoomIndex Place it in the world in the correct position Instantiate(newRoom, new Vector3(transform.position.x 8, transform.position.y 15, transform.position.z), Quaternion.identity)


How to edit key value pairs (like a Dictionary) in Unity's inspector? I have a spell system I am creating, the principle is as follows Each spell is an autonomous prefab. It contains a script with some properties (base damage, duration...) that can be modified in the inspector. I have a Spell enum listing all possible spells in the code, which is used in the game logic When I want to cast a spell, I need to be able to get this spell's prefab to instantiate it and read its informations Each actor (be it players or enemies) needs to have a list of possible animations for the spells The problems with how I am trying to implement are For listing each actor's animations I could use a Dictionary lt Spell, Animation gt , but dictionaries aren't supported by the inspector which makes it hard to easily edit multiple actors type. I need some way to easily access a spell prefab from the corresponding enum. Here too I could use a dictionary but I can only reference to prefabs in the inspector, not in code, meaning I wouldn't be able to fill this dictionary I am looking for a way to easily associate my spells enums to the corresponding prefabs and animations


Unity Transport Layer API How to manage client server connections I am currently working on a "Master server" system for our Unity Game using Unity's Low Level "Transport layer API" for networking. My problem is that I would like to prevent clients from connecting to eachother. I have tried not giving them a port on the Addhost() call, but it doesn't seem to change anything. They also do not seem to detect the connections, so basically I find myself with NetworkTransport.Connect(..) calls that work (the error byte is 0, meaning no error) but no actual connections. I don't understand what's going on. I can't really show my code because it's quite long, but here's how it works, in summary The Clients objects initialise a Socket as normal with only one Reliable channel, no port, and one connection allowed by default. Then they have the ability to connect to another socket, as you'd expect. My problem COULD be coming from there for testing purposes the IP I use for testing is 127.0.0.1. What I do not understand is, how can it "find itself" when it is not bound to any port ? And more importantly how can it NOT find the Master Server object whose socket IS bound to a port ? Speaking about Master Server, it's an object that also initialises its socket, but with a port and many allowed connections. When a client connects and the connection did not yield any errors, it considers the connection to the Master server to be successful and proceeds sending a message containing some information for the server about this client the username chosen by the player for example. When the master server receives a connection event, it registers the received ConnectionID and waits for more information from that same connection, for example the aforementioned username. Both the client and the server handle receiving messages with the NetworkListener class (Static). On each frame it executes the Listen() method which executes a "normal" NetworkTransport.Receive() body. I can give you that part of the code as it is fairly common in design public static void Listen() int recHostID int recConnectionID int recChannelID byte buffer new byte 1024 int recDataSize byte error NetworkEventType e NetworkTransport.Receive(out recHostID, out recConnectionID, out recChannelID, buffer, 1024, out recDataSize, out error) Debug.Log("Listening") switch(e) case (NetworkEventType.Nothing) break case (NetworkEventType.ConnectEvent) Debug.Log("Connection established. ConnectionID " recConnectionID) if (OnConnectionReceived ! null) OnConnectionReceived(recHostID, recConnectionID, recChannelID) break case (NetworkEventType.DataEvent) Debug.Log("Received data !") BinaryFormatter f new BinaryFormatter() MemoryStream stream new MemoryStream(buffer) Message f.Deserialize(stream) as NetworkMessage break case (NetworkEventType.DisconnectEvent) Debug.Log("Connection terminated. ConnectionID " recConnectionID) break Network message is a simple data structure which contains a ConnectionID (the one it's from), a message title and content. The title is used to determine the general purpose of the message. The content is the rest of the information. What happens in my current build of the client The user is prompted to enter a username, then he clicks "Search for match". The search for match button is supposed to trigger the connection to the Master Server. The logs say that the connection was successful (as no errors are detected) but no Connection event is received on either side. This of course prevents everything else from working. If you need further description of the problem just ask and I'll answer ASAP. Thanks a lot in advance !


Season Change Reveal Effect I was watching the teaser trailer for Seasons After Fall, and I was struck by the effect they use to transition between seasons (around 21 24 seconds) The level art, including the background and the foreground platforms, change from a sepia coloured autumn to a lavender winter, with the effect spreading outward from the player character a bit like water soaking through paper. It looks like more than just a palette change, as details in the leaf and bark patterns change in the transition. How could I achieve an effect similar to this in a 2D Unity game?


Jumping up quicker? (Paper Mario style jump) As shown here, Paper Mario's jump takes 8 frames go reach the max jump height and 12 frames to get back to the ground. This is pretty unusual, any idea how to jump up that quick with a rigidbody? I tried to AddForce when rigidbody.velocity.y gt 0, but that didn't work out. Any help would be appreciated, thanks in advance! Jump when pressing button and on ground jumpForce is a public float variable if (Input.GetButtonDown( quot Jump quot ) amp amp isGrounded) theRB.velocity new Vector3(0, jumpForce, 0)


How can I replace an object with a prefab so the prefab will be at the same position of the gameobject? I have some doors in the scene, each door at another position. I took one of the doors added to it a light and made a prefab of the door. Now I want to replace all the other doors with the prefab. Example of the door with the light I added and this door is also a prefab And this is example of another door that is not yet replaced by the prefab door with the light I want to replace this door with the prefab door with the light at the first screenshot. The question is if there is a easy way to do the replace ? I have more doors that I want to replace.


How to limit the speeding up of enemy movement? Is there a way of limiting my speeding my enemy script every time my player collects 10 points. I have a movement script attached to my enemies and every time my player collects 10 points my enemies get faster. I want to put a limit on that so that the movement script (attached to my enemies) doesn't increase all the time even if the player continue to collect 10 more points and onwards. I want the limit to be 40, so even if the player continues to collect another 10 points the movement should stay at 40. This is my speeding up my enemies script (this is used in my score script) if (Score 10 0) Increment movespeed variable from Movement script Movement.movespeed 4 And this is my movement script attached to my enemies public static int movespeed 20 public Vector3 userDirection Vector3.right public float lifetime void Start () Destroy (gameObject, lifetime) public void Update() transform.Translate (userDirection movespeed Time.deltaTime) How can I limit the movement speed so that it doesn't exceed the upper limit I want?


Blend Tree animation problems at rotation I have a Blend tree animation with two floats ( VelocityX, VelocityZ) that have idle, run , run right, run left , I use a pad to move it at world space When VelocityX is 1 it run left, 1 it run right When VelocityZ is 1 it run back, 1 it run foward It is working fine but the problem comes when I rotate the character in his Y axis, If I rotate the character 90 degrees on the Y axis, This system 'breaks' since blend tree is calculating VelocityX and VelocityZ from world space and not local space, So character is doing 'run foward' animation to go top but hi should do 'run right' animation since from character prespective he is moving to the right How I can implement that local rotation into my blend system? Any help or guide will be apreciated


How can I create a mirror with Unity? Can anyone explain how I can create a mirror effect like the one in this YouTube video using Unity Pro? I know that I need to use render textures to do it, but I am not sure how.


Antialiasing shader grid lines I would like to have in game grid lines similar to ones found in Unity editor. There is simple solution(first listing) based on shaders found on unity forums(on right image). However, that solution does not take in account antialiasing and drawn lines looks terrible even few units away from camera. float4 frag(vertexOutput input) COLOR if (frac(input.worldPos.x GridSpacing) lt GridThickness frac(input.worldPos.z GridSpacing) lt GridThickness) return GridColour else return BaseColour In order to address that, I tried using typical fwidth smoothstep combination float4 frag(vertexOutput input) COLOR float distX min(frac(input.worldPos.x GridSpacing), 1.0 frac(input.worldPos.x GridSpacing)) float distZ min(frac(input.worldPos.z GridSpacing), 1.0 frac(input.worldPos.z GridSpacing)) float dist min(distX, distZ) float delta fwidth(dist) float alpha smoothstep( GridThickness delta, GridThickness, dist) return lerp( GridColour, BaseColour, alpha) Even though it has nice fade, the result is not quite near to perfect not only the lines looks thinner(which can be somewhat fixed by increasing width), but also have various artifacts(e.g. in joints) and horizontal lines disappear much sooner than vertical ones. Detail image(anti aliased on left) I am interested in shader solutions, since according to answer to similar question relying textures there in can be no solution with textures. In addition I would like grid lines fade at reasonable distance(when closely inspecting aliased overview image you can see where plane ends) rather than continuing to infinity. Full current version(for testing purposes) with signed distance.


How to convert world coordinates to grid movement I'm producing a tactical 3D RPG game and I have the following issue I want the NPC to move through the grid. The grid is formed by tiles and each tile has a script attached to it. In this script, there is a variable called TilePosition which is a Vector2Int, that I use it to stores its X and Y values in the grid. The NPC character has a script attached to it called NPCPlayer, where a use a Vectir2Int named NPCGridPosition to stores its position in the grid. Also regarding the NPC, he has a script called NPCMovement. In this script, I've set a raycast that starts from the NPC feet and goes down. I use the raycast to take the TilePosition variable as it is written in the code public void MoveNPC() if (Physics.Raycast(transform.position, Vector3.down MaxDistance, out hitDown)) if(hitDown.transform.tag "Tile") Tile TilesPosition hitDown.transform.gameObject.GetComponent lt Tile gt () NPCPlayer NPCPosition this.GetComponent lt NPCPlayer gt () However, when I try to move the NPC through the grid, 3 rows ahead, he goes away, because he moves according to the world position, rather than moving according to his tile position. I'm using these lines of code to make him move public void MoveNPC() if (Physics.Raycast(transform.position, Vector3.down MaxDistance, out hitDown)) if(hitDown.transform.tag "Tile") Tile TilesPosition hitDown.transform.gameObject.GetComponent lt Tile gt () NPCPlayer NPCPosition this.GetComponent lt NPCPlayer gt () targetPosition.x TilesPosition.TilePosition.x 3 targetPosition.y TilesPosition.TilePosition.y this.transform.position Vector3.MoveTowards(this.transform.position, targetPosition,velocity) How could I make the NPC to move according to its position in the grid? I'll be glad if someone can help me a little bit with this.