_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | How to create an Editor class for a generic class For all my MonoBehaviour scripts, instead of them inheriting from MonoBehaviour they inherit from a generic class like so public abstract class MonoBase lt T gt MonoBehaviour where T MonoBase lt T gt public class Example MonoBase lt Example gt Now, I would like to make an editor script for all those MonoBase classes, and the closest I have gotten to a solution that will compile is CustomEditor(typeof(MonoBase lt gt )) public class MonoBaseEditor lt T gt Editor where T MonoBase lt T gt public override void OnInspectorGUI() this.DrawDefaultInspector() MonoBase lt T gt myScript (MonoBase lt T gt )this.target if (GUILayout.Button("Build Object")) But of course it doesn't really work. Am I missing something or is there really no way to make a generic editor class like it's mentioned in an answer here. |
0 | Implementing a lexicon for a word based game with C or C In my game project I have a lot of word existance checks based on some word bank. As usual arrays or map set are not realy appropriate for this due to their speed memory usage, I want to use Ternary Search Tree. After some googling I've realised that there's not so much info or code ready to use there. So I want to implement it myself. Question is can I write it in C and then export to Unity with cross platform support? To be more precise will I be able to use this cpp library on Android and iOS? Or maybe I should just write it in C which, I believe, will be slightly less efficient? |
0 | UI Text Won't Change Color in Unity 5 In Unity 5 on Windows 10, I try to change the text color from the Inspector and in scripts, but the color won't change. Here are some screenshots of my Text objects open in the inspector, with there colors set to red and white, but staying the default black in the Scene and Game windows Here are the lines of code I am using to change the color var textColor beatBestTime ? " FF0" "FFF" scoreText.text "Time " FormatTime (timeElapsed) " n lt color " textColor " gt Best " FormatTime (bestTime) " lt color gt " which I can verify are being run, but the color remains the same! |
0 | Unity LWRP alternatives for camera stacking I am working on upgrading a project in unity from a 2018 version to the latest 2019. One of the mechanics of the game is an AR (augmented reality) system. Some of the UI elements appear in the 3D world, but clearly as part of the hud. They need to be transformed as the camera moves, but should always be drawn on top of the 3d scene. The old project achieved this via camera stacking. All the AR elements were drawn on a different camera which rendered on top of the 3D camera. The clear flags were set to "depth only" and it removed all other elements from that camera. In the 2019 version of Unity with the Lightweight Render Pipeline (LWRP), the clear flags feature on the camera is missing. To the best of my research, camera stacking has been removed from LWRP. What are my alternatives? How can I now achieve this effect? I would like to stick to LWRP as I am using Shader Graph for many of the effects in the game. |
0 | New Unity version copies the settings of previous version I use Ubuntu 20.04. When I download a new version of Unity 3D through Unity Hub, this new version automatically takes the settings of the previous version. I have installed Unity 2020.1, and I am facing the same problem. I created a new project, but it written in 2020.1 that I used preview package. I didn't even installed any package in Unity 2020.1. I did install preview package in 2019.4. But I didn't even open the project with 2020.1. I only have one project with 2020.1. The new project I just created. I asking help because I faced this issue when I first installed 2019.1, 2019.2, etc. How can I flx it? Thanks |
0 | In Unity3D, how can I improve image clarity? The same images that appear clearly in Adobe Flash appear blurry in Unity. My game uses quads, cubes and sprites. I've tried the game on Android, iPhone, Mac and PC, but the image appears poor quality on all of them. A sample screenshot What can I do about this? |
0 | How do I ensure my Android build is not darker than in Editor? My scene on the Android Build looks much darker. Based on my research about the topic, and from the texture of the light on the spheres, I assume it is because the light uses per vertex render mode on Andriod. I am trying to force per pixel render on Android, these are the things I have tried set the Rendering to Important of the Light on the scene (There is only 1 directional) check the values of my RenderPipeline asset (the one came with the LWRP Template project), the Main light is Per Pixel, Additional Light (which doesn't seem to matter) is also Per Pixel set the Preset Light's Render type to Important in the Preset Manager I will have infinite levels, the map changes dynamically, so Baking the light is not an option. Can I achieve this somehow? Or at least force my editor to use per pixel so I can light up my scene more intuitively. |
0 | How can I access a script variable from another script in Unity? I'm creating a space shooter (think Space Invaders or Galaga) where the GameManager persists between scenes but the player and enemies don't. I need to access a boolean value from the player and enemies to define when and how the game should end. The PlayerController script contains a playerDead variable (attached to the Player GameObject) to tell the GameManager if the player has died and a enemiesDead variable to tell if all enemies have died. Because the GameManager persists but the others don't, it loses the references when a new level is loaded. I tried to have the GameManager find the script references dynamically, to no avail. It always errors with Object reference not set to an instance of an object when a new level is loaded. I've tried to get them with GameObject.FindGameObjectWithTag() and then using GetComponent lt ScriptName gt () to get the script and the variable in it. It compiles nicely and everything seems dandy, but then there's still no object reference. Am I just doing it wrong? So how can I reference a script and get a value from it without even touching the Inspector? EDIT Below is some code (everything else except the essential is scrapped) from the GameManager script, I tried to use Object.FindObjectsOfType() like this GameObject player GameObject enemies void Awake() DontDestroyOnLoad (gameObject) void Start () Reinitialize () void Update () if (enemies.GetComponent lt EnemyGrid gt ().enemiesDead true) gameEnd true if (player.GetComponent lt PlayerController gt ().playerDead true) gameEnd true void Reinitialize() player Object.FindObjectOfType(typeof(PlayerController)) as GameObject enemies Object.FindObjectOfType (typeof(EnemyGrid)) as GameObject But there's still no object reference. My intention was to run the Reinitialize() funtion each time a new scene was loaded, so that way the GameManager would grab the new objects each time. |
0 | OnMouseUpAsButton not always called I'm working on a 2D implementation of Free Cell in Unity 4.6.1, and I'm having trouble getting my click detection code working consistently. The code below should be called every time a card is clicked (they all have BoxCollider2D components) but it doesn't always happen. Handle Clicks on Card void OnMouseUpAsButton() print ("test") int cardLayerMask LayerMask.GetMask("Cards") RaycastHit2D hit Physics2D.RaycastAll(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, Mathf.Infinity, cardLayerMask) print ("Hit length " hit.Length.ToString()) if (hit.Length gt 0) print ("Hit") Even the "Test" print statement doesn't get called consistently, so it's not a problem with the raycast. If it manages to print the test, the raycast always works. Each time the game runs, the cards get dealt onto the playing field randomly into stacks. On each run, some subset of the cards don't call the above code. The number of cards that work correctly varies, as does their position on the field. It's not consistent with any particular card. I'm wondering if maybe there's an issue with the BoxCollider2D instances overlapping. The other colliders in the scene, like the one on the "table", always trigger OnMouseUpAsButton() successfully. I need to be able to register clicks on every card, so I need to find a way to make this work. Have any of you run into a similar issue before? If not, is there a way for me to work around this? Maybe a different way to detect the clicks on the cards? Here's a screenshot of an example card from the inspector. Aside from transform position amp script property values, all of them are identical (from a prefab) Update w Solution from Accepted Answer Using Byte56's solution, I was able to take care of this pretty easily. I've included sample code below. Note that to get the sample to work, the "top" object has to have the highest transform.position.z out of all the objects the raycast hits. I also put all the possible hit objects into their own layers so I can trigger different behavior based on what type of object is clicked. Handle clicks if (Input.GetMouseButtonDown(0)) Cast a ray, get everything it hits RaycastHit2D hit Physics2D.RaycastAll(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, Mathf.Infinity) if (hit.Length gt 0) Grab the top hit GameObject GameObject lastHitObject hit hit.Length 1 .collider.gameObject Determine layer of last hit object, take next steps as appropriate switch (LayerMask.LayerToName(lastHitObject.layer)) case "Cards" print ("Hit card!") break case "Table" print ("Hit Table!") break case "Cells" print ("Hit cell!") break |
0 | How can i do a "Crouch" with only a Character Controller with no rigidbody? I was following Bracky's fps tutorial but he didn't add crouching as an option. I took a stab at it but came up empty handed. Here is my script for player movement. public class PlayerMovment MonoBehaviour public CharacterController controller public float speed 12f public float gravity 9.81f public float jumpHeight 3f public Transform groundCheck public float groundDistance 0.4f public LayerMask groundMask Vector3 velocity bool isGrounded Update is called once per frame void Update() isGrounded Physics.CheckSphere(groundCheck.position, groundDistance, groundMask) if(isGrounded amp amp velocity.y lt 0) velocity.y 2f float x Input.GetAxis( quot Horizontal quot ) float z Input.GetAxis( quot Vertical quot ) Vector3 move transform.right x transform.forward z controller.Move(move speed Time.deltaTime) if(Input.GetButtonDown( quot Jump quot ) amp amp isGrounded) velocity.y Mathf.Sqrt(jumpHeight 2f gravity) velocity.y gravity Time.deltaTime controller.Move(velocity Time.deltaTime) And also have a separate script for mouselook, here that is aswell. public class Mouselook MonoBehaviour public float mouseSensitivity 100f public Transform playerBody float xRotation 0f Start is called before the first frame update void Start() Cursor.lockState CursorLockMode.Locked Update is called once per frame void Update() float mouseX Input.GetAxis( quot Mouse X quot ) mouseSensitivity Time.deltaTime float mouseY Input.GetAxis( quot Mouse Y quot ) mouseSensitivity Time.deltaTime xRotation mouseY xRotation Mathf.Clamp(xRotation, 90f, 90f) transform.localRotation Quaternion.Euler(xRotation, 0f, 0f) playerBody.Rotate(Vector3.up mouseX) How would I go about adding one without adding a rigidbody or changing my script fully to follow other tutorials? Thank you! |
0 | What are some ways to make a scene without walls and infinite terrain visually appealing? My Player Character is standing in the middle on flat infinite terrain. The player can see as far as the farplane of the camera. And there is nothing there which is... boring. I wanted to Plant a couple of trees which move with the player (but not rotate with them). But I would need tons of trees for that, and that would destroy performance. Next I've thought about a "foggy shadow", or a light or a cubemap with textures of things. But those things are visually totally ugly. Now I am in front of a hard decision and I dont know what to do. Here are examples of infinite terrain so you guys know what I mean. |
0 | How to create video from camera? I have a 3d scene and a camera I want to create video file from camera pre set movements. If it is possible, running application by command line (without needed to "show" at video, my camera) . Is it possible in Unity ? If yes what's the best approach ? Thanks |
0 | How to circle an uneven object with Camera at a fixed distance? Unity3d. I am trying to move an object with Camera around a fixed terrain (Mountain), while staying an set distance from its edge. I have the camera set to lookAt the mountain, and I want to circle the mountain. I was thinking about sine wave for circular motion but its not an exact circle as I need to move in or out to maintain the fixed distance from the mountains edges. It looks like I might need transform.RotateAround(..), but what about the adjusting to maintain a fixed distance from the edge of the uneven surface while maintaining the circular motion. transform.RotateAround (Vector3.zero, Vector3.up, 20 Time.deltaTime) Update Here is my current script for circling around mountain as first person object function Update () var mountain GameObject mountain GameObject.Find("QuantumCold B") transform.RotateAround(mountain.transform.position, Vector3.up,20 Time.deltaTime) Unfortunately there are two problems 1) The first person object appears to be falling or maybe its the main camera, but in any even there is a game screen looks like its falling below the mountain. 2) it is the mountain that seems to be rotating. Do I need to switch the main camera to be the first person camera. Why does the mountain appear to be rotating? |
0 | FBX animation works in 3DSMax but not with Assimp I have an FBX file that represent a plane with an animation of the gear opening. In my editor 3DSMax or in the Unity editor, the file and animation seem good, but when I use Open 3D Model(the official viewer of Assimp) or when I call the FBX file simply in an application, to see what the file will look like with the use of Assimp, I got some issues. The object seems normal at the beginning, but when I try to launch the animation, all my animated elements are going crazy. Here's what it looks like Here's my FBX FILE Do you have experience something similar ? Does it come from my file or a parameter in Assimp ? I am beginning to think that there is a problem with how Assimp handles pivot points, looks like objects are rotating using a different pivot point in Unity open3mod. |
0 | How can the board fit the screen perfectly in Unity's 2D Roguelike tutorial? I follow the tutorial 2D Roguelike tutorial. I want to understand how happen that 10x10 board of 32x32 sprites covers screen perfectly? Like what does this depend on? |
0 | How do I fix the "Failed to recompile android resource files." build issue? I've tried similar solutions I found on this website, nothing worked. There are thee errors that pop up... been banging my head for quite a while now, please help! Also note I updated my JDK using the download link (next to the browse option in the external preferences). Then linked it to this file, which I am lead to believe is the correct file. C Program Files Java jdk 9 Failed to compile resources with the following parameters bootclasspath "C NVPACK android sdk windows platforms android 24 android.jar" d "C Users Dylan Desktop ContentCreater Repo DoodlePlanes DoodlePlanes DoodlePlanes Temp StagingArea bin classes" source 1.6 target 1.6 encoding UTF 8 "com android vending billing R.java" "com SoloDeveloperStudio DoodlePlane R.java" "com unity purchasing R.java" "com unity purchasing googleplay R.java" warning options source value 1.6 is obsolete and will be removed in a future release warning options target value 1.6 is obsolete and will be removed in a future release warning options To suppress warnings about obsolete options, use Xlint options. 3 warnings UnityEditor.HostView OnGUI() UnityException Resource compilation failed! Failed to recompile android resource files. See the Console for details. UnityEditor.Android.PostProcessor.CancelPostProcess.AbortBuild (System.String title, System.String message, System.Exception ex) UnityEditor.Android.PostProcessor.CancelPostProcess.AbortBuild (System.String title, System.String message) UnityEditor.Android.PostProcessor.CancelPostProcess.AbortBuildPointToConsole (System.String title, System.String message) UnityEditor.Android.PostProcessor.Tasks.BuildResources.CompileResources (UnityEditor.Android.PostProcessor.PostProcessorContext context) UnityEditor.Android.PostProcessor.Tasks.BuildResources.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) UnityEditor.Android.PostProcessAndroidPlayer.PostProcess (BuildTarget target, System.String stagingAreaData, System.String stagingArea, System.String playerPackage, System.String installPath, System.String companyName, System.String productName, BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.BuildReporting.BuildReport report) UnityEditor.Android.AndroidBuildPostprocessor.PostProcess (BuildPostProcessArgs args) UnityEditor.PostprocessBuildPlayer.Postprocess (BuildTargetGroup targetGroup, BuildTarget target, System.String installPath, System.String companyName, System.String productName, Int32 width, Int32 height, BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.BuildReporting.BuildReport report) (at C buildslave unity build Editor Mono BuildPipeline PostprocessBuildPlayer.cs 263) UnityEditor.HostView OnGUI() UnityEditor.BuildPlayerWindow BuildMethodException Build failed with errors. at UnityEditor.BuildPlayerWindow DefaultBuildMethods.BuildPlayer (BuildPlayerOptions options) 0x001b9 in C buildslave unity build Editor Mono BuildPlayerWindowBuildMethods.cs 162 at UnityEditor.BuildPlayerWindow.CallBuildMethods (Boolean askForBuildLocation, BuildOptions defaultBuildOptions) 0x00050 in C buildslave unity build Editor Mono BuildPlayerWindowBuildMethods.cs 83 UnityEditor.HostView OnGUI() |
0 | Make non sprite render in front of sprite How do I make the non sprite (BasicSpellProjectile) render in front of the sprite (Tower 2)? Note The camera is located at z 10. The z positioning apparently doesn't do anything, and I am unable to set the sorting layer order of the non sprite as there isn't one such option. |
0 | GameObject remains null for some reason The idea is to access the function BlockWasDestroyed() from Combo class. Instead of var combo gameObject.GetComponent(Combo) I've also tried with var combo GetComponent(Combo) var combo Combo gameObject.GetComponent(Combo) var combo Combo GetComponent(Combo) But the console keeps telling it's null. However it could work when the function was static, but thing is now that function is calling another function, and so the errors happen once again. Here's my code so far Brick.js pragma strict public class Brick extends MonoBehaviour function OnCollisionEnter(col Collision) if(col.gameObject.name quot Ball quot ) var ballb gameObject.GetComponent(BouncingBall) var combo gameObject.GetComponent(Combo) combo.BlockWasDestroyed() ballb.velocityZ ballb.velocityZ 1 Score.score 20 Destroy(this.gameObject) |
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 | Does animation have internal "update" cycle where I can make calculations between steps? I am new to Unity and not game developer at all, so sorry if this question might be stupid. I have an animation in my project. Is there some points where Unity calculates recalculates the next position of animated character? Is there some function like for example quot OnAnimationSample() quot ? I want to make calculations between theese points. I didn't found anything in the documentation and hope that someone more experienced than me know some way to tackle, although the task is quite peculiar. I am programming a simulation environment for robots. There is a need to take screenshots at certain events happening by means of raycasting (gathering img data for CNN). The robot has various physical specification like for example speed. I don't want the environment depends on speed of the robot, so I am planning to make calculations and screenshots constatly for example in between two animation quot milestones quot . That will slow fps and overall game down, but I don't mind since I need only right data at right step. For example suppose there are exist such points in the Unity, when before taking any movement the Unity calculates the next state of the object being animated. I want to stuff my calculation and such, that next animation step won't start until all is done. I hope that explained not so tricky. Say if the explanation is obscure I will try my best again. |
0 | How can i scale a cube on one side on x only? I have in the Hierarchy a empty GameObject and a cube as child of it. The cube the child is at position 0,0,0 and scale 1,1,1 But when running the game the scaling is on both sides of the cube. I put the cube as child of the empty gameobject and scaling the empty gameobject but still it's scaling the cube on both sides. The script is attached to the empty GameObject using System.Collections using System.Collections.Generic using UnityEngine public class Walls MonoBehaviour Vector3 originalScale Vector3 destinationScale void Start() originalScale transform.localScale destinationScale new Vector3(100.0f, 0, 0) private void Update() if (transform.localScale.x ! 100.0f) transform.localScale new Vector3(1, 0, 0) This is a working solution using System.Collections using System.Collections.Generic using UnityEngine public class Walls MonoBehaviour public Transform objectstoScale private void Update() if (objectstoScale 0 .localScale.x ! 100.0f) objectstoScale 0 .localScale new Vector3(1, 0, 0) But i want to make that the same cube will also scale one side on the z. So the cube will be scaled on both x and z but without filling it one be like frames. So i tried this using System.Collections using System.Collections.Generic using UnityEngine public class Walls MonoBehaviour public Transform objectstoScale private void Update() if (objectstoScale 0 .localScale.x ! 100.0f) objectstoScale 0 .localScale new Vector3(1, 0, 0) objectstoScale 1 .localScale new Vector3(0, 0, 1) And i have now two cubes childs of the empty gameobject one cube position is 0.5,0,0 the second is 0,0,0.5 but what i'm getting is What i want to do is to create automatic a rectangle scaling a cube on 4 sides at the same time not filled rectangle. For example like this |
0 | Why am I getting a down arrow in my Unity scene when using Oculus Rift and how do I get rid of it? In Unity, I have set up a scene to try out in Oculus Rift. When I hit play in Unity, everything works fine until about 5 seconds later when I get an arrow (Assets OVR Textures out.png) that appears in the center of my screen and won't go away. What does this arrow mean and how can I get rid of it? It is obstructing my view of the level that I am trying to view. |
0 | Chess engine stock fish process for mobile I am making the chess interface I designed for a game. I am using the process to get answers from a stock fish binary stockfish new Process StartInfo new ProcessStartInfo FileName System.IO.Directory.GetCurrentDirectory () " Assets Scripts Stockfish stockfish.exe", Arguments "", UseShellExecute false, RedirectStandardOutput true, RedirectStandardInput true, RedirectStandardError true, CreateNoWindow true The problem I face is it worked for my Windows build but for mobile package build it won't work with the executable. Is there a way around it? |
0 | How to design context menus based on whatever the object is? I'm looking for a solution for a "Right Click Options" behaviour. Basically any and every item in a game, when right clicked, can display a set of options based on whatever the object is. Right click examples for different scenarios Inventory Helmet shows options (Equip, Use, Drop, Description) Bank Helmet shows options (Take 1, Take X, Take All, Description) Floor Helmet shows options (Take, Walk Here, Description) Obviously each option somehow points to a certain method that does what is says. This is part of the issue I'm trying to figure out. With so many potention options for a single item, how would I have my classes designed in such a way as to not be extremely messy? I've thought about inheritance but that could be really long winded and the chain could be huge. I've thought about using interfaces, but this would probably restrict me a little as I wouldn't be able to load item data from an Xml file and place it into a generic "Item" class. I'm basing my desired end result on a game called Runescape. Every object can be right clicked in the game and depending on what it is, and where it is (inventory, floor, bank etc.) displays a different set of options available to the player to interact with. How would I go about achieving this? What approach should I take to first of all, decide which options SHOULD be displayed and once clicked, how to call the corresponding method. I am using C and Unity3D, but any examples provided do not have to be related to either of them as I'm after a pattern as opposed to actual code. Any help is much appreciated and if I have not been clear in my question or desired results, please post a comment and I'll tend to it ASAP. Here is what I have tried so far I've actually managed to implement a generic "Item" class that holds all of the values for different types of items (extra attack, extra defence, cost etc...). These variables get populated by data from an Xml file. I have thought about placing every single possible interaction method inside of the Item class but I think this is unbelievably messy and poor form. I've probably taken the wrong approach for implementing this kind of system by only using the one class and not sub classing to different items, but its the only way I can load the data from an Xml and store it in the class. The reason I've chose to load all my items from an Xml file is due to this game having the possibility for 40,000 items. If my math is correct, a class for each item is a lot of classes. |
0 | Can I use flat shading on a generated mesh? I tried to generate a mesh from code in Unity. The problem is, that the edges are automatically smoothed. When I import a model into Unity, I can set the smoothing angle of the edges, but is something like this possible with a generated mesh? I would like to have no smoothing at all. |
0 | How to make one material on object with many parts inside? I have a weapon witch have many parts, it also have many materials. Do I really need to make it like that? It's like about 8 mats! ( |
0 | Unity Ragdoll moves away from parent So this is a weird one. I've looked it up but can't find anyone with similar issues. Basically I have a simple combat system and after the enemy health is zero I go through each rigidbody component in the enemy object and add a force to make it go flying on death. For some reason, the parent object isn't affected and stays still while the Skeleton goes flying. Does anybody know how to make the parent object follow the skeleton, or make the skeleton follow the parent because as of now they act as separate entities? I've tried just adding force to the parent but that only moves the parent object and none of the children. Would appreciate any advice! Thanks. |
0 | Unity 5.5.1f1 new UI system Button in scrollview is not working on Android. Is this known issue? Is there a workaround? It works perfectly in the editor, but on Android it only sometimes registers an OnClick when I press it with my finger. I'm on Unity 5.5.1f1 Is this a known issue? I'll post some videos of it if no one has seen this before. The scrollview is based on the default one from the Create UI scrollview menu Ive added a vertical layout group to it, to which I add prefabs that contain buttons. These are the buttons that are not working. The canvas is in front of the camera in worldspace and is scaled down to 0.02 in X and Y VVVVVVVVVVV UPDATE VVVVVVVVVVVVV I wrote my own workaround using 2D colliders instead of buttons The colliders are registering hits just fine. But when I wrote a class to not register hits if the scrollview moves, I get similar behaviour! Heres the crude little workaround class I wrote.. public class ScrollButton MonoBehaviour public StoreItem Item bool FingerDownOnMe public void BeOnClicked() VisualDebuggerRef.SetTxt("a store button" " " Random.Range(0, 10000)) FingerDownOnMe true This is called on all these objects whenever the scrollview moves public void ScrollviewMoved() FingerDownOnMe false void Update() 'UppedthisFrame' will be true whenever any touchs phase TouchPhase.Ended if (Refs.man.Clickdetect.UppedthisFrame amp amp FingerDownOnMe) FingerDownOnMe false Item.ButtonHit() I'm guessing Unities UI classes work in a somewhat similar way to my workaround one. The problem is that the scrollview is registering as being moved when it should not be. This may be because of my test device which is an S7. Maybe the touch resolution is so high it is registering movement that is smaller than one pixel?? Also maybe the fact the the entire canvas has been scaled down could be affecting this? Say Unities classes have a distance threshold, if they are not taking into account scale then working on a scaled down canvas might make the distances they are using too big, so the threshold is reached too easily Im going to add a distance limit to my workaround... VVVVVVVVVVVVV UPDATE2 VVVVVVVVVVVVVVVV This workaround code using colliders works perfectly.. public class ScrollButton MonoBehaviour const float scrollThreshold 0.25f public StoreItem Item bool FingerDownOnMe Vector3 HitPos public void BeOnClicked() VisualDebuggerRef.SetTxt("a store button" " " Random.Range(0, 10000)) FingerDownOnMe true HitPos transform.position void Update() 'UppedthisFrame' will be true whenever any touchs phase TouchPhase.Ended if (Refs.man.Clickdetect.UppedthisFrame) if (FingerDownOnMe amp amp Mathf.Abs((transform.position HitPos).y) lt scrollThreshold) Item.ButtonHit() FingerDownOnMe false I'm going to report this issue as a bug to Unity |
0 | Editor throwing NullReferenceException I have the following exception being thrown at compile time NullReferenceException Object reference not set to an instance of an object UnityEditor.Graphs.Edge.WakeUp () (at C buildslave unity build Editor Graphs UnityEditor.Graphs Edge.cs 114) UnityEditor.Graphs.Graph.DoWakeUpEdges (System.Collections.Generic.List 1 T inEdges, System.Collections.Generic.List 1 T ok, System.Collections.Generic.List 1 T error, System.Boolean inEdgesUsedToBeValid) (at C buildslave unity build Editor Graphs UnityEditor.Graphs Graph.cs 387) UnityEditor.Graphs.Graph.WakeUpEdges (System.Boolean clearSlotEdges) (at C buildslave unity build Editor Graphs UnityEditor.Graphs Graph.cs 286) UnityEditor.Graphs.Graph.WakeUp (System.Boolean force) (at C buildslave unity build Editor Graphs UnityEditor.Graphs Graph.cs 272) UnityEditor.Graphs.Graph.WakeUp () (at C buildslave unity build Editor Graphs UnityEditor.Graphs Graph.cs 250) UnityEditor.Graphs.Graph.OnEnable () (at C buildslave unity build Editor Graphs UnityEditor.Graphs Graph.cs 245) I know well enough what a NullReferenceException is and what causes one, but the stack trace above implies that it's being thrown by the editor or some other internal thing. Does anyone have any advice on how to debug this? |
0 | How to put labels at a specific point on any resolution I am working on a project in Unity 4.6.1 and I put the label at the top But when I put the Scene in full view this happened I made a Development Build and when I select my resolution (1366x768) the label goes behind the buttons. Is there any way to put the label at a specific point no matter what resolution? |
0 | Automated performance testing I'm wondering if there's anyway of automatically testing the performance of my game on multiple configurations because I know a game runs well on my computer but how do I know how well my game performs over a variety of hardware? Do I just simply have to rely on player feedback? |
0 | How to have random and different colors on multiple objects with one material? I want to have one material applied to multiple objects that has a random color on each object. How can I achieve this so that I don't need to use a different material for every object? This is in Unity 5 by the way. |
0 | Applying a torque to a different centre of mass In Unity I have an object with a circle collider attached to it and when I apply a torque to this object's rigidbody2D, it rotates as expected. However, I have now attached a sub object to this object with a polygon (trigger) collider which I am using to detect when something is in a cone in front of the ship. There is no rigid body (2D or 3D) attached to the child object. The only rigid body on the object is the one I am applying torque to. However, when I do this, the centre of mass of the ship is moved to the centre of this collider, which produces totally the wrong effect. This happens even if I move this collider to the root node (so both it and the circle collider are attached). I either need a way of getting the rigid body to ignore the child collider allow me to set the centre of gravity, or else some other way of detecting objects inside a region. |
0 | How to run Unity in "headless" mode? I need to run my game without graphics and user input (headless mode). I googled it but I actually couldn't find a solution, except something like this using UnityEngine using System.Collections using UnityEditor public class a MonoBehaviour public static void BeforeBuild() EditorUserBuildSettings.enableHeadlessMode true Unfortunately, this doesn't work for me as it seems to work only on Linux. Am I forced to run my instance on Linux? I would be really thankful if anyone could help me! |
0 | What is the proper way to instantiate multiple objects from a script while in the editor in Unity? I would like to, for example, be able to spawn a wall of stacked boxes and be able to play with the number of boxes in each dimension in the editor (previously I would be instantiating these at runtime, but it is annoying to not be able to see these in the editor). Currently I am using a bit of a work around, I am using the OnValidate method to achieve this, but its a bit of a bodge and my instantiated items do not spawn in play mode, I get the following error on play MissingReferenceException The object of type 'Lattice' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. Lattice. lt OnValidate gt b 8 0 () (at Assets Lattice.cs 22) UnityEditor.EditorApplication.Internal CallDelayFunctions () (at home bokken buildslave unity build Editor Mono EditorApplication.cs 346) Here is the script I am currently using public class Lattice MonoBehaviour public int nX 1, nY 1, nZ 1 public float offsetX 1, offsetY 1, offsetZ 1 public GameObject item Validate called only in editor and only on variable change void OnValidate() Clean() remove old items UnityEditor.EditorApplication.delayCall () gt spawnBox3Grid(item, transform, nX, nY, nZ, offsetX, offsetY, offsetZ) void Clean() foreach(Transform childT in transform) UnityEditor.EditorApplication.delayCall () gt Debug.Log(childT.gameObject.name) DestroyImmediate(childT.gameObject) void spawnBox2Grid(GameObject obj, Transform parent, Vector3 startingPos, int nItemsY, int nItemsZ, float zOff 1.0f, float yOff 1.0f, int k 0) Vector3 boxPos startingPos new Vector3(0, yOff 2, zOff nItemsZ 2) Vector3 zOffset new Vector3( 0, 0, zOff) Vector3 yOffset new Vector3( 0, yOff, 0) for (int j 0 j lt nItemsY j ) for (int i 0 i lt nItemsZ i ) GameObject instance Instantiate(obj, boxPos, Quaternion.identity, parent) instance.name string.Format( quot obj 0 1 2 quot , i, j, k) instance.transform.localPosition boxPos instance.transform.localRotation Quaternion.identity boxPos zOffset boxPos nItemsZ zOffset boxPos yOffset void spawnBox3Grid(GameObject obj, Transform parent, int nItemsX, int nItemsY, int nItemsZ, float xOff 1.0f, float yOff 1.0f, float zOff 1.0f) Vector3 xOffset new Vector3( xOff,0, 0) Vector3 boxPos new Vector3( xOff nItemsX 2,0,0) for (int k 0 k lt nItemsX k ) spawnBox2Grid(obj, parent, boxPos,nItemsY,nItemsZ, yOff, zOff, k) boxPos xOffset This YouTube video is probably closer to what I want, but I don't entirely understand it and was hoping there was a simpler way. Edit Some extra context Delaying the DestroyImmediately calls seems to be the only way to delete objects from inside OnValidate and if I don't delay the Instantiate calls I get SendMessage cannot be called during Awake, CheckConsistency, or OnValidate. Edit 2 I guess I can use this code for previewing in the editor then use a scriptable object to store the parameters of my Lattice objects and then re instantiate things at runtime? But that error that I'm getting is it trying to run OnValidate just before play? (When presumably, the things I've instantiated aren't stored permanently so the lattice object is lost?) There has got to be a cleaner way of doing this... |
0 | Should I combine multiple tiles of terrain as one mesh in Unity3D? I have a tiled terrain, generated by multiple noise algorithms. Currently, each tile is it's own GameObject, that has a handler for an OnMouseOver event. The area that is loaded at a time consists of 9 chunks that each contain 4096 tiles. This totals to 36864 tiles that are loaded at a time. On top of this, there are actual objects on top of these tiles. Is there any considerable performance difference if I were to combine some of these tiles into a single GameObject and mesh? |
0 | Question about coding rarity and non MonoBehaviour referencing I have a non MonoBehaviour script called Item which contains two classes. public class Item public string itemName public string itemRarity public Item(string newItemName) itemName newItemName and public class ItemRandomizer List lt Item gt itemContainer new List lt Item gt () public void AddItem(Item item, int amount) for (int i 0 i lt amount i ) itemContainer.Add(item) public Item GetRandomItem() int index Random.Range(0, itemContainer.Count) want to return item combined with rarity return itemContainer index I want GetRandomItem to not only return a random item "type", e.g., gloves, contained in the itemContainer list, but also combine it with a rarity (common, rare, legendary) and return that if possible. How can I code this functionality in a flexible way so that two base items with the same drop chance can have varying drop chances when it comes to their rare versions? Swords and axes have the same drop chance, but a rare sword might be rarer than a rare axe. I'd like to maintain that kind of flexibility. Also, if I make public string itemRarity a property of the Item class, but I want to set the rarity tier in GetRandomItem() in the ItemRandomizer class, how should I do that? Thus far, I've almost exclusively used MonoBehaviour classes so any pointers are appreciated. |
0 | How can it be that if I click on rawimage it's getting the right file name from the hard disk ? I don't understand it In this script once only I'm getting the all the files from the hard disk type png images. using System.Collections using System.Collections.Generic using System.IO using UnityEngine using UnityEngine.Networking using UnityEngine.UI public class SavedGamesSlots MonoBehaviour public GameObject saveSlotPrefab public float gap private Transform slots private string imagesToLoad Start is called before the first frame update void Start() imagesToLoad Directory.GetFiles(Application.dataPath quot screenshots quot , quot .png quot ) slots GameObject.FindGameObjectWithTag( quot Slots Content quot ).transform for (int i 0 i lt imagesToLoad.Length i ) var go Instantiate(saveSlotPrefab) go.transform.SetParent(slots) Texture2D thisTexture new Texture2D(100, 100) string fileName imagesToLoad i MouseHover.savedGameFName fileName byte bytes File.ReadAllBytes(fileName) thisTexture.LoadImage(bytes) thisTexture.name fileName go.GetComponent lt RawImage gt ().texture thisTexture Update is called once per frame void Update() At this line I'm doing reference from another script to a public static variable MouseHover.savedGameFName fileName Then in the MoueHover script that I'm using it calling it from each raw image event trigger I'm using also the mouse button down using System.Collections using System.Collections.Generic using System.Drawing using System.Drawing.Imaging using System.IO using UnityEngine using UnityEngine.EventSystems using UnityEngine.UI public class MouseHover MonoBehaviour public SaveLoad saveLoad public SceneFader sceneFader public RawImagePixelsChange rawImagePixelsChange public static string savedGameFName public static string folder public static bool loadingwithfolder false private bool loadGame false public void OnHover() Debug.Log( quot Enter quot ) rawImagePixelsChange.modifyPixels(0.3f) PlaySoundEffect() loadGame true public void OnHoverExit() Debug.Log( quot Exit quot ) rawImagePixelsChange.restorePixels() loadGame false private void Update() if(loadGame) if (Input.GetMouseButtonDown(0)) MenuController.LoadSceneForSavedGame false loadingwithfolder true folder Path.GetDirectoryName(savedGameFName) StartCoroutine(sceneFader.FadeAndLoadScene(SceneFader.FadeDirection.In, quot Game quot )) loadGame false private void PlaySoundEffect() transform.GetComponent lt AudioSource gt ().Play() At this line if (Input.GetMouseButtonDown(0)) After clicking the mouse left button inside I'm using a break point on one of the lines and I see that the variable savedGameFName contains the correct clicked raw image full directory with the file name, for example d screenshots screen 1920x1080 2021 01 26 18 56 46.png But how does it know to assign to the variable savedGameFName the correct file name of the clicked raw image? It's not a list or something, it's just public static string variable. and the only other using is in the first script when running the game once first time. I don't understand it. It's working fine!!! but I don't understand how. |
0 | Unity 3D C Shifting beetween worlds? Let's say I want to replicate Planeshifting from Legacy of Kain Soul Reaver in Unity. There are 2 realms Spectral realm and Material realm. The Spectral realm is based on the Material realm, only has the geometry distorted and certain objects fade out become non interactive. In Soul Reaver, it is used as means to go to areas where you normally wouldn't be able to in Material (distorting geometry), to use other powers (such as going through grates). My question is Is it even possible at all to implement this in Unity 3D? (I would need the Scene(level) or the objects to have 2 states somehow that I could switch beetween distort to real time.) |
0 | How can I use different fonts for different objects in Unity? In Unity 3.5, I have a font that is strangely linked to four game objects. I want to put separate fonts on each object. In the Inspector, when I click on the circle icon next to the "Text" attribute, I can select a font. But, then it changes the font on the other three objects as well. I was hoping Unity would have something like a material ID from 3DS Max. If I could put a new material ID on the other objects, hopefully I could assign a new font to the text mesh. Regardless, is there a way to assign a different font to each of my objects? |
0 | Animations in Unity are not working properly I've done a few animations in Blender for my 3D character but the problem is, that they look different in Unity. It seems like the eyes are moving too much. I tried to change many things in import like rig etc. but nothing helped at all. Here are screenshots Wrong animation Good animation |
0 | Moving large group of units 1 by 1 takes too long, how can I improve this? I use use Unity's own NavMesh AI system and I think it works pretty well. The only problem I have is that when I move large groups of units, they will find a path one by one, but it takes a really long time as you can see in the video https gfycat.com blankhalfdartfrog To set destinations I use this public bool SetDestination(Vector3 point) if (SamplePosition(point)) agent.SetDestination(point) return true return false I know I could wait until they all have pathPending false, but that would mean the entire group moves with a huge delay. Is there some way I can improve or fix this issue? Edit It is quite simple to recreate (if you have some basic knowledge on Unity NavMesh) simply create a "click to move" script that moves a List of units to where you clicked using the code above (just fill the list in Start on each unit). Put down a few obstacles and you're done. |
0 | can't make my unity character move so I'm starting with Unity , I followed the john lemon tutorial , and I wanted to apply what I learn on a model on my own coming from blender. Everythings works , animation , rotation , but not translation . For some reasons my character doesn't move at all . It might have to do something with root motion since I have apply root motion in grey with written just after "handled by script" . Not sure what to do .. I found something about character in place, I think I'm in this case but I'm not sure how to use it in my script .. https docs.unity3d.com Manual ScriptingRootMotion.html If you ask I'll give you my project . EDIT ok so I made some advances void OnAnimatorMove() m Rigidbody.MovePosition(m Rigidbody.position m Movement m Animator.deltaPosition.magnitude 10000) m Rigidbody.MoveRotation(m Rotation) Debug.Log("m Animator.deltaPosition.magnitude " m Animator.deltaPosition.magnitude) m Animator.deltaPosition.magnitude is actually always equal to 0 , explaining why my charachter doesn't translate but why is it always equal to zero ? |
0 | Populate triangles array when you already have sorted vertices array Input is a Vector3 of verticies. Length is unknown, it could be anything above 2 so these vertices form all kinds of multifaceted shapes with 3 being a triangle and 6 hexagon ish. Poor example to visualize vertices Vector3(..), Vector3(..), Vector3(..), Vector3(..), Vector3(..) Coordinates in that array are ordered counterclockwise. I also have the coordinates of center point that these verticies form (look at illustration below) it doesn't have to be used but if it helps.. Few examples of which shapes can occur and which cannot Now I need to build meshes out of them. For each shape I need Vertices array (which I already have, nicely ordered) Triangles array 3 indices (from vertices array) per triangle until all vertices are covered How to populate triangles array with these relatively easy shapes where each vertex has "direct line of sight" to every other vertices? Number of vertices is unknown of course. |
0 | New clients don't see objects spawned before they connect I'm making a game with UNet where the server must create some objects when he connects to the game, and all clients play with these objects that the server has created. A server connects to the game In his start method he calls a function CmdbuildEverything to spawn some objects to the game. A local player connects to the game. The local player should be able to see the objects that the server player has created. The code public class GameScript NetworkBehaviour void Start() if(base.isServer) CmdbuildEverything() Command void CmdbuildEverything() GameObject ob1 (GameObject)Instantiate(Resources.Load("Temple"), new Vector3(0, 0, 1), Quaternion.identity) GameObject ob2 (GameObject)Instantiate(Resources.Load("Temple"), new Vector3(0, 1, 0), Quaternion.identity) GameObject ob3 (GameObject)Instantiate(Resources.Load("Temple"), new Vector3(1, 0, 0), Quaternion.identity) NetworkServer.Spawn(ob1) NetworkServer.Spawn(ob2) NetworkServer.Spawn(ob3) The problem is that the objects are created only on the server player and don't appear on the clients payers. How can I solve that? |
0 | Textures in Unity3D appear with lower quality than in Photoshop I made game assets that look great in Photoshop, but they look like crap when I import then into Unity and run the game. Why? |
0 | Objects stick together on Collision I have a ball which has CircleCollider2D attached to it. It is also rigidbody. When it lands on a platform, it jumps . The platform is static, with Edge Collider attached. It also has a platform effector attached with quot Use One Way quot selected. Most of the times it works fine, but some times, the ball lands on the platform and instead of bouncing, just sits on the platform. When ball lands on the platform, following code is executed rb.AddForce(upForce, ForceMode2D.Impulse) upForce is Vector2(4,10) image shown below Why is this happening? |
0 | Rotation smoothing with Slerp snaps to center when switching between different destination vectors I'm making a 3D space shooter in Unity (think Star Fox). The ship, when I move it around the map, should rotate slightly (smoothly) in the direction I'm controlling it. I have smoothness mostly working. When I press an arrow key, the ship banks in that direction, and when I release it, it smoothly returns to the default rotation. However, if I quickly change the direction it's rotating before it has the chance to get back to the default rotation, instead of rotating from "banking left" to "banking right", for example, it instantly snaps to the default rotation before beginning the smooth rotation. Here's what it looks like In addition, when I connect a joystick (instead of using arrow keys) to control the ship, I get a different problem The ship has literally no smoothing at all, rotating one to one with the direction the joystick is rotated in. Here's what that looks like Here's the code that controls ship movement public bool inverted true public float speed 20 speed modifier of horizontal vertical movement public float rotSpeed 120 speed modifer of rotation (ship tilting) public float ZRotMax 30f public float YRotMax 50f public float XRotMax 30f public float width 30 public float height 15 public float centerDriftStrength 5 lower is stronger, higher is weaker. Update is called once per frame void Update () Get input float controlHorizontal Input.GetAxis("Horizontal") float controlVertical (inverted ? Input.GetAxis("Vertical") Input.GetAxis("Vertical")) Add mild center drift float moveHorizontal controlHorizontal ((transform.position.x) (width centerDriftStrength)) float moveVertical controlVertical ((transform.position.y) (height centerDriftStrength)) Modify position transform.position (new Vector3(moveHorizontal, moveVertical, 0) speed Time.deltaTime) Cosmetic rotation based on controller input Quaternion oldRot Quaternion.identity Quaternion newRot Quaternion.Euler(XRotMax controlVertical, YRotMax controlHorizontal, ZRotMax controlHorizontal) transform.rotation Quaternion.Slerp(oldRot, newRot, Time.deltaTime rotSpeed) In particular transform.rotation Quaternion.Slerp(oldRot, newRot, Time.deltaTime rotSpeed) Seems to be what I need to look at. rotSpeed should cap the speed of rotation on the ship, so that it can't instantly rotate in a different direction. Right now, when rotSpeed is less than 120 or so, the ship twitches while rotating, and if it's particularly low, like 10, the ship barely rotates at all. (The rotSpeed variable doesn't seem to be working anyways setting it to 30000 or something doesn't make the rotation any faster.) Basically, I want the ship to always rotate smoothly, never jumping instantly from one rotation to the next. I'm not sure if I need to use Slerp for this, or if there's some better smoothing method available to Unity. Thanks, and if anybody knows of other ways to smooth rotation between constantly changing Vector3s Quaternions, please tell me! |
0 | Implementing DirectX 7 light attenuation in Unity's Universal Render Pipeline I am create a modern Unity based client of an old MMO from 2000, and I am working on implementing their lighting system. Based on the data I have reverse engineered, it looks like they used a custom attenuation formula. The original client uses DirectX 7. I have found a reference sheet for DX7 light. http developer.download.nvidia.com assets gamedev docs GDC2K D3D 7 Vert Lighting.pdf The relevant info starts at page 17. In the URP, in Lighting.hlsl, I have set up linear attenuation float range rsqrt(distanceAndSpotAttenuation.x) float dist distance( positionWS, lightPositionWS) half attenuation 1.0f dist range Looks good! https i.imgur.com 5bfJ5fF.png Everything looks good. Now I am trying to (based on the document) recreate the same linear attenuation. It should look something like this DX 7 float range rsqrt(distanceAndSpotAttenuation.x) float dist distance( positionWS, lightPositionWS) half c0 1.0f half c1 1.0f half c2 0.0f half d dist range half attenuation 1.0f ( c0 c1 d c2 d d ) This should give me linear attenuation according to the doc, but it ends up bleeding light way past the range of the light. So I am convinced the distance is wrong. What kind of value is expected here? Normalized distance? It doesn't specify. I have played around with the distance a lot. Set it to the attenuation in the first code example, to the raw value, and a bunch of other values. No luck https i.imgur.com JWJ0HF2.png Does anyone have any ideas? |
0 | Duplicating actor in Unity New to video game development and im working in unity on a Mac right now. I also have been using unreal on my pc figuring them both out. Im trying to (in unity) quickly copy prefabs by dragging them to different spots on mac? Basically the unreal engine equivalent to Alt dragging your actor on windows. I've tried looking it up and shortcuts dont help and randomly pressing buttons and dragging is getting me nowhere fast |
0 | How to use a sprite mask or shader to mask a text? I'd like to know what I need to learn to apply a shader to achieve masking on the text. Here is my text object in game, I'm using a sprite mask to mask the game objects on the card, they're all in their own sorting layer, the order number is 11. Here is my text in the inspector However, everything on the card is being masked except the text. If someone could tell me what I need to learn to solve this problem that'd be great, can this problem be solved using a shader? |
0 | Making animations not smooth while using Record button In my 2D sidescroller game, I want to separate the animations for the head and the body of my character. While idling, my charcter's body bounces slightly up and down (kind of a breathing motion). Thus, the head should keep up. However, when I press Record and make adjustments for the head, the head moves up and down smoothly instead of following the body frame by frame. How can I remove the smooth transitions from one position to the other? Here is a screenshot from Unity demonstrating the hierarchy and the animation keyframes. |
0 | Constraining camera bounds within bounds based on Unity UI object dimensions I have a perspective camera which has bounds which I wish to constrain within larger bounds. All the bounds are calculated in world space. The code for containing the camera within the constraining bounds is straightforward var camRect this.cameraComponent.GetCameraWorldRect() var correction Vector3.zero if (camRect.xMin lt constrainingRect.xMin) correction.x Mathf.Abs(constrainingRect.xMin camRect.xMin) if (camRect.xMax gt constrainingRect.xMax) correction.x Mathf.Abs(constrainingRect.xMax camRect.xMax) if (camRect.yMin lt constrainingRect.yMin) correction.y Mathf.Abs(constrainingRect.yMin camRect.yMin) if (camRect.yMax gt constrainingRect.yMax) correction.y Mathf.Abs(constrainingRect.yMax camRect.yMax) this.cameraComponent.transform.position correction This can be visualized as The problem I am facing is that I have a UI object that is covering the right hand side of the screen and I am uncertain how to correctly calculate the width of the UI object so that the constrained camera bounds can take it into account. The camera that is drawing the UI object is configured as follows The camera that is being constrained is configured as follows Apart from the layer, the parameters which affect the rendering of the objects for each camera configuration are the same. The UI object has the following configuration with a Canvas Renderer This is how I am currently attempting to calculate to width of the UI object but given that the UI is being rendered using a perspective camera I wasn't too certain that ScreenToWorldPosition was correct. private float CalculateMenuWidth() Generate padding to account for the side menu var canvas LevelEditor.Instance.Menu.GetComponentInParent lt Canvas gt () var menuRect LevelEditor.Instance.Menu.GetComponent lt RectTransform gt () var menuRectMax menuRect.rect.max canvas.scaleFactor var menuRectMin menuRect.rect.min canvas.scaleFactor if (this.cameraComponent.orthographic) return Mathf.Abs(this.cameraComponent.ScreenToWorldPoint(menuRectMax).x this.cameraComponent.ScreenToWorldPoint(menuRectMin).x) Perspective camera requires distance for ScreenToWorldPoint var distance Mathf.Abs(this.cameraComponent.transform.position.z) return Mathf.Abs(this.cameraComponent.ScreenToWorldPoint(new Vector3(menuRectMax.x, 0f, distance)).x this.cameraComponent.ScreenToWorldPoint(new Vector3(menuRectMin.x, 0f, distance)).x) However, the size of menu returned by the method above appears to be too large. How can I correctly calculate the width of the UI object so it appears that the camera constraints do not allow the camera to travel past the UI object? EDIT I've added a link to a Unity project which is the minimal working example for reproducing the issue. https www.dropbox.com s mq36mfqz5wvvsch CameraConstraintGUIIssue.zip The camera can be controlled with WASD to translate and the Shift key will speed up the movement. The camera is constrained inside the checkerboard. An offset is created so that the camera should stop moving to the right once the right edge of the checkerboard is adjacent to the left edge of the menu. Unfortunately, I can't seem to calculate the size of the menu correctly so this occurs. The code for constraining the camera and calculating the menu size is in EditorCamera.cs. Edit2 The constraint from KingDolphin The constraint I am attempting to calculate (quoted from above, An offset is created so that the camera should stop moving to the right once the right edge of the checkerboard is adjacent to the left edge of the menu.) |
0 | How can I override OnTriggerEnter? I am trying to extend Unity's BoxCollider class. So I am extending it in the editor like such using UnityEditor using UnityEngine CustomEditor(typeof(BoxCollider)) public class MyBoxCollider Editor public override void OnInspectorGUI() EditorGUILayout.LabelField("My Box Collider") base.OnInspectorGUI() However, I cannot figure out how to override OnTriggerEnter, OnCollisionEnter, etc. How can I override these? They appear to be declared as private in the base class. My end goal is that when I add a BoxCollider to a GameObject, it has a label in addition to its normal stuff. Then when BoxCollider's OnTriggerEnter method is called, it prints out what the label says before continuing on about its business. (This is a simplification, but I think it helps clarify my objective.) |
0 | Scaling material texture to be 1pixel 1 unit I have a mesh I use to render a sprite texture I set up in a material. This mesh is planar XY aligned and stationary. It's vertexes are generated from a PolygonCollider. The problem is that I'm using 1 PPU in the rest of my sprites, but the sprite rendered in the texture looks extremely small. How can I make the scale of the texture's material, so the size of a pixel in the material is equal to 1 unit? I can't just scale it, because I need it to be EXACTLY 1 unit. |
0 | Automated performance testing I'm wondering if there's anyway of automatically testing the performance of my game on multiple configurations because I know a game runs well on my computer but how do I know how well my game performs over a variety of hardware? Do I just simply have to rely on player feedback? |
0 | 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) |
0 | Difference between unity scripting backend IL2CPP and Mono2x IL2CPP is a Unity developed scripting back end which you can use as an alternative to Mono when building projects for some platforms. Note IL2CPP is only available when building for the following platforms Android AppleTV, iOS , Nintendo 3DS, Nintendo Switch, Playstation 4 Playstation Vita, WebGL ,Windows Store, Xbox One I have a project(unity 5.2) which has switched for Android deployment. I tried to switch my scripting backed from Mono2x to IL2CPP and its showing me that IL2CPP on Andriod is experimental and unsupported So, my simple question is that if it is still not supported then why the option has included, what is the fundamental difference between IL2CPP and Mono2x. Why I switched to IL2CPP scripting backend ? what are its pros and cons? I have also checked in unity 5.5.2 there is not IL2CPP option in windows platform deployment. |
0 | Unity 3D move kinematic rigidbody I'm trying to move a kinematic rigidbody (a spaceship) with this code float xSpeed 0.0f float ySpeed 0.0f float zSpeed 30.0f Vector3 moveDirection transform.right xSpeed transform.up ySpeed transform.forward zSpeed ShipRigidBody.MovePosition(ShipRigidBody.transform.position moveDirection Time.deltaTime) but moving the ship using ShipRigidBody.MovePosition makes it go through other objects with kinematic rigidbody. The collision detection of both objects is continuous dynamic and works for both other rigidbody objects and the object with the character controller. I've tried not using a kinematic rigidbody for the ship but when it gets hitted by projectiles (with rigidbody) it moves and starts spinning around. So my questions here would be Should I use a rigidbody for the NPC ship or use a character controller? There is any way to prevent a rigidbody from move after collision of other rigidbody, besides making it kinematic? How can I move a kinematic rigidbody so it doesen't go through other kinematic rigidbodies? Thanks for your help! |
0 | How to make UI Button to rotate an gameobject? I'm trying to make a button to make a gameobject rotate and stay rotating in its own axis (Y) but I cannot make it work... As far as I know it's very simple Create an empty gameobject (or whatever you want) Make a script and attach it to the gameobject Create public methods Link the gameobject with the script attached to the button onClick event Click the button and test the script My problem is that I don't know how I'm wrong here are the scripts of my project This first script is my attempt using keys, and it works like charm using System.Collections using System.Collections.Generic using UnityEngine public class TurntableRotation MonoBehaviour public GameObject turntable public float turnSpeed public bool canRotate false void Start () void Update () StartTurntableRotation() StopTurntableRotation() public void StartTurntableRotation() if (Input.GetKey(KeyCode.I)) canRotate true if (canRotate) turntable.transform.Rotate(Vector3.up turnSpeed Time.deltaTime) public void StopTurntableRotation() if (Input.GetKey(KeyCode.P)) canRotate false if (!canRotate) turntable.transform.Rotate(0,0,0) This second script is my work in progress using System.Collections using System.Collections.Generic using UnityEngine public class TurntableUIBtns MonoBehaviour public GameObject turntable public float turnSpeed This is my public method used by the button public void StartTurntableBtn() This is my attempt to write the code for the object to rotate turntable.transform.Rotate(Vector3.up turnSpeed Time.deltaTime) As far as my knowledge goes, it is supposed to work, but I have to click every time to rotate my object, my goal is to click the button and make the object rotate and stay rotating |
0 | Auto generate optimal direction for Unity Raycast with specifications How can I have a Physics.Raycast auto generate a direction for itself to try to hit a given target through a restricted window of space? Update After much work, my problem has slightly morphed into one about mesh colliders given a (convex) mesh collider, how can I detect all of the points intersecting with the collider? Or, if this can be done easily, can I get one Vector3 per object that is within the mesh collider? Update This is kind of a long question, so I'll try to explain it the best I can I have 3 GameObjects a source, a target, and a "window". This window sits between the source and target. I want the source to make a raycast that points in the direction of the target (not necessarily it's transform.position, just a direction that will make it hit the target) and this raycast must pass through (collide and continue through) the window GameObject I would like to automatically generate this direction for the raycast to follow such that 2 happens I would like this algorithm to also recognize if the above is not possible As an added item, I would like this raycast to pass through (collide and continue through) any objects that may be in it's way between it and the window Here's an image describing my issue in more detail How can I accomplish this? Thank you for your help in advanced! |
0 | ScriptableObject not working after build in Unity? I have a GameObject with a ScriptableObject on it, stats. It works fine in editor but when I try to build I get a message, A script behaviour (script unknown or not yet loaded) has a different serialization layout when loading. What is wrong here? |
0 | Idle Walk animation problem and double button input axes I have 2 problems with unity3d. First, I created an animator and attached it to player. In animator I put 2 condition, Speed and Running (first is float, second is boolean). Default Animation is Idle. Then player press W, I want animation to fade from idle to walk and when he stop press the button, I want the animation to fade from walk to idle. Here is my problem. When I press W, he make walk animation, but after it he play half of idle animation and after it he enter again in walk animation. How can I loop the walk animation until he release W? And if he release, even if the animation isn't totally played, I need the animator to make transition to idle. How can I make this "transition"? Then I release W, he just go from walk to idle animation without any transition (and it is a kind of wear). Second, How can I put 2 input buttons on axes? I mean If he press W, there should go vertical axes. When he press W Left Shift, there should go running axes. How can I attach 2 buttons to 1 axes? I am new in unity and I want to figure out how to work with this things. |
0 | Unity RectTransformUtility.ScreenPointToLocalPointInRectangle What does the unity's RectTransformUtility.ScreenPointToLocalPointInRectangle do I've read unity documentation but I didn't get the clear meaning. |
0 | UNET start game with friend by finding their name, Android There is a game at the google play store called Fun Run 2 Multiplayer Race. I loved its feature to find friends by writing their names, and then to play with them. Is it possible to achieve that with UNET? How? Another one is called Virtual Table Tennis. There I have a lobby full of people from whom I can choose. Can I achieve that with UNET? How? |
0 | 2D diagonal movement using Rigidbody2D I have a problem with 2d player movement, as I am unable to move on the Y axis. Yet, the movement on the X axis is working as intended. Below, you can see my code public Sprite directionUp public Sprite directionDown public Sprite directionLeft public Sprite directionRight public float speed 0.1f public byte direction 0 0 up, 1 right, 2 down, 3 left private SpriteRenderer spriteRenderer private Rigidbody2D rb2D private Sprite directionArray Use this for initialization void Start () rb2D GetComponent lt Rigidbody2D gt () spriteRenderer GetComponent lt SpriteRenderer gt () directionArray new Sprite directionUp, directionDown, directionLeft, directionRight if(directionArray 0 ! null) spriteRenderer.sprite directionArray 0 Update is called once per frame void Update () if (Input.GetKeyDown(KeyCode.Keypad7)) rb2D.MovePosition(rb2D.position new Vector2( 1f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 2 else if (Input.GetKeyDown(KeyCode.Keypad9)) rb2D.MovePosition(rb2D.position new Vector2(1f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 3 else if (Input.GetKeyDown(KeyCode.Keypad1)) rb2D.MovePosition(rb2D.position new Vector2( 1f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 2 else if (Input.GetKeyDown(KeyCode.Keypad3)) rb2D.MovePosition(rb2D.position new Vector2(1f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 3 else if (Input.GetKeyDown(KeyCode.W) Input.GetKeyDown(KeyCode.Keypad8)) rb2D.MovePosition(rb2D.position new Vector2(0f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 0 else if (Input.GetKeyDown(KeyCode.S) Input.GetKeyDown(KeyCode.Keypad2)) rb2D.MovePosition(rb2D.position new Vector2(0f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 1 else if (Input.GetKeyDown(KeyCode.A) Input.GetKeyDown(KeyCode.Keypad4)) rb2D.MovePosition(rb2D.position new Vector2( 1f, 0f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 2 else if (Input.GetKeyDown(KeyCode.D) Input.GetKeyDown(KeyCode.Keypad6)) rb2D.MovePosition(rb2D.position new Vector2(1f, 0f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 3 By the way, please keep in mind I am quite new to Unity. EDIT 1 I have attached the entire script, some of the variables are unused right now(was testing other methods of movement). I tried to both Keypad 1, 3, 6, 9, as well as the combinations which I didn't get to work yet (but this is off topic and I will look into it once I will get the Y axis to move). Thanks, Zryw |
0 | Unity How does Time.smoothDeltaTime work I can't seem to find any actual information on what Time.smoothDeltaTime does or how it works. I would assume it takes a rolling average of previous deltaTimes but how does it do that? Is the average asymptotic? How sensitive is it to outliers? What is it's actual intended use case? If anyone could explain how it works, or link to a resource on what it is doing it would be really helpful. |
0 | Unity error after adding skybox material So I added the night material from the fantasy skybox asset I download from the asset store and the rest of my objects turned white for some reason I figured it was just a glitch like the light baking and it would be okay when I deployed my project Well I saved and built my project as usual and the objects all turn pink as if their materials did not exist and every time I go to play the game I receive the following error 'Assets Build ParcoreBeast Data Managed Assembly CSharp.dll' shouldn't be queried by IsAssemblyCompatible, missing IsInternalOrCompiledAssembly check ? UnityEditorInternal.InternalEditorUtility GetMonoIslands() UnityEditor.SyncVS SyncVisualStudioProjectIfItAlreadyExists() How do I fix this? |
0 | Coroutine not working (Unity) I made this code because I needed an image to display a couple seconds after an enemy spawns, but for some reason I can't make it work. There's no error in the console, but it doesn't display the image and I don't know what to do. Here's my script (it's attached to the enemy prefab) public class enemyAttack MonoBehaviour public float time 5f private IEnumerator coroutine public Image image private float t 5f void Start () image.gameObject.SetActive (false) image.enabled false coroutine nombredeCorutina (time, image) StartCoroutine (coroutine) private IEnumerator nombredeCorutina (float t, Image im) image.enabled true im.gameObject.SetActive (true) yield return new WaitForSeconds (t) coroutine nombredeCorutina (time, im) StartCoroutine (coroutine) |
0 | Calculate the starting position of a turning aircraft with inertial force to make it stop at desired position and heading Continued from the answer here, I have some problem when the aircraft in my game has inertial forces after going forward and turning itself. To illustrate, from the following image (https imgur.com a Xvqu2A7) the aircraft is moving from the point A gt B gt C' gt D. I planned to maneuver the aircraft from the point C' which is the point that would make the aircraft stop at the point D after turning with its full performance (using minimum turning radius). The question is how do I calculate the position of the point C' to make the aircraft roughly stop at the point D with the desired position and heading (It is roughly since there is also an inertial force after stopping the aircraft's engine.)? Any suggestions and answers would be appreciated. |
0 | Surface shader with VertexLit causes black object I wrote the simplest possible surface shader Shader "SimpleSurf" Properties MainTex ("Base (RGB)", 2D) "white" SubShader Tags "RenderType" "Opaque" LOD 200 CGPROGRAM pragma surface surf Lambert sampler2D MainTex struct Input float2 uv MainTex void surf (Input IN, inout SurfaceOutput o) half4 c tex2D ( MainTex, IN.uv MainTex) o.Albedo c.rgb o.Alpha c.a ENDCG FallBack "Diffuse" When the "Forward" rendering path is enabled the object looks fine! But when the "Vertex lit" rendering path is enabled, it looks became black Why it happened? How can I use surface shaders (or maybe write a Vertex Fragment shader which will consider spot lights) which do some effects in VertexLit path? |
0 | How to hide a sprite on trigger when the player enters the trigger zone? I am making a roof for my 2D top down survival game, and I want to make it so that the roof disappears when the player enters the building, and re appears when they leave. Here is the code I've written so far using System.Collections using System.Collections.Generic using UnityEngine public class Roof MonoBehaviour public GameObject roofGameObject void OnTriggerEnter2D(Collider2D collision) roofGameObject.SetActive(false) void OnTriggerExit2D(Collider2D collision) roofGameObject.SetActive(true) I got it to work so that, when I go in, the roof it disappears. But when I leave it stays disappeared. How can I fix that? |
0 | Apply transform.Translate to a specified object in the script In Unity3D, if I place a C script including transform.Translate on an object "A" in the hierarchy, it animates the translation of this object A. How in C can I apply that transform.Translate effect onto another object defined in the script itself? I want to write a script similar to this using UnityEngine using System.Collections public class Create Objects MonoBehaviour public float moveSpeed 2f public Transform otherObject void Update () if (Input.GetKeyDown (KeyCode.Q)) GameObject Object1 new GameObject ("Object1") otherObject.Translate (Time.deltaTime moveSpeed, 0, Time.deltaTime moveSpeed) But somehow I want that otherObject that I'm translating to refer to the Object1 I created when the user pressed "Q". Thanks DMGregory for your last code!... and finally, same as before but the objects are created and translated from position of each previous object creates. What is the new C code? |
0 | Can I replace the source image of slices by script? I have a Unity2D prefab that uses several slices from a single PNG. (in it sprite renderer, and in its animation clips). If I replace that PNG in the Finder, all slices taken from that PNG are automatically updated, which is great. But I want to do this by script just replace the PNG where all slices are taken from, with another PNG. This is so that each of my prefabs instances can all use a different spritesheet PNG source for its slices. Is this possible in Unity? |
0 | Add Atten property in Unity Shaderlab In Unity Shaderlab shader, Is there any way to apply Atten value? Using surface shader, and vertex fragment shader I can do it easily. But, I didn't find any reference to do that in Shaderlab syntax. Shader "Diffuse" Properties Atten ("Light Attenuation Power", Float) 1.0 lt how to apply? Color ("Main Color", Color) (1,1,1,1) MainTex ("Base (RGB) Transparency (A)", 2D) "" SubShader Pass SetTexture MainTex constantColor Color combine texture constant, texture constant this makes syntax error. constantColor Atten Color |
0 | How to resolve push block physics in a 2D side scroller puzzle I've been working on a 2D tile based side scroller puzzle game in Unity with obstacles such as doors, keys, fans, portals, etc., but one type of obstacle, push blocks, is giving me some issues. Here is how it is supposed to work The player (an certain other obstacles) can push the block from either side, and it should move smoothly until it is either blocked by another obstacle or there is no ground beneath it If it is pushed off an edge, it should fall into whatever hole is there, even if it is a snug fit. (left picture) The top of the block should be flush with other blocks or surfaces when they are at the same level of height. There are no slopes in the tileset, so this would happen often. Motion across the combined surfaces should be smooth, with no way to wiggle between adjacent blocks. (right picture) It must be able to respond to other forces in the game such as fans and gravity switches. I have been using Unity's built in physics engine, which has worked great for all other components of the game, but sometimes allows blocks to jump over holes, and sometimes blocks get stuck between other blocks when they shouldn't, so I have tried abandoning Unity's physics and made my own. It just made the rest of the game more glitchy and still failed to resolve the block problems. If I change just the way the blocks physics work, I may be able to lock its position to a grid, where it cannot be left between tiles. That way I could get the more snug collisions to work. If I did this though, it would cause problems with the rest of the interactions. A floating block with a fan underneath it bounces around too much to be locked to a grid. Does anyone know a design that would allow all these requirements of be met? |
0 | nullObjectException in OnDrawGizmos Function I was studding A Algorithm and it is showing a nullObjectException in my OnDrawGizmos function whenever it finishes compiling the code. Here is my code can anybody tell me what I am doing wrong? using System.Collections using System.Collections.Generic using UnityEngine namespace PathFinding public class Grid MonoBehaviour public Transform Startpostion public LayerMask Layer Mask public Vector2 gridWorldSize public float nodeRadius public float Distance public Node , grid float NodeDiameter int GridSizeX, GridSizeY public List lt Node gt FinalPath private void Start () NodeDiameter nodeRadius 2 GridSizeX Mathf.RoundToInt (gridWorldSize.x 2) GridSizeX Mathf.RoundToInt (gridWorldSize.y 2) GridCreator () void GridCreator () grid new Node GridSizeX, GridSizeY Vector3 bottomLeft transform.position Vector3.right gridWorldSize.x 2 Vector3.forward gridWorldSize.y 2 for (int y 0 y lt GridSizeY y ) for (int i 0 i lt GridSizeX i ) Vector3 WorldPositionOfCurrentNode bottomLeft Vector3.right (i NodeDiameter nodeRadius) Vector3.forward (y NodeDiameter nodeRadius) bool Wall true if (Physics.CheckSphere (WorldPositionOfCurrentNode, nodeRadius, Layer Mask)) Wall false grid i, y new Node (Wall, WorldPositionOfCurrentNode, i, y) private void OnDrawGizmos () Gizmos.DrawWireCube (transform.position, new Vector3 (gridWorldSize.x, 1, gridWorldSize.y)) foreach (Node n in grid) if (n.is Wall) Gizmos.color Color.white else Gizmos.color Color.yellow if (FinalPath ! null) if (FinalPath.Contains (n)) Gizmos.color Color.red Gizmos.DrawCube (n.postion, Vector3.one (NodeDiameter Distance)) |
0 | How to connect a 3D head to a body? I am new to Unity, game making, etc. I have downloaded the trial version of Avatar Maker and a similar Unity plugin called Didimo Editor, with the hope of using their features to make game characters that look like real people, using photographs. They both do more or less what I want. However, both tools output only heads, and do not connect them to 3D bodies. Avatar Maker has another plugin that allows for this, but it is only for male bodies and most of its features are not to my liking. So my question is how can I put these heads on working 3D bodies? The trailer for Didimo Editor seems to confirm that it can, at least, and Avatar Maker is able to export its heads to OBJ, FBX and Prefab, so I'm assuming maybe there is a way to do that too. |
0 | Problem with Raycasting in a 2D Game I'm new to using unity and came across a problem when I was following a tutorial. The game is in two dimensional space, and when my player walks over a certain tile the detection never goes off. Here's the code that I have, function calculateWalk() yield WaitForSeconds(0.3) var hit RaycastHit if(Physics.Raycast (transform.position, Vector3.down, 100.0)) Never evaluates to being true var distanceToGround hit.distance Debug.Log("Hit") if(hit.collider.gameObject.tag "tallGrass") walkCounter Debug.Log("Tall Grass") END if END if END calculateWalk() I've made sure to attach the script to my player, as well as tag the tiles that I want with "tallGrass". I've followed what was done in the tutorial, but for some reason it's not working out for me, not sure if this is all the code needed to help solve this problem, if more information is needed let me know, I also set my player 1 unit above the tiles. |
0 | 2d games unity vs Flash do people find unity better than flash for 2d games while unity is 3d engine , or Flash still better because it's made for 2d games and flash can get the job done faster ,and now flash is better for ios android 2d games . so what platform is the best for 2d games? |
0 | Collider Effeciency Question I'm creating a game where hundreds of rockets with colliders attached are shooting at a player. Should I write my script where 1 The player script reads the collision from hundreds of rocket colliders or 2 Each rocket collider updates information when colliding with the player Thanks! |
0 | Make a light only affect one object I'm wondering if it's possible to make a light source only affect one object? I know that it's possible to use layers and culling mask, but then I would need one layer for every single object which is not possible. Is there a way for example that I could make only children or siblings be affected by a light source? Or other solution? Have a nice day! Update 1 |
0 | How to load values into a script from a file? I have a prefab of a "generic unit " each one has a script with some public variables name, health, and attack. Currently, I am manually making copies of that prefab and editing their names, health and damage values in the inspector. This seems unwise to me. I would rather be able to make a simple file for each unit type, containing its important information, like this name "Archer" health 3 attack 1 And so on. Then, I would like to be able to turn that into actual GameObjects in Unity, presumably by instantiating the prefab and filling in its values with values from the file. I could then make a script that runs when the game begins and iterates through, making all the objects I need. However, I do not know the proper way to go about doing this. Is there some way to read files and slot values into variables of a script? To be clear, I would like to be able to tell Unity to make an Archer, then have it read the Archer file, look up its values for health and attack, then instantiate a copy of the Generic Unit prefab and slot the values that it read into the public variables of a script component of the newly created game object. |
0 | How to throw a ball vive controller object in unity3d I have this simple line of code that through the ball. Under arm throw is right while if i try through any else ways its through movement is weird like a curve from down to up. what i am doing wrong. how do i through the ball using controller (touchingObject) object direction correctly realistically. Additionally i am also encounter a problem that if i through one ball all the previous throw balls move in that direction also. what the heck is that? gameObject.GetComponent lt Rigidbody gt ().AddForce(touchingObject.transform.forward 1000) |
0 | How can I adapt A pathfinding to work with platformers? I have an A implementation that works in "top down" situations where gravity is not taken into account for pathfinding. But, I am looking to modify to work in a 2d platformer situation. I am using the Unity Engine in C but any examples or even pseudocode would be really helpful. I have found a source so far but it haven't been that helpful as I am not understanding the way they have adapted A , I have listed them below. http gamedevelopment.tutsplus.com tutorials how to adapt a pathfinding to a 2d grid based platformer theory cms 24662 (Very specific to authors implementation and hard to understand) |
0 | How to make child object a member of two parents in unity? So I have an parent game object that has multiple objects. This format is desirable GameObject object1 (abstract) subobject1 object2 (abstract) subobject2 object3 (abstract) subobject1 subobject2 There are two objects in the scene, subobject1 and subobject2 The problem is when i drag and drop one subobject from an object it removes it from the other object. When i copy the subobjects to another object, there are now two. I hope this makes sense. |
0 | What causes this graphics quality difference between WebGL Build and Unity 5 Editor? The Editor version and WebGL version of my Minesweeper clone have some graphics quality differences. I chose 'Fast' option when building this deployment. Is this the difference between 'Fast' and 'Fastest' options of Optimization Level in Build Settings, meaning that if I choose the 'Fastest' option, the WebGL deployment will be the same as Editor version, unlike below? If not, why this happens? |
0 | Override the position of bodypart with script on top of animation I have a character with an Idle and Move animation. Now I want to create an Attack animation. Here I want the hand to move towards the mouse position and back, using a script. The other hand should still follow the Idle or Move animation. When I use a script in FixedUpdate() to do this the position of the hand still follows the animation. If I use LateUpdate() and set hand.transform.position, this seems to represent the local position and not global position. Is there a proper way to create this Attack animation? using UnityEngine public class Attack MonoBehaviour public Camera camera public Transform body public Transform hand public string button public float time 5f public float begin 3f public float end 6f float step 0f bool pressed false float currentTime 0f int direction 1 private void Start() step (end begin) time private void Update() if (!pressed amp amp Input.GetButtonDown(button)) pressed true private void LateUpdate() if (pressed) setCurrentTime() Vector2 mouse camera.ScreenToWorldPoint(Input.mousePosition) Vector2 direction (mouse (Vector2)body.position).normalized hand.position (Vector2)body.position direction (begin (step currentTime)) void setCurrentTime() currentTime currentTime direction Time.deltaTime At End if (currentTime gt time 2) float overhead currentTime (time 2) currentTime currentTime overhead direction 1 Back at Begin if (currentTime lt 0f) pressed false currentTime 0f direction 1 |
0 | How to make a rigidbody come to rest faster I'm trying to move around a 3D rigidbody in Unity 2018.1.0f2 Personal. I am using a C script with the basic vector3 and velocity stuff from a YouTube video using System.Collections using System.Collections.Generic using UnityEngine public class Player MonoBehaviour SerializeField private Rigidbody playerBody private Vector3 inputVector private float xMovement private float zMovement SerializeField private float playerSpeed private float maxSpeed Use this for initialization void Start () playerBody GetComponent lt Rigidbody gt () playerSpeed 1 Update is called once per frame void Update () xMovement Input.GetAxisRaw("Horizontal") playerSpeed zMovement Input.GetAxisRaw("Vertical") playerSpeed inputVector new Vector3(xMovement, playerBody.velocity.y, zMovement) playerBody.velocity inputVector It works great with a cube I put it on, except for this if I move the rigidbody and then stop, it takes a long time for it rotate from go only one of the edges or corners just touching the ground (screenshot of what I mean, another screenshot) to resting flat. How can I make it fall back to stability faster? |
0 | Texturing different block types on an optimized voxel mesh I have a cubic world (like Minecraft) where I'm generating chunks. In those chunks, only visible vertices and faces are generated. Currently, it means that if I have a 2x2x1 chunk, it will generate 8 triangles for the top part (2 for each block). I'm trying to generate only two following this greedy meshing method If I combine adjacent faces together, I'd still like to be able to draw transitions in materials between adjacent blocks, something like this As you can see it has 3 different tiles grass, dirt grass transition, and dirt. Currently, my shader looks like this Shader quot MultiTexture Diffuse Worldspace quot Properties Color ( quot Main Color quot , Color) (1,1,1,1) TexAbove ( quot Above texture quot , 2D) quot surface quot TexSide ( quot Side texture quot , 2D) quot surface quot TexBelow ( quot Below texture quot , 2D) quot surface quot TexTopSide ( quot Top side texture quot , 2D) quot surface quot Scale ( quot Texture Scale quot , Float) 1.0 SubShader Tags quot RenderType quot quot Opaque quot CGPROGRAM pragma surface surf Lambert struct Input float3 worldNormal float3 worldPos sampler2D TexAbove sampler2D TexSide sampler2D TexBelow sampler2D TexTopSide float4 Color float Scale void surf (Input IN, inout SurfaceOutput o) float2 UV fixed4 c if(abs(IN.worldNormal.y gt 0.5)) UV IN.worldPos.xz c tex2D( TexAbove, UV Scale) else if(abs(IN.worldNormal.x) gt 0.5) UV IN.worldPos.yz c tex2D( TexSide, UV Scale) else if(abs(IN.worldNormal.z) gt 0.5) UV IN.worldPos.xy c tex2D( TexSide, UV Scale) else UV IN.worldPos.xz c tex2D( TexBelow, UV Scale) o.Albedo c.rgb Color ENDCG How would I modify this shader to work with faces that have been merged together? Or would I have to keep separate faces per block and handle them individually? |
0 | Low fps on Arm Mali GPU I was trying to google and understand my problem in two weeks but i am defeated, so i am asking for help. The main problem is that my custom unlit frag shader after certain amount of time on devices with mali gpu starts to drop fps i see it via fps counter in the cpu section. I dont know why in that section and not in render section, but with out this fps counter i can still feel the drop of fps. So on Samsung S4, Samsung sm t 380, xiaomi redmi note 5, samsung tab s2 is all ok, the drop was only on samsung s6 to solve the problem i just half the resolution by Screen.SetResolution function. I was thinking that drawing the full screen sprite on such a high res device is the point. Then i can test app on samsung sm t580 and the drop was there this device has low resolution than S6. I assume that the problem in arm mali gpu or i am sure in my hands. So again, i am rendering full screen with draw mode tile(countinuous) sprite with 3 textures, just changing theirs uvs in vert func and apply in fragment. This makes distorting effect. The shader show that i have 10 maths and 4 textures, yes 3 textures but i am making 4 sampling. The textures are 256x256 with repeat mode. I was trying diferrent textures compressions, dxt5, etc1 2, alpha8, R5 no effect. I was trying to different precisions half and float in different parts in shader no effect. I was thinking in alpha, so i took textures without alpha and not getting it from tex2D. Even the size of textures is doesnt matter, even if they 64x64. The dance with ZTest, ZWrite, Blend, Queue RenderType, other params no effect. My guess was that maybe on mali uv TEXCOORD0 must be only float2, not float3 or float4 no effect. I am applying Time.y and replace it with float from script no effect. Only reducing amount of tex2d in shader is working. Why? What i m doing wrong? |
0 | "SetSelectedGameobject" only highlights button on second try (Unity 2017.3) To support the use of a gamepad in the options menu I set SetSelectedGameObject and firstSelectedGameObject (which doesn't seem to do anything) to the button in the upper left, so it's highlighted. This works fine in my pause and option menus (panels that are enabled disabled) but there's also a third panel that displays the controls as an image. On this screen the first button is set as selected but it doesn't get highlighted until I go back to the pause menu and then open the "controls" screen again. The Hierarchy The ControlsPanel looks like this click All 4 buttons are set to "automatic" and they're all accessible to the gamepad but, like I said, the first one ("Keyboard") doesn't light up the very first time I access the panel. It should be like this Click on "Controls" in the pause menu ControlsPanel is enabled "Keyboard" button is highlighted Pressing right on the gamepad highlights the next button ("Controller") What actually happens Click on "Controls" in the pause menu ControlsPanel is enabled "Keyboard" button is still grey Pressing right on the gamepad highlights the next button ("Controller") Press the "Back" button ("ControlsPanel" is disabled and "PausePanel" enabled) Click on "Controls" again This time the "Keyboard" button is highlighted The "ControlsPanel" script public Image pic public GameObject controllerChoicePanel public GameObject firstControls private String controls private bool windows void Start() controls GetControls() windows GetOS() pic.sprite Resources.Load lt Sprite gt (controls) if(windows) controllerChoicePanel.SetActive(true) EventSystem es EventSystem.current es.firstSelectedGameObject firstControls es.SetSelectedGameObject(firstControls) Any idea why it would work fine in my pause options menu but not in the "Controls" one, even though I'm doing the same thing? |
0 | 2.5D UI, perspecitve view, distort objects by angle but not position Instead of thousand words, a few pictures to explain what I want to achieve How do I get the merit of UI objects rotation in perspective projection, but ignore the position of an object(as in Overlay Canvas)? UPDATE 1 Can you include an example of what your full UI or scene would look like? A usual bar which is used to hold stuff like score. Same base prefab is used for mana health and any other UI parameter on screen. But bars have different rotations, so here is one solution have a unique sprite for every special rotation and have a bunch of prefabs(nah). Or have one sprite, one prefab and set the rotation in scene(that's the way). Is there a reason you are asking for this in perspective projection? Just because I want to be able to rotate UI objects in scene and show the "depth" of rotated object. I'm not particularly stuck onto perspective projection, as long as I can achieve the "want" look without actually redrawing sprites for every unique angle. so I'm not sure what you are asking for. Are you asking how to skew an image in 2D, so that it looks like a 3D perspective projection? I know it sounds crazy, since it's obvious that in perspective looking at object which is above camera you get that "looking from down" look. And yet I feel you are onto something(and now am I), one way of thinking is actually to skew a 2D image to simulate rotation as in perspective view! |
0 | How to run different animations with same suffix for different public objects? I would like to be able to run the corresponding animation (ending with "Get" in the title) for whatever item GameObject I plug into this treasurebox. I made 2 prefabs for "item get" animations today. Both GameObjects consist of 3 sprites The image representing the item, and 2 lightray images that I enable disable in alternation to get a halo effect (see animation below). You can see the 2 prefabs and their corresponding animation components in the Project panel These next two images show how similar the animations are they even both require two of the same sprites, flareA and flareB. Here is the code I am currently using to set the state of the ItemBox GameObject and run the animations. You can see that while the itemGet prefab is public (that is, I can plug in whatever gameobject I want in the editor), line 27 explicitly calls for the animation belonging only to the turd item. using System.Collections using System.Collections.Generic using UnityEngine public class ItemBox MonoBehaviour bool disabled false private Animator anim public GameObject itemGet null void Start() anim GetComponent lt Animator gt () if (!disabled) anim.Play("ItemBoxIdleState") void OnTriggerEnter (Collider other) if (!disabled amp amp other.gameObject.tag "Player") anim.Play("ItemBoxGetItemState") GameObject itemClone Instantiate(itemGet, transform.position new Vector3(0, 0.375f, 0), Camera.main.transform.rotation) itemClone.GetComponent lt Animator gt ().Play("turdGet") Destroy(itemClone, 1.6f) disabled true How can I change line 27 (the line before 'Destroy') so that it runs the appropriate " Get" animation for whatever itemGet object I plug into the inspector? I think I am already close. I intend to make more items (not too many for now) and the animation I want to play will always be structured like "Get". UPDATE 07 29 19 I tried making a public AnimationClip object in the ItemBox script and putting that name in quotes for line 27 and thw script still works, but now I get an index error saying the animation state was not found. I don't think I can plug the name of the public variable into the .Play("") quotes and make it work I think it only worked because there is only one animation for that item anyway. I ended up removing this new variable and just keeping the .Play("") part as empty quotes and it still works. I might decide to add more animations to these item objects later so I still need to know how to specifically play the animation that ends in "Get". |
0 | Lighting large scene with dynamic lights Unity3D I am working on a game project where most of the action takes place in a large scene that is built to look like a space station. Because it is all technological and enclosed, I can't use a directional light to light the whole scene, and I need to be able to change the color of the lights for an alarm system. I can't bake the lights, because then I can't change their color, and I can't leave them all as dynamic lights, because I have about fifty spot lights, and they take up a huge amount of memory, so much so that the lights can't even render on mobile devices. Is there any way to do this without baking? I am getting about 3000 batches in the Unity Editor Stats on average, in some places it is higher. Even viewing the game in full screen in the editor makes the game run super slow because of the amount of rendering it has to do, and I have a pretty new computer. Here's a picture of my scene (As you can see, it is fairly large as you are able to see the UI box clearly from the scene editor) And here's the Stats box Here is an example of my scene in play mode UPDATE I removed the shadow casting, which isn't necessary for my project, and it improved the framerate slightly, and the batches number is smaller, averaging out at about 1500 now, but the performance still is not optimal. |
0 | Count Unity terrain size In blender? My unity terrain size is 150 150, and I want to create a plane in blender have the same size. How to figure the correct size ? |
0 | Scene dark when perspective camera is far from scenery I can't find anything about this subject in the docs or forums to know if this is normal behavior There seems to be a direct correlation between how close to the scenery my camera gets and how brightly lit the scene is. My camera is able to move up to 200 units from Vector3.zero. Here are two shots of the same piece of scenery one close up, one far away The camera is set to perspective, using deferred rendering. Things I've tried Turning off post processing Using auto expose in post processing Changing to orthographic (removes the issue, scene is uniformly bright at any distance) Changing the FOV Changing global lighting to use color rather than skybox Putting some lights at altitude This may be normal behavior amp I just havent noticed before. Can anyone confirm? Is there some way to prevent this happening? I don't want to use an orthographic camera but I do want the scene to be evenly bright at any distance from the camera. |
0 | Setting up a low res viewport to stretch in Unity I am working on porting a low res game over to Unity. In my previous engine, I had the option to set a native resolution (say, 160 x 144), and it would automatically stretch when the player entered fullscreen (with options for whether you wanted to keep the same aspect ratio, or stretch). I am having trouble figuring out how to set up something similar in Unity. I see that you can play around with resolution settings from Edit Project Settings Player. I tried various combinations of Default Is Fullscreen, Default Is Native Resolution, and Default Screen Width and Default Screen Height, but I haven't been able to get it to work. When I play the scene in the editor, the viewport is still much larger than my desired resolution. And when I Maximize On Play, the FOV is even larger. I Googled around, but couldn't find an answer that helped. Any advice? |
0 | Can Unity censor my content or invalidate my license for offensive content? If I make an offensive game can they pull my license and prevent me from selling my game? Like we're talking think of the most offensive thing you can think of you're in charge of the most efficient genocide against some specific racial religious political group, your choice... now imagine the game is mocking victims and generally being extremely rude, violent, and insensitive. Now I have no intention of making such a horrible game but I am using an extreme example to ask my question. It's not unheard of for less extreme things to get blocked by brands who didn't want to associate with them, for example I saw that Apple removed the Confederate flags from Civil War games in the App Store. Would Unity be able to prevent me from using their game engine or selling my game after I had already purchased appropriate Unity licenses and completed the game? Do they have that kind of power with their licensing model? Or would even the most extreme cases still be legally allowed to sell the content? I want to make something that may have some mildly provocative divisive content (not as offensive as say, South Park, which I know was made in Unity, but more serious than South Park) and I'm just making sure I don't get a bunch of work done and then get disappointed later, wishing I had gone with some kind of more free open engine. |
0 | How are methods like Awake, Start, and Update called in Unity? I'm developing with Unity 5 and I know that there are some methods you can use like in the code below public class MyGameElement MonoBehaviour private void Awake() private void Start() private void Update() private void FixedUpdate() and more I know what they do but I find it strange that the methods can be private. However they are not called into my code I've written. Here you've an image with code lens (I use VS 2015 Professional for coding) where you can really see that it has zero references. The second 'strange' thing for me is that the methods aren't overwritten. So my question is now is there anything that Unity has implemented into the MonoBehaviour class that the methods can call? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.