_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | How to enable the option "edit physics shape" in the Sprite Editor? I can successfully import .png files, create tilesets, and use them in my tilemaps in Unity. Thanks to DMGregory, I just learned that there exists an option to customize the Tilemap Collider 2D in the Sprite Editor, which allows me to set a custom collider for every tile instead of going through them one by one. The steps I follow while creating a tileset in Unity is as follows. Import the .png file. Open the Sprite Editor. Select the option Multiple for Sprite Mode. Select Slice from the Sprite Editor. Then, I create a Tile Palette in a folder, drop and drag my created tiles, and start creating my level. I have never encountered the option to modify the colliders tile by tile. What am I doing wrong? |
0 | Elegantly exposing properties in Unity inspector There are various game objects in my scene that share some common characteristics, so I created an interface, like so public interface IHasLimitedRangeOfMotionAlongZAxis float MinimumZ get float MaximumZ get For certain types that implement this interface, I would like MinimumZ and MaximumZ to be publicly assignable in the Unity inspector. Therefore, I would like to be able to expose these properties in Unity. I am aware that one approach is to write C scripts in the Editor folder to implement an ExposePropertyAttribute (see here). However, this approach is unsatisfactory for two reasons My solution is not co located with my Assets folder. I write my code in a separate solution, and then use pdb2mdb.exe to import my scripts into my Unity scenes. (The reason for doing this is to avail myself of C language features introduced beyond C 4.0, which nonetheless target .NET Framework 3.5.) I shall have to create a custom editor for every single type that implements the interface with publicly assignable properties. This leads to a lot of boilerplate code. Is there a more elegant approach than adding private backing fields with the SerializeField attribute for all of my public properties? |
0 | How do I connect Unity to a server backend developed in .net core? I'm currently running to a wall in my game development and I need now some discussion to clear my mind... In my mind I have a plan for some little online game (focused around clicking and idling), which I imagined could be served both on website and winapp, and in future even in mobile platforms. I have chosen C for it, build some server backend (join server, game server), but 'cause I want this server components be runned on linux, I have chosen .net core. Which is now my problem, because I'm building the game client in Unity, which only works in .net standard. My main problem now is that I have build some quot base network library quot for communication, written in .netcore with plenty of NuGet packages, which I now have implement to Unity to get it work, but there are now conflicts (the main one is that unity is using another version of System.Threading). Now I am wondering what steps should I choose nexts... There are some work behind now (but not so much, there are only some basic proceses for login and creating game worlds), so probably make that base network package compatible with .netstandard and .netcore. Or I am thinking if it isn't more suitable to choose some another technology like c and some 2D engine in it (which to choose?). What are you opinions? And what would you do in this situation? |
0 | Finding Endpoint of line in Unity I have a startpoint, magnitude(length) and direction and want to find endpoint to construct the line here is the code to make question more clear private Vector2 GetEndPoint(Vector2 startPoint, Vector2 direction, float magnitude) Vector2 endPoint some stfuff with parameters return endPoint And this is the visualization of what I want Hope I am clear enough, any suggestions is welcomed |
0 | Merging box colliders for optimization Look at the picture. The figure on the left shows the individual box colliders in green. The yellow boxes on the right are the results of the optimization of the original box colliders. What is the algorithm that makes this possible? |
0 | Skipping a loop in foreach? I'm trying to get Unity to filter through a list of nodes, but I am unsure on how to do so. This is what I have derived. foreach (TileNode z in map.nodes) int num TileNode z if(num 2 0) continue z.collider.enabled true However an error prompt states that 'z' is an unexpected symbol. Any advice on the proper syntax to deal with this will be greatly appreciated. Also, an example of how do peform filtering using LINQ will be helpful. |
0 | Unity how to check if object is fully covered by another objects (2d) I am creating an educational game for kids , and in one of the levels player must to paint animals , like in color book, so I created scene where 2 object , already colorful lion and white lion (white is above) and script, which is instantiating circle sprite masks in players touch position , how can I check if white lion is fully covered by masks and not visiable . P. S. If you have better idea for painting (like painting with brush) and checking , please say. |
0 | How to make my player move forward? PlayerMovement.cs using UnityEngine public class PlayerMovement MonoBehaviour public Rigidbody rb public float forwardForce 2000f void FixedUpdate() rb.AddForce(0,0,forwardForce Time.deltaTime) if(Input.GetKey( quot d quot )) rb.AddForce(30 Time.deltaTime,0,0, ForceMode.VelocityChange) else if(Input.GetKey( quot a quot )) rb.AddForce( 30 Time.deltaTime,0,0, ForceMode.VelocityChange) if(!Input.touchSupported) Still support PC keys if(Input.GetKey(KeyCode.D)) rb.AddForce(30 Time.deltaTime,0,0, ForceMode.VelocityChange) else if(Input.GetKey(KeyCode.A)) rb.AddForce( 30 Time.deltaTime,0,0, ForceMode.VelocityChange) else For touch devices if(Input.touchCount 1) var touch Input.GetTouch(0) var touchPos touch.position var isRight touchPos.x gt Screen.width 2f if(isRight) rb.AddForce(30 Time.deltaTime,0,0, ForceMode.VelocityChange) else rb.AddForce( 30 Time.deltaTime,0,0, ForceMode.VelocityChange) if(Physics.Raycast(transform.position,Vector3.down,0.5f) false) rb.velocity new Vector3(0, rb.velocity.y, 0) rb.constraints RigidbodyConstraints.FreezePositionZ else rb.constraints RigidbodyConstraints.None if(rb.position.y lt 1f) FindObjectOfType lt GameManager gt ().EndGame() I tried to debug am I able to click any button. Than, I noticed I got message in console. I think I am unable to add force to player. PlayerCollision.cs using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class PlayerCollision MonoBehaviour public PlayerMovement movement void OnCollisionEnter(Collision collisionInfo) Debug.Log(collisionInfo.collider.name) if (collisionInfo.collider.tag quot obstacle quot ) movement.enabled false FindObjectOfType lt GameManager gt ().EndGame() else if(collisionInfo.collider.name quot END quot ) FindObjectOfType lt GameManager gt ().CompleteLevel() void Restart() SceneManager.LoadScene(SceneManager.GetActiveScene().name) Ground Actually, now I think physics isn't working on Player. The Player object is floating. it isn't falling down. Even, it has RigidBody it's not freeze while running the game. |
0 | Reading a word list into an array I am making a simple hangman game, I have a small list of words in a .txt file separated by new lines. I put the word list into the assets folder. How can I find the path to the word list so I can use string wordlist System.IO.File.ReadAllLines("pathToFile") Or is there another solution of converting the word list into a string array? |
0 | Detect collision without reaction Okay, so this has been bugging me for quite some time now. I'm making an old school platformer type of game in 2.5D, I want objects to pass through each other, but I still want a collision to be detected. If the player gets hit by an enemy, I just want to detect a collision for receiving damage to the player, I don't want the player to move on impact, and I just want the enemy to continue moving where he was heading. I'm using rigidbodies and box colliders on my objects. First I thought using triggers combined with ignoring layers was the solution, but apparently trigger events aren't called when ignoring layers. I still want to be able to use AddForce and stuff for moving objects. Is there someway I can still utilize Unity's OnCollision... OnTrigger... Or other... for just detecting a collision and having no impact movement added when a collision occurs? Have a nice day! |
0 | Quaternion not giving correct value back. What am I doing wrong here? Right so I made a quaternion and assigned it a value but it reports back the wrong value. Here is the relevant code... Quaternion LeftTurnLimit Quaternion.identity float test 0.1f LeftTurnLimit Quaternion.Euler(test, 0, 0) Debug.Log(LeftTurnLimit) Expected result (0.1, 0, 0) (x, y, z) Result (0.0, 0.0, 0.0, 1.0) (x, y, z, w) So what am I doing wrong here? |
0 | Game testing solutions? I have a unity web browser game. Since I'm working on a small company with limited machines which are all of either 2GB RAM or 4 GB RAM with decent processors. I'd like to know if there are any web based or software 'solutions' to test the game with low configuration both hardware and network bandwidth. And, I have tried cross browser testing solutions, But I didn't see any solution with the option of testing a browser game made for the unity web player . |
0 | How do I remove specfic OptionData from Dropdown? How would I remove one of the elements from the dropdown? For example, how would I remove Sprites? Here is my code public Dropdown researchFeatureDropDown researchFeatureDropDown.options.Add(new Dropdown.OptionData("Sprites")) researchFeatureDropDown.options.Add(new Dropdown.OptionData("Scrolling 2000")) |
0 | How can I return the class as a Transform in the array instead of each property? public class TransformInfo public string sceneName public string name public Transform parent public Vector3 pos public Quaternion rot public Vector3 scale Then the method public static TransformInfo LoadTransformInfo() string jsonTransform File.ReadAllText( "d json json.txt") if (jsonTransform null) return null TransformInfo savedTransforms JsonHelper.FromJson lt TransformInfo gt (jsonTransform) return savedTransforms The return is But then when using it var test TransformSaver.LoadTransformInfo() Each item in the array contain the the TransfomInfo but instead I want it to return a Transform with already the info. So I can do for example Transform test1 test 0 Instead make a loop and assign each property from the Test to the new Transform test1. |
0 | How to load and unload objects at a certain radius from the player? I am making a procedurally generated space exploration game in unity. I'm currently generating 5000 stars in a cube of a fixed size. Each star just gets a random 3d coordinate. What I would like to do is to dynamically load and unload stars at a certain radius from the player. This would be the maximum view distance. The algorithm that does this must be working with a seed for the universe, as the stars need to be loaded in the same spot when you revisit them. My idea is something like in the amazing Space Engine. I have pretty much no knowledge of algorithms that can do this, so I ask for your help. |
0 | How do I use guilayout toggle event to check if true or false? OnGUI() for (int i 0 i lt scenes i ) GUILayout.Toggle(false, SceneManager.GetSceneAt(i).name) if (GUILayout.Toggle(true, "New Scene")) Debug.Log("True now !") First in the loop I'm adding some toggles. Then I want to do that if specific toggle is checked(true) do something and if unchecked(false) do something else. But the way I did it it's just changing the toggle to true automatic. |
0 | Check if GameComponent is ready in Unity? I am trying to create a MessageBox in Unity, but I'm having some troubles in C .. This is my code (I'll explain my problem later) MsgBox.cs public class MsgBox MonoBehaviour private UIButton btn ok NGUI Button private UILabel caption NGUI Label private GameObject box The message box container void Start() box this.gameObject btn ok box.transform.Find("btn ok").GetComponent lt UIButton gt () caption box.transform.Find("Title").GetComponent lt UILabel gt () the line below works fine, but I don't want to change the caption here this.Caption "This Works" public string Caption get return caption.text set caption.text value My Saved Prefab As you can see, my prefab have the MsgBox.cs attached to the Box component (wich is the box variable). But this code doesn't work Fail Code function createBox() GameObject wnd (GameObject)Instantiate(Resources.Load("Box")) MsgBox mb wnd.GetComponent lt MsgBox gt () bool foo true if (mb null) Debug.Log("MsgBox is null") foo false if (!(mb is MsgBox)) Debug.Log("mb is not MsgBox") foo false if (foo) Debug.Log("passed!") mb.Caption "Hello!" Console Output passed!NullReferenceException Object reference not set to an instance of an object MsgBox.set Caption (System.String value) (at Assets scripts MsgBox.cs) If I change this public string Caption get return caption.text set caption.text value to this public string Caption get return caption.text set if ( caption null) Debug.Log("Caption is null") else caption.text value and call createBox, the console give me this Caption is null Why? Why I can't change the caption from outside the MsgBox? Maybe the createBox() is being called first than Start()? PS. Using Unity 5 64 bit. My platform is WebGL. PS . English is not my native language, sorry. |
0 | Touch goes through UI objects on mobile I know this question has been asked a lot of times, and I have tried the solutions that were provided and I still have no valuable result, so I thought...maybe a new set of eyes could help. I have a game in which the player can navigate around the scene environment using a virtual joystick and look around the scene by scrolling through the screen(like it is seen in most mobile fps games). The problem that I am having now is that my "look around" script allows touch inputs to pass through UI elements on mobile, but everything works fine on the editor. Useful tips 1) I am using Unity 2019.3.0f5 2) I setup the script to work with Cinemachine Free Look, and my script(seen below) is attached to it. Here is my code using UnityEngine.EventSystems using UnityEngine using Cinemachine public class CinemachineCoreInputTouchAxis MonoBehaviour private readonly float TouchSensitivity x 10f private readonly float TouchSensitivity y 10f SerializeField private bool UseTouchControls true private static int Index 0 void Start() if(UseTouchControls) CinemachineCore.GetInputAxis HandleAxisInputDelegate private float HandleAxisInputDelegate(string axisName) switch (axisName) case "Mouse X" if (Input.touchCount gt 0 amp amp !IsPointerOverUIObject()) return Input.touches Index .deltaPosition.x TouchSensitivity x else return Input.GetAxis(axisName) case "Mouse Y" if (Input.touchCount gt 0 amp amp !IsPointerOverUIObject()) return Input.touches Index .deltaPosition.y TouchSensitivity y else return Input.GetAxis(axisName) default Debug.LogError("Input lt " axisName " gt not recognized.", this) break return 0f public static bool IsPointerOverUIObject() Called to check if the pointer is over a ui object bool value false for (int i 0 i lt Input.touches.Length i ) Index i value EventSystem.current.IsPointerOverGameObject(Input.GetTouch(Index).fingerId) if (value) break return value Can anyone please let me know what I am failing to see and how to fix it? |
0 | Is it possible to debug a Unity Android game directly on a device? I'm working on my game and every time I make changes to it I send the game to my mobile device to debug it. I want to know how I can directly debug my game using an Android device instead of the MonoDevelop editor? |
0 | Is it possible to get object rotation in a shader for dynamically batched objects? All the batched objects have the same rotation. To simulate the effect of directional light I need to determine the object sides actual (world) directions. Normally I would use unity ObjectToWorld amp unity ObjectToWorld for that, which is not possible when the objects are batched. Is it possible to pass the object rotation to the shader in one action (since it's the same for all of them) without breaking the batching? This is a simplified shader example (here I use colors instead of light shadow effect and only 2 sides instead of 4) Shader quot Test UnlitTest quot Properties MainTex ( quot Texture quot , 2D) quot white quot TopColor ( quot TopColor quot , Color) (1, 0, 0, 1) BottomColor ( quot BottomColor quot , Color) (0, 0, 1, 1) SubShader Tags quot RenderType quot quot Opaque quot ZTest Off ZWrite Off Lighting Off Cull Off Fog Mode Off Pass CGPROGRAM pragma vertex vert pragma fragment frag include quot UnityCG.cginc quot sampler2D MainTex float4 MainTex ST float4 MainTex TexelSize fixed4 TopColor, BottomColor struct vertData float4 vertex POSITION float2 uv TEXCOORD0 struct fragData float2 uv TEXCOORD0 float2 uvW TEXCOORD1 float4 vertex SV POSITION fragData vert (vertData v) fragData f f.vertex UnityObjectToClipPos(v.vertex) f.uv TRANSFORM TEX(v.uv, MainTex) f.uvW mul(unity ObjectToWorld, f.uv) return f fixed isTransparentPixel(fixed2 uv) return step(tex2D( MainTex, uv).a, 0.0) fixed isEdgePixel(fixed2 uv) uv mul(unity WorldToObject, uv) back to object space return isTransparentPixel(uv) fixed4 frag (fragData f) SV Target fixed isTransparent isTransparentPixel(f.uv) clip( isTransparent) fixed4 c tex2D( MainTex, f.uv) float2 borderSize float2(3, 3) border size in tex pixels float dy borderSize.y MainTex TexelSize.y fixed3 borderColor fixed3(0, 0, 0) float borderColorsCount 0 float2 uvW f.uvW UV in the world space Top edge fixed isEdge isEdgePixel(uvW float2(0, dy)) borderColor isEdge TopColor.rgb borderColorsCount isEdge Bottom edge isEdge isEdgePixel(uvW float2(0, dy)) borderColor isEdge BottomColor.rgb borderColorsCount isEdge fixed noBorderColor step(length(borderColor), 0) fixed hasBorderColor 1 noBorderColor c.rgb c.rgb noBorderColor hasBorderColor borderColor max(borderColorsCount, 1) return c ENDCG It gets a semi transparent image as a texture. The image is completely transparent at the edges and contains an opaque shape in the center. The shader colors the top edges of the non transparent shape in red and the bottom ones in yellow. It uses unity WorldToObject amp unity ObjectToWorld to check the edges facing directions in the world space. |
0 | How to stop a jump midair and remove y velocity in the process What I want to do is to cut a jump midair by turning off the y velocity when the player releases the jump button (like in Hollow Knight). I managed to do that with rb.velocity new Vector2(rb.velocity.x, 0f) My problem is when I cut the jump and I am midair, if I repeat the release jump button process, the whole thing happens again, the character staggers as long as I am releasing the jump button continously. I would like to be able to do that only once when I am off the ground. I am a noob when it comes to coding so I don't really know what to do. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Events public class PlayerController MonoBehaviour public Animator animator private Rigidbody2D rb public float speed private float moveInput public float jumpForce private bool isGrounded public Transform feetPos public float checkRadius public LayerMask whatIsGround private float jumpTimeCounter public float jumpTime private bool isJumping private bool facingRight true public float jumpDownForceY 0 void Start() rb GetComponent lt Rigidbody2D gt () void Update() isGrounded Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround) if (Input.GetButtonDown( quot Jump quot ) amp amp rb.velocity.y 0) rb.AddForce(Vector2.up 700f) if (Mathf.Abs(moveInput) gt 0 amp amp rb.velocity.y 0) animator.SetBool( quot Running quot , true) else animator.SetBool( quot Running quot , false) if (rb.velocity.y 0) animator.SetBool( quot Jumping quot , false) animator.SetBool( quot Falling quot , false) if (rb.velocity.y gt 0.2) animator.SetBool( quot Jumping quot , true) if (rb.velocity.y lt 0) animator.SetBool( quot Jumping quot , false) animator.SetBool( quot Falling quot , true) if (isGrounded true amp amp Input.GetButtonDown( quot Jump quot )) isJumping true jumpTimeCounter jumpTime rb.velocity Vector2.up jumpForce if (Input.GetButton( quot Jump quot ) amp amp isJumping true) if (jumpTimeCounter gt 0) rb.velocity Vector2.up jumpForce jumpTimeCounter Time.deltaTime else isJumping false if (Input.GetButtonUp( quot Jump quot )) isJumping false rb.velocity new Vector2(rb.velocity.x, 0f) void FixedUpdate() moveInput Input.GetAxisRaw( quot Horizontal quot ) rb.velocity new Vector2(moveInput speed, rb.velocity.y) Flip(moveInput) private void Flip(float moveInput) if (moveInput gt 0 amp amp !facingRight moveInput lt 0 amp amp facingRight) facingRight !facingRight Vector3 theScale transform.localScale theScale.x 1 transform.localScale theScale |
0 | All scripts in Unity game can not be loaded I can not provide a "why" here, because as far as I can tell it happened spontaneously after saving an edit to one of my scripts, it just started happening. But here's the problem Every single one of my scripts, while still in the same Scripts file, can no longer be found and loaded. All the Script Components (take the Game Manager component for example) now look like this or like this Attempting to locate the scripts by going Add Component Scripts Desired Script doesn't work, because there isn't even a Scripts item in the Add Component menu. I have already looked this up, and none of the answers I found were applicable Yes, every script's file name is the same as the Class name within them I have tried reimporting all assets (Assets Reimport All), no success. Taking all scripts out of the project, restarting unity and then reimporting the scripts. Nothing Removing all script components, then reapplying them. It didn't work because, as I said, there was no Script item in the Components menu. This is a pretty game breaking, literally, because this is a hobby game (I'm not doing this as a job, it's just in spare time). If I can't restore the game as it was, I won't be able to bring myself to restart it. So any help is greatly appreciated. |
0 | Draw "rasterize" irregular circle onto a 2D grid I'm using the midpoint circle algorithm to choose cells on a 2D grid which outline a circle. However, I need to incorporate some random noise so that I get an irregular circle, and this method won't work anymore given how it works. Another stack exchange answer describes an equation (the "pink noise" example) I'd like to try but I'm not sure on the best approach to implement it. I can replicate the equation via code, but I'll need to start choosing grid cells coordinates differently and I'm not sure the best solution. How can I "rasterize" an irregular circle like this? |
0 | Keeping 2 objects within cameras view I have two object to control and I wanted to keep them at cameras view without adjusting the cameras size but the camera can move only in positive y axis meaning ones it goes up it shouldn't move down but it's okay if one object gets out of bounds. Since its 2D the camera is Orthographic view. |
0 | How can I add an in game level editor? I have 200 prefabs and a scene with an infinite flat plane. I want to allow user to edit the scene add, remove, rotate, place that prefabs and save load resulting "scene" in some custom format. How can I implement this? |
0 | How to delay jump to syncronize with an animation ? I'm using Unity and First Person Controller. If i press the jump button, my charachter jump immediately. I want,instead, that jump movement starts after (for instance) 1 second, to be syncronized with a jumping animation I trigger. How to do that ? Thanks |
0 | How can I add a glow effect around a pair of wings in Unity without post processing? Basically I want to use post processing and then I found a tutorial to achieve my goal. However, the artist want a pure shader to achieve this, without any C script hanging in the main camera. Any idea to implement? |
0 | Some submeshes of my gameobject dissapear when I set the bindposes Well, I'm trying to animate some Source models imported into Unity3D using this Unity Source Tools library https github.com lewa j Unity Source Tools To animate a Mesh generated by this tool I need to create a SkinnedMeshRenderer replacing the MeshRenderer and the MeshFilter components, so I created this method private static void ReplaceRenderer(this GameObject obj, SourceStudioModelv2 model) if (obj.GetComponent lt SkinnedMeshRenderer gt () ! null) return var mesh Object.Instantiate(obj.GetComponent lt MeshFilter gt ().sharedMesh) const bool debugPoses true const bool useNativePoses true var nativeBuilder debugPoses ? new StringBuilder( quot Native Matrix n new string(' ', 10) n quot ) null var unityBuilder debugPoses ? new StringBuilder( quot Unity Matrix n new string(' ', 10) n quot ) null var nativeMatrix model.GetBindPosesFromModel(nativeBuilder).ToArray() var unityMatrix obj.transform.GetBindPoses(model.Bones, unityBuilder).ToArray() if (debugPoses) Debug.Log(nativeBuilder.ToString()) Debug.Log(unityBuilder.ToString()) var matrix useNativePoses ? nativeMatrix unityMatrix mesh.bindposes matrix Object.Destroy(obj.GetComponent lt MeshFilter gt ()) Object.Destroy(obj.GetComponent lt MeshRenderer gt ()) var skinned obj.AddComponent lt SkinnedMeshRenderer gt () skinned.sharedMesh mesh skinned.rootBone obj.transform skinned.bones model.Bones As you can see, I'm creating two bind poses, because one of them is created from this part of the code https github.com lewa j Unity Source Tools blob c5469deb1d630c1582c940ff3cdb0f69fc55eda3 Assets Code Read SourceStudioModel.cs L724 L728 And this is how I create the bindposes Native Poses private static IEnumerable lt Matrix4x4 gt GetBindPosesFromModel(this SourceStudioModelv2 model, StringBuilder sb null) for (var i 0 i lt model.MdlBones.Length i ) var mdlBone model.MdlBones i From https stackoverflow.com a 49268287 3286975 var matrix (new Matrix4x4( new Vector4(mdlBone.PoseToBone 0 , mdlBone.PoseToBone 1 , mdlBone.PoseToBone 2 , mdlBone.PoseToBone 3 ), new Vector4(mdlBone.PoseToBone 4 , mdlBone.PoseToBone 5 , mdlBone.PoseToBone 6 , mdlBone.PoseToBone 7 ), new Vector4(mdlBone.PoseToBone 8 , mdlBone.PoseToBone 9 , mdlBone.PoseToBone 10 , mdlBone.PoseToBone 11 ), new Vector4(0, 0, 0, 1) )).transpose sb?.AppendLine( quot i matrix.ToString( quot F2 quot ) quot ) yield return matrix Unity Poses private static IEnumerable lt Matrix4x4 gt GetBindPoses(this Transform transform, Transform bones, StringBuilder sb null) for (var i 0 i lt bones.Length i ) var bone bones i var matrix bone.worldToLocalMatrix transform.localToWorldMatrix sb?.AppendLine( quot i matrix.ToString( quot F2 quot ) quot ) yield return matrix And these are the values that each of them gives to me Unity Bindposes https pastebin.com 9tybGq7Z And this is the result Native Bindposes https pastebin.com YRZVq04y But this one doesn't show anything. I saw this reference on internet https hg.alliedmods.net hl2sdks hl2sdk file 4966093d3274 utils studiomdl simplify.cpp l3745 But I'm not sure if I'll be able to transcript this into Unity and if it will be useful... If you would like to test this model out I created a .unitypackage file for you to test https mega.nz file xKpRSYwJ j3ckM3GyFDFZKI6Y OvN2cmcGC GudGe2finLRQoA4U So I don't know how to proceed in this case, could anybody help me out with this? |
0 | Should I code game logic separately from game engine scripts I'm developing a game in Unity3d, economic strategy. I wonder if I should code logic inside unity scripts, or write it as an external module library? By game logic I mean game model, which describe game entities, they relation with each other, their methods. And this logic has nothing to do with and doesn't need to know anything about networking, rendering, representation etc. If I do it inside unity scripts, then logic is tied to unity engine and I don't see a way to implement multiplayer(client server) without rewriting whole logic for server side, where unity cannot be used. I would like to define logic outside of scripts, and later, reference it inside some "main" unity script. This way I could implement multiplayer easily. Is this a common practice, or should I avoid it, or maybe there is some alternative patterns? |
0 | How to smooth jagged pixel edges in Unity? So I am reading an image from a png file into a 2D sprite. This sprite serves as a "province" in my game. Currently, I am getting this If you look closely, you will notice that you are seeing the square corners of each pixel, because I am mapping the image on a 1 1 ratio of pixels world coordinates. What I want is a slightly rounded corner in these places. Look at the 2 dimensional provinces in this example I have been googling around for algorithms, but most answers simply say "use a shader" and don't describe the techniques used to do this (until now I have not done much with shaders). If you would like to see my working code for the province system, it is posted on my answer to my own question here. |
0 | Why is the IntelliSense not working when I open a new script in Visual Studio? The strange thing is that opened scripts or newly opened ones are working fine. It's the new created C scripts that are not working. With not working, I mean the MonoBehaviour is not in light blue color it's in black color. In this screenshot I took, I marked it with a red circle. What have I tried so far? I have closed Visual Studio and started over again. Since it didn't solve it, I closed the unity editor and started it over again, to no avail. I pressed 'clean solution', I pressed 'rebuild solution', I pressed 'build solution'. What else can I do ? And why are the other scripts working fine? If I type gameo...it will auto complete it to GameObject but in this specific script it's just not working. This is a screenshot of the editor. I have in the Hierarchy a Ladder object. In the Assets I created a folder name Ladder and a script name Ladder. But this Ladder script is not working. This is the Ladder script and this script was working before but once I created another script inside the ladder folder name Raise empty script the Raise script didn't work and now the Ladder is not working either. But other scripts are working fine. using System.Collections using System.Collections.Generic using UnityEngine public class Ladder MonoBehaviour public Transform charcontroller private bool inside false private float heightFactor 3.2f private void OnTriggerEnter(Collider other) inside true private void OnTriggerExit(Collider other) inside false private void Update() if (inside true amp amp Input.GetKey("w")) charcontroller.transform.position Vector3.up heightFactor |
0 | Animator consecutive set parameter problem I'm having a little problem with my animations transitions. I have this diagram http imgur.com Se8Ix1L My transitions is made by updating the parameter "stateparam". My code, changing the parameter http imgur.com HlypG2L I change stateparam to 2 and right after to 0, then my animation don't restart every frame. But when I play, the my parameter doesn't change the animation and only change the stateparam to 0. I already debugged and it's passing in the line that change to valid transition value. But i don't know why my animation doesn't changes. If I play and change stateparam manually, it works. If I take off the SetInteger "0", let only the valid value, the code works, but my animation keep restarting before it can finish itself. I don't know if the parameter change it's too fast to do the transition or it's any buggy. Any help ? |
0 | How to make Flood fill algorithm return different Lists of separate groups in the grid? So i have this flood fill method public int groupedCells(int y, int x, int value) base state if (!gSetup.isValidLocation(y, x) gSetup.getCell(y, x).value ! value gSetup.getCell(y, x).cMAtch.isInMatchPool) return 0 keep track of matched cells gSetup.getCell(y, x).cMAtch.isInMatchPool true collect int up groupedCells(y 1, x, value) up int left groupedCells(y, x 1, value) left int right groupedCells(y, x 1, value) right int down groupedCells(y 1, x, value) down sum int total up left right down 1 return total basically i have this grid and currently if i click on a yellow triangle, the method above will tell me how many of them are next to each other. What i want is a solution that will run all over the grid, and check if a group has less than 3 triangles then do (A) if it has 3 triangles then do (B) if it has 4 triangles then do (C) etc ... Am not sure about this, but i thought the best way is to have a list for every group, and then check those conditions over the lists. I tried it here but the list keep re initializing itself, so it always either have 0 cells or 1 public List lt CellSetup gt listedCells(int y, int x, int value) List lt CellSetup gt cList new List lt CellSetup gt () base state if (!gSetup.isValidLocation(y, x) gSetup.getCell(y, x).value ! value gSetup.getCell(y, x).cMAtch.isInMatchPool) return cList keep track of matched cells gSetup.getCell(y, x).cMAtch.isInMatchPool true cList.Add(gSetup.getCell(y, x)) collect List lt CellSetup gt up listedCells(y 1, x, value) up List lt CellSetup gt left listedCells(y, x 1, value) left List lt CellSetup gt right listedCells(y, x 1, value) right List lt CellSetup gt down listedCells(y 1, x, value) down return cList The result of that method when its called here for (int y 0 y lt gSetup.cell2DArray.GetLength(0) y ) for (int x 0 x lt gSetup.cell2DArray.GetLength(1) x ) print(listedCells(y, x, 1).Count) is printing "1" three times and "0" 22 times. Thank you |
0 | What is the most efficient technique for range detection? I have a bunch of patrolling enemies that fire projectiles when the player is in projectile range a specific radius. Which method is the most efficient and elegant? overlapSphere sphereCast triggers square magnitude anything else? I am using Unity. |
0 | Why don't my generated instances update when I change their prefab? I m making an Editor tool a ScriptableWizard that instantiates a prefab on a grid. But I find that when I update the prefab, the instances don t update. When I instantiate prefabs interactively in the Editor by dragging them from the Project panel to the Scene or Hierarchy, then updates to the prefab affect the instances as expected. I see another difference between my scripted instances and the ones created when I drag the prefab into the scene when I do it interactively, the instance in the hierarchy is listed in blue. But the instances I create from script using the same prefab are listed in black, similar to objects created directly in the scene. Here s the hierarchy the JitterPrefab was dragged into the scene, and the ones under gridParent were instances of the JitterPrefab generated from my script Here s how I m generating the instances public GameObject prefab ... void OnWizardCreate() ... Transform instance Instantiate (prefab.transform, pos, rot, parent.transform) instance.name string.Format ("L 0 D2 R 1 D2 C 2 D2 ", l, r, c) ... When I make a change on the prefab, e.g. change the radius of the Jitter script from 0.025 to 0.25, the manually created instance updates But the script generated instances do not What am I doing wrong? Why are my scripted instances no longer connected to the original prefab? And, separately, how to I tell in the editor (or in script) whether an object in the scene is an instance of a prefab or not? |
0 | Unity OnRenderImage hides UI I have a component which renders a few different cameras and the images. However, this obscures my UI when in Screen Space Overlay mode. I can put the canvas in WorldSpace mode, which works, but then the UI is affected by the image effect I've built and is, of course, not locked to the camera. Suggestions? Update additional details At design time, the OVR camera rig contains a single camera centered between the "eyes." This component is attached to the camera rig's centerEyeAnchor. At run time, the rig creates two additional cameras one for each eye. These aren't supposed to be modified by user code. (Among other things, their projection matrices are pretty weird.) I need to modify the image per eye. I created a new component which create two additional cameras per eye. One renders a low res version of the entire scene, the other renders a high res image of a portion of the screen, each to a dedicated RenderTexture. Pseudocode void Update() called once per frame called twice per frame once per eye void OnPreRender() called twice per frame once per eye void OnRenderImage(RenderTexture source, RenderTexture destination) low res render of entire scene var camOuter m cameras ... hi res render of part of the scene 10 20 of original image area var camInner m cameras ... update cameras to match current eye camera camOuter.copyFrom(Camera.current) camOuter.targetTexture m outerTexture render scene to low res texture camOuter.Render() camInner.copyFrom(Camera.current) camInner.targetTexture m innerTexture target texture that the Oculus wants to render to var ovrTexture Camera.current.targetTexture save projection matrix var originalProjectionMatrix camInner.projectionMatrix var scale new Vector3(m innerTexture.width 1.0f ovrTexture.width, m innerTexture.height 1.0f ovrTexture.height) zoom pan matrix to clip to part of the scene var gazeMatrix Matrix4x4.Scale(scale) offset projection gazeMatrix.m03 (1 2 gaze.x) scale.x gazeMatrix.m13 (1 2 gaze.y) scale.y camOuter.projectionMatrix gazeMatrix amp originalPRojectionMatrix render hi res portion of the scene centered at gaze pixel camOuter.Render() restore projection matrix cam.projectionMatrix originalProjectionMatrix composite images m material.SetTexture("InnerTexture", m innerTexture) m material.SetTexture("OuterTexture", m outerTexture) Graphics.Blit(null, destination, m material) (I'm also worried that there may be additional scene renders happening in the background.) The problem is that the UI does not render if set to Screenspace Overlay or Screenspace Camera. I can get it to render in Worldspace, which may be the only way to do this, but then it seems I'd need to create yet another hi res texture matching the viewport dimensions and render the UI layer to that, and keep it locked to the current eye's camera position. Alternatively, I could re use one of the current cameras, I guess, and just tweak its settings. Is there a better way to do this? Ideally, I'd like to have the engine just render the UI as it does in other applications without having to jump through hoops. However, at this point, I'll take anything I can get that works and looks good. Update the 2nd Okay, it looks like the UI is rendered perfectly if I use a regular camera instead of the OVR rig. ( Having the rig in the scene, though, prevents it from drawing at all. |
0 | How to put the game object to the upper left corner of the screen in Unity and make it visible entirely on all screens of mobile devices I have game object which displays health indicator in my 2d video game in Unity. This gameobject contains a lot of sprites and i put it into left top corner of the screen. In my game editor it is visible entirely but on my mobile device is visible only half of it. How can i make it visible entirely on all screens? Can anyone help me to solve this problem please. P.S. I have some ideas how to do this 1. Create health indicator from GUITexture elements. But it is not good for me, because health indicator consists of a lot of small elements and it will take a lot of time for me to resize every GUITexture according to my needs. Put my gameobject with health indicator into another gameobject with zero transform, and then put parent GO into top left screen using Camera.main.WorldToViewport method. But may be there is more easy way to do this? |
0 | Jumping onto higher ground Collider issues What's the general solution to the following character animation problem (I'm using Unity)? You have a character with a capsule collider and a jump animation that allows you to jump onto higher ground (such s boxes, etc.). The character shouldn't be able to jump unrealistically high so she goes into a crouched posture while in the air and the collider is scaled accordingly in an animation curve. However when the character jumps onto the box to land, the character animation (and collider) want to extend back to wards the ground but there is not enough space and either collision detection fails and the character falls into the geometry or the collider starts a collision fight with the box and keeps bumping up and down, keeping the character in an airborne state. Please see screenshots to get a better idea... What would be a good way to work around this problem? |
0 | Blue, Red and pink Materia Hi guys i just started using unity recently but today after working on some animation blending, most (not all) prefabs changed to look like this What's the cause, and how can i fix it? i tried creating a new project then copied my Asset directory to it but still. also when i try importing a new character i still see the same. Material structure. |
0 | How to make it so my cursor is not behind the UI? My cursor keeps going behind the UI how to make it go above? |
0 | Can animation parameters only be changed in scripts? I have a very simple animation parameter in the Animator, a boolean that is "true" when a shooting animation is playing (to stop the game logic from allowing more shooting during a gun recoil animation). I assumed I'd be able to access this in animations, i.e. setting it to true when a shooting animation started, and false when it ended. But I just can't see how to access it in my animations. It's not available under "Add Curve". Am I missing something? I can do this in other ways, but this just seemed like the cleanest. |
0 | Push Notification to start a scene I was wondering whether I can use APNs in iOS to trigger an event in my game, like start a scene without user clicking the notification. Is it possible to use remote push notifications for events like this? |
0 | Is it possible to have two trigger zones around the same GameObject in unity? I have created a trigger zone to make sure that only only gameobject passes through it at a time. The moment the gameobject1 entered the trigger zone, it is given a particular tag but I am not how to stop other gameobjects from entering the zone. Is it possible to have two trigger colliders attached to a same object like an outer and inner trigger such that only one gameobject is allowed to pass through the inner one while all other gameobjects wait at the outer one. |
0 | How do I find a component, deferring to the children or parent if there is none? I'm trying to create a function in C in Unity that will take a GameObject and a Component, and return an attached Component from the base, child, or parent elements. If the target GameObject does not contain the requested Component, I wish to look to any children. If there are no children, or the children do not contain the requested Component, I wish to look to the parent. How do I find a component, deferring to the the children or parent if there is none? |
0 | Unity using WWW to download image from web. Not working from my own website, but does from other urls I have this script attached to a RawImage file in my games UI public class DownloadImage MonoBehaviour string url "http megabrogames.rf.gd pic.jpg" string url "https i.imgur.com xBSyvRx.jpg" IEnumerator Start () WWW www new WWW(url) yield return www GetComponent lt RawImage gt ().texture www.texture Both jpg files are the same. One I uploaded to Imgur, this works. The other is on my own website. The url to my website works fine, I have checked in on two computers and several browsers. All I get is the red question mark. But if I uncomment the other one instead it all works perfectly. My problem is that I have hard coded the url into the game, and I want to change the image each week. It has to be the same URL for that to work, but i think with Imgur it will auto assign whatever url it feels like. thanks for any help |
0 | Image effect console error I have imported image effects from asset store in my project. When imported, I've got 5 error messages Assets Standard Assets Effects TonemappingColorGrading Editor TonemappingColorGradingEditor.cs(370,134) warning CS0618 UnityEditor.TextureImporterFormat.AutomaticTruecolor' is obsolete Use textureCompression property instead' What to do ? |
0 | Unity scene preview keyboard controls I am learning to use Unity, and found I disliked the way moving around the scene editor is implemented. The left and right arrow keys move the scene quot camera quot left and right as expected, but the up and down editor moves forwards and backwards. Is there a way to change the controls to make it more like a quot traditional quot WASD movement, similar to how Minecraft on touch devices does it (up, down, left, and right moves exactly as it sounds, and rotation is by clicking and dragging the mouse)? Thank you for your time. |
0 | Ping Pong bat is not detecting the collision with the wall I have been learning Unity for last couple of days. I want to make one simple ping pong game. The idea is simple. The game has a Sphere as a ball, a plane as ground, 2 rectangles as bats and 4 rectangles as walls. Look at the image It is a 2 players game. One player will use 'W' and 'S' key and another player will use 'Up Arrow' and 'Down Arrow' on the keyboard to move the bat up and down. But I have a problem here. If a player moves the bat at the limit (up or down), the bat does not detect the collision with the wall. It just goes through the wall. Look at the image. The bats and the walls have Box Collider, but still the problem persists. So what should I do so that the bat detects the collision with the wall. |
0 | Instantiate unity sometimes lags the game some times it doesnt I have a script that instantiates a object lets say every half a second. THis object is of the type .fbx and has a file size of 53kb, lets call this object A. When i use this object my script instantiates the objects without any freezes or any other problems. Now i have an other object also of type .fbx and also with a filesize of 53kb lets call this object B. Now when i want to instatiate object my my game freezes a few frames upon instantiation. Why? Is there a way to instatiate objects more efficiantly? I already looked at using object pooling but this doesnt really works in my case. See here a screenshot for object A, and its components See here object B and its components Per request the code that does the instantiation of the objects public class ForLoopVisualization1 MonoBehaviour public DetectorAreaScript ElementDetector public GameObject TowerElement public Transform TowerElementsParent public bool WigglyTower false public float ElementSpacing, Wiggeliness private Collider BuildElementCollider private Transform BuildElementTransform private Vector3 TowerElementPos private int TowerElementCount, CreatedElements private bool StartBuildingTower false private float Delay 0.5f, TowerElementSize Use this for initialization void Start () ElementDetector.DetectedData OnObjectEnterDetector Destroy(TowerElement.GetComponent lt Rigidbody gt ()) TowerElementSize TowerElement.GetComponent lt Collider gt ().bounds.size.y TowerElementPos TowerElementsParent.position new Vector3(0, TowerElementSize 1.5f ElementSpacing, 0) Update is called once per frame void Update () if(StartBuildingTower amp amp CreatedElements lt TowerElementCount) Delay Time.deltaTime if(Delay lt 0) CreatedElements var te Instantiate(TowerElement, TowerElementPos, Quaternion.identity) te.transform.SetParent(TowerElementsParent) if(WigglyTower) TowerElementPos new Vector3(Random.Range( Wiggeliness, Wiggeliness), TowerElementSize ElementSpacing, Random.Range( Wiggeliness, Wiggeliness)) else TowerElementPos new Vector3(0, TowerElementSize ElementSpacing, 0) Delay 0.4f else if(StartBuildingTower) StartBuildingTower false StartCoroutine(EjectVar()) add when bugs are fixed.. void OnObjectEnterDetector(System.Object sender, DetectedVariableData data) if(data.DetectedObjectType DetectedType.Variable) var vals ElementDetector.DetectedVariable.GetVariableValue() TowerElementCount vals.IntValue if(CreatedElements gt 0) foreach (Transform child in TowerElementsParent) Destroy(child.gameObject) CreatedElements 0 TowerElementPos TowerElementsParent.position new Vector3(0, TowerElementSize 1.5f ElementSpacing, 0) StartBuildingTower true IEnumerator EjectVar() yield return new WaitForSeconds(0.8f) ElementDetector.EjectDetectedElement(new Vector3( 1, 0, 1)) If something is unclear let me know so i can clarify the post! |
0 | unity update boolean from other script So my problem is that the color of the sprite should only change if the Boolean is true. My theory is that the Boolean isn't being update. So how do I update the Boolean the whole time and see if it is getting changed. Thanks Guys, public class controlborder MonoBehaviour private SpriteRenderer m spriteRenderer public float loopdelay 2f public static bool startstop public void Start() m spriteRenderer GetComponent lt SpriteRenderer gt () StartCoroutine(Changecolor(2f)) public void Update() private IEnumerator Changecolor(float loopdelay) while (true) startstop control.changecolorborder lt this bool Debug.Log(startstop) while (startstop) yield return new WaitForSeconds(1F) int random Random.Range(1, 4) if (random 1) m spriteRenderer.color Color.blue else if (random 2) m spriteRenderer.color Color.red else if (random 3) m spriteRenderer.color Color.green else m spriteRenderer.color Color.yellow |
0 | Creating a content pipeline for a Unity I have a game with lots of assets, such as data files, images, etc. My understanding is that Unity is optimized to know about all resources at build time. i.e. binding those assets to Scene GameObjects or prefabs. And for performance reasons, dynamically loading files from the Resources folder is discouraged. My question is how can I set up a "content pipeline" for converting my asset files stored outside of Unity into a format that Unity expects. With the XNA toolset you can create a separate project and "build" the content into a bundle. Is there way to achieve similar results in Unity? Or is the best I can do creating an external tool, and simply copying files into my Unity Textures or Unity DataFiles folder and generate the Unity metadata files myself? If there isn't an off the shelf solution, do you have any experiences or recommendations with solving this problem? |
0 | Setting Camera's Viewing parameters manually I am working on Context aware camera in Unity. in this project i have to set parameters of the camera each frame manually depending on what camera sees on the screen. New View (v) direction is given and Up (u) and Right (r) vectors should be such that they minimize torsion with previous frame's u and r. I have deployed the following code to accomplish the given task Vector3 viewNew m Normal Vector3upNew Vector3.Cross(viewNew,m CameraPrevTransform.right).normalized Vector3 rightNew Vector3.Cross(viewNew, upNew).normalized ... transform.forward viewNew transform.up upNew transform.right rightNew The problem is it seems like Unity tries to automatically adjust parameters when one of the directions (up, forward, right ) are set. Is there a workaround ? is it possible to get more control of the camera? |
0 | TextMeshPro Shader choices difference (when to use) Actually I can see the visual difference that bitmap sprite shows blurry text like this pink distance field seems like missing texture distance field surface grey and lastly distance field masking overlay seems to show the correct expected result so what's the difference between those two? (masking overlay) |
0 | How should I organize 2D sprites? I'm using a Unity Tilemap in my 2D game, and I have several hundred 32x32 sprites. Most of the examples I've seen using sprites have a few consolidated sprite sheets that contain all of the game's sprites. For instance, I'd have a few 1024x1024 sprite sheets that contain all of my game's sprites. Those examples all say that the reason to do it this way is that performance is improved when sprites are packed together like that. The problem with these large consolidated sprite sheets is that it's difficult to find the sprites that I want when I'm making a tile pallet or animated scripted sprite. For example, I have two 1024x1024 sprite sheets called "House Interior 1" and "House Interior 2" that contain all my walls, floors, furniture, doors, windows, and miscellaneous interior objects. Now I want to create one Unity tile pallet that has only tiles for western style houses and one tile pallet that has only tiles for eastern style houses. Each tile pallet is going to require some, but not all, sprites from both of my sprite sheets (House Interior 1 and House Interior 2). Additionally, I want to create some animated tiles. Each animated tile will use a few sprites from somewhere in the middle of one of the large sprite sheets. My problem is that each sprite sheet image has so many child sprites that it becomes very tedious and time consuming to visually scan through each huge sprite sheet to find the tiles I want, and then drag each of them individually onto my tile pallet. Making animated tiles results in the same problem because when I assign each animation frame, I have to find the correct sprite from a huge list of sprites that are named House Interior 1, House Interior 2, House Interior 3, and so on. I'd like to have smaller sprite sheets that only contain one specific type of sprite, rather than huge sprite sheets of often unrelated sprites. For example, I'd like to have one sprite sheet that has only masonry walls, one that has only brick walls, one that has only the animation frames of a fireplace, and so on. That way it'll be easier to build up Unity tile pallets by dragging several sprite sheets into the tile pallet in the Inspector, and it'll be easier to find my animated tiles because I can easily find the sprites named Fireplace 1, Fireplace 2, and Fireplace 3. So my questions are How big of a performance hit will I experience if I don't pack my tiles together into a few big spritesheets? Is it even worth taking this into account considering modern devices are so powerful compared to what is necessary to do sprite based graphics? Is this a case of balancing the pros and cons of both methods, or is it generally strongly recommended that I large consolidated sprite sheets? |
0 | Position Unity UGUI ScrollRect Content Position from Script I have a map in my game the user can interact with. I am using Unity UGUI ScrollRect to let the user move the map on the screen. Only one area of the map is visible at a time and you can scroll it to get to the desired level (just like in King games). The content of this map system is an Image and level buttons which are all children of the map image. I want my ScrollRect to point to the current active level when the map loads. For example, if I am on level 30 then on loading the map level the content of the ScrollRect should be on the portion of the map where level 30 is. I can't find anything regarding managing ScrollRect's content position |
0 | Flipped camera with Google VR I just imported latest Google VR SDK into Unity and made a simple scene that has only Main Camera, plane, and single zombie just standing there with T Pose. In Main Camera, I added GvrPointerPhysicsRayer component, and it has GvrReticlePointer as child object. Running in Unity Editor seems fine but when I build and run, whole world is just flipped. I can't find any related issues about this anywhere, and struggle with this almost a day. Why camera flipped and how do I fix it? What am I missing? Using Unity 2019.1.0f2 and gvr unity sdk 1.200. Any advice will very appreciate it. P.S. I saw the warning message in project settings default orientation Virtual Reality Support is enabled. Upon entering VR mode, landscape left orientation will be the default orientation unless only landscape right is available. This message never disappear whatever default orientation selected. |
0 | How can I access a GameObject variable in mono script from editor script? In the mono script using UnityEngine public class TileTest MonoBehaviour public GameObject prefabPathOnTerrain Then in the editor script at the top private SerializedProperty prefabPathOnTerrain Then inside OnEnable() private void OnEnable() prefabPathOnTerrain serializedObject.FindProperty( quot prefabPathOnTerrain quot ) And then inside a method I want to use it as a GameObject And instead using CreatePrimitive to use Instantiate But doing GameObject go Instantiate(prefabPathOnTerrain) Will not work. public void TerrainObjects(GameObject gameobject) Terrain terrain Terrain.activeTerrain var cube GameObject.Find(string.Format( quot Terrain 0 1 quot , gameobject.transform.localPosition.x, gameobject.transform.localPosition.y)) if (cube ! null) return if (cube null) GameObject go Instantiate(prefabPathOnTerrain) cube GameObject.CreatePrimitive(PrimitiveType.Cube) cube.transform.localPosition new Vector3(terrain.transform.localPosition.x gameobject.transform.localPosition.x, 0, terrain.transform.localPosition.z gameobject.transform.localPosition.y) cube.transform.localScale new Vector3(gameobject.transform.localScale.x, gameobject.transform.localScale.y, 1) cube.transform.parent GameObject.Find( quot Terrain Map quot ).transform cube.name string.Format( quot Terrain 0 1 quot , gameobject.transform.localPosition.x, gameobject.transform.localPosition.y) cube.tag quot Terrain Map quot |
0 | ScreenToWorldPoint returning wrong position even when given Z plane I have a NavMeshAgent placed on a character model. When I log agent.transform.position I get (4.5, 0.1, 4.5) which is correct (this is a 2.5d game and movement happens along the x and z axes). I am trying to set up a script so that when I click a location on the screen, the character will turn to face that location. The problem I'm facing is that the coordinates returned by Camera.ScreenToWorldPoint are not correct Vector3 mousePos Input.mousePosition mousePos.z Camera.main.nearClipPlane Vector3 targetPos Camera.main.ScreenToWorldPoint(mousePos) Debug.Log(agent.transform.position) Logs (4.5, 0.1, 4.5) Debug.Log(targetPos) Logs (0.1, 16.7, 0.7) In this example, I'm clicking on the same place as the agent but the targetPos is not nearly the same. The y axis of targetPos is static (the same no matter where I click), which seems correct. However the values for x and z are not correct. How do I get the correct coordinates for a click? edit I have this workaround, but I want to know how to solve the original question still RaycastHit hit if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100, rotateTargets)) Vector3 targetPos hit.point targetPos.y agent.transform.position.y Vector3 direction (targetPos agent.transform.position).normalized Quaternion rotation Quaternion.LookRotation(direction) agent.transform.rotation rotation agent.updateRotation false return true |
0 | Best approach for destructible car in Unity I'm developing a simple racing car game. I'm wondering what is the best approach to manage visually car destruction. For instance i think one option (expensive) is to build car 3d model with 'separate' mesh, each for any component (bump, door, glass) and relative cooliders.. Other options ? Thanks |
0 | Smooth Flat shaded meshes cause shadow artifacts (understanding the source of the problem) I'm using blender to create assets to use in Unity3D, and I'm having some trouble understanding how the smooth flat shading interacts with shadows, I'm sorry if it has been asked before, but all the "related" answers refer only to the shading of the object itself, not the shadow it casts. I'm a 3D artist, I do not understand Unity and the mechanics behind it the same way I understand 3D stuff, I'm also trying to understand if the problem lies in the 3D object or some configuration in Unity. I'm using a real time directional light. 1 and 2 are flat shaded. 2 has open geometry while 1 has closed geometry, both have such artifact but it's clearly seen on 2. 3 and 4 both have closed geometry. 3 is fully smooth shaded while 4 is flat shaded. Solution A Mess around with Bias and Normal Bias. With Normal Bias at 0, the shadow artifacts are gone but the mesh itselt gets some other artifacts. Solution B Use Two sided shadows, this method completely fixes the problem, in any situation, but it adds another draw call and makes it more expensive (I'm not 100 sure it does) is this an optimal solution? This same issue was discussed in a closed group but no one could give me a conclusive answer. However, someone who works with 3DS Max said that exporting a mesh with proper smoothing groups does not result in these artifacts, I tested that in 3DS Max and it did not work I think I did it the right way, but I'm not 100 certain. For all the proposed methods, I tested several times, with diferent mesh modifier and exporting options. I'm using mostly .fbx but I also tested in .obj format (which includes a specific option for smoothing groups in blender). Smooth shaded objects work perfectly, flat or smooth flat shaded objects result in this drama. Please help me to bring light to this issue, I might be blind to some obvious aspect, I'm confused because in the other discussion I was presented with contradicting arguments without conclusive proof of anything. Now I don't know if the problem lies with Blender export or Unity configuration. Let me know if I can provide more information. |
0 | Running Unity Build through Command line I recently developed a game in unity and would like to build it to a standalone application using the command line. Is there a way to do that? Specifically, without opening the Unity Editor how can I use the command line to build my project to a standalone application? I am using Linux. |
0 | Static variable not holding its value I am creating a real time multiplayer game in Unity 3d. When a game ends I set a static boolean value called "waitingToEndGame" to true. In Update() it waits a few seconds before moving to a new scene like this if (waitingToEndGame) waitTime Time.deltaTime if (waitTime gt 5f) showGameScores false waitingToEndGame false if (type "Multiplayer") MultiplayerController.Instance.LeaveGame() GameObject levelManager GameObject.Find("Level Manager") levelManager.GetComponent lt LevelManager gt ().LoadLevel("MainMenu") DisableAllMovingObjects() My problem is that even though I am setting the boolean value to true it acts as if it doesn't change and it doesn't make it into the code above to move to the main menu. I even had debug statements printing here as well and they seem to just suddenly stop. |
0 | Why my object Triggering too far? I have some issues with detecting the collision when OnTrigger2d, as you can see in my screenshot below, that actually too far from the object. this my script private void OnTriggerEnter2D(Collider2D collision) if (collision.tag quot Obstacle quot ) anim.SetBool( quot isDeath quot , true) GameManager.instance.GameOver() private void OnTriggerExit2D(Collider2D collision) if (collision.tag quot Obstacle quot ) anim.SetBool( quot isDeath quot , false) |
0 | Objects aren't rotating in sync This is a follow up question to How to reapply force applied to one object to another object I want to make two objects move, react to collisions and other stuff as if they were one. For example, Objects A and B are entangled. When Object C rams into Object A and starts moving with it, Object B should start moving with it. When Object B hits a wall, Object A should act like it also hit a wall. I tried changing position speed every frame, but this only works when done in one direction. Now, I want all forces applied to any of the objects to also apply to the other objects entangled to it. Edit This is the new code which only fails when multiple collisions happen at once using System.Collections using System.Collections.Generic using UnityEngine RequireComponent(typeof(Rigidbody)) public class EEScript MonoBehaviour public List lt EEScript gt activeObjects public new Rigidbody rigidbody public Vector3 lastPosition Start is called before the first frame update void Start() rigidbody gameObject.GetComponent lt Rigidbody gt () Update is called once per frame void Update() lastPosition transform.position private void OnCollisionEnter(Collision collision) foreach (EEScript entangled in activeObjects) if (entangled this) continue Rigidbody rb entangled.rigidbody if (rb is null) continue rb.velocity rigidbody.velocity rb.angularVelocity rigidbody.angularVelocity entangled.transform.position entangled.lastPosition transform.position lastPosition |
0 | How to prevent intepolated texture in fragment shader (Unity CG) Think about minecraft all the textures in minecraft have a very nice crisp pixelated look. Well, I'm trying to write a shader that will do this but it appears "sampler2d" returns some sort of interpolation between pixels of the underlying texture. I'm pretty new to shader writing and I'm not even sure if it can be done but I'm hoping to get a nice crisp blow up of small textures rather than a blurry one like this If anyone knows a way to make a shader crisp rather than interpolated like this (using Unity), I'd be thrilled to know as this hitch is pretty detrimental to what I'm trying to accomplish... Here's the subshader as it is right now (it's skipping all the light calculations and just outputting the sampler as I'm just trying to resolve the blurry texture sampling) SubShader Pass Tags "LightMode" "ForwardBase" CGPROGRAM pragma vertex vert pragma fragment frag user uniform float BlendVal uniform sampler2D DiffuseTex uniform sampler2D NMTex uniform sampler2D PixelMap uniform float4 DiffuseTex SV uniform float4 SpecColor uniform float SpecIntensity uniform float4 RimColor uniform float RimIntensity uniform float RimCoefficient unity uniform float4 LightColor0 struct vI float4 pos POSITION float3 norm NORMAL float4 uv TEXCOORD0 struct vO float4 pos SV POSITION float4 uv TEXCOORD0 float3 worldPos TEXCOORD1 float3 normDir TEXCOORD2 vO vert(vI i) vO o o.uv i.uv o.worldPos mul( Object2World, i.pos).xyz o.normDir normalize(mul( float4(i.norm, 0.0), World2Object).xyz) o.pos mul(UNITY MATRIX MVP, i.pos) return o float4 frag(vO i) COLOR float3 lightDir float3 viewDir normalize( i.worldPos WorldSpaceCameraPos.xyz) float atten float3 normDir normalize(i.normDir) float4 RimLight float4 DiffuseLight float4 SpecularLight float2 UVCoord i.uv.xy float4 test tex2D( PixelMap, UVCoord) float4 Clrx0 lerp( Directional Light if( WorldSpaceLightPos0.w 0) lightDir normalize( WorldSpaceLightPos0.xyz) atten dot(lightDir, normDir) point light else float3 dist i.worldPos.xyz WorldSpaceLightPos0.xyz lightDir normalize(dist) atten (1 length(dist)) (dot(lightDir, normDir)) DiffuseLight atten LightColor0 SpecularLight atten LightColor0 SpecColor SpecIntensity pow(max(0.0,dot(reflect(lightDir, normDir), viewDir)), 1) (1 tex2D( DiffuseTex, i.uv.xy).w) RimLight atten LightColor0 RimColor RimCoefficient pow((1 saturate(dot( viewDir, normDir))), RimIntensity) saturate(dot(lightDir, normDir)) float4 totalLight DiffuseLight SpecularLight RimLight float4 fin float4(UVCoord.xy,0,0) return test Fin totalLight ENDCG |
0 | How can I create a custom PropertyDrawer for my Point struct? I created a Point struct System.Serializable public struct Point public int x public int y I am trying to create a property drawer for it, so that when it shows in the inspector, it is shown in a Vector2 field. I have the following script in the "Editor" folder using UnityEditor using UnityEngine CustomPropertyDrawer(typeof(Point)) public class PointEditor PropertyDrawer public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) EditorGUI.Vector2Field(position, label, property.vector2Value) It shows up in the inspector the way I want, but the values are locked at 0. Basically, I am trying to access the Point instance from inside the OnGUI method, but this could be the completely wrong approach. How can I make this so that when the values are changed in the inspector, the respective Point is also changed? |
0 | unity spriterenderer scale to fit screen portion let me explain what i have. a camera that render only a sprite ( sprite renderer) and what i'm looking for is to scale that sprite renderer to fit a screen portion (not the entire screen) for example 0.145 (normalized) anyone can help me? fix i mean, from 0 to 0.145 so the entire area ( it will be a 125x125 image ) so i need to keep the aspect ( same width and height) and i'm using orthographic camera |
0 | Is a mesh OK to use for grass if there will be 1000's of them across the terrain? Am creating a low poly game in Unity 3D for PC. The terrain is made in Blender, so it's a fixed size, but quite large for the player to explore. I want to add things such as grass and flowers, but am not sure the best practices are for creating those types of assets. Is using a mesh for small clumps of grass the wrong way to do this if there will be 1000's of them? I will likely be using the occlusion culling system Unity provides, but I'm not sure if I still need to look at doing things such as grass in a different way for performance sake. |
0 | Speech recognition in Unity 5 for Android I've been working on a game in which the player have to say particular words to perform various tasks. For example, if the player says "boat", a boat pops up in the game. The game I'm building is specifically for offline play, on an Android device. Just for reference, there is a game titled "Pah!" which implemented this offline speech recognition for one specific word. In this game, when you say "pah", the GameObject moves jumps. I've tried everything from speech to text to forums, and even tried Google and used using Windows.Speech, but nothing works. From what I've learned, I need to use the Google speech API for Android speech recognition. I am a bit new, when it comes to Java. I gave it a try and created a basic script, which I thought might take at least one input in speech from the player, but Unity disagrees and says it couldn't recognize the script. I created another script in C , by taking help from tutorials, but when I switch the platform from Windows to Android it doesn't work, because Unity.Windows.Speech is a Windows namespace I am blank, and hence, this question. I have googled, visited forums, and even looked at YouTube videos for an answer. I came across a few Unity assets which I paid for, and they are all garbage. If anyone could help me, how do I implement speech recognition in Android, using Unity 5? |
0 | How does the Unity3D entity system work? I saw the Java Artemis Entity Component System and thought of the entity system in Unity3D. In Artemis for example you can only add one component type to each entity and the logic is not in the component. In Unity3D it's completely different. Can someone explain me how the entity system in unity 3d works? I mean, is Unity3D a real entity system, or is it something else? |
0 | collision detection and normals from rigidbody Until now I've been developing my player character using a Character Controller, but have since decided to switch to rigidbody due to the controller's limitations. In order for my movement code to run as expected I need to know when the player is colliding with anything, and the normal of the surface it's colliding with. This is easy with a Character Controller, but is there a simple way to do it with a rigidbody? Here is a stripped down version of the script I'm using for collisions. Used in other scripts (Necessary) public GameObject ground null public Vector3 groundNormal public bool onGround Used internally public bool isColliding public float slopeLimit Character Controller public CharacterController controller void Start() controller GetComponent lt CharacterController gt () void Update() Check if the player is colliding with anything (Character Controller) if (controller.collisionFlags CollisionFlags.None) isColliding false else isColliding true Check if the player is standing on the ground if (isColliding amp amp groundNormal ! Vector3.zero) onGround true else onGround false void OnControllerColliderHit(ControllerColliderHit hit) Check for floor if (Vector3.Angle(transform.up, hit.normal) lt slopeLimit) Store floor object data ground hit.gameObject Store ground surface normal groundNormal Vector3.Normalize(hit.normal) else reset variables ground null groundNormal Vector3.zero slopeLimit is a static value. Additionally, getting the ground object isn't actually necessary atm, but I plan on using it later. Edit Currently I'm using controller.collisionFlags to detect when the player is colliding with something and haven't been able to find a similar alternative. Setting the isColliding bool to true using Rigidbody.OnCollisionStay would be simple, but setting it to false without use of another void function seems difficult. is that possible at all? |
0 | Import Blender model into Unity with Textures I tried a very straightforward import of the Monk model from https opengameart.org content monk into Unity 5.6.1f1, and ended up with no color texture on the model. Why? |
0 | How can I get my physically based sky to be blue all the way down? I'm rendering with a physically based sky. I want to get a very simple light blue background but below the horizon the sky becomes grey brown. How can I get it so that the sky is blue all the way down? As if the edge of the city was the edge of the world. I also want to make the blue sky brighter, especially at the bottom. |
0 | How to make high quality gifs of Unity game play I've seen several Unity game play gifs, mostly on twitter. Are there any tools for making high quality gifs in Unity that are quite flexible? For example, I video recording tool that captures the game window and allows users to make gifs of portions, possible specifying the desired quality. Generally, I am looking for a tool that is quite flexible (has a lot of options for capturing gifs) and possibly game window video. UPDATE Some examples are here and here. Generally, several of the gifs that are hash tagged madewithunity a really high quality. |
0 | How to stop the Unity Editor from continuously rendering? Look closely at the image below. Even though the game is not running the scene shows that green wheel is spinning. This means the scene is being rendered constantly and my battery is dying. I know Unity used to not do this and was in fact one of the reasons I liked Unity over some other engine that defaulted to always running and would make my laptop fans start up even when just sitting idle in the editor. Is there any way to get Unity to render on demand. Meaning, only render when I interact with it, when I move the camera or change a setting like it used it? I saw in preferences there's an "interaction mode" setting but the best it can be set to is don't render faster than 30fps. That's not useful. Is there some other setting to get the editor to only render when interacted with? |
0 | Limit the boundary of Touch a game that I currently working on is in a way that player should actually draw a rainbow on the screen by tap and drag gesture in order to make a hills for the car. but the issue that i currently facing on is if the player wants to pause the game by touching the right most button on the screen above, the game will stop but the hill that he was drawn will remove. I actually not have any idea how can i put exception for that button on the screen because everytime i calculate the whole pixels on the screen for drawing hills. do you have any idea how can i solve this issue ? btw, this is my code if it's required http pastebin.com VnLAQbzW |
0 | Using keyword NonSerialized causes Property to disappear from Inspector I have the following class to represent items in an inventory System.Serializable public class InventoryItemInfo MonoBehaviour public int Row 0 public int Col 0 public int Rotation 0 public InventoryItemType ItemType public int Amount public int EffectiveWidth 0 public int EffectiveHeight 0 public int Width 0 public int Height 0 public bool Selected false public Vector3 TilePosAccordingToCurrentRotation public Vector3 TileScaleAccordingToCurrentRotation NonSerialized public Transform TheNicelyPositionedMesh HideInInspector private int iCurRow 0 private int iCurCol 0 private int iRotationToCheckForDirtyness 1 public Vector3 DefaultRotation public bool Initited false public bool Dirty true private bool bInitialRotationGotten false (...) With the keyword NonSerialized , the property "TheNicelyPositionedMesh" disappears from the Unity Inspector. I don't see why. Why is that keyword coupled with the visibility in the Inspector? Thank you! |
0 | When to destroy Google AdMob InterstitialAd object? There are a few answers on this question but they don't give a satisfactory answer. I am using a singleton AdManager class that persists throughout the game. I am not sure if I should destroy the instance of InsterstitalAd each time after displaying an ad. This answer says that an InterstitalAd object can only be used once, however in my current implementation I use the same instance multiple times without any ill effect. using System using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement using GoogleMobileAds.Api public class AdManager MonoBehaviour public InterstitialAd interstitialAd private string InterstitialAdId "test code" public static AdManager Instance null void Awake() MobileAds.Initialize(initStatus gt ) RequestInterstitialAd() SceneManager.sceneLoaded OnSceneLoaded Singleton class if (Instance null) Instance this else if (Instance ! this) Destroy(gameObject) DontDestroyOnLoad(gameObject) void OnSceneLoaded(Scene scene, LoadSceneMode mode) DisplayInterstitialAd() public void RequestInterstitialAd() interstitialAd new InterstitialAd(InterstitialAdId) interstitialAd.OnAdClosed HandleOnInterstitialAdClosed interstitialAd.LoadAd(new AdRequest.Builder().Build()) public void HandleOnInterstitialAdClosed(object sender, EventArgs args) interstitialAd.LoadAd(new AdRequest.Builder().Build()) public void DisplayInterstitialAd() if (interstitialAd.IsLoaded()) interstitialAd.Show() public void DestroyInterstitialAd() interstitialAd.Destroy() As I understand the InterstitalAd object refers to a UI element, while the actual content of the ad comes from AdRequest, so I can reload the ad content without affecting the InterstitalAd object. Do I need to call DestroyInterstitalAd() after each time after an ad is displayed? I want to prevent any memory leaks from happening during long plays. |
0 | How to do pixel per pixel modeling in unity3d? So generally I want to have api like pixels.addPixel3D(new Pixel3D(0xFF0000, 100, 100,100)) (color, position) where pixels is some abstraction on 3d sceen objet.So to say point cloud. It would have grate use in deep space stars modeling... I want to set each pixel by hand (having no image base or any automatic thing)... So point is modeling something like Or look at alive flash analog here How to do such thing in unity? |
0 | Distinguish between HTC Vive controller grip buttons in Unity In Unity, I can check for grip button presses via the SteamVR API like so if(controller.GetPressDown(SteamVR Controller.ButtonMask.Grip)) ... This results in either true or false so I can only check if any grip button was pressed but not specifically which one. For Unity's Input API the documentation states 1 The grip trigger differs between platforms The HTC Vive controllers each have two grip buttons but both map to the same axis. The value for these buttons is 0.0 when not pressed and 1.0 when pressed (intermediate values between 0.0 and 1.0 are not possible). Source https docs.unity3d.com Manual OpenVRControllers.html In this case it is again not possible to differ between the two grip buttons. Is there any way in Unity to check which one of the grip buttons of a HTC Vive controller is pressed? |
0 | Rotating a gameobject in the Inspector doesn't change direction When I add a Cube to a scene, the blue axis ( forward) of the cube points into a certain direction. When I now change the Y rotation of the cube to 90 in the inspector, the blue arrow doesn't rotate. I would have expected it to rotate with the rotation that I have defined for the cube. What is happening here? To explain more in detail why this is bothering confusing me I want to rebuild the RE4 inventory (which is actual 3D). The items in this inventory can be moved within the "grid" To do that I have created a suitcase and then I added a gun to it As one can see, I have assigned the facing direction properly The blue axis ( forward) points into the direction of the gun. Now I wanted to rotate the gun in such a way that it is shown like in the original RE4 inventory. To do that, I apply a rotation of Y 90. The gun looks correctly now However, the blue axis now faces the wrong direction in my opinion. Why does it not rotate along with the rotation of the gameobject? This really confuses me because now when I want to move the gun left or right, I have to change its X position value instead of changing the Z position value. This just seems wrong to me. Can somebody tell me what I'm missing here? Thank you. |
0 | Draw wireframe models for Gear VR app in Unity I want to create a 3D Android app for Gear VR that does lets me do the following Read an input file with a bunch of coordinates of points (including information about how they should be connected) Draw a wireframe model with these points Walk around and through the model in first person to look at it from different angles using a gamepad controller. I don't want to directly interact with it! (Maybe have more than one model displayed at the same time, including filled ones) Is it possible to draw 3D wireframe models in Unity using coordinates instead of using already finished models that were created in Blender Maya etc, and if so, how? |
0 | Unity trigger problem I have been making my first game but I have encountered a small problem. To show the text when you win, you have to go into a block with the OnTriggerEnter line. I cannot get to this block however, because when I put my player (a sphere) as a trigger it just passes through the ground. How do I fix this? |
0 | How to run a long task without freezing my game? I have a component that is in charge of generating a level at runtime, and this is an operation that takes quite some time. As a consequence, I experience a hang when this operation is executed (when the scene is loaded). This problem can be summarized to the fact that SceneManager.LoadSceneAsync in fact is not async at all in its second phase, when it initializes all the objects. There are three approaches I have searched for and thought about Slicing the operation as explained on this video This is non trivial, I would have to rewrite chunks of code for the sake of avoiding a few seconds hiccup at scene load. Furthermore, the person explaining in the video says that they changed Unity source code which I don't have access to. Running the operation in a background thread This is definitely interesting, it would require minimal changes. The only problem is that at some point I have to create Unity objects (GameObject, Mesh etc) and this is not possible when outside Unity thread. I was thinking more or less of this code to be run on the background thread class Builder public void Build() 1. do something long 2. create Unity object with result from 1 something like that await RunInUnitySynchronizationContext(() gt new GameObject(...)) 3. do extra stuff on the result of 2 The thing is I have no idea at all on how that second step should be written, if possible at all. Use a non animated Loading screen and wait for it to finish This is the simplest and effectively does away with the problem by 'just' hiding it. Question What's an effective approach to solve this problem? |
0 | Unity AudioClip lags when played My AudioClip is lagging when I play it in Unity3d. The AudioClip is supposed to play when you left click inside the game window. Steps I've tried for fixing it Uncompressing the .wav sound file. Setting the clip variable of an AudioSource to a clip and then playing the sound, but that's a different story. How the issue occurs When I start the game, on the first click it plays fine. But then after a few clicks, it starts slowing down and or lagging. This is my code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI RequireComponent(typeof(AudioClip)) RequireComponent(typeof(AudioSource)) public class GameProcess MonoBehaviour public Canvas Game public AudioClip explosion AudioSource beatBox Transform btn Vector3 canvasMin Vector3 canvasMax Vector3 pointerMin Vector3 pointerMax Vector3 pointerPos void Start () btn Game.transform.FindChild("Pointer") canvasMin Game.GetComponent lt Collider gt ().bounds.min canvasMax Game.GetComponent lt Collider gt ().bounds.max pointerMin btn.GetComponent lt Collider gt ().bounds.min pointerMax btn.GetComponent lt Collider gt ().bounds.max beatBox GetComponent lt AudioSource gt () void Update () if (Input.GetMouseButton(0)) beatBox.PlayOneShot(explosion) if (!(pointerMin.x lt canvasMin.x) !(pointerMin.y lt canvasMin.y)) if(!(pointerMax.x gt canvasMax.x) !(pointerMax.y gt canvasMax.y)) btn.transform.position Input.mousePosition else btn.transform.position.Set(pointerPos.x 1, pointerPos.y 1, 0) else btn.transform.position.Set(pointerPos.x 1, pointerPos.y 1, 0) |
0 | Unity store data in database Is it possible to store assets used in a Unity game (2D or 3D) in the database? I think it is less efficient but want to have single source of truth and maybe have the game contact the database everytime it loads to get the new updates. |
0 | How to make rhythm game long notes in Unity? I'm making a rhythm game for a university course and I can't figure out a way to make the long sustained notes. For reference, this is what I mean taken from Guitar Hero I already have a system working for regular notes. The way I do it is that the notes are stored in an external file as numbers which represent the absence or presence of a note as well as what type of note it is, separated into musical bars 000 010 020 001 There are three lanes for the notes to be, and this means that in this particular bar there are notes wherever it's not 0 (with the numbers being different types of notes). I had thought of using this system to create long sustained note start and end markers (say 3 and 4) and that create another game object which would be the line between the start and end markers. But the way my note generator works is that the notes are not all generated at once because that'd be pretty heavy. Instead, the notes are generated at a certain time taking into account its speed so that it's instantiated and will reach the player's activator when it's supposed to. The following is a part of my note generator code, put in the Update method if current song time time offset is greater than time taken for all executed bars so far spawn the next bar's notes if (songTimer timeOffset gt (barExecutedTime barTime)) StartCoroutine(PlaceBar(noteData.bars barCount )) barExecutedTime barTime And here is the PlaceBar coroutine go through all notes in a bar creates an instance of note prefab depending on which note is meant to be spawned private IEnumerator PlaceBar(List lt SongParser.Notes gt bar) for (int i 0 i lt bar.Count i ) if (IsThereNote(bar i .bottom)) GameObject obj (GameObject) Instantiate(GetNotePrefab(bar i .bottom, true), new Vector3(bottomLane.transform.position.x distance, bottomLane.transform.position.y, bottomLane.transform.position.z 0.3f), Quaternion.identity) if (bar i .middle ! 0) GameObject obj (GameObject) Instantiate(GetNotePrefab(bar i .middle, false), new Vector3(middleLane.transform.position.x distance, middleLane.transform.position.y, middleLane.transform.position.z 0.3f), Quaternion.identity) if (bar i .top ! 0) GameObject obj (GameObject) Instantiate(GetNotePrefab(bar i .top, true), new Vector3(topLane.transform.position.x distance, topLane.transform.position.y, topLane.transform.position.z 0.3f), Quaternion.identity) yield return new WaitForSeconds((barTime bar.Count) Time.deltaTime) So if I were to make start and end markers, the start marker would not know where the end marker is because it doesn't exist. Could anyone help please? |
0 | View individual UI Rect boxes when multiple UI elements are selected? I have 2D UI layout with multiple text boxes over the canvas, I need to easily be able to see where the Rect boxes for each are positioned, so that I can see where the safe areas are for placing buttons etc. Selecting each individual item shows its own individual Rect box, but selecting multiple items just shows one big box around all of them. Is there a way of selecting multiple items and see each individual Rect box? It's extremely time consuming having to go and check each one individually. |
0 | UnityEditor related classes can not be referenced. Why? I have two classes. Both of them are placed in the editor interface field folder. using System using UnityEngine namespace editor.interface field public class RequiredInterfaceAttribute PropertyAttribute public readonly Type type public RequiredInterfaceAttribute(Type type) this.type type using UnityEditor using UnityEngine namespace editor.interface field CustomPropertyDrawer(typeof(RequiredInterfaceAttribute)) public class RequireInterfaceDrawer PropertyDrawer public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) if(property.propertyType SerializedPropertyType.ObjectReference) var requiredAttribute this.attribute as RequiredInterfaceAttribute EditorGUI.BeginProperty(position, label, property) property.objectReferenceValue EditorGUI.ObjectField(position, label, property.objectReferenceValue, requiredAttribute.type, true) EditorGUI.EndProperty() else var previousColor GUI.color GUI.color Color.red EditorGUI.LabelField(position, label, new GUIContent( quot Property is not a reference type quot )) GUI.color previousColor I have another class. using editor.interface field using UnityEngine namespace interface user.implementations public interface IInterface public class InterfaceUser MonoBehaviour SerializeField RequiredInterface(typeof(IInterface)) UnityEngine.Object interfaceImplementation The RequiredInterface(typeof(IInterface)) line throws the following error The type or namespace name 'RequiredInterfaceAttribute' could not be found (are you missing a using directive or an assembly reference?) Assembly CSharp csharp(CS0246) I can not understand why does not Unity see the RequiredInterfaceAttribute class and how could I make it see it. |
0 | Creating Saving and Loading Materials in Runtime I'm trying to create a material during runtime like this In my Assets I have a Render Texture and one Material I created an Script where I attach the Render Texture to Material I save in my project a PNG Image File for later use public void CreateAndSaveMaterial() RenderTexture.active renderTexture Texture2D tex new Texture2D( renderTexture.width, renderTexture.height, TextureFormat.ARGB32, false) tex.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0) tex.Apply() File.WriteAllBytes(Application.dataPath url, tex.EncodeToPNG()) tempObject.mainTexture tex RenderTexture.active null The PROBLEM 1.The Material works in rutime, after quit playing, the Material resets ( 2.The created PNG File not working only if the file is reimported in Unity, I tried with AssetDatabase.CreateAsset(obj, fileName) AssetDatabase.SaveAssets() AssetDatabase.Refresh() But unsuccessfully, works only in Editor not in build app ( Any suggestions? Thanks in advance! |
0 | How can I return the class as a Transform in the array instead of each property? public class TransformInfo public string sceneName public string name public Transform parent public Vector3 pos public Quaternion rot public Vector3 scale Then the method public static TransformInfo LoadTransformInfo() string jsonTransform File.ReadAllText( "d json json.txt") if (jsonTransform null) return null TransformInfo savedTransforms JsonHelper.FromJson lt TransformInfo gt (jsonTransform) return savedTransforms The return is But then when using it var test TransformSaver.LoadTransformInfo() Each item in the array contain the the TransfomInfo but instead I want it to return a Transform with already the info. So I can do for example Transform test1 test 0 Instead make a loop and assign each property from the Test to the new Transform test1. |
0 | Leaderboard Testing on Google Play Services I have a shared Google Play Developer account so that he allowed me to publish a game app. Next, I want to know if in order to test the online highscore is to upload the APK and publish it first before adding a new game at the Game Services section. One thing, according to this link and this link on setting up Google Play Services, these tutorials on implementing code for the leaderboard is possibly applied on the Manifest. Is it still the same in Unity if I added the lib folder onto the plugins folder of the Unity project and how? |
0 | Unity protect MonoBehaviour derived classes from instantiating via new in C When the class hierarchy grows and you deal with a lot of custom types in your project, it sometimes becomes hard to remember which types are allowed to be created via new and which types are derived from MonoBehaviour and therefore can't be created via new but must instead be attached to the GameObject as a Component. Is it possible to have some safety mechanism for this? The goal would be to have two base classes to control the ability to use new on a certain type. Ideally resulting in a compile time error instead of an easy to miss warning in the console ("You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. Blah blah."). My attempt to make the constructor protected, like this public class UnCreatableBase MonoBehaviour protected UnCreatableBase() using new should be not allowed public static T Create lt T gt () instead this method allows object creation return GameObject.Instantiate (Resources.Load ("Prefabs " typeof(T).Name) as GameObject).GetComponent lt T gt () public class CreatableBase public CreatableBase() new is ok here still allows me to write var whyDoesThisWork new UnCreatableBase() I can access the protected constructor even from an outside scope. Now, the obvious solution would be to make constructors of MonoBehaviour derived classes private. Manually. All of them. Manually. I was wondering if there's a way of achieving the same in a more generic way. |
0 | Voxel terrain generation performance problems I am trying to create a minecraft clone to practice some stuff in Unity including Raycasting, terrain generation and player controlls. Terrain is generating without any problem with a perlinNoise. My problem is the then following performance problems. The terrain is only 1 block high with no underlying blocks. Each block constist out of 6 quads with a 64x64 texture. I generate terrain at 200 x 200 size. I can't imagine why 4000 voxels with such simple textures can lag out whilst my pc runs objects with 50k tris and complex textures without any problem. My code ... public int xVoxels 200 public int zVoxels 200 ... for (int x 0 x lt xVoxels x ) for (int z 0 z lt zVoxels z ) voxel script parameter GameObject newVoxel GameObject.Instantiate(voxel) Vector3 position new Vector3() position.x xVoxels 2 x position.z zVoxels 2 z PerlinNoise stripped out for testing position.y 0f newVoxel.transform.position position Solutions I tried Combining meshes Combining all meshes to a single one per material worked wonderfully... until I wanted to interact with each voxel determined by Raycasting from the Camera, I had a raycast hit to the combined mesh and not to my determined voxel Generating the planes myself Instead of using the unity plane object I generated all vertecies myself, same performance problems |
0 | How to use a decal logo tatoo texture on a object or character? It appears I've misunderstood the purpose of Standard Shader's "Secondary Texture" options. If I wish to map temporary details to an object, what is the Unity appropriate way to do this? I am referring to effects like the following Tatoos Blood Spatters Logos Decals etc... I'm aware that I could have two materials, but this is render inefficient, and I avoid hackish workarounds when I can. Standard practice? EDIT Per the comment below, I will elaborate slightly In my specific case I'd like to have one of two scenerios 1 Areas where a logo can be inserted (player created), pre uv assigned. 2 Drag drop logo placement, similarly, but without constraints. This would mean of course passing UV boundaries. |
0 | How to "merge" multiple intersecting circles so that only the outer edges of each show? In my RTS (In Unity) each unit or building has strategic circles in a similar fashion to SupCom. If you have multiple units or buildings selected it looks like the picture to the left. I want to make it look like the picture to the right, where anything inside the outer edges of their circles is no longer shown. I draw these using vectrosity, mentioning this just in case vectrosity provides a way of doing this, or can be modified to do this. The circles are essentially just an array of points with lines drawn in between them. How would I go about "merging" the circles inside of their overlapping area? This is similar to How to make unit selection circles merge?, however I am not interested in a shader solution. Edit To re explain the above. I'm not seeing how the answers are applicable. I've read through the other thread before posting, which is why I posted it here to avoid this exact thing (being marked as a duplicate). I have an array of points with straight lines in between them to create a circle like effect. This is not a true circle, but a really granular polygon. I am interested in solutions that are achievable in C within Unity, not with shaders or with rendering mechanics. Edit2 Another picture based on one of Roberts suggestions This seems viable, though computationally expensive. If I have a circle made up of 250 points, and 50 circles all intertwined that's 615,500 checks in a worst case scenario. |
0 | stop object while falling The object have forwardForce. using UnityEngine public class PlayerMovement MonoBehaviour public Rigidbody rb public float forwardForce 800f void Start() void FixedUpdate() rb.AddForce(0,0,forwardForce Time.deltaTime) if(Input.GetKey( quot d quot )) rb.AddForce(30 Time.deltaTime,0,0, ForceMode.VelocityChange) else if(Input.GetKey( quot a quot )) rb.AddForce( 30 Time.deltaTime,0,0, ForceMode.VelocityChange) Now, the issue is I want to stop that object while falling down(not on that ground anymore).The camera will keep running but, I just want to stop that object. Which means if the is not on ground anymore than velocity 0 |
0 | Is it possible to configure a unity project so it only runs on a device? I am want to give someone a sample Android Unity project and I want them to be able to run it only on a device, not the simulator. Is there a way that I can configure the project so that it will only run on a device? |
0 | Sprites do not refresh reimport with ScriptedImporter using the SpriteEditor I've created an importer for Aseprite Files with the ScriptedImporter classes. I'm working on supporting the latest features of Unity like the secondary texture and this should work without bigger issues. The current issue I'm facing is when I change the sprites in the Sprite Editor or from a feature of my own, the asset won't get changed in the project window unless i switch to another folder and switch back. Do I have something wrong in my importing order or is something missing? I tried to refresh or reload the asset in the AssetDatabase but that didn't worked. The OnImportAsset method looks like the following. I implemented the ISpriteEditorDataProvider to support the sprite editor. public override void OnImportAsset(AssetImportContext ctx) name GetFileName(assetPath) aseFile ReadAseFile(assetPath) GenerateAtlasTexture() if (spriteImportData null spriteImportData.Length 0) SetSingleSpriteImportData() GenerateTexture(ctx.assetPath) ctx.AddObjectToAsset("Texture", texture) ctx.SetMainObject(texture) foreach (Sprite sprite in sprites) ctx.AddObjectToAsset(sprite.name, sprite) With the GenerateAtlasTexture method I create a sprite atlas out of the aseprite file. I had to create my own SpriteImportData class because Unitys struct won't get stored through the serialization process and I have to store the import settings of each sprite in a way. The GenerateTexture method uses Unitys own TextureGenerator class to generate the textures or sprites and store them in a instance variable called sprites. Here is the link to the repo. It is currently in the "sprite editor" branch. https github.com martinhodler unity aseprite importer tree sprite editor Thanks a lot |
0 | Upon import, isosphere is missing To build my tank for a Unity game, I am using Blender. Currently, I am making a turret consisting of an isosphere with half of the faces removed (I needed the bottom to be "flat") with some minor visual edits, two cylinders (one is the hatch, the other the antenna), and a cube to act as a hinge The inside is hollow. When I imported it to Unity (drag and drop from File Explorer straight to Unity Assets folder), the entire isosphere was missing as you can see from the preview I have tried to correct the normals with CTRL N as mentioned in other Blender forum pages but it still doesn't work. How exactly do I make my isosphere appear in Unity? NOTE This works if imported as a .fbx file but I would much prefer the file to be a .blend file instead (which is default). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.