_id
int64
0
49
text
stringlengths
71
4.19k
0
Per component Shader Blend in Unity Context I'm writing a 2D mobile game in Unity where the graphics are essentially black lines drawn on a background image plus some lighting. Running full RGB calculations for every step seems like a waste of processing power. What I'd like to do is render everything in grey, alpha and then multiply by the sRGB background image in a separate shader at the end. Actually, ideally, I'd like basically to specify custom components like grey, highlight, additive, alpha , each of which can be ignored in a given pass, and then do a custom operation with those when I apply the background image, like ceil(src (dst.r dst.g)) half4(dst.b). I can figure out how to do that between 2 textures within a shader, but not between texture and screen (a.k.a. src amp dst). Question Basically, is there a way of writing a per component replacement of the built in Blend functions? Because something like Blend SrcAlpha OneMinusSrcAlpha only works with the full float4 or half4 vectors. Or do I need to grab the screen like a texture and handle it within a pass block, and then do Blend Off or Blend One Zero? Or do something with RenderTextures perhaps? My intuition suggests that that would undo some of the efficiency I'd gained in previous steps, though...?
0
How to disable collider2D when another gameobject is on top of it Each black colored square has a BoxCollider2D. How can I disable the collider after I put another game object on top of it? Here is the sample output
0
Optimization of Cube based World I'm currently working on taking an idea I've been toying with in C and bringing it into Unity, but I'm struggling to figure out how to make it performant and how to do things the "Unity way". My world is made up of cubes and cube shaped tiles viewed from a fixed angle ( la Monument Valley). I've watched their behind the scenes video and seen that they have a step in their workflow that removes the unused faces from their cubes and combines them into quads. I want to achieve something similar. Ideally I want to build up my world using a bunch of prefab cube objects (with different textures and components) and then run some kind of process over my scenes before I export play to optimize them (otherwise I'm going to be doing potentially thousands of draw calls that I don't need to do and have lots of colliders I don't need). My questions are as follows What hooks does Unity provide to do this sort of processing? Should I be using PostProcessSceneAttribute for this? I understand that I can use Mesh.CombineMeshes to combine my cubes, but what about for their colliders? How can I determine groups of cubes that are touching (for removing faces and combining colliders)? In my C project I keep all of the blocks in a 3D array and use that, but using the Unity editor to place the blocks means I don't have this available. Is there a way I could easily build one from my scene, or is there a more "Unity" way of doing this? Is my approach sensible? Or should I drop the idea of placing individual cubes in the editor and take a different approach?
0
Rotate perspective camera to align screen width to procedural object's width (Unity, C ) I give up. After much trying and searching, I have to say I was unable to achieve the following task, for which I must call for your wise advice. In my current Unity 5 application (using C ), there is a procedurally generated object (therefore with variable shape) to which the camera should be aligned when players hit a given key. By aligned, please understand it making the width of the screen parallel to the longest part of the object. The idea is represented in the following picture, where in black one can see the irregular object, in yellow is the bounding box. In other words, it means that I want the camera to be rotated so to align to the longest side of the object's bounding box. I tried that. Still, I was unable to properly calculate the correct angles so to rotate the camera in a way that the horizontal axis of the screen becomes parallel to the width of the objects' bounding box. Any help would be much appreciated.
0
What does 'vertex splitting' mean? In the documentation of MeshUtility.SetPerTriangleUV2 it is said the following Will insert per triangle uv2 in mesh and handle vertex splitting etc. What do they mean by 'vertex splitting' ?
0
How to handle data for a competitive multiplayer games I am kinda new to Multiplayer Games and I am really wondering how I should handle my data Should each player send and update their data to the database (server) everytime one of their essential variables changes (like health or ingame currencies), or should they save the data as long as the game is running and then update the data all at once at the end of, lets say, each round? I was thinking about using Firebase and Unity and here's a scenario Let's say 2 players connect to a game. Then one of them gets damage and the other one gets gold. Does the data change get sent to the FireBase Database immediatly or should I just update everything when the round ends they disconnect?
0
How to prevent "reverse" displacement from a collision? In my game I can throw a hammer. The hammer moves based on physics in Unity. The hammer destroys the first object it touches. I want it to continue moving as though it didn't touch anything when this happens. To try and achieve this, I made it destroy objects using a separate, larger trigger collider, intending to destroy the object before the physical collision occurs. However, when moving at very high speeds (as in the GIF), both colliders hit at once, so the hammer moves and the object deletes. How can I prevent the hammer from moving when before the trigger occurs, or (I suppose more realistically) "reverse" the movement such that there's no perceptible collision? I tried using the impulses from each of the contacts in the collision to apply forces in reverse, but didn't really understand what I was doing and ultimately failed. NOTE I cannot simply disable the physics collider, because it doesn't destroy everything.
0
Unity3D Smooth rotation for seek steering behavior I am trying to implement Reynolds' seek steering behaviour, but I am having problems on the rotation part. This is what I have void FixedUpdate() get position of current waypoint Vector3 targetPos new Vector3(path currentWaypoint .x, transform.position.y, path currentWaypoint .z) velocity vector towards target Vector3 desiredVelocity targetPos transform.position calculate the steerforce required for the desired velocity based on current velocity Vector3 steerForce desiredVelocity currentVelocity steerForce new Vector3(steerForce.x, 0, steerForce.z) steerForce Vector3.ClampMagnitude(steerForce, maxSteer) create a move vector to be added to agent's current position Then normalize it so it can be scaled according to the agent's max speed Vector3 moveVector steerForce.normalized moveSpeed Time.fixedDeltaTime transform.Translate(moveVector) How would I do it so my agent will be rotated smoothly based only on the code above? I tried rotating based on the current velocity, but the agents is rapidly rotated in one frame towards the target waypoint. I am not working with rigidbodies. Am I doing something wrong? What am I missing? Thanks, Jack
0
Is it possible to export animations from Blender to Unity prefab without re exporting entire character? I have a fully rigged and animated character that I recently exported from Blender as an FBX to Unity. I need to make more animations for the character now but I am very tired of exporting the entire character every time I make a change. I do not need to update texture coordinates or vertex weights (probably). Is there a way to record a new animation in Blender and attach it to the existing Unity character? Or alternatively, is there now a viable way to produce quality animations for characters inside of Unity? My character needs to move fingers and toes but does not have facial animations.
0
No intellisense with with Unity 5.5, Visual Studio Code integration, OSX 10.12.1 I get this with the listed software. It doesn't recognize object types and I can't use reference finding. I have the Omnisharp plugin installed and updated. Just wondering if this is supposed to work properly yet. I'm opening it with Assets Open Project In Code.
0
A scriptManager (singleton) not storing a variable (in the same scene) The script below is called every time I pickup an item and stores an instance of it in the array "mainInventory". The problem is when I access the array after picking up another item its empty. The script is on the MainCamera. public class InventoryManager MonoBehaviour public static InventoryManager instance null public Image inventoryPanel0 public Image inventoryPanel1 public Image inventoryPanel2 public Image inventoryPanel3 public Image inventoryPanel4 public Image inventoryPanel5 public Image inventoryPanel6 private Item mainInventory Use this for initialization void Awake () Singleton if (instance null) instance this else if (instance ! this) Destroy(gameObject) mainInventory new Item 7 public void pickedUp(Item item) Below checks which slot item belongs in bool positionFound false int currentPositionCheck 0 while (!positionFound) if (mainInventory currentPositionCheck null) positionFound true else currentPositionCheck Adds item to slot mainInventory currentPositionCheck item Adds image to inventory panel switch (currentPositionCheck) case 0 inventoryPanel0.sprite item.icon break case 1 inventoryPanel1.sprite item.icon break case 2 inventoryPanel2.sprite item.icon break case 3 inventoryPanel3.sprite item.icon break case 4 inventoryPanel4.sprite item.icon break case 5 inventoryPanel5.sprite item.icon break case 6 inventoryPanel6.sprite item.icon break default Debug.LogError("Expand inventory", this) break Item public class Item MonoBehaviour public string name public Sprite icon private MessageManager messageManagerScript private InventoryManager inventoryManagerScript private bool inRange private void Start() Gets managers GameObject managerContainer GameObject.FindWithTag("MainCamera") if (managerContainer ! null) inventoryManagerScript managerContainer.GetComponent lt InventoryManager gt () messageManagerScript managerContainer.GetComponent lt MessageManager gt () else Debug.Log("Can't find camera containing maangers") Update is called once per frame void Update() If in range and player presses key if (inRange amp amp Input.GetKeyDown(KeyCode.F)) Destroy(gameObject) OnTriggerExit(new Collider()) Pickup item inventoryManagerScript.pickedUp(this) private void OnTriggerEnter(Collider other) inRange true Displays pickup message if (other.gameObject.tag "Player") messageManagerScript.displayPickupMessage(name) private void OnTriggerExit(Collider other) Removes pickup message messageManagerScript.removeDisplayMessage() inRange false
0
Using Unity built in sprites programatically I'm trying to figure out how to use the "Panel" built in resource in a game I'm making. I've been able to figure out some potential solutions, but I can't quite figure out how to put all of the pieces together. panelImage.sprite UnityEditor.AssetDatabase.GetBuiltinExtraResource lt Sprite gt ("UI Skin InputFieldBackground.psd") panelImage.sprite Resources.GetBuiltinResource(typeof(Sprite), "Resources unity builtin extra Background.psd") as Sprite The first produces the button sprite, which is almost what I want, but not quite. The second doesn't work at all. I'm missing some small piece of what it takes to make this work, but I can't quite figure it out. How can I use the panel background programmatically?
0
How can I create light shafts like Journey's in Unity? I'd like to create cartoon looking sun light shafts that look very close (or identical) to the ones in very well known and loved games like Journey and Ori How can I accomplish this?
0
Are there game engines like Unity but for 2D? I really like the convenience of unity3d. The ability to edit the level and see my results in real time are great. My problem is the idea I want to implement is 2d and uses 2d sprites. Scaling sprites appears to be a problem for me and all advice I receive says to purchase 150 dollars addons for unity. I love the physics components and the rapid prototyping but I figured that maybe unity is not the tool for the job for this 2d game. Is there any 2d game engine like unity but for 2d games that would work on the PC and Android? Or is this something most people code themselves and make? To me the most important features of Unity3d were its ease to see what was edited and then have it apply instantly. Thank you. Most searches seemed to give me frameworks and not a large engine suite.
0
Mirror problems after building game in unity Hi I am facing a weird problem in unity when I build a particular scene. Here is the screenshot of how the mirror looks when I play the game from inside the unity editor And here is how it looks once I build this scene and then play it The quality settings at Edit Project Settings Quality are these And the player settings at File Build Settings Player Settings are these So how do I fix this? What do I need to change or is there any other entity?
0
How to line up rigidbody velocity with speed of moving floor So, I have a player who remains in the same X position. the floor moves from right to left underneath the player, and I am using tiles of 1 unit. Here's my jumping stuff if (RB.velocity.y lt 0) RB.velocity Vector2.up Physics2D.gravity.y (FallMultiplier 1) Time.deltaTime else if (RB.velocity.y gt 0) RB.velocity Vector2.up Physics2D.gravity.y (JumpMultiplier 1) Time.deltaTime if ( Input.GetKey(KeyCode.Space) amp amp IsGrounded amp amp JumpDelay lt 0) RB.velocity Vector2.up JumpVelocity JumpDelay 0.1f Debug.Log("Jumping") And here is what moves the floor Vector2 NewPosition TF.position NewPosition.x Time.deltaTime Speed TF.position NewPosition So, what I want to happen, is I have a movement speed for the floor, and I want to make it line up such that if I jump where the player is directly in the middle of one floor tile, they will land (say 4 tiles later) directly in the middle of another tile. I can get close by tweaking the velocities... but this feels the wrong way. I want to know what values I might be able to use, and how to calculate what velocities they should be. Speed of floor right now is at 5, Jump Multiplier at 1.75 and Fall Multiplier at 7. There of course do not line up as I hope, but it gives example values in case that helps. How would I solve this to say, for example, with the given multipliers, what should the floor speed be to line up perfectly?
0
Swipe Detection with mouse in Unity This is my swipe detection code. This code uses touch input. I want to do this using the left mouse button. So basically I want to 'swipe' using the mouse.How can I achieve that? public float maxTime public float minSwipeDist float startTime float endTime Vector3 startPos Vector3 endPos float swipeDistance float swipeTime Use this for initialization void Start () Update is called once per frame void Update () if(Input.touchCount gt 0) Touch touch Input.GetTouch(0) if (touch.phase TouchPhase.Began) startTime Time.time startPos touch.position else if (touch.phase TouchPhase.Ended) endTime Time.time endPos touch.position swipeDistance (endPos startPos).magnitude swipeTime endTime startTime if(swipeTime lt maxTime amp amp swipeDistance gt minSwipeDist) SwipeFunc() void SwipeFunc() Vector2 distance endPos startPos if(Mathf.Abs(distance.x) gt Mathf.Abs(distance.y)) Debug.Log("Horizontal swipe") else if (Mathf.Abs(distance.x) lt Mathf.Abs(distance.y)) Debug.Log(" vertical swipe")
0
How to fix this elbow issue when converting to humanoid Good day, how can I fix this? it looks fine in Blender and generic but not when I switch to humanoid. There is no error on rig tab but there are in animation tab under the import message that say quot is in between humanoid transforms and has rotation animation that will be discarded quot and I can't seem to fix it. Here are the things I've tried so far Put the right bones to the right slots. Enforce T pose. Translation DoF. Clicked Generate Retargeting and applied it.
0
How to "merge" multiple intersecting circles so that only the outer edges of each show? In my RTS (In Unity) each unit or building has strategic circles in a similar fashion to SupCom. If you have multiple units or buildings selected it looks like the picture to the left. I want to make it look like the picture to the right, where anything inside the outer edges of their circles is no longer shown. I draw these using vectrosity, mentioning this just in case vectrosity provides a way of doing this, or can be modified to do this. The circles are essentially just an array of points with lines drawn in between them. How would I go about "merging" the circles inside of their overlapping area? This is similar to How to make unit selection circles merge?, however I am not interested in a shader solution. Edit To re explain the above. I'm not seeing how the answers are applicable. I've read through the other thread before posting, which is why I posted it here to avoid this exact thing (being marked as a duplicate). I have an array of points with straight lines in between them to create a circle like effect. This is not a true circle, but a really granular polygon. I am interested in solutions that are achievable in C within Unity, not with shaders or with rendering mechanics. Edit2 Another picture based on one of Roberts suggestions This seems viable, though computationally expensive. If I have a circle made up of 250 points, and 50 circles all intertwined that's 615,500 checks in a worst case scenario.
0
Android Device Screen Flicker I have made sudoku type game. I am about to complete my game in 2d. At present, my game run smoothly on higher configuration devices such as Sony Experia Sola, Samsung Note 2 and Google Nexus. But it creates screen flickering problem in my HCL ME tablet. I don't what is problem going on. I notice that when I load prefabs then it start flickering problem. If I don't create any prefab then it don't flicker at all. At present my development game resolution is 2048x1536. So friends I need support from your side. If you want any more detail then I will provide any time.
0
How to best apply colliders on a rough 3D shape I have a 3D model for a level in unity. I want to add colliders to it. What is the best type of collider for this model? And,it is 3D
0
Teleport Not Working in Unity 2D So I'm basically trying to get my character to "use" a set of stairs by teleporting from one stairway door to another. Each stairway door will be paired with one other stairway door. Here's the code, I feel like it should be working...my Debug.Logs are even outputting the correct information. Also FYI, I have the Transform doorPairedWith as public so that I can just drag and drop the stairway door that each one is supposed to be paired with. using UnityEngine public class Stairs MonoBehaviour Player player public Transform doorPairedWith Vector3 doorPairedWithPosition Vector3 playerPosition BoxCollider2D playerCollider BoxCollider2D stairsTriggerCollider bool playerIsNearStairs false void Start() player Player.instance playerPosition player.transform.position doorPairedWithPosition doorPairedWith.position playerCollider player.GetComponent lt BoxCollider2D gt () stairsTriggerCollider GetComponent lt BoxCollider2D gt () void Update() UseStairs() void UseStairs() if (playerIsNearStairs true) if (Input.GetKeyDown(KeyCode.E)) Debug.Log("Attempting to use stairway door named " doorPairedWith) playerPosition doorPairedWithPosition void OnTriggerEnter2D(Collider2D collision) if (collision.gameObject.tag "Player") playerIsNearStairs true Debug.Log("Player is near stairs " playerIsNearStairs) void OnTriggerExit2D(Collider2D collision) if (collision.gameObject.tag "Player") playerIsNearStairs false Debug.Log("Player is near stairs " playerIsNearStairs)
0
How to change TPS camera angle in Unity I'm very new to Unity and this may simply be a failure of google fu but I hope someone here can help me out. I'm working through a series of tutorials on how to create an RPG in Unity, making small improvements and embellishments as I go to make sure I understand the concepts. I've built a player character with walk and run animations and a camera which follows the player around and stays aimed at the centre of the character model using the following code. using System.Collections using System.Collections.Generic using UnityEngine public class CameraFollowPlayer MonoBehaviour GameObject target Start is called before the first frame update void Start() target transform.parent.gameObject Update is called once per frame void Update() transform.LookAt(target.transform.position) The problem with this is the angle this leaves the camera pointing at in game is to acute, making it difficult to see what is ahead of the character. How can I adjust the target of the LookAt instruction to result in a shallower X axis rotation of the camera?
0
How to use an overlapping shader so that it uses layers sort from sprite renderer and its transparent Im using the shader from question , but once I put it in the game, and my character gets close to it, it will be hidden by the shadow of the tree, which is transparent. Any way to make the shader transparent and or maybe use the sprite renderer sort layer system I have been trying to use stencil configurable shader with no luck Thank you for your help Not sure what combination of these should work The character is using a normal sprite renderer.
0
Can't get the current animation state name (hash or .IsName) to work I have some hard times trying to get the current animation state name in Unity, to perform specific actions while I'm in a certain state. I want to know when I'm the "ThoughtsStill" state, I only have the default layer (Base Layer) To do this, here is what I tried AnimatorStateInfo curr state animator.GetCurrentAnimatorStateInfo(0) if (curr state.shortNameHash Animator.StringToHash("ThoughtsStill")) Debug.Log("I'm in ThoughtsStill state"). which is not working. I also tried with IsName() method but it is not working too (both tried to compare "Base Layer.ThoughtsStill" and "ThoughtsStill"). I'm certain that I'm going in this ThoughtsStill state but I don't know why I can't get it. Do you guys have any ideas or leads? Thanks !
0
Unity game debugging on Xcode This question has two parts 1. How to get meaningful information out of Xcode crash logs? The game runs fine on the editor but when running on an iOS device it crashes and then gives information like this How can I dig out which script actually causes this? 2. Which Xcode debugging tools are available for Unity games? There are plenty of them mentioned here. Especially the frame capture and Instruments profiling seem very handy.
0
Unity method framework for handling different input modes I'm a very new Unity developer who's looking for a best practice or framework for handling different input modes. I'm working in C . Here's a contrived example Sample Map Application Control Scheme 1 W A S D keys move map up right down left. Escape key closes application Spacebar opens menu and switches to Control Scheme 2 Control Scheme 2 W A S D moves menu selection up down into submenu back to parent menu. Escape key closes menu and switches to Control Scheme 1 I realize this is a silly contrived example, but it demonstrates the point. When we are in a menu we don't want the W A S D keys to also move the map while we are trying to navigate the menu. This could be done with a bunch of if statements such as if(moveMode) read keypresses and move map else if(menuMode) read keypresses and menu navigation But you can see how this would get messy very quickly if we had lots of modes. We could also end up with a lot of nested if statements if we have sub modes for controls. Surely there's a cleaner way to do this? Any best practices for this? Any frameworks?
0
Can a prefab of a complete Unity scene be created? Can we create a prefab out of a complete unity scene, so that we can instantiate the complete scene like we instantiate gameobjects in unity.
0
Dynamic model scaling Imagine a (3D) game like Railroad Tycoon 3. Player selects a rail track, clicks LMB and drags the mouse to the end position. During this drag, the rail track model scales and adopts to the landscape, so user sees the resulting track in dynamic. The question how this can be done? A brief idea links sketches will be enough. I just don't know how to start (I'm novice game developer). If it is matter, I use Unity as a game engine. Thanks in advance.
0
ECS Stats, damage types damage calculation Prologue Im quite new to data oriented programming and my goal is to implement a runescape stats damage mechanic. This is quite a pretty complex topic Runescape Mechanics 1 and i havent found any ECS related sources on that topic yet. In the following example we see a bunch of items which modify the weares stats based on a few conditions. This happens in two different variants, either for the damage calculation only, or as a buff. Brine sabre and Brackish blade increase damage against crabs. or Silverlight and Darklight increase ability damage by a scaling of 25 124 against most demons. The exact damage bonus is based on your base Attack and Strength, and the monster's base Defence. The problem Such a RPG system is very complex. There different damage types, different resistences and other stats. Having a strong OOP background and no real experience in DOP, i cant find a suitable architecture to fill those needs. In my current approach every stat is a component. Items and Buffs are structs. A item quot buffs quot its owner and the buff modifies his stats. This works so far, but i have no idea how i could realise the damage calculation, while still keeping it that flexible as it is in runescape. This little example would just be able to buff the stats... not deal, receive or modify the damage itself. The stats public struct Health float max float value public struct MeeleDamage float base float value public struct MeeleResistence float base float value Item amp Buffs public struct Item string name int amount bool equipable List lt Buff gt buffs public struct Buff string name float duration Condition applyable ToBuff stat float value Its also important that an entity can also deal damage to multiple other entities in one frame. How would you implement such an complex mechanic ? Any examples are appreciated !
0
Unity assets file structure I'm writing a map editor for a game built with Unity (5). I want to reuse as much of the resources from the game as possible. That means textures and meshes. I know they are somewhere in the assets files, but I need to be able to extract that data during runtime since I cannot (and do not want to) redistribute those files. Additionally, given that the game receives frequent updates, I need to be able to calculate the offsets each time the editor is started. I also need to know how the textures connect to the objects in the game. In order to do that, I need to know what the structure of assets file is, or at least find a way to extract them all and then use hex editor to figure out how they're put together. I know there is a devxdevelopment tool that can do the latter, but I don't really have any money to spend on this. Can you give me any info or pointers that would enable me to figure this out?
0
Should recoil be an animation or script? Should recoil for a rapid fire gun be be done through an animation or a script? I want the recoil to increase as I continuously fire, like a lot of FPS games do. I was initially considering achieving this through a script in unity that rotates the gun slightly each time I fire, but I realized that since I plan to have most rapid fire guns be 2 handed weapons, at some point, the left hand won't be on the weapon. However, since I also want the recoil to increase as I fire, I'm not sure how I can achieve this in an animation. How is recoil typically done? Input on this would be very much appreciated.
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
0
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)
0
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?
0
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
0
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.
0
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?
0
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?
0
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 ()
0
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?
0
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)
0
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
0
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...
0
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?
0
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)
0
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.
0
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
0
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.
0
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
0
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!
0
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?
0
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.
0
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)
0
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?
0
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?
0
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.
0
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!
0
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?
0
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?
0
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?
0
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.
0
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
0
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.
0
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?
0
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?
0
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?
0
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?
0
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.
0
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.
0
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
0
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.
0
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
0
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)
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
0
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.
0
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?
0
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.
0
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 ?
0
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?
0
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.
0
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?
0
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?
0
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.
0
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?
0
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.
0
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?
0
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?
0
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")
0
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.
0
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!
0
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.
0
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?
0
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)
0
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?
0
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.
0
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?
0
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)
0
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?
0
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