_id
int64
0
49
text
stringlengths
71
4.19k
0
Tweaking screen transitions not to fire every time in Unity I'm making a simple screen transition system for my game which consists of two states firing the right clips (one for the starting half od the transition animation, one for the ending one) and a condition between the end and start one which is set to true when user wants to change the level (so that the Start animation would fire in the previous animation and the End in the new one). This is cool and all but poses two problems firstly, the game starts with the End phase animation which looks a bit weird. Secondly, since the Restart button in the main game just reloads the level, it causes the End transition to fire every time too which looks weird and out of place. How would I go about tweaking the Animator so that the End phase only runs when I actually change the level as opposed to when starting the game or reloading the current scene? Maybe there's some way to pass some kind of a parameter when loading a new scene that I'm not aware of? This way, I could just pass a flag like shouldFireEndAnimation so that it does not fire when the game just starts or a level restarts?
0
Third Person Flying Camera I am having issues creating a third person camera for my Rogue Squadron (N64) like game. First I have posted my issue on the official Unity Answers site here. So far my ship is behaving as I want and the camera follows position correctly (XYZ), however, it doesn't rotate how I would like. My first attempt was to set the rotation of the camera to the rotation of the ship and realized that is not what I am looking for either. I have found some information on rotating around a (pivot) point but I am having trouble understanding them. For example, I have found this and this but Im not sure how they work. The end result would be something like the camera found here. Thank you for any help, I would greatly appreciate a description of what you are doing how it works. Lastly this is done in C in Unity. I can provide my code if needed.
0
Can't go above max speed with RigidBody2D.AddForce() I'm having trouble making a character move faster than a certain limit using RigidBody2D.AddForce(). My game is a top down 2D game (constrained to the x y plane). I'm using a float 'MovementSpeed' to scale a normalized vector passed to RigidBody2D.AddForce(), however, when I increase MovementSpeed past 1000, there's almost no noticeable difference in the object's "speed" going from 100 to 1000 is a drastic difference, but there's almost no noticeable difference going from 1000 to 1000000. Here's my WASDMovement() function (called during FixedUpdate() ) private void WASDMovement() Vector3 translationVector Vector3.zero if (Input.GetKey(KeyCode.W)) translationVector new Vector3(0.0f, 1.0f, 0.0f) if (Input.GetKey(KeyCode.A)) translationVector new Vector3( 1.0f, 0.0f, 0.0f) if (Input.GetKey(KeyCode.S)) translationVector new Vector3(0.0f, 1.0f, 0.0f) if (Input.GetKey(KeyCode.D)) translationVector new Vector3(1.0f, 0.0f, 0.0f) translationVector.Normalize() rigidbody2D.AddForce(translationVector MovementSpeed) Here's a video demonstrating my problem to make it easier to see what I'm doing wrong http youtu.be 9kwKvfDOYoo
0
How could you create an SSX style snow trail in unity3d? So it SSX (a snowboarding game) when you are snowboarding you leave behind a dents in the snow(like a trail) .It's like how if you take a step in the snow you will leave a footprint behind but with a snowboard you leave a trail of where your snowboard has been. Can you create this or is this not supported by unity? If you can, how? Thanks in advance
0
Fading back and fourth Unity Image alpha I'm trying to create a way in which if I press a button, it'll highlight other objects whilst at the same time fading other objects. I also have other buttons that will fade and highlight different objects. Some of which may have been modified by the first button. I had done this originally in a really dumb way like so public void Highlight() foreach (Image image in imagesToHighlight) Color c image.color if(c.a lt maxColor) c.a maxColor image.color c foreach (Image image in imagesToFade) Color c image.color if(c.a gt halfColor) c.a halfColor image.color c This works, but I was wanting it to happen gradually to provide a smother transition. I managed to get the fade working, by changing the code to this IEnumerator Fade(Image image) float elapsedTime 0.0f Color c image.color while (elapsedTime lt 1) yield return fadeInstruction elapsedTime Time.deltaTime c.a 1.0f Mathf.Clamp01 (elapsedTime fadeTime) image.color c I then call the method in my foreach loop like so foreach (Image image in imagesToFade) StartCoroutine (Fade (image)) Again, this works fine. The problem I'm having is checking to see if the image is faded, and if it is and needs to be highlighted, it reverses from the fade value to the highlight value (0.5 to 1.0). I thought this would be a simple change as did this IEnumerator HighLight(Image image) float elapsedTime 0.0f Color c image.color while (elapsedTime lt 1 ) yield return fadeInstruction elapsedTime Time.deltaTime c.a Mathf.Clamp01 (elapsedTime fadeTime) image.color c Simply changing the alpha line. However, now my image alphas jump all of the place in the highlight method. I'm at a loss as to how I can fix this. Can someone please tell me what I'm doing wrong?
0
Unity 5.x Network Synchronization Concepts Bear with me, It will be long read I am working on the new Unity Networking system. I was using Photon and old (legacy) unity network API's before. But as it seems there are some good benefits of the new system than the previous ones, so I want to stick with it. (Despite of it being uncompleted) But there are some points that doesn't make sense to me with the API. Data Sync for example. So, in the old systems (both in Photon and legacy unet) we had functions called OnPhotonSerializeView or OnSerializeNetworkView depending on which API we use. Both API's are very similar as you may know. So in these functions we could send and recieve data between clients and server. Which makes sense, and was really usefull. But aperantly they changed this concept, (or it still exists, and i couldn't find it) There is a new thing called SyncVar , which syncs the data "ONLY" from server to client automatically. (Which really, literally doesn't make sense, I mean why not sync both server to client AND client to server? That would make everything much easier) According to the documents, you can ONLY send data from client to server by using Command 's. Which is basically (as far as I understand), "one way" version of old good RPC calls. Instead of calling function in all other clients, it calls it in the server. So, you can send data to server with function parameters like the way we did it with the old RPC 's before. Which is usefull on point but If this is the only way to send data to server, then it doesn't make any sense to me.. I mean there are variables that needs to be kept synced all the time, back and forth, like position or rotation vectors. And sending them with Command calls, contradicts with the concept of network framework in my mind. We used to avoid this kind of situation before, right? Why make it the obligation now? Or are there simply any other ways to send data from client to server that I couldn't find yet? There is a custom serialization with the SyncVar , with OnSerialization and OnDeserializaton functions. Which really looks like the good old OnSerialize functions but apperantly it's diffrent as it does what the SyncVar does. OnSerialization is only called on server, and Deserialization is only called on client. So we can only send from server to client even with it. If Command is the only way to send data to server, please say so. And clarification about why this concept is reasonable would be really nice. Please enlighten me more with the new concepts of the new UNET framework. Thanks in advance for any help.
0
Accessing enum value in other scripts I am attempting to make a global MaterialAssign script that I can assign to anything and have an enum selector in the inspector to assign a material type. This would then drive hitFX and soundFX variation in other scripts. My selector script MaterialAssign.cs using System.Collections using System.Collections.Generic using UnityEngine public class MaterialAssign MonoBehaviour public enum MatSelection defaultMat, metalEnemy, metalWall, dirtWall public static MatSelection currentMat Attempt at usage in another script if (MaterialAssign.currentMat MaterialAssign.MatSelection.metalEnemy) selectedHitFX bulletMetalEnemyFX else if (MaterialAssign.currentMat MaterialAssign.MatSelection.metalWall) selectedHitFX bulletMetalWallFX I have no errors in the console BUT the enum selector doesn't show up in the inspector, so I'm assuming no value is ever passed. I read that enums can't have a static value, but not sure how to handle that. Any assistance would be most appreciated or alternate approaches welcome! I'm purposely trying to stay away from tags, but can go down that path if needed.
0
Preparing a 2D character to export from Blender to Unity? I'm an animator for a game currently, and I don't have Unity (can't download due to too much gigs coupled with slow internet,) but the game designer told me I can use Blender to export animations into Unity. I asked if I needed to prepare multiple files to export, and they told me that I could just have one file with all the animations in it. The game, as stated in the title, is 2D. My problem now is, how do I turn a rig into an actual character with different animations under it? (Right now I only have an 'idle' animation, but need to make running, jumping, walking, etc.) I mean how do I save this 'idle' animation and work on another animation without overwriting the previously finished animation(s)? Thank you much
0
How to correctly draw a 2D polygon in Unity I'm trying to draw a 2D polygon using GL.Line however I'm not getting a polygon but separated lines instead. In the example below, I would expect a rectangle formed by the spheres My code is the following void OnPostRender( ) GL.PushMatrix ( ) mat.SetPass ( 0 ) GL.LoadOrtho( ) GL.Begin( GL.LINES ) GL.Color( Color.white ) for ( int i 0 i lt spheres.Length i ) currentVector Camera.main.WorldToViewportPoint ( spheres i .transform.position ) GL.Vertex3 ( currentVector.x, currentVector.y , 0 ) GL.End() GL.PopMatrix() Also, I found this tutorial example but is not exactly what i'm looking for, since in the example, all have the same origin point. I'm asumming that the correct way of achieving what I want, would be to call the Gl.Vertex3 method once for each of the 2 points that form each line From A to B (GL.Vertex3 call 2 times) From B to C (GL.Vertex3 call 2 times) From C to D (GL.Vertex3 call 2 times) From D to A (GL.Vertex3 call 2 times) Is this the right way of doing this? Thanks in advance.
0
Which image effect is this? This is a screenshot from RE7. I have once seen the same image effect in Unity, but I don't remember the name I'm not talking about AA or DOF here, I mean this grainy greenish thing, I don't know how to describe it... At first I thought the name was something like quot Anisotrophic filtering quot , but that didn't bring up anything that looked like it. Can anybody tell me the name of the effect that I see here? Edit It can be seen in the start screen of this video, too https www.youtube.com embed aaN3MNb9ij0?feature oembed Both screenshots look pretty similar to me, so I guess it's the same effect? Edit 2 The pixels seem to shift into red blue the closer they get to the edge of the screens. I have drawn red arrows to region where this effect is very visible to me. These pixels appear as quot shifted quot to me. I think this effect is more visible at the edge of the screen. Thank you.
0
Consume input events in Unity 4.6 How do I consume the input events in the new 4.6 unity gui system? If I click on a button for instance I don't want anything else non GUI related that might be listening for mouse input to react to the event.
0
World Canvas InputField cursor precision control from RenderTexture output in Overlay UI How do you have a world canvas input field cursor be controllable from the input being mapped from a UI overlay with its raw image supplied from render texture from a render camera? Described another way World Canvas Input Field gt Render Camera creates renderTexture for gt Screen Overlay UI Raw Texture gt Main Camera How do you have the cursor position be mapped from the Screen Overlay UI Raw Texture?
0
Player animating the wrong direction once he is rotated I have used the scripting root motion move the player when using an 'inplace' animation. All works correctly until the players rotation is off 0,0,0. This is expected as the movement is along the transform.z axis but how can I account for the rotation in the script and apply it so the movement is correct in game? The gorillacontroller script is the script we are trying to fix On playerGorilla. animator is on the playergorilla. The gorilla1 is the gameobject holding the mesh and the bones for the character. I will also add the transforms are moving this was my silly mistake because I had tool handles in global instead of local. This makes it even more confusing however because all tranform.z (blue axis) are facing the correct way for the animation to work but the animation is only ever playing in the original direction where the rotation is 0,0,0,0. using UnityEngine using System.Collections RequireComponent(typeof(Animator)) public class RootMotionScript MonoBehaviour void OnAnimatorMove() Animator animator GetComponent lt Animator gt () if (animator) Vector3 newPosition transform.position newPosition.z animator.GetFloat("Runspeed") Time.deltaTime transform.position newPosition
0
Can Cruncher crunch Daz models? I have a number of Daz 3D models that I would like to use in my Unity shooter game. The only problem seemed to be the high poly count of the Daz models. However, I just came across the Cruncher Polyreduction tool (http assetstore.unity3d.com content 4294). Is it possible to use this plugin to incorporate Daz models in my game?
0
Problem with Animating on local position Unity Currently, I am having a Cube that needs to be animated to roll on its edge. Using unity built in animation feature, I created 4 animations (RotateUp, RotateDown, RotateLeft, RotateRight). At the end of each animation I would put an Event to call a method on my script. To be able to move the object every time the animation is played, I put the cube with animator attached inside a parent object. Below is the script attached to my cube. using System.Collections using System.Collections.Generic using UnityEngine public class RedCubeBehavior MonoBehaviour Animator anim bool isMoveTriggered false void Start() anim gameObject.GetComponent lt Animator gt () void Update() if (Input.GetKeyDown(KeyCode.UpArrow)) MoveUp() else if (Input.GetKeyDown(KeyCode.DownArrow)) MoveDown() else if (Input.GetKeyDown(KeyCode.LeftArrow)) MoveLeft() else if (Input.GetKeyDown(KeyCode.RightArrow)) MoveRight() if (isMoveTriggered) if (IsBackToIdle()) transform.parent.position transform.position transform.localPosition Vector3.zero isMoveTriggered false void AnimationFinished() anim.Play("IdleState") public void MoveUp() if (isMoveTriggered) return else Debug.Log("MoveUp") isMoveTriggered true anim.Play("RotateUp") public void MoveDown() if (isMoveTriggered) return else Debug.Log("MoveDown") isMoveTriggered true anim.Play("RotateDown") public void MoveLeft() if (isMoveTriggered) return else Debug.Log("MoveLeft") isMoveTriggered true anim.Play("RotateLeft") public void MoveRight() if (isMoveTriggered) return else Debug.Log("MoveRight") isMoveTriggered true anim.Play("RotateRight") bool IsBackToIdle() return anim.GetCurrentAnimatorStateInfo(0).IsName("IdleState") Every time the arrow key is pressed the object would rotate but in the end when AnimationFinished() is called, the cube would just roll back to its starting position (because of playing IdleState). It will only work (the object didn't return to its starting position) if I pressed the arrow twice quickly. I've tried to not call the IdleState (which is only an empty state), but what happens next is it just won't play another animation again when triggered. What should I do in order to get it work without having to press the key twice?
0
In Unity, how do you check if a camera is rendering anything? (Unity 2018.3) I'm trying to have a camera automatically disable if it's not rendering anything. Is there a simple way to check if a camera is blank empty? Edit Alternatively, is there a way to prevent a camera from rendering if there is nothing in it's view? For example, I do not want MSAA applied to a blank camera. (I'd hope it would attempt AA, but effectively do zero work)
0
Manage vertical levels rendering I've been working on a semi professionnal project for more than one year. The game is in 3D with a TopView camera. In this game, the player will be in very vertical spaces, with lots of ladder and stairs. The actual problem is that I need to show only what is at the actual height of the player. I have made a shader that 'cut' the objects above a given height. The problem is that my mesh are open above this height, and we just see nothing inside. If you have any idea on how to make something to fill an open mesh or any other system that will do the job, i'll be very pleased to read you ) This is what I have This is what I aim to (black above top of walls)
0
FullSerializer Update serialized property name Currently we have some ScriptableObjects that are referenced by their name. This comes with some issues as names may change and also they don't have to be unique. We would like to switch to UUIDs. using FullSerializer System.Serializable fsObject(Converter typeof(CharacterDataConverter)) public class CharacterData public CharacterSO player public CharacterSO mentor The mentor field is currently serialized as mentorName. With the changes the serialized field name would be mentorUid. This is handled by the CharacterDataConverter, but this has to be updated all the time when CharacterData class changes and is often forgotten. Much simpler would be to use fsProperty using FullSerializer System.Serializable public class CharacterData fsProperty(Converter typeof(PlayerConverter) public CharacterSO player fsProperty(Converter typeof(CharacterSOConverter), Name quot mentorName quot ) public CharacterSO mentor But this can handle only either mentorName or mentorUid. Is there another solution? Maybe using versioning?
0
OnInspectorGUI Custom properties are not displayed in the right order I basically made a lot of research and wasn t able to find any solution. So my problem I ve made some variables disappear appear depending on an enum with a custom editor script. But if they appear they do not appear at the position where the normal editor variables would appear override public void OnInspectorGUI() base.OnInspectorGUI() GunCard myScript target as GunCard EditorGUI.indentLevel switch (myScript.aimingControlType) case AimingControlType.Manual myScript.hasAimAssistance EditorGUILayout.Toggle("Has aim assistance", myScript.hasAimAssistance) break case AimingControlType.AutoTargeting myScript.targetPreference (TargetTypes)EditorGUILayout.EnumPopup("Target preference", myScript.targetPreference) myScript.requiresLineOfSight EditorGUILayout.Toggle("Requires line of sight", myScript.requiresLineOfSight) myScript.requiresPossibleTargetOnScreen EditorGUILayout.Toggle("requires possible target on screen", myScript.requiresPossibleTargetOnScreen) break EditorGUI.indentLevel Here is where they appear That are the raw variables in the scriptable object Header("Aiming Controls") public AimingControlType aimingControlType HideInInspector public bool hasAimAssistance HideInInspector public bool requiresLineOfSight TODO implement gt requires 180 HideInInspector public bool requiresPossibleTargetOnScreen TODO implement gt requires 180 HideInInspector public TargetTypes targetPreference HideInInspector public bool isAutoShootWhenAimOnTarget I know I m basically adding new variables to the inspector in my editor Script but it would be really useful to order them. Is there a way to do that? P.S sorry for the funny typo in the picture )
0
How to place same canvas on multiple cameras in Unity? I know how to do It on one, but I don't know how to do it using multiple cameras, 3 of them are important, i want to show the whole UI except for the minimap. I need to change the camera angle on some spots, while keeping the same canvas for displaying the number of coins XP and the current level.
0
How to calculate acceleration distance(frictionless, massless) Object A is moving via. 2D rigidbody by velocity V and in script is defined breaking power P. Every frame of breaking (P Time.deltaTime) is subtracted from velocity V (in other words, ignoring mass). How i can calculate distance D required to slow down to target velocity tV ? I'm not actually using force power but i setting velocity directly with this line of code Vector3 dir transform.TransformDirection(Vector3.up) ship.rb.velocity Vector2.MoveTowards(ship.rb.velocity, (dir maximalSpeed) ship.massModifier, speedGain ship.massModifier) (Don't worry about ship.massModifier, Basically heavier ship hulls are slower) I'm self learning Indie developer and i need this for AI to my game. Enemy in space ship have nothing like space breaks so only way how to slow down is to turn ship by 180 degrees and thrust forward in counter direction.I need to know this to calculate distance from target required to slow down and prevent possible collision with target.
0
Unity animations threading As one cannot play around with threads themselves, the user made code that uses unity's API is executed on the main thread. I'm sure unity uses some sort of thread management on its own though. Thing is, I wrote some basic UI animation toolkit (rotate, scale, lerp alpha, move and tie events etc) that as being user code runs on the main thread, taking up CPU power, even if they are not vital to be completely synchronized with the logic. (Event connected to them only start other animations). I would like to know if Unity uses another thread for animations as well and if so, is it possible to mark this UI toolkit to be executed on that thread or as I said user code with unity api can be only ever executed on the main thread?
0
Unity LWRP alternatives for camera stacking I am working on upgrading a project in unity from a 2018 version to the latest 2019. One of the mechanics of the game is an AR (augmented reality) system. Some of the UI elements appear in the 3D world, but clearly as part of the hud. They need to be transformed as the camera moves, but should always be drawn on top of the 3d scene. The old project achieved this via camera stacking. All the AR elements were drawn on a different camera which rendered on top of the 3D camera. The clear flags were set to "depth only" and it removed all other elements from that camera. In the 2019 version of Unity with the Lightweight Render Pipeline (LWRP), the clear flags feature on the camera is missing. To the best of my research, camera stacking has been removed from LWRP. What are my alternatives? How can I now achieve this effect? I would like to stick to LWRP as I am using Shader Graph for many of the effects in the game.
0
Unity Improvements to skinnedMeshRender.BakeMesh performance or alternatives? I'm running to a situation where I need to do some manual deformation to a skinnedMeshRenderer's mesh vertices after applying some blendskinning. I'm finding that the following code takes 15ms to run. I've calculated the time both by running it 100 times and measuring time difference, and by using the Unity Profiler. Mesh bakedMesh new Mesh() skinnedMeshRenderer.BakeMesh(bakedMesh) The mesh has 7000 vertices. I just need loop through each vertex to get its current (blendskinned) position relative to its gameObject's local origin. The goal is to calculate the amount of deformation it experienced. so something like (pseudocode) for i in vertices deformation i originalVerticies i bakedCertices i It's the call to BakeMesh that is slowing things down, which is required to get bakedVertices i . Is there another way to get backedVerticies i without actually baking the mesh? Maybe some kind of manual calculation to simulate baking but only on the vertices? or perhaps some way to speed up the baking process? Additional info The reason i'm calculating the deformation is to undo unity's automatic linear blend skinning, since at runtime I want to move some bones without affecting the mesh. However, when I move the bones, unity's automatic linear blend skinning kicks in and deforms the mesh, so this is a way to calculate how much it was deformed so I can "Undo" this blend skinnning by adding the deformation back on to the vertices. Perhaps there is a more elegant solution, but I can't find any way to temporarily turn off the automatic linear blend skinning. Note that I need to do this every single frame. I'm currently at 15ms for this script, which is really pushing the 16ms limit to maintain 60fps. When I add other scripts etc into the scene it will for sure be laggy. I would also like it to run at at least 90fps since i hope to use this script in VR in the future.
0
Unity2D Collision Issue I have a crate setup (in pic below) with a rigid body component, box collider and 3 circle colliders(they allow me to push the crate most of the time without getting stuck on the floor textures which are normal box colliders) As you can see in the pic there are collisions detected between the crate and floor even though they are not physically touching. How can i make the collisions more precise as my crate gets snagged on the floor textures when there is minuscule difference between the floor box colliders?
0
Is this Possible to force gameobjects (coliders etc) to get stretched based on the aspect ratio of the screen? Well with unity3D, I am in big trouble whenever I use sprites. As for textures I compensate for a evener look by Stretching it (Screen.width amp Screen.height that's fine for low end 2D games). Now If I have an Image and based on content of Image (Let's say I want to add BoxCollider for the walls in image). It works, but for only one aspect ratio. As I am making game for Android. I am having bunch of different resolution amp Aspect ratios. Is this possible to stretch my coliders or other game objects so that I can Work easily???? please help me. I am in a rush (
0
Moving a GameObject to a position, waiting, and then moving it again Hello hello ) Ive been attemping to move a platform (a door basically), and it has partually worked. What works so far is i can move an object from A to B and wait, however it will not move it towards C afterwards, here is my code (note that all of the Debug.Logs work). Here is my code. public class OpenDoor MonoBehaviour public Transform origPos public Transform targetPos public float speed public GameObject button private ButtonScript bs private void Start() bs button.GetComponent lt ButtonScript gt () void Update() if (bs.buttonActive) Debug.Log("Button Active 2") StartCoroutine(MovePlatform()) bs.buttonActive false IEnumerator MovePlatform() float step speed Time.deltaTime bool arrived false while (!arrived) transform.position Vector3.MoveTowards(transform.position, targetPos.position, step) if (Vector3.Distance(transform.position, targetPos.position) 0) Debug.Log("DISTANCE 0") arrived true yield return null if (arrived) Debug.Log("Arrived") yield return new WaitForSeconds(1) Debug.Log("Waited") transform.position Vector3.MoveTowards(transform.position, origPos.position, step) Any assisstance would be greatly appreciated )
0
Physics2D.Raycast not hitting any colliders I am making a topdown 2d game and want to get the x,y of mouse clicks so I can move the character to that location. I am writing a CharacterController script which performs the mouse click check and raycast in the Update function void Update () if (Input.GetMouseButtonDown (0)) RaycastHit2D hit Physics2D.Raycast(Input.mousePosition, Vector2.up) if (hit.collider ! null) Debug.Log (hit.point) This runs whenever I click the mouse, but the if(hit.collider ! null) condition is never met. I've looked around for other solutions, such as Unity Raycast not hitting to BoxCollider2D objects, but when I change my code to the one used in that answer RaycastHit2D hit Physics2D.Raycast( Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector3.back ) then the if(hit.collider ! null) block is always true, even if I click on empty space, and it always returns the same coordinate. To illustrate this, here is a video of me clicking the game view. The green area has a 2d box collider that is very closely mapped to its boundaries. You can see that the logged hit.point is always the same. video is here https i.imgur.com uhNp8wC.gifv screenshot
0
Why Does unity LightPosition 0 Seem to Depend on Camera Position? I'm trying to write a fairly basic shader but I keep running into lighting issues with Unity. My first problem was trying to figure out which variable stored the light's position in world space. (I'm only working with one light, at least at the moment). I finally found something that responds to movement of my light source unity LightPosition 0 . However the shader still didn't do what I wanted it to do, so I did some debugging I have a basic vertex and fragment shader and what I'm currently doing in the fragment shader is float4 c float4(0, 0, 0, 1) float3 lp normalize(unity LightPosition 0 ) c.rgb lp return c This should just set the color of my object to the normalized position of the light source, correct? What I see in my scene is my object changes colors when I move my camera around it (I'm not moving the light source at all, it is a separate entity). The color also seems to increase in strength as I zoom in. To me, it seems as if unity LightPosition 0 is related to my camera's position, as well as orientation and zoom level, yet the documentation I've found says it should represent the position of the light in world space. I tried switching to using the following float3 lp float4( unity 4LightPosX0 0 , unity 4LightPosY0 0 , unity 4LightPosZ0 0 , 1.0 ) ...but that only colors my object red regardless of the light's actual position. Additionally, I've set the LightMode tag to Vertex. It seems like simply getting the world position of the light source shouldn't be this difficult. What am I not doing correctly? EDIT I've been playing around with the camera and light position and I think that unity LightPosition 0 actually puts out position in the projection space. If I place the light source in the lower left corner of the screen, the object is black. Upper left the object is green (0, 1), upper right is orange (1, 1), and lower right is red (1, 0). When I place it in the lower left (0, 0) and move the camera in front of it, it becomes blue. This is consistent with the depth value behavior. (0, 0, 0) would appear as blue. Now, how to get it from projection back to world?...or should I use a different variable?
0
Rotate object always at same speed on screen, no matter camera distance? I am rotating a globe like XCOM's hologlobe, I rotate it using Quaternion.RotateTowards(Quaternion from, Quaternion to, float maxDegreesDelta). I found a good value for maxDegreesDelta, in my case it is 5.0f. There is a limit on how close or far the camera can be, let's assume clos is 1.0f and far is 2.0f. I want to be able to zoom into the globe, but obviously when I do, it rotates a bit too fast then. When zoomed out, rotation speed is satisfying When zoomed in, rotation is too fast, making it more difficult to manipulate And the problem is even more evident as game view size gets bigger, i.e. fullscreen. Using Mathf.Lerp and Mathf.InverseLerp, I've tried to make maxDegreesDelta and mouse delta proportional to the distance the camera is but it's hardly convincing. Note I rotate the globe, not the camera. Question How can I ensure object rotates at same speed on screen, no matter how close or far camera is ? Code (assumes there is a sphere of radius 0.5 at Vector3.zero and camera is positioned at Vector3.back) using UnityEngine using UnityEngine.InputSystem namespace Test2 public class GeoScapeController MonoBehaviour region Public public Transform TargetObject public Camera TargetCamera Range(0.01f, 1.0f) public float Sensitivity public bool Smooth public float ZoomDistanceMin public float ZoomDistanceMax endregion region Private SerializeField HideInInspector private Quaternion TargetRotation SerializeField HideInInspector private int ZoomLevel SerializeField HideInInspector private int ZoomLevels SerializeField HideInInspector private Vector3 ZoomVector SerializeField HideInInspector private Vector3 ZoomVelocity private void Reset() Sensitivity 0.05f Smooth true ZoomDistanceMin 0.625F ZoomDistanceMax 1.25F ZoomLevels 10 private void Start() TargetRotation Quaternion.LookRotation(TargetObject.forward, TargetObject.up) ZoomVector TargetCamera.transform.position private void Update() var mouse Mouse.current var delta mouse.delta.ReadValue() var scale new Vector4( 1.0f, 1.0f, 1.0f) var x mouse.leftButton.isPressed ? delta.y scale.y Sensitivity 0.0f var y mouse.leftButton.isPressed ? delta.x scale.x Sensitivity 0.0f var z mouse.middleButton.isPressed ? delta.x scale.z Sensitivity 0.0f var r Quaternion.AngleAxis(x, Vector3.right) Quaternion.AngleAxis(y, Vector3.up) Quaternion.AngleAxis(z, Vector3.forward) if (Smooth) hopefully, quaternion limits won't be crossed ! TargetRotation Quaternion.RotateTowards(TargetRotation, r TargetRotation, 2.5f) TargetObject.rotation Quaternion.Slerp(TargetObject.rotation, TargetRotation, Time.deltaTime 5.0f) else TargetObject.rotation TargetRotation r TargetRotation var wheel (int) mouse.scroll.ReadValue().y 120 if (wheel ! 0) ZoomLevel Mathf.Clamp(ZoomLevel wheel, 0, ZoomLevels) var lerp1 Mathf.InverseLerp(ZoomLevels, 0, ZoomLevel) var lerp2 Mathf.Lerp(ZoomDistanceMin, ZoomDistanceMax, lerp1) ZoomVector Vector3.back lerp2 TargetCamera.transform.position Smooth ? Vector3.SmoothDamp(TargetCamera.transform.position, ZoomVector, ref ZoomVelocity, 0.3f) ZoomVector endregion
0
How to instantiate cubes at every given positions I have a list of coordinates in 3D (XYZ) list 226.29, 485.28, 345.396 , 298.292, 108.226, 551.422 , 452.987, 164.874, 416.242 , 562.8, 29.4951, 297.651 , 610.087, 99.9056, 156.377 , 470.804, 12.3284, 428.671 , 590.609, 197.615, 137.146 I want to instantiate cubes at every given positions, how to define given list correctly in C and use it as a vector3 ? I tried something like that.. for (int i 0 i lt 7 i ) Instantiate(prefab, new Vector3(list i ), Quaternion.identity)
0
In unity, how do I rotate a vector in relation to the player? I am making a radar script in a unity FPS game project I am making for class. I already have a working example of a radar script that works in relation to the player's position. However the rotation is in relation within the world map, not the player's view. In code I have it kinda like this (not actually my code, as I don't have it with me right now, but basically the same algorithm) if (isPlayerInViewRange(otherPlayer i ) these are both normalized Vector dir getDirectionFromPosition(player, otherPlayer) dir rotateDirectionInRelationshipToPlayer(player, dir) problem here dir new Vector3(dir.x, dir.z, 0) dir.Scale(MapToRadarPosition, 0, MapToRadarPosition) radarDot i dir radarDot i .setActive(true) else radarDot i .setActive(false) Any ideas what I am missing, I feel like I am missing some obvious function to do it.
0
Rotating UVs by X degrees I would like to make a tileable texture with UV noise in Unity Shader Graph only, but I have a problem. After creating simple noise from UV, I want to rotate it by 90 degrees, but the node Rotate (as well as Rotate About Axis) doesn't rotate my UV (like a picture in PS), instead it changes the colors in it from black amp white to red (yellow, green, ...) amp black. Could you tell me please, how to fix it? Some context Based on the answer https gamedev.stackexchange.com a 23631 , I want to rotate the noise three times (so 0 90 180 270 ), multiply them and thus normalize the edges to make the texture tileable. Instead of it, even at 0 rotation the color of noise is changed to yellow somehow and the multiplication is everything but not the result I want. That's how I wanted to do it
0
Unity Failed to build APK. See console for details i am getting this error whenever i am trying to build a project. i looked at so many solutions but this one just doesn't go away. This is the error CommandInvokationFailure Failed to build apk. C Program Files Java jdk 9 bin java.exe Xmx2048M Dcom.android.sdkmanager.toolsdir "C Users Mohit AppData Local Android sdk tools" Dfile.encoding UTF8 jar "C Program Files Unity Editor Data PlaybackEngines AndroidPlayer Tools sdktools.jar" stderr Exception in thread "main" java.lang.reflect.InvocationTargetException at java.base jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java 62) at java.base jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java 43) at java.base java.lang.reflect.Method.invoke(Method.java 564) at SDKMain.main(SDKMain.java 130) Caused by java.lang.NoClassDefFoundError sun misc BASE64Encoder at com.android.sdklib.internal.build.SignedJarBuilder. lt init gt (SignedJarBuilder.java 177) at com.android.sdklib.build.ApkBuilder.init(ApkBuilder.java 446) at com.android.sdklib.build.ApkBuilder. lt init gt (ApkBuilder.java 422) at com.android.sdklib.build.ApkBuilder. lt init gt (ApkBuilder.java 362) at UnityApkBuilder. lt init gt (UnityApkBuilder.java 214) at UnityApkBuilder.main(UnityApkBuilder.java 34) ... 5 more Caused by java.lang.ClassNotFoundException sun.misc.BASE64Encoder at java.base java.net.URLClassLoader.findClass(URLClassLoader.java 466) at java.base java.lang.ClassLoader.loadClass(ClassLoader.java 563) at java.base java.lang.ClassLoader.loadClass(ClassLoader.java 496) ... 11 more stdout exit code 1 UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.AndroidSDKTools.RunCommandInternal (System.String javaExe, System.String sdkToolsDir, System.String sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.AndroidSDKTools.RunCommandSafe (System.String javaExe, System.String sdkToolsDir, System.String sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.HostView OnGUI() what i have tried so far 1) downgrading android sdk 2) moving zipalign file from build tools to tools folder 3) setting up keystore
0
Can I create realtime textures with text? I have a large number of items in my game, that will eventually have a texture associated with them. The problem is, for right now, I have nothing. I would really like to do something with, say, the first 2 letters of the object's name. As my main system will be pure textures, I really don't want to add a text object to the texture, I would really like to just create a texture with the object's first two letters. Is there a way I can create a texture, realtime, with font rendered on that texture? Preferably without a camera render texture, unless I can create them once. I really want to create a unique default texture for each item at runtime, preferably with some kind of font. Can I do this?
0
Unity vr device support I have been looking for a list of VR devices that unity supports (or that you can use to develop VR games with). However i have been unable to find a list. Currently im looking at BOBO VR Z4 But to make sure i do not make any incorrect purchases so it would be really helpful to know supported devices. Also it is worth noting i'm going to be using the newest version of Unity. (which is currently version 5.6)
0
Will my huge sprites for a 2d game create performance issues? I'm new to Unity, and have been confused about this issue for a while. Some people say that for 2D games you don't need to worry about performance (I'm making the game for PC, not mobile) while others report bad performance with larger sized sprites I have a long scene with some large background sprites, measuring about 14552x3308 (weird resolution I know, would that also cause issues?) All methods of scaling it down and resizing in Unity lead to jagged edges (these are basically hills so I need them to be significantly bigger than the player character) I always keep the image size in the inspector similar to the resolution of the actual file, and set the filter mode to Point, so the jagged edges are not due to that, but only because of me scaling up a smaller file size to fit the scene. If I use the original sprites of 14552x3308, it's perfectly smooth (image size set to 8192 in inspector) but each file takes about 120mb in the profiler. All combined, my assets are showing a usage of 1.25 GB for this scene. How bad is this? Should I be trying to keep it under 1GB? I don't really know what the best practices are in this situation, so I don't know what to aim for. I'd ideally like to keep the sprites at this large size so that I don't have to redraw anything.
0
My runtime mesh is not being created where it's vertices are located, need help I'm trying to create a quad at runtime and I'm encountering an issue where the mesh does not show up in the scene where it's vertices where set. In the following picture you can see the ship, and to the far right the mesh. The 4 white dots around the ship where drawn after the mesh was made using the 4 vertices of the mesh. My Code Handles the method calls for the mesh creation private void BoundingMeshCreation() Quaternion currentRotation ResetPosition(new Quaternion(0, 0, 0, 0)) BoundingPointsType boundingPoints DetermineBounds() Mesh boundingMesh CreateBoundingMesh(boundingPoints) AssignMesh(boundingMesh) ResetPosition(currentRotation) Creates the mesh filter and assigns the mesh private void AssignMesh(Mesh boundingMesh) MeshFilter newMeshFilter gameObject.AddComponent lt MeshFilter gt () newMeshFilter.mesh boundingMesh VectorLine testPoint new VectorPoints("testPoint", boundingMesh.vertices, null, 5) testPoint.Draw3D() Creates a bounding mesh for the unit private Mesh CreateBoundingMesh(BoundingPointsType boundingPoints) Mesh boundingMesh new Mesh() boundingMesh.name "Bounding Quad" Vector3 vertices new Vector3 4 boundingPoints.LowerLeftPoint, boundingPoints.LowerRightPoint, boundingPoints.UpperRightPoint, boundingPoints.UpperLeftPoint int triangles new int 6 0, 2, 1, 0, 3, 2 boundingMesh.vertices vertices boundingMesh.triangles triangles return boundingMesh Resets the units rotation to the specific quaternion and returns the quaterion from before the reset. Bit of a hack for now to make sure that the original box is the proper size. private Quaternion ResetPosition(Quaternion toResetTo) Quaternion currentRotation transformV.rotation transformV.rotation toResetTo return currentRotation Determines and returns the bounding box points private BoundingPointsType DetermineBounds() Vector3 maxBounds childSprite.GetComponent lt Renderer gt ().bounds.max Vector3 minBounds childSprite.GetComponent lt Renderer gt ().bounds.min BoundingPointsType boundingPoints new BoundingPointsType(new Vector3(maxBounds.x, 1, maxBounds.z), new Vector3(minBounds.x, 1, maxBounds.z), new Vector3(maxBounds.x, 1, minBounds.z), new Vector3(minBounds.x, 1, minBounds.z)) return boundingPoints I've even tried manually setting the vertices like the following Vector3 UpRight transformV.position Vector3 UpLeft transformV.position Vector3 LowRight transformV.position Vector3 LowLeft transformV.position UpRight.z 1 UpRight.x 1 UpLeft.z 1 UpLeft.x 1 LowRight.z 1 LowRight.x 1 LowLeft.z 1 LowLeft.x 1 Vector3 vertices new Vector3 4 LowLeft, LowRight, UpRight, UpLeft boundingPoints.LowerLeftPoint, boundingPoints.LowerRightPoint, boundingPoints.UpperRightPoint, boundingPoints.UpperLeftPoint I'm at a loss, and have no idea what I'm doing wrong. My dynamic meshes seem to work perfectly fine for everything else in the game. Thanks.
0
Cannot open a package from the Unity Asset Store website Yesterday I found an asset on the Unity Asset Store website, clicked the button "Open in Unity", and it was opened in Unity. Today, when I did the same thing, I got the error message below I opened the Defaults Apps page in Windows 10 Settings. But what do I do from here?
0
Model mesh overlapping while animating in Unity but not in Blender I made an FPS model in blender and created reload animation when I imported that model in Unity I saw that while the magazine ejecting from the rifle it overlapped some of the gun parts. Then I went back to the blender and changed some keyframes and positions in the blender but in Unity, it showed me the same problem. I tried many times it looks fine in the blender but in the Unity, it has the same problem.
0
Why does my Outlined Diffuse 3 shader seem "detached" at a distance? I'm using the Outlined Diffuse 3 shader from Unity and I'm having a problem with it the outline looks great when the camera is near the object, but at a distance, it looks detached. From nearby (looks good) From afar (looks bad see the shelf and books) How can I fix this graphical anomaly?
0
Migrate from NGUI to Unity UI I used NGUI 2 and NGUI 3 for our UI. Now want to upgrade to Unity 4.6 and migrate all NGUI to Unity UI. Is there any tools? What's the best practice?
0
Turning the camera when the player turns I have a 3rd person view of the player character, and I wish my camera to follow the player both when he moves and when he rotates. So far I have the movement correct public class CameraController MonoBehaviour public GameObject player private Vector3 offset Use this for initialization void Start() offset transform.position player.transform.position Update is called once per frame void LateUpdate() transform.position player.transform.position offset However the rotation of the camera does not change when the player looks in either direction. How can this be done?
0
Unity Animation (2D) Cannot drag sprite into animation I am trying to create animations for my sprite which are configured to the quot Multiple quot option. When I try to drag the sprite into the timeline for the animation it won't do anything. It will just go back into the folder like nothing happened. I don't know if this is normal or there is a problem. Thank You. EDIT First I created a 2D animation, I gave it a name, docked and locked the animation then tried to drag the sprite into the timeline and didn't let add components nor drag the sprite i spliced.
0
Unity Kinect Current, and active wrapper options? What are some current wrapper solutions for using the Kinect with Unity? The initial primesense one seems not to be in active development. I'm aware of the Zigfu one, however are there any open source alternatives?
0
How to make a script on a prefab act on a particular scene instance? I am building Actionables (Windmill, Coal) on a Planet by hovering the mouse over the Planet and clicking on it. Actionables are prefabs, which have an Actionable component, with the same setup (at the moment). Once the player is happy with the location of their Actionable, they click LMB, which activates onClick callback, which is supposed to call Planet.Build(), which adds the Actionable on the Planet permanently (saves it into an internal array). I also have a quot Turn Off quot Button, which calls stopBuilding() when clicked, disabling the preview placement. When stopBuilding() is invoked by the button click, everything works as expected. I also want to be able to call Planet.stopBuilding() (which, by removing the actionableModel, disables hover preview on the Planet) from Planet.Build(), such that the player does not need to click the Turn Off button described above after building an Actionable. Inside Actionable prefabs I can only assign other prefabs, but I need them to interact with the scene object. I cannot override the Planet object in Actionable instances, as they are generated on the fly. How do I access the scene object Planet from Actionable prefab? Here is my Planet and its stopBuilding method so far public class Planet MonoBehaviour private GameObject actionableModel ... public void stopBuilding() For debugging only Planet planet GameObject.Find( quot Planet quot ).GetComponent lt Planet gt () Debug.Log(planet.actionableModel) Debug.Log(this.actionableModel) And here is the Actionable component which has a UnityEvent property onClick, which calls stopBuilding() on a click event. public class Actionable MonoBehaviour public class OnClick UnityEvent lt GameObject gt public OnClick onClick new OnClick() ... void OnMouseDown() onClick.Invoke(gameObject)
0
Send post request with content type I used a php server to communicate with my unity application . I want to send post data with content type so that my php server can use the approriate variable for the content type , for example if i send post request with content type quot file quot , my php server can use FILES instead of POST , and i am a beginner and i'm too skeptical to use POST to handle upload request from unity application to server . My best guess is that i must use something from WWWForm to achieve it , but in my opinion the documentation isn't friendly enough for beginner like me . Can someone here lend me a hand to achieve this ? (sending post request with content type) Oh , also , i'm sorry for too much using php in my example , below is how i achieve it in html, i can achieve it in html by using something similar to this code (this html send POST request to upload a pictures with quot file quot as it content type) lt form method "POST" enctype "multipart form data" gt lt label gt Browse Image lt input type "file" name "pictures" style "display none" gt lt label gt lt br gt lt button name "upload" gt Upload Now lt button gt lt form gt Please forgive me if my english is too bad , thank you .
0
Panel gets transparent when accessing the offsetMin of RectTransform I need to place 3 panels side by side in my application. It was working fine with Render mode Screen space Overlay. Now due to some other requirement, I had to change the Render mode to Screen space Camera. Now when I access the offsetMin of RectTransform of the panels so that it shifts to the right, the panel gets transparent. I commented the code where I'm accessing and the Panel doesnt get transparent then. I'm not sure why it is happening. The requirement is place a 3D model in canvas, so I had to change the Render mode. If there is a way to place 3D model in canvas with Screen space Overlay. That would be great as well.
0
Unity soft blur effect for dark void edges I'm a former Flash dev working in Unity (or in 3D for that matter) for the first time. For the game I'm working on, I've designed an interior room like so To represent void space outside the bounds of the current room, there's just black. In order to hide the back faces of the exterior facing walls, I've created a snug fitting mesh cutout which sits just below the lip of the wall. If I moved the camera below the surface, you would clearly see that. I'm quite new to Unity, and have very little experience with shaders. Anyway, I figured this would be a good place to try for creating my first shader, but I'll need some help. I'd like to blur soften the edges where the wall lip meets the void, like so The only way I could achieve this effect would be by hacky means, like by using a gradient texture ( 00000000 FF000000) UVed around the edges of the wall lips, but I suspect there is a more elegant solution by rendering the black surface with a shader. Currently, even with a basic understanding of fragment shaders and the rendering process, I would have no idea where to start if I tried to write my own. When I read shader script I can only stare in wonder at the sheer etherealness of it. I just don't know how to craft a solution in such basic terms, but I'd love to learn. I understand the answer is probably as simple as 'use a gaussian blur', but i would appreciate some more input to steer me on the right path, and maybe some examples to help me understand.
0
Send a Push Notification from a device to another device (Unity, Firebase) I have setup Firebase authentication in my game for Android. I need to implement a feature in my Android game, where a user can challenge another player. I need to implement it this way The user is shown the list of all users registered on Firebase on the Game. To any user, he can tap on a button for respective user to send a challenge. When, he taps, a push notification is to be recieved by that user. When he taps on the notification, he is redirected to a specific part of the game. Maybe a specifc scene for now and he is shown there the Challenger's name. I have explored the Firebase documentation, but it does not provide information for client client push notifications. Maybe there are other options available like GameSparks and OneSignal. But I don't know if there is a requirement of own Server for implementing it.
0
How to move rotate different parts of an entity indepently from each other? Background I am playing around with a simple isomorphic 3D shooter where a player controls a character which can shoot other players. Here's an example scene where you can also see the hierarchy for the game objects and the controlling script As you can see, I have created a simple turret which consists of three parts Guns Torso Bottom Just to be more clear, here's a screenshot of the turret close up with its armature In Unity, I have already created a simple PlayerController.cs script (see beloc) which allows a player to move the entire game object around using W, A, S, D and look using the mouse. However, I want to rotate the Bottom independently. So if the Player moves left, the bottom should rotate towards that direction but the torso should still focus on the mouse position. Now the first question is how I can do that. I don't know how to get access to the game objects and rotate them independently. The second question is how I can or should design the player game object s.t. I can exchange models more easily. What I mean by that is Imagine the player switches the weapon. Obviously, only the guns should change but e.g. not the entire character. Only the mesh etc. should change dynamically. I am sure this isn't that hard to accomplish but I couldn't find a simple example that kind of explains how to do it. PlayerController.cs public class PlayerController MonoBehaviour SerializeField public float moveSpeed 1f private Vector3 forward private Vector3 right public LayerMask layerMask Start is called before the first frame update void Start() this. forward Camera.main.transform.forward this. forward.y 0 this. forward Vector3.Normalize(this. forward) this. right Quaternion.Euler(new Vector3(0, 90, 0)) this. forward Update is called once per frame void Update() if (Input.anyKey) this.Move() this.MouseLook() public void Move() var rightMovement this. right Input.GetAxis("HorizontalKey") var upMovement this. forward Input.GetAxis("VerticalKey") transform.position (Time.deltaTime this.moveSpeed Vector3.Normalize(rightMovement upMovement)) var heading Vector3.Normalize(rightMovement upMovement) if (Vector3.Magnitude(heading) gt 0.0) transform.forward heading void MouseLook() Ray castPoint Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(castPoint, out hit, float.MaxValue, layerMask)) Vector3 direction hit.point transform.position direction.y 0.0f transform.forward Vector3.Normalize(direction)
0
Why is FindObjectOfType(MyType) not finding anything? Why would I get the following log? Start OpponentMotionReceiver motion receiver not found true public class ScoreAnimation MonoBehaviour private OpponentMotionReceiver cachedObject private void Start() cachedObject FindObjectOfType lt OpponentMotionReceiver gt () private void OnDestroy() var motionReceiver FindObjectOfType lt OpponentMotionReceiver gt () if (motionReceiver null) Debug.Log("motion receiver not found") if(cachedObject ! null) prints true, another proof that the gameObject is active Debug.Log(cachedObject.gameObject.activeInHierarchy) public class OpponentMotionReceiver MonoBehaviour private void Start() Debug.Log("Start OpponentMotionReceiver") private void OnDisable() never enters Debug.Log("OnDisable OpponentMotionReceiver") private void OnDestroy() never enters Debug.Log("OnDestroy OpponentMotionReceiver") P.S. This is extremely simplified version of the code so that the rest brings no confusion. If you need more details, I'd be pleased to answer you!
0
Add Atten property in Unity Shaderlab In Unity Shaderlab shader, Is there any way to apply Atten value? Using surface shader, and vertex fragment shader I can do it easily. But, I didn't find any reference to do that in Shaderlab syntax. Shader "Diffuse" Properties Atten ("Light Attenuation Power", Float) 1.0 lt how to apply? Color ("Main Color", Color) (1,1,1,1) MainTex ("Base (RGB) Transparency (A)", 2D) "" SubShader Pass SetTexture MainTex constantColor Color combine texture constant, texture constant this makes syntax error. constantColor Atten Color
0
Sort buttons in unity 2D I've a list of buttons that I create using XML stored data. To achieve it, I've created a Prefab. These buttons are created correctly, and now I want them to be sorted for the user. public List lt GameObject gt myButtons As I said, now I want to sort them. I've found out that sorting the List itself, buttons are sorted in the UI. myButtons.Sort((x, y) gt ...) The problem is, that I don't have the necessary data to sort them within them. This leaves the .Sort() method unavailable for use. I've tried to sort them adding an script to each one, which contains the data that I need to use to sort them. However, it doesn't work correctly and I seem unable to find out why, so I'm wondering about other more direct methods to sort them. Notice that I'm referring to simple buttons in a 2D game, and that they're all inside the same parent gameobject. Technical Details Let's start by the basics I want to order the buttons taking into account if the user has reached a point in which the item it represents should be available. This is stored in an instance of a class that represents the items related to the buttons of the question. public class myItemClass Here there are other properties public bool available Therefore, we've a correspondence between two lists public List lt myItemClass gt myItems public List lt GameObject gt myButtons Where myItems 0 is related represented by myButtons 0 ... NOTICE that this relation exist at the initialization of the game, so i need to keep it at any moment (meaning, having to sort both lists). What I tried To be able to order my buttons depending on if the items are available or not, what I've done is Creating an script myItemScript, which has a reference to my original items from the other list. Sorted the items using Sort function over them. public class myItemScript MonoBehaviour public OtherClass.myItemClass dataObject And then sorting them like myButtons.Sort((x, y) gt y.GetComponent lt myItemScript gt ().dataObject.available.CompareTo(x.GetComponent lt myItemScript gt ().dataObject.available)) As I said before, both list need to be following the same order, so just after it, I order the item list as well myItems.Sort((x, y) gt y.available.CompareTo(x.available)) Checking Debug As result, I found that items were in fact sorting different. However Items inside myItems List were sorted as expected. Buttons in UI (and hence, myButtons List were not sorted as expected. Mixed items (available true false) were mixed and not ordered in two blocks, one first and then the other one. This was checked using breakpoints within VS2017 and pausing the game in Unity interface.
0
How to interpolate colors around the spectrum of hues? I wanted to generate a 7 segment display whose color brightness varies with time, this can be done by just using linear relationship. Color activeColour2 new Color(1, DateTime.Now.Millisecond 0.001f, DateTime.Now.Millisecond 0.001f) So in 1 complete second, it produce color in the range of (1,0,0) to (1,1,1) as in the code below using System using UnityEngine public class ClockDigit2 MonoBehaviour static readonly bool , SEGMENT IS ACTIVE new bool , true, true, true, true, true, true, false , 0 false, true, true, false, false, false, false , 1 true, true, false, true, true, false, true , 2 true, true, true, true, false, false, true , 3 false, true, true, false, false, true, true , 4 true, false, true, true, false, true, true , 5 true, false, true, true, true, true, true , 6 true, true, true, false, false, false, false , 7 true, true, true, true, true, true, true , 8 true, true, true, true, false, true, true 9 public Color32 inactiveColour Color.black public SpriteRenderer segments new SpriteRenderer 7 public void Display(int number) Color activeColour2 new Color(1, DateTime.Now.Millisecond 0.001f, DateTime.Now.Millisecond 0.001f) var digit number 10 if (digit lt 0) digit 1 for (int i 0 i lt 7 i ) if (SEGMENT IS ACTIVE digit, i ) segments i .color activeColour2 else segments i .color inactiveColour void Update() Display(DateTime.Now.Second) However, now I want to interpolate through all the colors in the circle above over 1 second. I don't know how to express this as a formula for R, G, and B. The RGB value is not linear relationship as you spin the selected color in the chart, you can notice the RGBA components vary together in a nonlinear form. I considered using Lagrangian interpolation. However, this will not be accurate or might fail greatly because if you take a reference point at the circle and assume in 1sec, it made a complete revolution, you will notice there is a certain period of time where the RGB value is constant along the path either 0 and 1. So is there any method to get a formula that perfectly fits the color chart with respect to time?
0
How can I handle ball interaction with lanes in a pinball game? In a pinball game, how can I handle collision or constraints on the ball for convincing movement on those highway rails tracks? I assume using physics and a mesh collider would not work, even when the poly count is really high the ball still bashes into all those faces instead of hugging a smooth, round wall. I could constrain the ball to a spline but I foresee problems with the balls speed and proper physics. I'm wondering if it is possible to tell the ball that mesh corners below a certain degree should be treated as round. Perhaps only when coming from a certain angle?
0
How do mobile games implement time gates unhackably? Is it possible in offline games? I'm thinking about porting my game to Google Play, and it would be free to play with time gates which are skippable if you watch an ad. What are the ways of implementing an unhackable time gating? Is it possible without internet connection? If yes, how? If no, is there a way to implement it without custom backend, using Google Play's services? Or should I care about this at all? Because... It doesn't affect other players... Most of the audience couldn't do it anyway, and if the game stays small, hacks couldn't really spread. Then maybe I should just let them hack those time gates, it's a marginal revenue loss. What do you think?
0
Get world position of random point inside bounds I am trying to get a random world position inside my targets collider, so that I can fire an arrow at it. I have tried a bunch of different solution but can't seem to get it right, for example (this code is on my target) Inside Awake colliders GetComponentsInChildren lt Collider gt () I want this to work on a unit with a single capsule collider and a building with 8 different box colliders public Vector3 GetRandomPoint() Bounds b new Bounds() for (int i 0 i lt colliders.Length i ) b.Encapsulate(colliders i .bounds) float minX gameObject.transform.position.x gameObject.transform.localScale.x bounds.size.x 0.5f float minZ gameObject.transform.position.z gameObject.transform.localScale.z bounds.size.z 0.5f return new Vector3(Random.Range (minX, minX), gameObject.transform.position.y, Random.Range (minZ, minZ)) In the scenario I'm having issues with right now, the trageet simply has a single capsule collider. This return a point quite far away from my target, but I cant find the issue. EDIT Here is another one I tried without success public Vector3 GetRandomPoint() Bounds b new Bounds() for (int i 0 i lt colliders.Length i ) b.Encapsulate(colliders i .bounds) var target new Vector3( UnityEngine.Random.Range(b.min.x, b.max.x), UnityEngine.Random.Range(b.min.y, b.max.y), UnityEngine.Random.Range(b.min.z, b.max.z) ) return b.ClosestPoint(target)
0
Why even use coroutines in Unity? I have been thinking about the use of Unity's coroutines recently, and while I've used them in the past, and am already aware of their bad reputation (although I've also seen posts on the unity forums of people who seem to absolutely swear by them), the more I think about it, I'm kind of struggling to see any compelling reasons to use them at all instead of simply creating a new component and simply performing the logic of the coroutine in said new component's Update method. By using a IEnumerator coroutine inside of another component, it seems to me like all it accomplishes is decreasing the cohesiveness of individual components and the re usability of the component using them. Is there any convincing argument to actually use coroutines in Unity and would I be missing out by simply not using them? Are there any scenarios I'm overlooking where their use would either be required or prove incredibly useful?
0
Starting Couroutine in newly activated gameObject I'm working on a UI system that animates an element's properties using coroutines. Every element that should be animated has a component called AnimatedUIElement which provides the function Enter(). The function Enter() is basically starting coroutines depending on the chosen animation settings, but only after calling Enable(), which sets the gameObject active with gameObject.SetActive(true) , updates its component references and makes the element interactable. AnimatedUIElement also defines an Exit() function acting similar, but disabling the element after the animation. public class AnimatedUIElement MonoBehaviour private CanvasGroup canvasGroup ... public void Enter() ... TriggerEntry() private void TriggerEntry() PlayChildrenEntry() Calls Enter() on all animated Children Enable() StartCoroutine(SomeAnimation(...)) private void Enable() gameObject.SetActive(true) Init() canvasGroup.interactable true canvasGroup.blocksRaycasts true private void Init() canvasGroup GetComponent lt CanvasGroup gt () ... private IEnumerator SomeAnimation(...) ... public void Exit() Similar to Enter, but disabling the element Now I want to open the options panel by clicking a button in the game's UI. The panel is inactive (unticked) in the beginning, while the AnimatedUIElement component is enabled. UI Hierarchy Options Button calls Enter() on Options Panel. The desired setup in the Button Component calling OptionsPanel.Enter() and MainPanel.Exit() But clicking the button throws the following exception Coroutine couldn't be started because the the game object 'Main Menu Button' is inactive! UnityEngine.MonoBehaviour StartCoroutine(IEnumerator) AnimatedUIElement AnimatePosition(Vector2, Vector2, Single, AnimationCurve) (at Assets Animated UI Elements AnimatedUIElement.cs 265) AnimatedUIElement TriggerEntry() (at Assets Animated UI Elements AnimatedUIElement.cs 93) AnimatedUIElement Enter() (at Assets Animated UI Elements AnimatedUIElement.cs 73) AnimatedUIElement PlayChildrenEntry(Transform) (at Assets Animated UI Elements AnimatedUIElement.cs 219) AnimatedUIElement TriggerEntry() (at Assets Animated UI Elements AnimatedUIElement.cs 79) AnimatedUIElement Enter() (at Assets Animated UI Elements AnimatedUIElement.cs 73) UnityEngine.EventSystems.EventSystem Update() In this stack trace you can see that the Options Panel did not start coroutines as no animation was defined in its component, but called Enter() on its children, which are animated. Using debug logs I found out that, while Init() is called immediately after Enter(), Awake() is called after the coroutines (which happen later in the program flow) throw errors. This makes it seem like the object is not available instantly after calling setActive(true). Is there an explanation and possibly a fix for this behavior?
0
How to write a unit test in Unity? is there a tutorial and patterns to write unit tests in Unity ? Should we use the classical c way and test the code or should we test the interactions in UI ? If so how?
0
Unity Particle System Shuriken Setting particles in code with random row in texture animation? Good day, I'm attempting to randomly generate a space scene (quite large actually) in Unity through C code mainly. So far, I've gotten stunning results up to what image 2 will show you. However, now I'm looking to expand the look with more random particles. So, I've made a texture atlas of 8 in a vertical row, which works on the random setting if you have an emitter and the particle system is called with PS.Play() Assigning different materials would only work on a per particle system basis(which would be new texture PER cloud, so to speak) which is not what I want. So, my question How can I use the Shuriken Particle System's Texture Sheet Animation functionality through code, without having an "active" particle system? More precisely, I wish to use the 'Random Row' feature of it to assign random textures to each particle. Since I can't share my code (due to policies), here is a bit more info on how I do it I create an array with coordinates for each cloud. Assign a particle system to that cloud. Randomly generate all the particles for the cloud with relative offsets. Use PS.setParticles(particlesArray) Using a Texture Atlas consisting of the letters A to H to test, only B showing on all particles. Using a Texture Atlas consisting of the fog particles to test, only 2nd showing on all particles. Thank you DMGregory for the help, I've tested it multiple times and it works perfectly now, I've also went ahead and tweaked a few of my settings just to get a more "clear" space
0
How to stop 3D model from reflecting light like plastic I was browsing SketchFab and found a 3D model I decided to try in Unity. This is how the model looks in SketchFab's viewer When I put it in Unity, I used a Directional Light object As you can see, it looks like plastic. I have been playing with the light's intensity, but the model seems to always reflect light as if it were some sort of plastic (unlike SketchFab's viewer). How can I make it look like the above image? The model is https sketchfab.com models 1ee9b44352c840bda4202895948c30bb
0
How to setup a public github unity repo with paid assets? From what I gathered (like in this thread or here) I am allowed to push my own game code on github and choose a license, as long as I avoid putting assets I do not own. I want to make it public to be able to show it (to potential employers for instance) but I cannot make it open source as I plan to use paid assets (like DoozyUI). I can avoid pushing the asset itself on the repo (with .gitignore for instance). Should I prevent gameobjects created with this package to be pushed as well ? That would make the game unusable, even with the rights to use the package... Once that is settled, Is it ok to push it to github without license ? Specifically, I do not know if objects generated by a paid asset are still considered that asset or not... Edit I asked the question directly to DoozyUI support, which quickly responded You can upload your project, without the Doozy folder. Thus excluding our source code from being shared. Also, unsert a disclaimer letting anyone know that DoozyUI is required to be installed (before getting your files) for the project to work. You can share any GameObject (or prefabs) you create, but they will not work if DoozyUI is not installed due to missing references (scripts). Once Doozy is installed, they will work as expected. Thus anyone who has the system will be able to see use your project.
0
Unity Player Gets Stuck Between Tiles I am creating an endless game, which constantly spawns tiles. The problem is that after a few tiles the player gets stuck on random tile and stops moving. I noticed this problem even when i was designing a level, where when I align two tiles side by side, the player gets stuck on the junction of these two tiles. I am including a video link to my problem. Please help me and please try to be in detail because i very very new to Unity. Video for the problem im facing. https photos.app.goo.gl JrCPWkGclUA2UiMy1 using System.Collections using System.Collections.Generic using UnityEngine public class TileManager MonoBehaviour public GameObject tiles private Transform player private float SpawnLocationZ 30.0f private float tileLength 36 private float amountOfTilesOnScreen 5 private float SafeZone 45 private List lt GameObject gt activeTiles private int lastPrefabIndex 0 private bool StartCompleted false Use this for initialization void Start () activeTiles new List lt GameObject gt () player GameObject.FindGameObjectWithTag("Player").transform for(int i 0 i lt amountOfTilesOnScreen i ) Debug.Log("Start Method") SpawnTile( 1) Update is called once per frame void Update () if((player.transform.position.z SafeZone gt (SpawnLocationZ amountOfTilesOnScreen tileLength))) Debug.Log("started") SpawnTile(0) DeleteTile() void SpawnTile( int prefabIndex) if(prefabIndex 1) GameObject gor gor Instantiate(tiles 0 ) as GameObject gor.transform.SetParent(transform) gor.transform.position Vector3.forward SpawnLocationZ SpawnLocationZ tileLength activeTiles.Add(gor) else GameObject go go Instantiate(tiles Randome() ) as GameObject go.transform.SetParent(transform) go.transform.position Vector3.forward SpawnLocationZ SpawnLocationZ tileLength activeTiles.Add(go) void DeleteTile() Destroy(activeTiles 0 ) activeTiles.RemoveAt(0) private int Randome() if(tiles.Length lt 1) return 0 int randomIndex lastPrefabIndex while(randomIndex lastPrefabIndex) randomIndex Random.Range(0, tiles.Length) lastPrefabIndex randomIndex return randomIndex
0
How can I make a chest that can be opened and shut in SteamVR? I'm working in Unity with SteamVR for a school project. I'm trying to have a chest that can be opened and shut. I tried using a hinge joint but it would break if the attached body was static which is what I want. I'm now trying to use a circular drive which works better but the lid to the box will move away from the intended position when colliding with the body of the box which is set to static and kinematic. I can fix this by setting the lid to kinematic but it won't collide with the body anymore. Both the lid and body are properly colliding with the hand and with a sphere I added to help test collisions. I'm assuming the issue is that two kinematic objects can't collide with each other but I don't know how else to approach this.
0
Networking player input, UI, and ability use I am currently working on a project to learn more about networking, specifically authoritative network architecture. In most authoritative systems you capture a player's input queue them up then send them to the server after a certain count or time has passed. The input is "copied" to the local(client) loop and run as prediction while it waits for the server to return the authoritative state back to the local(client) for correction. The states are also sent to all connected players to recreate the observed behavior of remote players. This system works well for things like player movement and shooting(raycasts). This gets more complicated as we start to integrate UI and player skill ability bars. In most MOBA or MMO games there is UI that can also create "input". In these cases there isn't a truely 100 right way to accomplish the goal of networking these pieces. You wouldn't need or want the UI to be run on the server in most cases. I have come up with a few concepts of sending the input for these to the server and would like to know if I am close to conventions that are used in professional system or if I am even thinking about it in the right way. Case 1 Mapped config agreement In this model the player can assign abilities to a skill bar that is both clickable and correspond to the number keys on the keyboard. This "mapping" of abilities to bar slots is stored in a player config and is sent to the server. When the player presses a number key or clicks on an icon an input is generated and added to the input sent to the server that looks something like this BarId 1,BarIndex 1,KeyId 1 When this is received by the server the server looks up the player UI config that was sent to the server and see what abilityId was stored on that place in the bar, check if it is a valid move then update the server state. Case 2 Server Command In this case the player class has a UseAbility(abilityId,target) method that can be called from the client player instance but is executed on the server instance, this bypasses the normal input gathering loop by executing the command on the server immediately so incorporating this into the client server step systems isn't clean. Borrowing the use case from Case 1 The player presses the button on the keyboard or clicks the UI button. This is "mapped" locally to a specific skill. The button keypress calls UseAbility(0x00012,self) and is run on the client and server immediately it is checked for validity and then a state is sent to all connected players. Those are the two cases I have right now. One works well with how input is gathered and sent to the server for processing. The other makes more sense in that the code can be more explicit but it appears to break the server authoritative structure. Would you guys please tell me what you think and maybe we can have a conversation about best practices. Thanks for reading my post.
0
Free Look Camera Like Arma 2 while pressing ALT I'm trying to create a simple script that give me the possibility to rotate the camera while pressing a key. So, in a pseudo code way, how I can intercept the Input event and limit the player's movements to hold the character direction? I should tweak the MouseLook script? Or completely create a new one?
0
How come changing the speed of an animation isnt making the animation speed up? I made an animation of a bow string being pulled and another animation of the string being released but my issue is that I need the string to snap back quickly. I changed the speed of the release animation which is what makes the string go back to being straight (as if you had just released it). However, changing the speed isn't making the animation happen any faster... Any ideas why this might be happening?
0
Simple Water surface simulation problems (GDC2008 Matthias Muller Hello World) Im attempting to implement a simple height field water surface simulation outlined in Matthias Muller's GDC 2008 talk. "http www.matthiasmueller.info talks gdc2008.pdf" I can't seem to see why it my implementation doesnt work. Could anyone help? Any advice or help would be much appreciated. The main processing loop is below The obstruction array is initialized as 1. And the source just adds 0.1f to a point. void wave() for( int i 0 i lt size i ) height i source i height i obstruction i for (int i 1 i lt iwidth 1 i ) for(int j 1 j lt iheight 1 j ) velocityField indexFind(i,j) (height indexFind(i 1,j) height indexFind(i 1,j) height indexFind(i,j 1) height indexFind(i,j 1) ) 4 height indexFind(i,j) velocityField indexFind(i,j) dampening height indexFind(i,j) velocityField indexFind(i,j) int indexFind(int x, int y) return (x iwidth y) This is what happens (height field rendered as a texture on a plane) This is the page from the link that outlines the algorithm
0
Why is my enemy object shaking in my AI code? My script here is attached to an 'enemy' object. My enemy walks to certain "points" if the player is far away from him. If the player gets close to him, the enemy follows the player. The problem is that after chasing the player, when he escapes, the enemy should walk back to the "points". Now I see the enemy object shaking and walking far away from the expected direction?! public class enemyscript MonoBehaviour public Transform target public Transform waypoint points NavMeshAgent ePath private int farPoint 0 public float elife 100f,distance,look range 20.0f Use this for initialization void Start () ePath GetComponent lt NavMeshAgent gt () ePath.speed 2 Update is called once per frame void Update () distance Vector3.Distance(gameObject.transform.position, target.transform.position) if (ePath.remainingDistance lt 0.5f) nextpoint() if (distance lt look range) attack() void attack() ePath.SetDestination(target.position) ePath.speed 6 void nextpoint() if (waypoint.Length 0) return ePath.destination waypoint farPoint .position farPoint Random.Range(0, waypoint.Length) ePath.speed 2
0
What is the speed difference between cross platform HTML5 games and native mobile games? Microsoft is advertising and promoting cross platform HTML5 game development. I am thinking of creating a simple 2D side scroller game and I am trying to decide what engine should I use for creating it. I am trying to understand if there is a big difference between developping once in Unity and exporting to different platforms or simply develop it once in HTML5 in Visual Studio and publish it everywhere. What are the drawbacks and benefits for each? Is there any speed lag difference? any tips are useful
0
button thumbnail slider effect unity3D I am trying to make this effect for buttons. i.e the middle one is bigger and is selected. the buttons can be moved left or right by swapping with finger. Does anyone have any idea how to do it?
0
Shoot projectile same direction weapon faces I want to be able to shoot a projectile from a weapon mounted on a vehicle. Right now I am able to do it but only in front of the vehicle. I managed to rotate the weapon to the direction the mouse is facing, but the projectile still goes straight. I believe that the issue is that the velocity of the projectile is the problem here. Right now I have it like this if (playerShooting NPCShooting) if ((timer gt cooldown) amp amp hasEnergyAvailable()) timer 0 GameObject intantiatedProjectileContainer Instantiate(projectileContainer, transform.position, transform.rotation) as GameObject Rigidbody instantiatedProjectile intantiatedProjectileContainer.GetComponentInChildren lt Rigidbody gt () if (playerController) instantiatedProjectile.velocity transform.TransformDirection(new Vector3(0, 0, speed transform.root.GetComponent lt PlayerController gt ().getZSpeed())) Where speed is the projectile speed and it's added to the vehicle speed. I thought that this should shoot forward but with the parent rotation, can someone tell me what I'm missing here? Thanks!
0
How can I make a 2D Sprite bleed glow colors at a particular spot? I am trying to make a gauge glow over the color it is at. For example, in the image below, when the needle is pointing at the red, the red is glowing. When it is pointing at the green, then the green is glowing. I want to replicate this My gauge will be on a gradient, so I cannot just color a particular segment. (There are no segments.) I am working with 2D sprites. I have looked into the Bloom asset as suggested here, but I have been met with nothing but failures. (Probably because that guide is for 3D.) How can I take the color at a particular position and make it bleed glow like in the images above?
0
Unity networking, make player disappear for all clients As title says I need to make the player disappear when he gets in car. Right now, it works as a single player, but since I am new to unet I don't really know how to achieve this, I tried some ways, but they didn't work. Here is script Client void OnControllerColliderHit(ControllerColliderHit hit) so if we hit car if(hit.collider.tag "Vehicle") if we pressed "E" if (Input.GetKeyDown(KeyCode.E)) call method to disable some stuff taht should be disabled, like controller, shoot, weapons etc. if (isServer) CmdCall(inVehicle, hit) else RpcCall(inVehicle, hit) Command void CmdCall(bool invehicle, ControllerColliderHit hit) RpcCall(inVehicle, hit) ClientRpc void RpcCall(bool invehicle, ControllerColliderHit hit) disable(inVehicle, hit) I can't see any errors in console but I cant enter play mode cause there are some compiler errors, which again i cant see in console. thank you for any tip, comment, downvote, upvote, or hint ) Nick.
0
Unity Failed to create decoder for ScreenSelector.png My game works fine in the editor, but when I build and run the build the view is zoomed in, my tilemap is missing, and the camera follows a gameobject it should not. How it should look and how it looks I checked the logs and this is the error I am served Failed to create decoder for 'C Users Hamuel The First Documents Jetplatformer Builds Builds Data ScreenSelector.png' 0x80070002 Further Investigation shows that ScreenSelector.png is absent from the path stated in the error. I cannot find anything that says what ScreenSelector.png is, or does. I am using the post processing stack by unity. Any help would be much appreciated!
0
Vuforia AR VR sample with Google Cardboard SDK I cannot switch from augmented reality to virtual reality I have followed the Integrating Cardboard to the AR VR Sample latest tutorial. I have configured the provided scene sample according to that tutorial. I have compiled it to Android without any problem. The game load an AR scene with a yellow pointer in the center. If I understood well, if a glaze at the ImageTargetStones GameObject, it will switch to VR. Unfortunately I cannot find that GameObject anywhere. I only see the AR scene with nothing than the yellow pointer. I don't find what I'm missing. Why is not that ImageTargetStones GameObject in the AR scene? UPDATE 1 I think I want to use Vuforia for an uncommon use. I think that's a reason of a possible misunderstanding. I don't want to use its image recognition possibilities. I want to switch between AR to VR when glazing to a button. I have tried to duplicate the VRButton to move it to an independent place of the scene with no parent. I have checked its IsTrigger checkbox. I have added a PointerEnter EventTrigger that set Focused to true. I have added a PhysicsRaycaster to both AR Camera and MainCamera (child of CardboardMain Head). Nothing happens when I gaze at the button. I have to compile everytime I want to try it by the way. I did not manage to make it work in the editor. UPDATE 2 I haven't been able to do it with vuforia yet. I have done it with WebCamTexture. Specifically, I have used the scripts of this answer http answers.unity3d.com answers 687987 view.html . The result is not nice because the image from camera seems closer than it actually is (with Vuforia, there is not that problem)
0
How to get neigbor pixel coordinates in Unity HLSL shader I am writing Mandelbrot set shader for Unity. I wrote an Image Effect shader and it works. Unfortunately, each point quot shimmers quot on translate scale. This is because, for each shader call I compute value for only one mathematical point, which is infinitesimal. On even small translation, the value can change drastically. So, I would like to compute math value not for one point, but for several. But for this I need to know, which aother points belong to my pixel, and for this I need to know the distance to neighbor pixel. Unfortunately, my incoming values are float and I don't know, how to step to next pixel. How to accomplish?
0
Unity3d Access the OnClick parameters of Button in a script I have a button and I have attached another script "PlaySound" for this button, which plays audio on button click. As soon as the audio gets completed, I want to stop the animation which I am triggering here in OnClick of Button. How do I access the Ellen gameObject and 0 parameter which I set in the Inspector window (check the picture) in the PlaySound script
0
Shader that draws just vertex points The game I am developing is in unity and I want to make a shader which can be put on a mesh that only 'draws' color on each vertex point. I am not proficient with shaders, and out of all my searching I have come up empty handed I unfortunately don't even know how to look up this question (I seem to only find results about point clouds, which only serves to confuse and scare me more P). Any help or if you can point me in the right direction on what to search, I would be very much greatful.
0
do i need a deterministic game engine for ball physics multiplayer game? I want to create a simple soccer game but where the ball physics is accurately rendered across the network. I looked at Photon's Quantum engine and it is too expensive for indie devs at 1k month for only 500 CCU. Is there an alternative approach? Basically I need the ball physics to be as accurate as possible.
0
Unity DontDestroyOnLoad FindObjectsOfType(GetType()).Length is always returning 1 I'm trying to have an object with the DontDestroyOnLoad property. I want an object with NetworkIdentity to persist across scenes, so I can have a holder script for RPCs. This answer suggests the following code public void Awake() DontDestroyOnLoad(this) if (FindObjectsOfType(GetType()).Length gt 1) Destroy(gameObject) Despite this, I still end up with duplicate objects. FindObjectsOfType(GetType()).Length is always returning 1, and I don't know why, or how to fix it. It makes no difference whether this object is a prefab instance or a simple object in the hierarchy. I have also tried to clone this object in my NetworkManager script, which is automatically persistent, but GameObject.Find("ObjectNameHere(Clone)") is always returning false. However, the above solution seems simpler so I'd prefer to figure out FindObjectsOfType(GetType()).Length.
0
Transform.Rotate micro stutter? Hey all I have a quick question. I am new and obviously still learning the basics of programming scripting. However I am confused by the result of a simple script. The goal is to have a Start Menu with a 3d background.The camera is attached to an Empty Object, which has a script that is meant to constantly rotate. My confusion, is whether I am live testing in Unity, or a built executable. When the empty object is rotating, it will have a pause or a few milliseconds, and then continue with its rotation. Almost like a planned micro stutter. Regardless of where it is in its cycle. How can I make the rotation as perfectly smooth as possible? Below is the script for rotating the empty object that the camera is attached to. public class cameraAnchor MonoBehaviour public float speed 5f Update is called once per frame void Update () rotate camera anchor around y axis transform.Rotate(Vector3.down, speed Time.deltaTime)
0
Unity Mobile project, button problem "CrossPlatformInputManager.GetButton" not working Good afternoon, I have a problem with an input in my code Before testing it on mobile I tried on PC and the code to make my player sprint was like this var sprintPressed Input.GetKey(KeyCode.LeftShift) var targetSpeed maxSpeed if (attacking) targetSpeed attackMoveSpeedMultiplier else if (sprintPressed) targetSpeed sprintMultiplier And everything was working fine. My player increases the movement speed as soon as I press "Left Shift" button. Then I changed the code to make it work with a mobile button var sprintPressed CrossPlatformInputManager.GetButton("Sprint") var targetSpeed maxSpeed if (attacking) targetSpeed attackMoveSpeedMultiplier else if (sprintPressed) Debug.Log(sprintPressed ? sprintMultiplier 1) just to see if it take a button targetSpeed sprintMultiplier I also make a change for a controller so instead, to press WASD I use a screen joystick. That's work fine. But when I press a button to make a sprint, nothing happens. I insert a debug log line and when I press a button it just return 1 single value (sprintMultiplier) and not 1 per frame as it should be because this function is in the Fixed Update. I check in Google and I found this tutorial https www.youtube.com watch?v nGYObojmkO4 amp t 851s amp list PLXVRS21ln3JIbFLPwf9bdH3thHmmYRJGi amp index 16 Pretty much what I did but in his video, it's working. In my project doesn't. Can someone help me, please? Many thanks beforehand
0
How do you animate collide against a tessellated mesh? Now that I have a implemented tessellation for my mesh, I am trying to understand how I can leverage the generated primitives. Example I have the following track mesh generated procedurally, it consists of quads, in the first picture you can see one of them I am highlighting using the mouse. In the following picture, the shader applies some tessellation, you can see that now a quad has generated 16 quads. Question (two folded) Now that I have more control points for each of my quad, suppose I want to deform one of them, for instance, to look like the following How is one supposed to apply such transformation ? basically, what in terms of code behind shader code infrastructure is required to achieve such thing. How can collisions be checked for against that deformed mesh ? from what I've understood, a mesh collider would be unpractical since it's a heavy operation that just forbids real time updates
0
When an object is launched off screen, is there any way to know if it's coming back? In this scene, the object becomes invisible and then comes back In this scene, the object becomes invisible but does not come back Is there any way I can tell if an object will come back when it becomes invisible? Edit Thank you to S. Tar k etin for the solution private void Update() if (isInvisible) if (IsNotComingBack()) OnInvisible?.Invoke() private void OnBecameInvisible() isInvisible true private bool IsNotComingBack() var pos cam.WorldToViewportPoint( rb.position) var extents cam.WorldToViewportPoint( spriteRenderer.sprite.bounds.extents) var isNotComingBack pos.x extents.x lt 1 pos.x extents.x gt 0 return isNotComingBack
0
Room lighting in Unity I am trying to make a plain white room in Unity. I used six planes for the walls, but I can't figure out how to get the lighting to not look so harsh and uneven. The top picture is my best attempt using two directional lights, and the bottom picture is the look that I am trying to replicate. It is from a demo scene in the Google VR SDK 1.50 for Unity. It uses only a single point light, but when I turn it off in the scene view, it doesn't change the appearance of the room at all. How can I make my room look more like the Google VR demo? EDIT I made a big improvement by changing all my walls to be static so that they receive indirect lighting, and adding a single point light above the roof.
0
How can I recreate the camera used in Swordigo game? What sort of camera does the Android game (2.5D) Swordigo uses? Is it an orthogrpahic camera? I think it is an angled orthographic projection. How can I recreate that sort of camera in Unity?
0
Synchronize objects' movements moved by coroutine function I'm using Unity version 5.3.5. I'm having problems to synchronize the movement of three different objects from point A to point B and vice versa. To move the objects I use the following code public float time public Vector3 endPos private Vector3 startPos void Start() startPos transform.position void FixedUpdate() if(transform.position startPos) StartCoroutine(Move(gameObject.transform, startPos, endPos, time)) if(transform.position endPos) StartCoroutine(Move(gameObject.transform, endPos, startPos, time)) public IEnumerator Move(Transform thisTransform, Vector3 startPosition, Vector3 endPosition, float time) float i 0f float rate 1 (time) while(i lt 1) i Time.deltaTime rate thisTransform.position Vector3.Lerp(startPosition, endPosition, i) yield return null As long as all of the objects have the same "time" value, their movements is correctly synchronized regardless the distance that they have to cover. The problems arises when they all have different "time" value. For example, if they have to move backwards and forwards from startPos(0,0,0) and endPos(5,0,0) with the following "time" value Object A time 1 second Object B time 2 second Object C time 4 second After 4 second, they should all be again at the same start position. However, what happen is that the fastest object (Object A) has a delay over the other two and this delay increase over time. How can i fix this problem?
0
Is it possible to use true Blinn Phong lighting on Unity Android IOS? I've noticed that the Unity's Legacy Shaders Specular shader does not work on mobiles due to the lighting model being incompatible. I then tried using the Mobile Bumped Specular shader, but this shader does not support non directional lights. So I tweaked the mobile specular shader to remove the noforwardadd argument, but I noticed that specular highlights are improperly positioned for non directional lights, even after removing the halfasview interpolateview argument. Does Unity even support non directional specular highlights on mobile devices?
0
Input.GetAxis returns wrong sign only for 1 and 1 I'm using an Xbox 360 controller on Windows 10 with Unity, and the maximum values have the opposite sign as the rest of that side. For example, if I tilt the stick up, I get values from 0.1 to 0.99, but then I get a 1 when the stick is at maximum. Have I configured it to be this way by mistake? I have reproduced the issue in a clean project and using another controller. void Update () float pitch Input.GetAxis("Vertical") Debug.Log (pitch) I have discovered that if the axis is inverted (i.e. not as shown in the image) then returned values have expected signs. I will add this workaround as an answer for anyone else who may encounter this problem, but I will refrain from accepting it to allow for answers addressing the root cause.
0
How do you turn off all scene lighting in the game view like you would with the scene view button? In the scene view, there's a control bar with a 'lighting' button that lets you toggle scene view lighting. This turns off all shadows and all light sources, i.e. makes it so that all objects are seen as fully bright on all sides. How do I do the same for the game view?
0
Create Script from custom templates issue They are created with the default name and cannot been named on creation I was just being introduced to the AssetDatabase class, and I was curious of creating Script Templates, such as Interfaces, pure C classes, and a MonoBehaviour template more suitable for my work style. I tried to emulate a solution I found on Unity Forums, and the template creation goes well, except that the name gets setted once it is created, and it doesn't let you name the created asset, as the Unity Scripts let you once you create them. The fact that the name is not changed by the user, makes the script on its default state, with the exact code the template has, without changing the SCRIPTNAME s declared, throwing errors, and being counterproductive with the time optimization goals I had in mind. using UnityEditor using UnityEngine using System.IO public class CustomScriptsCreator public const string CONTEXT MENU PATH "Assets Create Custom Scripts" lt summary gt Custom Scripts default Path. lt summary gt public const string CONTEXT MENU CUSTOM C SHARP " C MonoBehaviour" public const string CUSTOM TEMPLATE FOLDER PATH "Assets Custom Script Templates" public const string CUSTOM C SHARP TEMPLATE PATH "C Script CustomMonoBehaviourScript.cs.txt" public const string PATH NOT FOUND MESSAGE "Script Template Not Found" public const string WINDOW ERROR MESSAGE "There is no Template at path n n" public const string WINDOW OK ANSWER "Ok" MenuItem(CONTEXT MENU PATH CONTEXT MENU CUSTOM C SHARP) public static void Create(MenuCommand cmd) Object selection Selection.activeObject if (selection ! null) string path AssetDatabase.GetAssetPath(selection) if (File.Exists(path)) path Path.GetDirectoryName(path) if (string.IsNullOrEmpty(path)) path "Assets " THIS WAS JUST A FAILED TEST... Object obj Resources.Load("ScriptTemplates " CUSTOM C SHARP TEMPLATE PATH) if(obj ! null) AssetDatabase.CreateAsset(obj, Path.Combine(path, "NewScript.cs")) else EditorUtility.DisplayDialog ( PATH NOT FOUND MESSAGE, WINDOW ERROR MESSAGE (CUSTOM TEMPLATE FOLDER PATH " " CUSTOM C SHARP TEMPLATE PATH), WINDOW OK ANSWER ) string newName EditorUtility.SaveFilePanelInProject("Save Your Prefab", "NewScript.cs", "cs", "Please select file name to save prefab to ") File.Copy((CUSTOM TEMPLATE FOLDER PATH " " CUSTOM C SHARP TEMPLATE PATH), Path.Combine(path, "NewScript.cs")) if(AssetDatabase.CopyAsset((CUSTOM TEMPLATE FOLDER PATH " " CUSTOM C SHARP TEMPLATE PATH), Path.Combine(path, "NewName.cs"))) IT CHANGES THE FILE NAME SUCCESSFULLY, BUT NOT ON THE SCRIPT. AssetDatabase.RenameAsset(Path.Combine(path, "NewName.cs"), "KillMePlease.cs") AssetDatabase.Refresh() else EditorUtility.DisplayDialog ( PATH NOT FOUND MESSAGE, WINDOW ERROR MESSAGE ((CUSTOM TEMPLATE FOLDER PATH " " CUSTOM C SHARP TEMPLATE PATH)), WINDOW OK ANSWER ) The paths are ok, since the script is being created. If there is more information you need, let me know. Thanks in advance.
0
How to activate GearVR Menu in my own Unity Apps? So in normal GearVr Apps, which you can download from the marketplace, you can activate the GearVr Menu to control brightness etc. with a long click on the back button. But this does not work for all of my apps which I made with Unity for the GearVr, is there something special I have to import into my project?
0
ArgumentNullException Parameter name format I have made a simple game using Unity with Vuforia and exported for Android and iOS. It works fine on Android, but on iOS it crashed and gave the error ArgumentNullException Argument cannot be null. Parameter name format at System.Type.GetTypeFromHandle (RuntimeTypeHandle handle) 0x00000 in 0 at System.String.FormatHelper (System.Text.StringBuilder result, IFormatProvider provider, System.String format, System.Object args) 0x00000 in 0 at System.String.Format (IFormatProvider provider, System.String format, System.Object args) 0x00000 in 0 at System.String.Format (System.String format, System.Object args) 0x00000 in 0 at UnityEngine.Debug.LogFormat (System.String format, System.Object args) 0x00000 in 0 at Vuforia.TrackerManager.InitTracker T () 0x00000 in 0 at Vuforia.TrackerManager.InitTracker T () 0x00000 in 0 at Vuforia.TrackerManager.InitTracker T () 0x00000 in 0 (Filename currently not available on il2cpp Line 1)
0
Failed to load QCARWrapper.dll I am using unity 5.1.0f(64 bit) and Vuforia SDK Version vuforia unity 5 0 5 The web cam is operating normally in windows but in unity in Play Mode not. I am getting an error message "failed to load QCARWrapper.dll expected 64bit architecture..." Can anybody help out solving this issue?
0
convert view space normal to world normal Im writing a shader that uses Unity's CameraDepthNormalsTexture to get both the view normal and depth values. I return a color from my fragment shader equal to the normal values sampled. I am having problems converting the view normal into a world normal so that when my camera tilts around, the fragment colors shouldnt change. How can turn my view normal world normal in my fragment shader? Relevant code is marked with TODO below Shader "Custom DepthNormal" Properties MainTex ("", 2D) "white" HighlightDirection ("Highlight Direction", Vector) (1, 0,0) SubShader Tags "RenderType" "Opaque" Pass CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" sampler2D CameraDepthNormalsTexture sampler2D CameraDepthTexture struct vertexOutput float4 position in clip space SV POSITION float2 depth TEXCOORD0 float4 scrPos TEXCOORD1 float4 position in world space TEXCOORD2 vertexOutput vert(appdata full v) vertexOutput output output.position in clip space UnityObjectToClipPos(v.vertex) use the helper function instead of MATRIX MVP as per documentation mul(UNITY MATRIX MVP,float4(v.vertex,1.0)) output.position in world space mul(unity ObjectToWorld,v.vertex) recall computeScreenPos does not divide by w, but because this is not an image effect, diving by w here will WARP things unless we are completely parallel to viewing camera output.scrPos ComputeScreenPos(output.position in clip space) return output float4 frag(vertexOutput input) COLOR float3 normalValues float depthValue extract depth value and normal values recall computeScreenPos does not divide by w, so if you want proper screenUV for use in tex2D divide xy by w https forum.unity3d.com threads what does the function computescreenpos in unitycg cginc do.294470 float2 screenUV input.scrPos.xy input.scrPos.w DecodeDepthNormal(tex2Dproj( CameraDepthNormalsTexture, input.scrPos), depthValue, normalValues) Alternatively DecodeDepthNormal(tex2D( CameraDepthNormalsTexture,screenUV), depthValue, normalValues) TODO CONVERT TO WORLD NORMAL? float4 worldNormalValues mul(unity ObjectToWorld,mul(UNITY MATRIX IT MV, float4(normalValues,1.))) THIS ISNT RIGHT ( float d pow(depthValue,2) return float4(normalValues.x,normalValues.y,normalValues.z,d) ENDCG fallback "Diffuse"
0
Shader intersection radiate outwards I've been working on a water shader for a project I'm currently working on and have been trying to work on the intersections between objects in the water to create a foam effect that radiates outwards. I'm very new to shaders so my code is probably horribly inefficient! But here it is Shader "Unlit WaterShader" Properties Color("Color", Color) (1,1,1,1) IntersectColor("Intersection Color", Color) (0,0,0,0) MinIntensity("Minimum intensity", Float) 0.04 MaxIntensity("Max Intensity", Float) 0.4 SubShader Tags "Queue" "Transparent" "RenderType" "Transparent" LOD 100 Pass CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" sampler2D cameraDepthTexture struct appdata float4 vertex POSITION float4 uv TEXCOORD0 struct v2f float4 screenPos TEXCOORD2 float4 vertex SV POSITION float4 Color float4 IntersectColor float MinIntensity float MaxIntensity v2f vert (appdata v) v2f o o.vertex UnityObjectToClipPos(v.vertex) o.screenPos ComputeScreenPos(o.vertex) return o sampler2D CameraDepthTexture fixed4 frag (v2f i) SV Target float currentDepth tex2Dproj( CameraDepthTexture, UNITY PROJ COORD(i.screenPos)).r float linearDepth LinearEyeDepth(currentDepth) float depthDifference linearDepth i.screenPos.w if(depthDifference lt MinIntensity) Color IntersectColor return Color ENDCG It works well enough But now Id like to maybe try increase the intensity of the intersection. I know increasing MinIntensity doesn't really do what I want it to do, as it only shows more and more of the image submerged in water, which removes the effect of shoreline foam. I'd also like the outline of the objects in the water to spread out and fade out over time, I've tried using a sin wave for this but haven't been able to achieve the desired look.
0
What is a proper way to handle player inputs based on different states? So, I have two ideas how to do that Use enum to define current state and check current state value before running certain method group in Update. Code void Update() switch(currentState) case 1 InputGroup1() break case 2 InputGroup2() break lt ... gt And so on. I don't think that this is a good idea because of possible performance drops. Same concept about current state, but instead of checking it and running method groups, "head" script will check current state and activate corresponding script, disabling others. For me it looks like best way in terms of performance and usability. And also, is it better to keep all input checks in one giant script component and call functions you need from it? Essentially creating centralized Input Manager.