_id
int64
0
49
text
stringlengths
71
4.19k
0
Can't figure out what's making the player teleport back to spawn I've been working on a multiplayer game that uses pathfinding and I'm really confused over this one weird bug. On your screen, the other player glitches between the spawn point and his current location. It seems like there's a problem with the interpolation as it doesn't do this when I comment out transform.position Vector3.Lerp(transform.position, bestGuessPosition, Time.deltaTime latencySmoothingFactor) Does this have anything to do with the way I'm moving the player? using UnityEngine using UnityEngine.AI using UnityEngine.Networking public class MinionController NetworkBehaviour public Camera cam public NavMeshAgent agent Vector3 velocity Vector3 bestGuessPosition float ourLatency float latencySmoothingFactor 10 Update is called once per frame void Update() if (hasAuthority false) bestGuessPosition bestGuessPosition (velocity Time.deltaTime) transform.position Vector3.Lerp(transform.position, bestGuessPosition, Time.deltaTime latencySmoothingFactor) return if (Input.GetMouseButtonDown(0)) Ray ray cam.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit)) agent.SetDestination(hit.point) Command void CmdUpdateVelocity(Vector3 v, Vector3 p) transform.position p velocity v RpcUpdateVelocity(velocity, transform.position) ClientRpc void RpcUpdateVelocity(Vector3 v, Vector3 p) if (hasAuthority) return velocity v bestGuessPosition p (velocity (ourLatency))
0
Instantiated Object returns Null outside Start method I'm attempting to access an instantiated 'goalTemp' GameObject from a different function inside the same script. I'm getting the information in the Start method, assigning the GameObject find get component script code to a variable. When I'm printing the results outside the Start method, it returns null, even though the 'goal' variable is public. void Start() GameObject goalTemp (GameObject)Instantiate(goal,respawnGoalLocation CreateLevel.currentLevel 1 ,Quaternion.identity) goal goalTemp.gameObject public void Explode() Debug.Log(goal) Instantiate(rockParticle, goal.transform.position, goal.transform.rotation) Instantiate(explosionParticle, goal.transform.position, goal.transform.rotation) What am I doing wrong here? Thanks for your time!
0
Prototype experience Unity3D vs UDK Has anyone yet prototyped a game in both Unity3D and UDK? If so, which features made prototyping the game easier or more difficult in each toolkit? Was one prototype demonstrably better than the other (given the same starting assets)? I'm looking for specific answers with regard to using the toolkit features, not a comparison of available features. E.g. Destructable terrain is easier in toolkit X for reasons Y and Z. I can code, so the limitations of the inbuilt scripting languages are not a problem.
0
Unity network player synchronization issues with HingeJoint(s) I have a vehicle with custom wheels which are connected to it by the HingeJoint components. Everything works perfectly when using this car in single player mode. Wheels are actually as Cylinders. They have HingeJoints attached through which they are bound to the vehicle's Rigidbody. Then I set JointMotor.force and the wheels are getting rotated and the vehicle is moving. It all works very naturally in terms of physics, I don't need to emulate anything. Still, there is an issue with network synchronization in multiplayer mode and I have no idea how to solve it. It's said that the proper way to sync the position of a physical object is to use rigidbody.MovePosition(), but any manipulation with Rigidbody leads to the collapse of the vehicle hinge joints. The only method that works is setting transform.position directly. But this is not recommended for physics and it doesn't allow to synchronize the vehicle smoothly with no twitching. Is there a way to solve this somehow? I'm using Photon for networking (if it matters in the question context).
0
How do I make my prefabs spawn behind the UI? I'm making a game where three characters spawn in specific locations. I made three gameobjects called stations so I could take the transform positions and spawn the three caracters there. And I have a UI element that is supposed to stay in front of everything. But the problem is that when I hit play, the three characters spawn in front of the UI element. I already checked the positions related to the camera but it doesn't seem to be it. Does anyone know how to help me?
0
Move car at same speed I want to move car on each game play run with same speed. At present I was getting each time different velocity. I want to fix that. Here is game play area on which I was moving car At present I was moving car in infinite motion without any kind of control. When it collide with wall, it will its direction based on collision calculation. Here is my source code that I was using to move car void Start () direction new Vector2 (Random.Range ( 1f, 1f), Random.Range ( 1f, 1f)) void FixedUpdate () float angle Mathf.Atan2 (direction.y, direction.x) Mathf.Rad2Deg float targetRot Mathf.LerpAngle (myRigidbody.rotation, (angle 90f), 0.1f) myRigidbody.MoveRotation (targetRot) myRigidbody.velocity direction speed myRigidbody.MovePosition (myRigidbody.position direction Time.deltaTime speed) Debug.Log("vel mag " myRigidbody.velocity.magnitude) void OnCollisionEnter2D (Collision2D other) ContactPoint2D contact contact other.contacts 0 direction 2 (Vector3.Dot(direction, Vector3.Normalize(contact.normal))) Vector3.Normalize(contact.normal) direction Following formula v' 2 (v . n) n v direction 1 Dont know why I had to multiply by 1 but it's inversed otherwisae Vector2 reflectedVelocity Vector2.Reflect(direction, contact.normal) direction reflectedVelocity At present on each run of car, I was getting different velocity that I have checked via debug statement. So my target is to move car with same speed always.
0
unity2D Top Dow Mobile rigibody2D im using this code for my 2D TopDown mobile player movement.but when i move player With UI Image buttons player keep moving.it didnt stop.and also player starting of move he is very slow. the he accelerate his speed.how can i fix this. i add BoxCollider 2D and Rigibody2D my sprite.the set Gravity to 0. this is my code. public class PlayerScript MonoBehaviour public float speed 150f float hInput void FixedUpdate() Move (hInput) public void Move(float horizontalInput) if (horizontalInput.Equals(1)) rigidbody2D.AddForce (Vector2.right) if (horizontalInput.Equals(2)) rigidbody2D.AddForce ( Vector2.right) if(horizontalInput.Equals(3)) rigidbody2D.AddForce (Vector2.up) if(horizontalInput.Equals(4)) rigidbody2D.AddForce ( Vector2.up) public void StartMoving(float horizontalInput) hInput horizontalInput
0
Replacing assets in Unity real time but keeping the references intact I'm looking forward to adding mod support into my game by allowing users to easily replace some assets with their own versions. The way I want it to work if there's, say, a certain texture in some folder in my compiled game, I replace the texture with the same name in my resources, but I keep references intact. That means that the texture will be replaced for every material using this texture. I don't want to change materials themselves to reference the new texture, mainly because I'll have to keep a list of materials for each texture, and because materials might be replaced by potential modder as well. It's also important to note that I want to give people the ability to change basically anything (but scripts). Sounds, music, textures, meshes, materials, fonts, localization files, shaders, so the list of references might be absolutely changed upside down and that is absolutely not the solution.
0
Unity Terrain Tools plants trees sideways My tree is clearly straight, but painting trees result in sideways ones. What can cause this? Tree is straight when placed manually as a prefab.
0
Get all supported resolutions for a monitor I've been receiving complaints from users that my game doesn't support the 16 10 aspect ratio. Currently I list everything in Screen.resolutions in a dropdown and allow the user to pick from that. I have since come to the understanding that the first element is not necessarily the native resolution of the monitor. I've found the Display class but this appears to only give the native resolution, not all scaled resolutions. E.g. if the monitor is 1920x1080 then I need a list of 1600x900, 1280x720, 640x360 etc. I thought about just multiplying by some scale factor but then I'm afraid I'll get something obscure like 885x497.8. And if I have a pre determined list of resolutions for a specific aspect ratio, how do I support obscure aspect ratios like widescreen for example.
0
How can I scale a color component by Time.deltaTime and still fit it into a byte? I am confused about this issue, and I can't find why I get this and how to fix it properly from the Google searches I've tried. This is a short version of my code byte redtarget 70 byte greentarget 222 byte bluetarget 255 byte opacitytarget 1 byte redcurrent 0 byte greencurrent 0 byte bluecurrent 0 void OnMouseOver() redcurrent redcurrent redtarget Time.deltaTime greencurrent greencurrent greentarget Time.deltaTime bluecurrent bluecurrent bluetarget Time.deltaTime if(redcurrent gt redtarget) redcurrent redtarget if(greencurrent gt greentarget) greencurrent greentarget if(bluecurrent gt bluetarget) bluecurrent bluetarget theobject.GetComponent lt Renderer gt ().material.SetColor(" EmissionColor",new Color32(redcurrent,greencurrent,bluecurrent,opacitytarget)) Please ignore the other errors that could have been introduced when I copy pasted it to here. And this is the error I get As you see the error, "cannot implicit convert type float to byte", the problem is caused by Time.deltaTime that returns a float value, and I need a byte due to Color32. Is there any way to turn Time.deltaTime to byte? Or should I use another type of color that use floating point numbers? I'm a beginner with Unity so I'm sorry if this has already been asked somewhere as I said, I can't find it on the Internet.
0
How to program an attack that I control with the arrow keys? I'm making a 2D game prototype in Unity and I want to have the player attack be a sword that hovers around the player with its direction being fixed to the direction you indicate with the arrow keys. So if the sword is in the upward position and you press the left button, you can see the arc it takes and an enemy in the way of that arc takes damage. The game is not a platformer. It's on a flat surface. edit I want to know how to have the sword hover in a radius to the player and point the direction i press the arrow keys. I want to get the action of moving the sword to these positions to do damage to an enemy. But if the sword is in a upwards position and the player presses down, I want it to do an action that attacks the whole radius around the player, on a cooldown. How would I go about programming this? I'm new to programming so I would greatly appreciate some helpful pointers. Edit2 So this is how far I have gotten public class SwordSwing MonoBehaviour public Transform swordHolder Update is called once per frame void Update () if (Input.GetKeyDown(KeyCode.LeftArrow)) swordHolder.transform.Rotate(0, 0, 90) if (Input.GetKeyDown(KeyCode.RightArrow)) swordHolder.transform.Rotate(0, 0, 90) if (Input.GetKeyDown(KeyCode.UpArrow)) swordHolder.transform.Rotate(0, 0, 90) if (Input.GetKeyDown(KeyCode.DownArrow)) swordHolder.transform.Rotate(0, 0, 90) I don't know if this is right, because when I use the arrow keys it just turns the sword 90 degrees and not to the specified position I want it to move to. So Candid Moon said that I have to use Mathf.Lerp() and StartCoroutine() but I have no idea how to use them. I'm not really sure how to animate this either, I have done some animations in Unity but have a hard time implementing them into anything. The hierarchy is now Player SwordHolder Sword Now I also have this script if (GetComponent lt Rigidbody2D gt ().velocity.x gt 0) transform.localScale new Vector3(1f, 1f, 1f) else if (GetComponent lt Rigidbody2D gt ().velocity.x lt 0) transform.localScale new Vector3( 1f,1f,1f) That flips the player sprite when i move left. This also flips the sword, I don't really want this. How do I stop it? Let me know if there is anything I missed, I'm trying to learn.
0
MySQL for MMO Development... What do i have to consider ? Im currently developing an little mmo. Its pretty basic, players can walk around... gather some resources... build some simple buildings and craft things. Before i began to develop i read a lot about benefits using MySQL... Now im not sure if MySQL was the right choice for such a project. Currently i store player specific data in real time, that means... once a player crafted, builded or gathered something, a server request is send which triggers a MySQL Query to insert a new Row into the specific table. This happens everytime a player moves, crafts, gathers or builds something. I dont only store player specific data in those tables... also world specific data, for example if one player visits a zone which was last updated 6 hours ago, i refresh this zone with resources and mobs. The server is generating them and after that, it inserts them as a bulk into the database. With only one active player this works fine... but i have no idea if this will still work with dozens or hundreds active players at the same time. The serverside itself is able to handle them... but i have no idea if the database is able to. I also heard bad stuff regarding table locks... That this is somekind of major iusse using MySQL, how does this effect dozends of database actions per seconds ? And could possible "share" be a solution for this ? What else do i need to consider while using MySQL for a mmo ?
0
Sprites lose quality when in Unity Whenever I drag a sprite sheet into unity, it, for whatever reason, distorts. Is there any way to remedy this? Original Distorted
0
Unity2D Wrapping a line around an object I have this 2d platformer made out of box colliders. I have the player connected to a point by a LineRenderer and a DistanceJoint2D, for use in physics puzzles. This tool lets him link to a location and then do grappling hook things with it, like retract the rope at speed to spiderman around. What I want to do is move the distance joint around the object, thus changing the angle at which the player is pulled. Like in this image. Very similar to this more general, unanswered question that doesn't not give any specific math. I know I'll be making a list of positions and then move the joint's anchor around whenever it wraps unwraps, but I'm not sure how to tell when and where it wraps on something.
0
How do I make a transition between two states to be slowly? Now it's doing the first New State then it's jumping to New State 0 Instead I want it to slowly move between the two states. I want to see the animation transition slowly changing from state to state. For example when you see a character sitting and then standing so to see the transition from sitting to standing slow.
0
Turn and point Animation not ending in correct position I have Right Turn, Point amp talk Mixamo animation. I am playing animation in this order Play Idle animation Turn animation Point Animation Then, run Turn animation again with speed to bring it back(reverse) and then finally played Idle animation and loop continue. But the problem is, each time when I return from step 4 my character rotation is different. And over different iterations the character rotation become completely changed. The rotation of the character increment in each iteration. How can I solve this problem? I am learning this but unable to understand.
0
Image looks GOOD on the editor but BAD (blurry) on the HTML5 export I have a red bar that looks good inside Unity editor, but when I export the build it looks very strange. Any idea on how to fix this? The image on the left is the one with the strange bad looking red bar...
0
Texture not working on object I have a project that I'm having a bit of trouble with. Let me try and explain. In short, I'm trying to apply a texture to an object, but instead it is a solid color. I built a building in "Autodesk 123d design", and exported it as stl. Then I used an online converter to convert it to obj, then added that to the unity scene. I created a material with a texture and tried to apply it to the object, but it was a solid color. I think the UVs on the object might be messed up. I tried some things in blender, but had no luck. Any ideas on how I can fix this? Edit Here is the 3D model I'm working with http www.123dapp.com 123D Design Conisbrough Castle Keep 4578568
0
Refresh UI after changing source code I was trying following things. GameManager bool gameHasEnded false public GameObject completeLevelUI public void CompleteLevel() completeLevelUI.SetActive(true) public void EndGame() if(gameHasEnded false) gameHasEnded true Invoke( quot Restart quot ,2f) void Restart() SceneManager.LoadScene(SceneManager.GetActiveScene().name) EndTrigger public GameManager gameManager void OnTriggerEnter() gameManager.CompleteLevel() I get a log in the console quot END quot . Earlier I was using Console.Log( quot END quot ) on CompleteLevel(), but I changed that source code. The old code seems to be working and not the new one. It's like Unity couldn't refresh that source code. (And I am sure that I have successfully saved the C file.) using System.Collections using System.Collections.Generic using UnityEngine public class PlayerCollision MonoBehaviour public PlayerMovement movement void OnCollisionEnter(Collision collisionInfo) Debug.Log(collisionInfo.collider.name) if (collisionInfo.collider.tag quot obstacle quot ) movement.enabled false FindObjectOfType lt GameManager gt ().EndGame()
0
Should I scale gravity for small objects? If I am working with objects that are small in real life, but in the Unity world they are scaled larger, should I increase the Gravity with the scale of the objects? For example, if an object of size one would actually be 10 cm across, would gravity scaled to be 10x make the object behave more like a small object would in real life. I know objects fall at the same rate, but the rate is the same so small objects fall more in proportion to their size don't they?
0
Changing alignment within a vertical layout group I have a vertical layout group that has text bubbles instantiated into it. Instantiating them always aligns them to "lower middle". However, I'd like to have them on opposite sides for a message app effect. Right now, I'm changing the anchoredPositions of each instantiated UI object in Update. Is there any better way of doing this?
0
Rotate an object on itself, from one random Quaternion to another I have a situation I have a 3D object in the world. let's say a sphere. I have 2 random directionnal vector vector A, and vectorB My question is How to I rotate over time my object, from A to B ? The vector A is important I don't want to simply rotate the forward of the object from current forward to B. I know I can use the function vector3 C Vector3.SmoothDamp(...) in unity to lerp between my 2 vectors A amp B. but then ok, I have vector3 C, how do I apply the rotationof my object to C ? if don't want to do gameObject.transform.forward C I want something like gameObject.transform.rotation SomeQuaternion(C, initial rotation A). or something. Thank you for help ! PS I don't want to parent unparent gameObject or something like that, i want the math answer, using Quaternion.
0
How can I have realistically bending flexing paper? I am a new hobbyist to Unity and I working on a game where the player goes around picking up clues in the form of paper notes to solve a mystery. So far, thanks to the help I got here, I was able to animate a note made from a UI canvas and an image in game world to fly and rotate to align itself in front of the first person camera. Although, it looks nice, it still looks like a rigid plank of wood rather than a piece of paper. Is there a way I could bend flew distort the canvas to give the illusion of a piece of paper rather than piece of wood? Is it possible to bend a canvas or should I go towards another solution, like using an actual plane or quad during the animation effect?
0
Are environments built in external applications or in Unity? Totally new to game development here I know models are never built in Unity, but what about environments? Is it common to say, build an office building environment with hallways and doors (sans furniture and props) in Blender and import that into Unity and assemble the scene there?
0
How can I avoid tight script coupling in Unity? Some time ago I started working with Unity and I still struggle with the issue of tightly coupled scripts. How can I structure my code to avoid this problem? For example I want to have health and death systems in separate scripts. I also want to have different interchangeable walking scripts that allow me to change the way the player character is moved (physics based, inertial controls like in Mario versus tight, twitchy controls like in Super Meat Boy). The Health script needs to hold a reference to the Death script, so that it can trigger the Die() method when the players health reaches 0. The Death script should hold some reference to the walking script used, to disable walking on death (I'm tired of zombies). I would normally create interfaces, like IWalking, IHealth and IDeath, so that I can change these elements at a whim without breaking the rest of my code. I would have them set up by a separate script on the player object, say PlayerScriptDependancyInjector. Maybe that script would have public IWalking, IHealth and IDeath attributes, so that the dependencies can be set by the level designer from the inspector by dragging and dropping appropriate scripts. That would allow me to simply add behaviors to game objects easily and not worry about hard coded dependencies. The problem in Unity The problem is that in Unity I can't expose interfaces in the inspector, and if I write my own inspectors, the references wont get serialized, and it's a lot of unnecessary work. That's why I'm left with writing tightly coupled code. My Death script exposes a reference to an InertiveWalking script. But if I decide I want the player character to control tightly, I cant just drag and drop the TightWalking script, I need to change the Death script. That sucks. I can deal with it, but my soul cries every time I do something like this. Whats the preferred alternative to interfaces in Unity? How do I fix this problem? I found this, but it tells me what I already know, and it does not tell me how to do that in Unity! This too discusses what should be done, not how, it does not address the issue of tight coupling between scripts. All in all I feel those are written for people who came to Unity with a game design background who just learn how to code, and there is very little resources on Unity for regular developers. Is there any standard way to structure your code in Unity, or do I have to figure out my own method?
0
Level Asset design for performance Unity I am a big fan of modular assets. Currently I am designing a 3d game for mobile and I don't know how I should create my levels to get the most out of the device. Should I... create lots of "small" (1x1x1 meter) assets and build my level using them or create one geometry for the entire level? What about textures? Should "all" objects share one highres texture and only display their part using the right UV settings (like say in minecraft)or should I create an individual texture for each object?
0
How to make a script work when clicked only on the given prefab? I am very new to unity but not to C . I am working in Unity 2D I made this prefab called LongLane. Its basically a collection of sprites of road, put together into a Gameobject. Now I wanted objects to spawn on the road when I ONLY click on the road, I can spawn the object on the road but they spawn regardless of where I click. I have written some code but they aren't clear and readable. So how do I make a script work only when clicked on that specific prefab
0
How to access GameObject to which MonoBehaviour is added from C Attribute Unity's RequireComponent inherits from System.Attribute. Somehow they made it that whenever component is added it has a reference to GameObject its being added to. So they can callAddComponent to it. I am trying to replicate that behaviour. My theory is that because UnityEngine.RequireComponent has types stored inside class they do it by reflection later. In method AddComponent lt T gt they get T class attributes from type and then try to cast them, get information from them, and apply to GameObject. If that is the case, then I doubt I will be able to do something with it, unless I have access to change AddComponent lt T gt somehow. Is there another way around it?(that is no problem to do in code (just extension), but what about how it will work in inspector) Maybe apply different method to Unity s default component addition. EDIT AttributeUsage(AttributeTargets.Class, AllowMultiple true) public class RequireComponentAttribute Attribute public RequireComponentAttribute(Type type, int quantity) if (quantity lt 0) throw new ArgumentOutOfRangeException("Required components quantity cannot be negative") if UNITY EDITOR endif
0
Control Torque Inputvector I'm faced with the following problem I'm trying to implement a rigidbody based movement for my submarine game which means I want (need?) to useAddForce() and AddTorque() in order to get proper collision detection. Currently I'm achieving the desired rotational behavior by quaternion multiplication rotation. But with this approach, the submarine bugs through the terrain. To avoid that it seems my only option is to use a rigidbody. Here's a video illustrating the problem. On the left is the correct behavior. I want to keep the nose pointing where it has been tilted at and not rotate around a fixed axis, Vector3.up in this case. How can I calculate the correct input for AddTorque(vec3) to get the result I need? Left attempt with quaternions (what I need) input2 Input.GetAxis("Sideways") transform.rotation Quaternion.Euler(0, input2 Time.deltaTime rotation speed, 0) transform.rotation Right attempt with torque (which doesn't quite work yet) in Update() rotateY Input.GetAxis("Sideways") void FixedUpdate() experimenting with AddTorque() and various inputs didn't get me any further rb.AddRelativeTorque(Vector3.up rotateY speed) I hope someone can point me in the right direction, thanks in advance.
0
Why moving platform script is not working? I have some code attached to a moving platform public Transform pos1, pos2 public float speed public Transform startPos Vector3 nextPos Start is called before the first frame update void Start() nextPos startPos.position Update is called once per frame void Update() if (transform.position pos1.position) nextPos pos2.position else if (transform.position pos2.position) nextPos pos1.position transform.position Vector3.MoveTowards(transform.position, nextPos, speed Time.deltaTime) private void OnDrawGizmos() Gizmos.DrawLine(pos1.position, pos2.position) But my platform does not go to the pos2 when it reaches the pos1. What is wrong here?
0
Unity Loading Image? I have a quastion about loading screen in unity. I don't want to make a scene between to levels Main Menu Loading Scene Game level . I want to use Canvas "Image"that run at the start of the game level and then disappear after few seconds Main Menu Game level . Is this good idea ?
0
Things not appearing in front of canvas (follow up) Follow up related question to Things disappear in front of Canvas I'm having a very similar problem, where things are not appearing in front of my canvas. This time a particle system. I have tried the suggestions outlined in my previous questions (which worked then) but this time none of them will work You can see that the particle system is on top of the children and also I have added a canvas and overwritten sorting (the two suggestions in my previous post) yet the particles are not visible in front of the canvas.
0
Unity 2D Platformer Controller responsiveness issue I've been designing some basic controls for a 2D platformer and managed to get the feeling that I've been looking for when moving and jumping, but something is not quite right, it's not very responsive. Most of the inputs are detected, but a lot of times, for example, the simple action of pressing some key to jump is completely ignored and the player ends up falling when the key was pressed at the right time. I don't consider that I'm developing on a laptop with low specs at all if that matters. Looking at some other questions it has always been said that input detection should be inside the Update function and that physics related stuff should be on FixedUpdate, however, it has not always been very clear what exactly should be on which function, as far as I understand it should go something like this...right? using System.Collections using System.Collections.Generic using UnityEngine public class PlayerController MonoBehaviour public float speed public float jumpForce public float groundCheckRadius public Transform groundCheck public LayerMask groundMask private float direction private bool facingRight private bool shouldJump private bool isGrounded private bool shouldFall private SpriteRenderer renderer private Rigidbody2D rigidbody void Awake() this.renderer GetComponent lt SpriteRenderer gt () this.rigidbody GetComponent lt Rigidbody2D gt () void Start () this.facingRight true this.shouldJump false this.isGrounded false this.shouldFall false void Update () this.direction Input.GetAxisRaw("Horizontal") this.isGrounded Physics2D.OverlapCircle(this.groundCheck.position, this.groundCheckRadius, this.groundMask) this.shouldJump Input.GetKeyDown(KeyCode.S) amp amp this.isGrounded if (this.facingRight amp amp this.direction lt 0 !this.facingRight amp amp this.direction gt 0) this.Flip() if (Input.GetKeyUp(KeyCode.S) amp amp this.rigidbody.velocity.y gt 0) this.shouldFall true void FixedUpdate() Vector2 velocity this.rigidbody.velocity if (this.shouldFall) velocity.y 0f this.shouldFall false if (this.shouldJump) velocity.y this.jumpForce velocity.x this.speed this.direction this.rigidbody.velocity velocity private void Flip() this.renderer.flipX this.facingRight this.facingRight !this.facingRight I'm not sure if I got the idea of Update vs FixedUpdate correctly because of this lack of responsive jumps, and I'm guessing that if I add some more mechanics, later on, those will react the same or worse. Something that I noted is that if I move everything to update it now feels right every time I press the jump button, but I'm still not sure if that should be the right approach when building tight controls. And I still feel lost about what everyone means by "You should manage physics in FixedUpdate", what do you mean by physics here?
0
why does Physics.Raycast always return my player game object instead of the object I clicked? I have 3D world. I want to detect when the player clicks on a game object in the world. In this image, I have 2 objects I want to detect mouse click on. The white sphere does have collider on it. The dumpster does not. The behavior is the same as noted below. I am getting the mouse down detection. When I check the RaycastHit, I always get the player game object transform and not the game object I clicked on in the world. If I remove the raycaster checks, then I get mousedown for anything in the game not just mouse down over the game object. I need to be able to distinguish between clicks on different game objects. I found a post here and added a PhysicsRayCaster, but it didn't change the behavior. The problem isn't getting the event. My problem is detecting which game object the player clicked on in the world. Here's my code public class InventoryItemSearchHandler MonoBehaviour private void Update() if (Input.GetMouseButtonDown(0)) Ray ray UnityEngine.Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit)) CompareTo always fails because hit.transform.name is always "Player" and not the name of the object clicked on if (0 hit.transform.name.CompareTo(transform.name)) print("mouse down") EDIT In the image below (compared to the one above) I do get the correct transform in the RaycastHit type when I click on the white sphere (and when I click on the dumpster I get the player transform as noted above). So it looks like the player object is getting in the way. What would be causing that?
0
Updating transform position after root motion I have an animation of a character climbing with root motion in it (i.e. the character moves generally upwards for a couple of units during the animation). It is intended as a one shot, not a loop. The skeleton is fairly standard hips spine 1, hips right leg, hips left leg etc. The root is the hips and the pivot is between the soles of the feet. I know its generally best to make in place animations without root motion but scripting the upward movement using Vector3.Lerp etc looks unrealistic (in reality when rock climbing for example the upward motion will come in perdiodic bursts as the knees are first bent, then extended, rather than a constant movement upwards), so I want to keep the root motion in the animation. Problem is when the animation has finished Unity still considers the transform pivot to be in its original location, before the skeleton climbed up two units. Is there any way to instruct Unity that the new transform position is where the characters feet have ended up after the animation has finished? I figure I could parent the hips to an empty which moves the charaters around normally, detatch the empty before the root motion climb, move it by the same amount the hips moved then re attach but is there a less hacky way? Some kind of transform.returnToOriginalOffset method perhaps?
0
Issues loading in AudioSource at runtime using WWW class I am having an issue with loading in an OGG audio file to my project. Basically I want to set my game up so that players can drop audio files into a folder called Playlist in the game directory then they can listen to this music while they play. For some reason my audio clip never becomes instantiated. I have an Audio Source in my scene with this script attached to it. As you can see I have commented out some code for the time being as I am trying to get a simple case of only 1 audio file playing at this stage. So my question is what exactly am I doing wrong here? I have printed out the file path and it comes out as file B Users Matt Development Unity Projects Space Game Playlist 19 Tumbling Dice.ogg which is the location to my audio. However when I print out the audioLoader.audioClip.name it comes out as blank... RequireComponent(typeof(AudioSource)) public class MP3AudioImporter MonoBehaviour private List lt string gt playlist private string musicDir "B Users Matt Development Unity Projects Space Game Playlist " private int currIndex 0 void Start() string songs Directory.GetFiles( musicDir, " .ogg", SearchOption.TopDirectoryOnly) playlist new List lt string gt (songs) StartAudio() void StartAudio() WWW audioLoader new WWW("file " playlist currIndex ) Debug.Log(audioLoader.audioClip.name) audio.clip audioLoader.audioClip audio.Play() currIndex if (currIndex gt playlist.Count) currIndex 0 Invoke("StartAudio", audio.clip.length 0.5f)
0
World space coords for 2d images How can I make an 2d image using World space coords with a shape? Like a circle instead of a quad.In 3d you can modify the vertices but if I want a smooth circle there will be too much vertices. What I want to achieve is something like a cirle mask that will be move over the global texture at runtime. So has anyone done something similar? I've tried combining some shaders with two uv's one for world space and one for alpha uv mesh but it gives some weird artifacts. This is the how the shader looks on the right Shader "Unlit WorldspaceTiling" Properties MainTex ("Texture", 2D) "white" SubShader Tags "Queue" "Transparent" "IgnoreProjector" "True" "RenderType" "Transparent" LOD 100 ZWrite Off Blend SrcAlpha OneMinusSrcAlpha Cull Off Lighting Off ZWrite Off Fog Mode Off Pass CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" struct appdata float4 vertex POSITION float2 uv TEXCOORD0 struct v2f float2 uv TEXCOORD0 float4 vertex SV POSITION sampler2D MainTex float4 MainTex ST v2f vert (appdata v) v2f o o.vertex mul(UNITY MATRIX MVP, v.vertex) Gets the xy position of the vertex in worldspace. float2 worldXY mul( Object2World, v.vertex).xy Use the worldspace coords instead of the mesh's UVs. o.uv TRANSFORM TEX(worldXY, MainTex) return o fixed4 frag (v2f i) SV Target fixed4 col tex2D( MainTex, i.uv) return col ENDCG
0
Is it possible to have a point light cast shadows but no reflection? I'm working in Unity 5.3.6. I have a point light that is simulating sunlight from a window. It looks great, except the floor reflects a bright white circle. I want the floor to reflect other lights in the room, just not this one. Is this possible?
0
Instantiating prefabs by dragging in scene not working So I have this problem where I try to instantiate prefabs as in this video for example. I can take instantiate one prefab to the scene, but if I try to instantiate a second one to the scene (whether it's with the same prefab or a different one), instead of creating an instance of the second prefab, it brings the first instance I had created to my mouse and I'm in position to move it by dragging it around. The only work around I have for this so far is to drop into the hierarchy instead of the scene (which works fine), but I have to carefully avoid the scene while dragging and dropping, otherwise the above described issue happens instantly. Am I doing something wrong, or is this a bug of some kind? EDIT I managed to reproduce the error in a consistent manner. I don't know why it happens, but it does every time. It doesn't involve code and it is very simple to reproduce (at least for me, perhaps not for you if you're not doing the wrong thing that I do...). I created a new project. I created a cube and a sphere. I turned them both into prefabs and deleted the original instances (they have the .prefab extension in my folder, so I am sure). I drag dropped the cube in, works fine. I drag the sphere in, and it appears as a cube which I have to position (by releasing the click), and my initial prefab instance of the cube is gone.
0
How to run code selectively only when a specific trigger collider has been hit I have 2 objects both with trigger colliders. The first object has only 1 trigger collider (imagine this to be a sword). The second object (a person) has multiple colliders. One is a non trigger collider (used for collision detection for walls, ground) and then multiple trigger colliders on different parts of the body (the purpose is for hurt box). Now when the sword hits the person, I want to only process code for those trigger colliders and to be able to detect which of those trigger colliders got hit (arm, leg, etc.). But the event only exposes a parameter hit for the other collider void OnTriggerEnter(Collider other) if (other.gameObject.layer LayerMask.NameToLayer(Constants.LAYER HITBOX PLAYER)) Run code here I want to run code only when certain trigger collider are hit, like for example, when the head is hit, or the body, etc. How do I get this info to be able to run conditional code on this method?
0
How can I scale object on one side only with a speed factor? using System.Collections using System.Collections.Generic using UnityEngine public class ScaleOneSide MonoBehaviour public float speed 1 float mfX float mfY Use this for initialization void Start() mfX transform.position.x transform.localScale.x 2.0f mfY transform.position.y transform.localScale.y 2.0f Update is called once per frame void Update() if (Input.GetMouseButton(0)) Vector3 v3Scale transform.localScale transform.localScale new Vector3(v3Scale.x 0.1f, v3Scale.y 0.1f, v3Scale.z) transform.position new Vector3(mfX transform.localScale.x 2.0f, mfY transform.localScale.y 2.0f, 0) transform.localScale new Vector3(v3Scale.x 0.1f, v3Scale.y, v3Scale.z) transform.position new Vector3(mfX transform.localScale.x 2.0f, 0, 0) transform.localScale Vector3.Lerp(transform.localScale, new Vector3(v3Scale.x 0.1f,0,0), speed Time.deltaTime) When using only this two lines it was working fine without changing the speed transform.localScale new Vector3(v3Scale.x 0.1f, v3Scale.y 0.1f, v3Scale.z) transform.position new Vector3(mfX transform.localScale.x 2.0f, mfY transform.localScale.y 2.0f, 0) But now I'm trying to add to the scaling a speed. I want when I press the mouse left button it will scale the object according to the speed.
0
How to disable spring joint in unity 3d How can I disable Spring joint in unity 3d, since disabling feature only available in 2d mode, I am not able to find any way to disable it via script
0
Unity 2D graphical glitch cuts sprite diagonally While making a game in unity, we found a graphical glitch that only happens on one of our mobile devices (a htc) where the screen will be oddly sliced by a triangle as shown in this image I've searched online but found no problem. We're using unity 2D, it only does it on the HTC but we have no idea why. The background is a 3D quad with a texture wrapped around it (so we can make it move with the character when the character is running, without having one large background). Any help would be greatly appreciated. Thanks
0
Is it possible to somehow change the collider points to match sprites during the animation in Unity? Is it possible to somehow change the collider points to match sprites during the animation in Unity? I am using the Unity built in animtion recording feature. I would like to change the points of some of my colliders as animation goes, while at the same time I am changing the respective sprites. I was not able to find any solutions so far. Any ideas how I could do that? I have a few attempts to overcome the problem. Create a few game objects with the different preset points for the colliders. The solution will work. But it is crazy hard to develop and maintain resources wise. I will have to spend an immense amount of time creating a separate game object with a collider for each frame. And also the maintenance will be very lame. Because I will need to add a wrapper around all the places where I access collider. So that the wrapper would return the currently enabled collider. I can buy the 2DColliderGen. But I do not want to spend money on that. And also it is not completely what I am looking for, because even with it I will have significant difficulties developing my animations, maintaining my game and extending it.
0
How to bounce the ball off a collider and destroying it using trigger? I am making a Breakout game. I have bricks with box colliders and the ball is a rigidbody2d with circular collider. I have applied the PhysicsMaterial2D on the ball with bounciness set to 1 so the ball is bouncing off the bricks as intended. Now I want to detect this collision in C so I could destroy the brick but I cannot enable the isTrigger property as it will disable the collisions in that brick. So, I am looking for a way to do that.
0
Unity setting rectTransform on an UI Image with a Vector3, do I need to convert coords? I am trying to build a menu with a cursor. I created the menu and that in the unity UICamera on the canvas. It looks great. I want the cursor to move so what I did was move the cursor by hand and record the values at each location I want the cursor to possibly be (see attached). The problem is later when I try to set the value to these via this pauseCursor.rectTransform.position new Vector3 ( 45f, 80.6f, 0) It fails and looking in the inspector again the x,y values are like 300, 800 or something. I am guessing I need a conversion I just am not sure where or how. Do I get the Ui camera reference and use the WorldToScreen?
0
Difference between 2 quaternions I need to patch an animation during LateUpdate. I'm rotating the "chest" bone according to the mouse delta. This is to mimic aiming a pistol. During this aiming, the "neck" bone should stay relatively still. As changing the chest bone's location rotation yaw automatically changes the "neck" bone's local yaw rotation, I store the chest bone's rotation BEFORE I apply a new rotation to it. Then I calculate the difference between the old and the new rotation. Then I apply this rotation yaw difference to the neck bone. The inspector gives me nice values to work with. When I inspect the rotation values by script, I get reprensations that I can not easily work with. Here is an example While the Inspector shows "15.4", the localEulerAngle shows "344.6". If I use "344.6", the neck rotation goes Berzerk of course. How should this be solved? For completeness, here is the entire void private void pHandle LateUpdate Aim() Vector3 nOldChestRotation Chest.localRotation.eulerAngles Fade old input before capturing new, so we don't dull the freshest data. float yawBlend Mathf.Pow(1.0f Aim yawInputFalloff, referenceFramerate Time.deltaTime) A Lerp toward zero is just the same as a multiplication by the blend factor. Chest yawRate yawBlend Accelerate by mouse movement over the past frame. (May need adjustment for display resolution). Chest yawRate Input.GetAxis("Mouse X") float yawDelta Chest yawSpeed Chest yawRate Time.deltaTime float offCenterYaw Chest currentYaw Chest yawCenter float fDesiredChestYaw Chest currentYaw yawDelta float fHeroRotation 0f if (fDesiredChestYaw gt Chest rotateRange) fHeroRotation fDesiredChestYaw Chest rotateRange we don't rotate the chest beyond the allowed "Chest rotateRange", so simply act like the user didn't move the mouse Chest yawRate 0 yawDelta Chest yawSpeed Chest yawRate Time.deltaTime else if (fDesiredChestYaw lt Chest rotateRange) fHeroRotation (Chest rotateRange fDesiredChestYaw) Chest yawRate 0 yawDelta Chest yawSpeed Chest yawRate Time.deltaTime If we're moving away from the center, slow down as we approach the edge. if (yawDelta offCenterYaw gt 0) float extremityYaw offCenterYaw Aim yawMaxRange yawDelta 1.0f extremityYaw extremityYaw this.transform.Rotate(0, fHeroRotation, 0) Ensure we never overshoot the allowed range. Chest currentYaw Mathf.Clamp(Chest currentYaw yawDelta, Chest yawCenter Aim yawMaxRange, Chest yawCenter Aim yawMaxRange) Vector3 nNewChestRotation new Vector3(Chest.localEulerAngles.x, Chest currentYaw, Chest.localEulerAngles.z) Chest.localRotation Quaternion.Euler(nNewChestRotation) float fChestRotationDifference nNewChestRotation.y nOldChestRotation.y the neck should not rotate with the chest. So I first counter rotate it against the new chest rotation, then rotate it a little towards the chest rotation Neck.transform.localRotation Quaternion.Euler(0, Aim NeckYaw fChestRotationDifference (fChestRotationDifference 0.5f), 0)
0
Why the skyline continues to stay on the same place and how to change this? I started my first Unity3D project and in this game main hero should be able to fly up passing clouds and then reaching open space but i faced with the problem. No matter how long and fast i am flying after takeoff the skyline continues to stay on the same place. Currently i'm going to rotate the main hero so that skyline would go down. But maybe someone can suggest me more common and better way to achieve the effect of leaving the Earth? I think it would be bad idea to post all my code here because there is a lot of code that does not relate to the topic. But i will try to explain what i'm doing now and i will show you short piece of code. I have global parent object and a main hero is added as a child to it. Then when as main hero moving up relative to the global object i start to rotate this global object around z axis so that gradually the main hero is looking to the sky. And for skyline i'm using procedural skybox. I hope this piece of code will explain better of what i'm doing now using UnityEngine using System.Collections using UnityEngine.UI public class PlayerController MonoBehaviour float gravity GameObject global main hero s parent Vector3 startHeroLocalPos start hero position relative to the global object public float degreesPerUnit 1.0f global object will rotate by this amount of degrees after the player has moved up by one unit void Start () global GameObject.FindGameObjectWithTag ("GlobalObject") startHeroLocalPos transform.localPosition void Update () float curAngle (transform.localPosition.y startHeroLocalPos.y) degreesPerUnit global.transform.rotation Quaternion.AngleAxis(curAngle, Vector3.back)
0
How should I account for the GC when building games with Unity? As far as I know, Unity3D for iOS is based on the Mono runtime and Mono has only generational mark amp sweep GC. This GC system can't avoid GC time which stops game system. Instance pooling can reduce this but not completely, because we can't control instantiation happens in the CLR's base class library. Those hidden small and frequent instances will raise un deterministic GC time eventually. Forcing complete GC periodically will degrade performance greatly (can Mono force complete GC, actually?) So, how can I avoid this GC time when using Unity3D without huge performance degrade?
0
How to instantiate new GameObject at position of old GameObject onAnimationComplete I have a GameObject that is a Farmer that plants Seeds. The Seeds will animate into Plants. Once that animation is complete, I'd like to replace my Seed with a Plant. This happens hundreds of times per game at arbitrary positions. I've tried this as something I built off of this question Unity detect animation 39 s end public class SeedScript StateMachineBehaviour SerializeField private GameObject seed override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) Destroy(this) animator.GetComponent lt TreeScript gt ().GrowTree(seed) Instantiate (tree, this.position, this.rotation) Obviously, this doesn't work at all. Doesn't even compile. I've also looked at these co routines https answers.unity.com questions 981948 statemachinebehaviour startcoroutine.html but again, I need to get position data from the animating object. Yes, I could just merge my Seed and Plant classes together, let's pretend I cannot do that and MUST instantiate some arbitrary new object at the position of another object on some animation completion.
0
Wheels not facing right direction when car faces different directions I am creating a real time multiplayer driving game in Unity. I am using google play's real time multiplayer service. I am having an issue where the wheels of the cars that are over the network are not facing the right direction. What I am currently trying to do is just add the calculated steering angle to the current rotation of that particular player's car, but for some reason the wheels face the wrong way and rotate incorrectly if the car is facing certain directions. Logically I thought what I have is correct. Basically for each wheel I use this code car.transform.rotation Quaternion.Euler(0, car.transform.rotation.y steerAngle, 0) So I find the rotation of that car and then I add the steer angle to it. Why wouldn't this work?
0
Coding style about collisions with geometry Let's say I'm writing 3D Pacman. I have "Dot" objects throughout my maze, that are structured as follows in the Inspector Dot (GameObject) Sphere w Collider When I run into the sphere trigger, I can trivially say "Get me your parent and check if it's a Dot" However, I hate baking in the knowledge that some spheres have parents that are Dot objects. If the trigger were on the Dot itself that problem would solve itself, as I could just call GetComponent(). What's a good programmatic style approach to finding out what logical Game Object actually owns the geometry you've collided with? I could add a Tag of "Dot" to the sphere but that's just a level of confirmation, I still would have to walk up to it's parent and check.
0
How can I launch Visual Studio via a double click on a C script in Unity? This is my first time using Unity and I am following the tutorial for the 2D RogueLike Game. Everythings seems to be working properly, apart that I cant get Visual Studio to launch, if I'm double click my c scripts. What I have tried so far Checked my preferences, that External Script Editor says "Visual Studio 2017" Reinstalled Unity and Visual Studio. Unity Version 2019.3.0a2 Personal Hope somebody can help me. Additional information After double click, nothing seems to be happening, even my mouse doesnt show a load icon When I create a new project, the bug (dont know if bug, or my fault) is still there. I can open the .sln file from my project in Visual Studio. Visual Studio can even autocomplete unity based code then, before it was a "miscellaneous file" and didnt autocomplete code like for example "Transform" or "Rigidbody2D".
0
Is There a Way To Keep Precision When Transforming GameObjects I've seen this issue before, but it's never been a particular issue for me until today. I have each "room" of a dungeon created with a class script that contains details of that room. During the process of building the dungeon, rooms may be mirrored or rotated. When I rotate the y axis, it updates properly the first time, going from 0 to 180, but if I mirror it back and forth, it begins to get very small variances away from true 0 and 180. Over time, this could impact some things. The code I'm using to do this is public void RoomMirror() transform.Rotate(0, (transform.localRotation.y 180) ? 0.0000f 180.0000f, 0) Mirror !Mirror Swap(ref east, ref west) I added the four places in the float to try to overcome this issue, but it doesn't seem to be making any difference. Thanks!
0
How can I spin a child capsule of a cube parent? I have a parent cube and to make it like a surface I had to change the rotation of the cube on the X to 90. and as a child, I added a capsule, and to make the capsule like standing I had to change the capsule X also to 90. The result is The reason I put the capsule child of the cube is that I want the capsule to move with the cube. The capsule rotation on the X is also 90 Then in a script at the top, I added speed and index variables for the rotation private int index 0 private int rotationIndex 0 In the Update RotateTo() And the method curvedLinePoints is a List private void RotateTo() var distance Vector3.Distance(capsule.position, curvedLinePoints rotationIndex .transform.position) if(distance lt 0.1f) rotationIndex Determine which direction to rotate towards Vector3 targetDirection curvedLinePoints rotationIndex .transform.position capsule.position The step size is equal to speed times frame time. float singleStep rotationSpeed Time.deltaTime Rotate the forward vector towards the target direction by one step Vector3 newDirection Vector3.RotateTowards(capsule.forward, targetDirection, singleStep, 0.0f) Draw a ray pointing at our target in Debug.DrawRay(capsule.position, newDirection, Color.red) Calculate a rotation a step closer to the target and applies rotation to this object capsule.rotation Quaternion.LookRotation(newDirection) The problem is that because the capsule is a child when I rotate the capsule it looks like the capsule changes its shape and not spinning around itself. If I remove ut the capsule from the prefab and will rotate it on its own it will spin fine but when it's a child of the cube the result is I tried before running the game to play with the capsule rotation in the editor in the inspector changing the Y and Z values and the result is like in this screenshot. but I want to spin it around itself but because it's a child of the cube it's not spinning but looks like it's changing its shape. The workaround I found is to create an empty GameObject at 0,0,0 and put both Platform and Capsule as a child of it. Then I added this part to the script above private void LateUpdate() capsule.localPosition transform.localPosition new Vector3(0, 1.4f, 0) This way the Capsule is following the Platform. The empty GameObject is just to put them both together. and for testing I just did in the Update capsule.Rotate(0, 10, 0) and it's working fine. Now I have to figure out how to make this rotation with the code in the RotateTo method.
0
Box collider has different behavior in 2 clients I'm new to Unity. I am making my first Game and faced with problem. I have a plane and 4 gameobject that has box collider surrounded this plane. there are a few spheres as players inside of the plane.I built the game. I run 2 instances of the game and add force to a sphere and send this force to other client through node server. But border reflection angle differs in 2 clients. I checked value of the force in 2 clients and that is the same. Any help would be appreciated.
0
2d Grid Generation (Unity C ) I am creating a simple program in Unity C that will generate a 2d grid using a 2d sprite prefab. I am stuck here, I don't know what to do. When ran, I receive an error. Assets Generator.cs(22,75) error CS0165 Use of unassigned local variable grid object' I am a beginner, so I'm not sure what to do. This is most likely a rookie mistake, so thanks in advance. using UnityEngine using System.Collections public class Generator MonoBehaviour public float Width 20 public float Height 20 public Transform grid object private GameObject , grid new GameObject 20,20 void Start () CreateGrid() private void CreateGrid() for (int x 0 x lt Width x ) for (int y 0 y lt Height y ) GameObject grid object (GameObject)Instantiate(grid object) grid object.transform.position new Vector2( grid object.transform.position.x x, grid object.transform.position.y y) grid x,y grid object
0
Adding Color to button after cloning public GameObject button public void Start() GameObject button1 Instantiate(button) as GameObject button1.transform.SetParent(canvas.transform, false) button1.transform.position new Vector3(7, 0, 2) I have cloned the button game object now want to add color to that game object how can i do it ?
0
Why don't objects far away from the camera experience floating point issues? In Kerbal Space Program, a space exploration game made with Unity, Floating origin technique is used to overcome the floating point precision issues. While in map view, the world (a scaled space with miniature celestial bodies) is recentered around the camera every frame so glitches don't occur when viewing unsafely distant planets. But when such planets are observed from an 'unsafe distance' (more than 10 000 units in scaled space), they're still rendered normally. Why don't floating point issues occur?
0
How can I reflect a point about a line in Unity? I am drawing a line using the line renderer in the following way public class MyLineRenderer MonoBehaviour LineRenderer lineRenderer public Vector3 p0, p1 Use this for initialization void Start () lineRenderer gameObject.GetComponent lt LineRenderer gt () lineRenderer.positionCount 2 lineRenderer.SetPosition(0, p0) lineRenderer.SetPosition(1, p1) From the image below, the line P0P1 is known and so is point A. How can a point B, which is the reflection of A about the line P0P1 be found?
0
Draw line inwards in Unity using Line Renderer Is there a way to draw the line inwards instead of from the center using Line Renderer in Unity? Another option would be to move the Vector points inwards by half the width of the line, but If I have a complex polygon how do I do it uniformly? EDIT Found this https stackoverflow.com questions 1109536 an algorithm for inflating deflating offsetting buffering polygons which may be useful
0
Unity How do I fix the players model rotation in a NetworkManager to spawn properly? How do I fix the players model rotation in a NetworkManager to spawn properly? I created a game with the NetworkManager code. Player Model is a cone I made and imported. all works fine but when the NetworkManager spawns the player model it is sideways. I have tried turning it in 3ds but the player remains sideways when it is spawned by NetworkManager on run, Ohterwise the model is fine in unity, and no matter how I rotate it, in or out of unity , The NetworkManager Rotates it. All other objects attached to the main object remain with proper orientation all, All other objects including instantiated ones appear properly.
0
What physics settings do I need to apply to make the pool game realistic? I want to create a pool game using Unity. I added the spheres as playballs and cubes as the walls. I added a rigidbody to all objects and Im able to do some basic collisions like in a pool game. My Question is What physics settings do I need to apply to make the pool game realistic? Right now, it's a bit weird. The ball does not bounce off the walls realistically and also the ball to ball collisions are not ok. Any suggestions?
0
How to implement Fog Of War with an shader? Okay, I'm creating a RTS game and want to implement an AgeOfEmpires like Fog Of War(FOW). That means a tile(or pixel) can be 0 transparent (unexplored) 50 transparent black (explored but not in viewrange) 100 transparent(explored and in viewrange) RTS means I'll have many explorers (NPCs, buildings, ...). Okay, so I have an 2d array of bytes byte , explored. The byte value correlates the transparency. The question is, how do I pass this array to my shader? Well I think it is not possible to pass an entire array. So what technique shall I use to let my shader know if a pixel tile is visible or not?
0
Setting SteamVR Camera Target Eye before SteamVR installed in Unity I'm writing a plugin that can be used in both VR and non VR projects. I have a Camera that is used to display UI containing some game info on a secondary monitor. My problem is that when the end user adds my plugin and then imports steam vr, this UI camera's Target Eye is set to "Both" by default. I can't have any SteamVR code in my plugin. But I can't adjust Target eye property of the camera without it. I just want it so that the camera doesn't change when a user imports SteamVR. I want it to always render to the main display (target eye none) So just to clarify, I have my plugin, written in a non vr project with a standard Unity camera. There is no Target Eye setting for this standard camera. User wants to use it in VR project, imports plugin into SteamVR Project Camera used to render UI gets automatically converted (wrongly) into SteamVR camera Defaults to Target Eye Both Need it to be Target Eye None At the moment to avoid users submitting countless bug reports, I have to provide warnings in like 6 places telling users to dig way into my built in prefabs to adjust this setting manually if they use SteamVR. It's not easy for new Unity users, and I want to make adoption as easy as possible.
0
Score does not increment by 1 in Unity I have made a simple code where once the player moves through the collider that acts as a trigger then Unity adds a score. However, it increases by increments of 8 and I am not sure why. using System.Collections using System.Collections.Generic using UnityEngine public class Game MonoBehaviour public int Score 0 void Start() Update is called once per frame void Update() private void OnTriggerEnter2D(Collider2D other) AddScore() void AddScore() Score
0
Unity Text Mesh Pro can not get referenced in VSCode I am using Text Mesh Pro in my Unity 2019.3.4f. The TMP works fine in unity, but in the code editor, Visual Studio Code, the TMP related things are marked with red wave underline, which means the VSCode could not get the reference of TMP. In my csproj file, the TMP reference exists, here are some related codes lt ProjectReference Include quot Unity.TextMeshPro.csproj quot gt lt Project gt e8ae9ed6 ed86 3de7 e777 7e6794b003b2 lt Project gt lt Name gt Unity.TextMeshPro lt Name gt ProjectReference Include quot Unity.TextMeshPro.Editor.csproj quot gt lt Project gt af8771c0 66d3 f01a 48b5 78951bce8a23 lt Project gt lt Name gt Unity.TextMeshPro.Editor lt Name gt My TMP works fine in every aspects, but there are code warnings in the VScode, quot could not fine the namespace of TMPro quot . Is there anyone know how to fix it?
0
How can I let the user choose his own background image? Dear Stackoferflow Fourm I would like to have a function in my Android Game Programming that allows the user to choose his own background image (I would like to let the user change the plane image) Unfortunately I have no idea how I could do that. If someone knows how to do it I would be very happy.!
0
List of Lists for sending paths from client to server? I have a client server scenario and I'm looking into distributed AI. I want the server to move x amount of ai characters around a map by pathfinding and then send the x amount of paths to the client which will apply each path to its corresponding AI character. This is for research purposes to see if this approach, by sending the new path of each server AI to the client AI for it to follow, is better than constantly sending a positional update across a network everytime a server gameobject moves slightly. I would like this X amount to range anywhere from 10 to 2000, a big ask i know, but i'll go into what I have atm. Atm I have this working for 2 AI characters and it can be expanded, but with my existing code it would mean an awful lot of copying and pasting! So on the server when the path is created it is sent to a script which can bundle it into an RPC an send it on its way public class GrabbingArrayFromUnitScript NetworkBehaviour public List lt Vector3 gt receivedArrays new List lt Vector3 gt () public List lt Vector3 gt receivedArrays1 new List lt Vector3 gt () ClientRpc void RpcPosFromServerToGoTo(Vector3 path, String name) if (name "SeekerPrefab") receivedArrays.AddRange (path) UnityEngine.Debug.Log ("Received") if (name "SeekerPrefab (1)") receivedArrays1.AddRange (path) UnityEngine.Debug.Log ("Received 1") public void PrintPath(Vector3 path) if (isServer) UnityEngine.Debug.Log("Send Array ...") RpcPosFromServerToGoTo (path, transform.name) UnityEngine.Debug.Log("Sent!!") So as you can see from the above if I wanted to add more AI characters in I would have to add more if statements to the RPC call, and if I wanted 2000 AI in that would be alot of copying. So what could I do here to reduce this code down? Would I use a list of lists? Any help would be greatly appreciated!
0
How do I determine the rotation of a Tile using Tilemap in Unity 2d? I want to know the rotation of the tile in C in order to do some logic on another object that is sitting on the tile. The rotation matters for the logic. I don't see anything except GetTileData in the doc, but that doesn't actually seem to "Get" the tile data. I could cast to Tile but not all tiles are Tile. Alternatively, I think I can get the rotation if I can get the GameObject for the tile but I have no idea how to do that either from a BaseTile. Anyone have any suggestions? Maybe I'm trying to do this wrong and I should make different tiles for each orientation or extend BaseTile or some other solution instead of trying to determine rotation. Any help or ideas would be greatly appreciated! Additional info When I inspect around in the Unity editor I see that the rotation is stored in Z in something called "Grid Selection" but I can't find a programmatic way of accessing that.
0
How to get the file location of missing sprite in unity? I accidentally moved some of my sprites and now I can't remember where they were originally. Now in Unity, it says missign sprite. So can't I get the location saved in scene file??? i.e. if it is referring to Desktop file.extension and I move it to Desktop files file.extension, can I get Desktop file.extension in Editor???
0
How to await player input using Coroutines How can I accept player input using Coroutines, pausing execution of Unity while the player has not yet provided input? It seems like a simple problem, but I can't seem to figure it out. Here is my latest attempt. In this program I want to do some logic and pause in the middle, continuing only when the player has inputted some data. Someone please tell me I'm on the right track O using System using System.Collections using System.Collections.Generic using UnityEngine public class InputTester MonoBehaviour int choice 1 valid choices for this example are 0 and 1 void Start() StartCoroutine(DoSomeLogic()) IEnumerator DoSomeLogic() print("Starting...") print("Awaiting your choice 0 or 1. ") yield return StartCoroutine(WaitForKeyDown(KeyCode.Alpha0) WaitForKeyDown(KeyCode.Alpha1)) how to combine these two into a single method that gives the player a choice? print("Continuing...") switch (choice) logic based on the choice IEnumerator WaitForKeyDown(KeyCode k) while (!Input.GetKeyDown(k)) yield return null SetChoiceTo(k) private void SetChoiceTo(KeyCode keyCode) switch (keyCode) case (KeyCode.Alpha0) choice 0 break case (KeyCode.Alpha1) choice 1 break StopAllCoroutines() how do I stop all the coroutines that accept player input? print(choice)
0
Why use Time.deltaTime in Lerping functions? To my understanding, a Lerp function interpolates between two values (a and b) using a third value (t) between 0 and 1. At t 0, the value a is returned, at t 1, the value b is returned. At 0.5 the value halfway between a and b is returned. (The following picture is a smoothstep, usually a cubic interpolation) I have been browsing the forums and on this answer I found the following line of code transform.rotation Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime) I thought to myself, "what a fool, he has no idea" but since it had 40 upvotes I gave it a try and sure enough, it worked! float t Time.deltaTime transform.rotation Quaternion.Slerp(transform.rotation, toRotation, t) Debug.Log(t) I got random values between 0.01 and 0.02 for t. Shouldn't the function interpolate accordingly? Why do these values stack? What is it about lerp that I do not understand?
0
Shadow Glitch on Mesh Stitches I use LWRP, one Directional Light and Hard Shadows with 1024 resolution. When I imported this super simple mesh from blender this happened What is this weird line on the stitch of the mesh and how do I fix it? I tried using Soft Shadows with higher quality but it did not help.
0
Problem with Input.GetKeyDown to set a counter in Unity multiple values in only one pressing Using Unity 5, I want to use have one keyboard key ("f") increase a counter when pressed. It means, using Input.GetKeyDown("f") function in a way that if "f" is pressed when the counter 1, then the counter is set to be equal 2. If counter was equal 2 when "f" is pressed, then counter is set to 3. However, it does not work properly it seems that Unity detects the key being pressed many times, no matter if it was only pressed once. See the code that illustrates the situation using UnityEngine using System.Collections public class TestingKeyGetRecursion MonoBehaviour int counter 1 void Update () if(counter 1 amp amp Input.GetKeyDown("f")) counter 2 Debug.Log(counter) if(counter 2 amp amp Input.GetKeyDown("f")) counter 3 Debug.Log(counter) if(counter 3 amp amp Input.GetKeyDown("f")) counter 1 Debug.Log(counter) void OnGUI() GUI.Label(new Rect(30, 10, 250, 20), "counter " counter.ToString()) As you can see in the console if you run the above example, the values are properly set into the counter variable and printed in the console. However, it happens several times in the same key hit and, in the end, the counter ends up equal as it started, i.e. equal 1. Can anyone please explain 1) why does the Engine behave like that 2) is there a way to solve such situation? I cannot substitute the counter with a bool variable and just do "counter ! counter" when "f" is pressed.
0
In Unity, how do I make text annotations appear when I mouse over GameObjects in playmode? How do I make text appear when I mouse over GameObjects in game? What is the Unity jargon for this? I'm assuming it's 'annotations'.
0
Am I experiencing a gimbal lock problem when rotating my cube? So I'm trying to build a simple mechanic where the player see's 3 sides of a cube at a time top, left and front(I called the front side "Right" in my code, due to the orthographic view). The player can click on the front side or left side of the cube to rotate the cube so that the side that was pressed moves and becomes the top face. I want to smooth animate the rotation. The red faces are the faces that the user can click on. My Logic seems to work quite well when I click on the left face (Rotating along the x axis), but doesn't seem to work well for the front right face(It usually works once and then does weird stuff on the next click, this is on the z axis) public class CubeRotator MonoBehaviour private const float STOP THRESHHOLD 0.1f private const float ROTATE AMOUNT 90f SerializeField, Header("Touch Quads Colliders") private Collider touchQuadLeft SerializeField private Collider touchQuadRight SerializeField, Space(10) private float timeToRotate private bool mustRotateLeft false private bool mustRotateRight false private float targetX 0.0f private float targetZ 0.0f private float xVelocity 0.0F private float zVelocity 0.0F int layerMask private void Start() layerMask LayerMask.GetMask("Touch Quad") void Update() ListenForTouch() RotateCube() private void ListenForTouch() if (Input.GetMouseButtonDown(0)) Vector2 touchPoint Input.mousePosition RaycastHit rayCastHit Ray ray Camera.main.ScreenPointToRay(touchPoint) if (Physics.Raycast(ray, out rayCastHit, 150f, layerMask)) if (rayCastHit.collider touchQuadLeft) mustRotateLeft true targetZ targetZ ROTATE AMOUNT zVelocity 0f else if (rayCastHit.collider touchQuadRight) mustRotateRight true targetX targetX 90f xVelocity 0f private void RotateCube() float zAngle transform.rotation.eulerAngles.z float xAngle transform.rotation.eulerAngles.x if (mustRotateLeft) zAngle Mathf.SmoothDampAngle(zAngle, targetZ, ref zVelocity, timeToRotate) if (Mathf.Abs(zVelocity) lt STOP THRESHHOLD) mustRotateLeft false if (mustRotateRight) xAngle Mathf.SmoothDampAngle(xAngle, targetX, ref xVelocity, timeToRotate) if (Mathf.Abs(xVelocity) lt STOP THRESHHOLD) mustRotateRight false transform.rotation Quaternion.Euler(xAngle, 0f, zAngle) Inspector Values I've tried several things, the only problem I can think of is, gimbal lock. Thanks in advance.
0
How can I assign a layer to tiles on an individual level? I've just started out with my first game in Unity. It's a simple 2D Platformer with a tile based level. When coding in the movement, I used the Physics2D.OverlapCircle() and an empty to check whether my player was touching the ground. However, I need to use a layer to make sure only the ground is detected. my code below fixed update used for physics calculations void FixedUpdate() right or left arrows being pressed float moveX Input.GetAxis( quot Horizontal quot ) Vector2 moveDir new Vector2(moveX playerSpeed, rb.velocity.y) rb.velocity moveDir update used for spacebar input and force void Update() if (Input.GetKeyDown(KeyCode.Space)) rb.velocity Vector2.up jumpForce Time.deltaTime is my circle overlapping any other colliders Collider2D collider Physics2D.OverlapCircle(feet.position, checkRadius, groundLayer) Debug.Log(collider) When I tried assigning layers to my tiles, I couldn't find a way to do it. I would be really grateful if anyone could show me how to, or if anyone can tell me a more efficient way to deal with jumping in a 2D platformer.
0
Add points to a prefab in Unity I have a prefab that looks like this I have created a couple of 'points' in the Hierarchy using 'Create Element' and I would like to attach them to the prefab, however drag and drop over doesn't work. Why is that?
0
How to publish a Unity desktop game without a security warning? When I build a Unity game as a Windows Desktop application, zip the folder, and upload the zip to itch.io, then anyone downloading the zip from itch.io and running the game gets a security warning from Windows. Is there a way to build the game in a way that will not show this warning?
0
How do I get a popup menu to block clicks from hitting UI elements beneath it? You can see in the picture that I have a Canvas with a popup menu in it. I just enable this, and it covers the main menu stuff. Clicks go through it and hit stuff in the main menu. I've tried adding an EventTrigger to the PopupRoot object, and adding an event to listen for PointerClick events, but it doesn't fire. EventTrigger trigger m popUpRoot.GetComponentInChildren lt EventTrigger gt () EventTrigger.Entry entry new EventTrigger.Entry() entry.eventID EventTriggerType.PointerClick entry.callback.AddListener((eventData) gt PopupClickBlocker((PointerEventData)eventData) ) trigger.triggers.Add(entry) I'm open to other suggestions. My current system is horrible button click events query the Popup to see if it's enabled or not, then return doing nothing if it is. This doesn't work for sliders very well, so I want to do this the right way.
0
Fade into scene in Unity SteamVR I am using this code below for a gradual fade into a scene next level in Steam VR (HTC Vive) The whole idea is to cover up the scene loading icon which is viewable for 3 4 seconds, and the default Steam landscape scene. The fade (to red) works fine BUT it comes in after the loading icon so this defeats the whole purpose of it. Is there any simple way to fix this? thanks public class NewFade MonoBehaviour private float fadeDuration 4f private void Start() FadeFromWhite() private void FadeFromWhite() set start color SteamVR Fade.View(Color.red, 0f) set and start fade to SteamVR Fade.View(Color.clear, fadeDuration)
0
How to render a large, seamless platforming world without scene transitions? In the game Limbo for example, the whole 2 3 hours of gameplay takes place in one continuous world. The player navigates from one area to another seamlessly, with no obvious loading or transitions. It looks like the whole game world (ie. all the ground sprites and every puzzle) is always active on and off camera. Is that feasible? How can I make a large world like this without overwhelming the player's device with all the content that needs to be loaded?
0
Can I change the background color where a sprite is shown in the inspector? this is how a sprite shows in the inspector. It's white pixelart with transparent background. Is there a way to change the background checkered pattern color in the inspector so I can actually see the sprite? Note I don't want to change any color in the game, just the background in the inspector, in the editor, so there's some contrast and I can actually see the sprite pattern.
0
Can I legally remove the default Unity splash screen by removing it from the APK? While using Unity I export an Android game as an APK. When the APK is run, the first thing that is displayed is the Unity splash screen. I worked out that I could replaced that image by opening the APK like a zip file, looking for the splash screen image (App.apk assests bin Data splash.png) and replacing it with any image I wanted. Is it legal to publish Unity powered Android game apps with modified splash screens like this? I remember that some games on PS3, 360 and Wii have been created with Unity but don't display a Unity splash screen when run on their respective consoles.
0
What is wrong with this character slope math? I'm making a sidescrolling platformer and have implemented some code that should convert the characters speed to an X speed and Y speed based on the angle of the surface they are on. This actual math for this was taken from a web page and I don't know if it's right or not. xSpeed and ySpeed are derived from speed, based on the angle xSpeed speed Mathf.Cos(angle) ySpeed (speed Mathf.Sin (angle)) gravity The angle is found with this code RaycastHit ground Physics.Raycast (transform.position, Vector3.down, out ground, 1.5f) Debug.DrawRay (transform.position, Vector3.down.normalized, Color.green, 2, false) if (ground.collider ! null) angle Vector3.Angle (ground.normal, Vector3.up) else angle 0 This works fine when walking on a flat surface, but freaks out when walking on a slope. I believe the problem lies with the angle itself.
0
Lighting doesn't work properly in WebGL build only at one place So I have a 2d game where a player walks around the level (top view) with a flashlight in front of him. Everything works fine in the editor, however whenever I build it for WebGL and test it in my browser, one room only one, has a problem with lighting, and as I walk in different parts of the room lighting changes in a weird way, and the floor is blinking in the first half of the room, as well as the flashlight is barely visible (if at all). Here's how it looks in the editor and is supposed to look like And here's a few screenshots from the web build P.S. Everything works fine in a standalone build. Also there seems to be no problem when I disable the 4 lights (the whole room works fine), these are the lights (the ones that look like from a window)
0
Best way to handle tick based resource generation in an online multiplayer strategy game I'm building an online multiplayer strategy game. The game has no offline mode and requires syncing up to a server. Part of this game is constructing buildings which will generate resources each second. These resources would be generated whether the player is online or offline. If this was a purely offline game, this would be easy get the delta between when the app was closed and when it was opened again and multiply by resources per second and just fast forward everything. Since it's an online game, and other players can be affected by the resources an offline user has, these calculations have to occur on the backend. My question is if I have 10,000 players, each with 20 buildings generating resources on a per second basis, how on earth should I handle 200,000 things all at once and syncing to a database?
0
Need a little more help with rotating sword around player (Unity 2D) this question is somewhat similar to my last question (found here). This time, I have upgraded to the new Input Manager and updated the script that uses the controller, but now I'm having trouble with having the sword rotate around the player and towards the mouse. The image below might help visualize this better. Here's my current code public void Update() var gamepad Gamepad.current var mouse Mouse.current if (controllerControl) x gamepad.rightStick.ReadValue().x y gamepad.rightStick.ReadValue().y else x mouse.position.ReadValue().x Here's where I think the problem is y mouse.position.ReadValue().y convert the input into an angle in radians, and convert that into degrees float rads Mathf.Atan2(y, x) float degrees rads Mathf.Rad2Deg use trig to position sword sword.localPosition new Vector3(Mathf.Cos(rads) distance, Mathf.Sin(rads) distance, 0) rotate to face away from center. note that the angle atan gives us is oriented differently than unity's rotation, so we have to reverse it and add 90. sword.localEulerAngles new Vector3(0, 0, degrees 90) The boolean quot controllerControl quot will change based on which input device the player chooses. The sword is a child of a box object. If someone could point me in the right direction, that would be much appreciated.
0
Unity Is it possible to copy a rig from one model to another Lets say I have a model with a ready humanoid rig and a humanoid model with no rig. Can I somehow copy the bones from the rig to the model with no rig in unity?
0
Making a gameObject push the player I am working on a Unity 3D game for Oculus and I have problems with making my objects to apply physics on a player. So getting rid of a CharacterController and using something like a rag doll is not an option. I am using OVRPlayerController, that has a Rigidbody with mass 1 and a box collider on it. My gameObject has a Rigidbody of mass 100, and a box collider. But when the object hits the player it just goes through it, whereas I want it to push the player in x direction. I tried using onColliderHit but it doesn't even recognize the collision between the player and the object, so I checked box collider on the object to be a trigger and I use OnTriggerEnter() to recognize the collision. I tried to translate the player's position on collision, but player gets positioned to weird places out of my map for some reason. Here is what I use info.transform.Translate(new Vector3( 0.5f, 0.0f, 0.0f)) info.transform.rotation Quaternion.identity I also tried to manually set the x position of the player but this doesn't work, and I know I am not supposed to do it. I searched for answers for a long long time, so please don't answer to this with something like "oh, have you tried googling it, there are a lot of similar questions" etc.
0
How to test for adjacency? I need to come up with a better way to test for adjacency in a grid environment. Imagine that the blue is water, the green is land, and the red dot is a character. What I need to do is efficiently return a list of Vector positions of all grid tiles for the "island" that the character is on. I have attempted to do this with raycasts using the following procedure. raycast at all of the immediately adjacent nodes surrounding the player. if (hit land) then add hit to adjacent list. raycast at all immediately adjacent grid cells around each of the previous hits on land. (if they have not already been tested) if (hit land) add to the adjacent list. loop until no more hits on land. this seems to work okay, but is not very fast. If possible I need to maintain the raycasting because the levels are randomly generated at run time.
0
Restricting my horizontal slash attack I've been working on making this slash attack for my character in the unity engine. The whole point to this script is to put the damage range in sync with the slashing animation. The slash is completely horizontal and is scripted out make enemies bounce back. I have most of that but what I really need to restrict it on x axis. If I haven't explained it enough let me give you an example of what its doing. When an enemies in front of me but above the area my swing attack shouldn't be able to reach. I use my swing attack and it still does damage anyways. what I need is a way is restrict my hit detection range between two angles rolling around the x axis. I'm sorry if I didn't explain this so well just tell me if I need to make something more clear. this is the code I've come up with what I've got it doings is it applies damage it can tell if an enemy is in front of it (uses the dot product for that) it can even knock said enemy backwards void Knockback() Vector3 grenadeOrigin transform.position I'm building this controller using explode for knock back and this stuff was based off of a grenade script Collider colliders Physics.OverlapSphere (grenadeOrigin, radius) foreach (Collider hit in colliders) Rigidbody rb hit.GetComponent lt Rigidbody gt () if (rb) Vector3 dir (rb.transform.position transform.position).normalized float direction Vector3.Dot(dir, transform.forward) Debug.Log(direction) if (direction gt 0.1) this is where i tell if something is in front of me rb.AddExplosionForce(power, grenadeOrigin, radius, 0) This is where we apply force to our enemy and various other rigid bodies hit.gameObject.SendMessage("Damager", Damage, SendMessageOptions.DontRequireReceiver) This is where we apply damage to the enemy
0
Unity ScrollRect many objects perfomance issue I have scrollrect setup and over 1000 objects to scroll through. Currently i'm Instantiating all the 1000 objects at once and notice fps drop. I'm using 2d mask and disbale pixel perfect. Both gave a perfomance boost, but i still Think the bottleneck is that i have 1000 objects already created on the scene. Instead create what is visible to the eye. What can i do? I've looked into pools. But i dont know how i should use it in my case. Since the inventory is dynamic. public void ShowInventory(PlayerObject player) for (int i 0 i lt inventory.GetContainerSize i ) Item item inventory.GetContainer i Button itemButton Instantiate(buttonPrefab, content) itemButton.GetComponent lt InventorySlot gt ().SetInventorySlot(player, item, item.amount)
0
I installed Linux Build Support, but I need an archive to build, how can I get this? I m building a game for Mac, Windows and Linux, I builded the Windows and Mac game, but in Linux, says that need a x86 64 archive, like the image shows, what do I do?
0
How do I get a Light's Range value in Shader? I'm trying to write a simple frag vert shader that, depending on whether it is in the range of a light, will paint the appropriate colour from either the 'lit' texture or from the 'unlit' texture. Therefore, I need to compare the distance between the light to the range of the light. I've been googling all kinds of things, but I can't seem to find a way of accessing the range value of the light. Is there a way to do so? If not, is there some kind of derived data I could use as an alternative? I was able to find this method here, which seems to be the most promising so far, however after playing around for a bit, I still can't seem to get what I need. There's some talk about LightMatrix0 not being populated. Can anyone confirm? I've also had it suggested to use SetFloat() and pass in the range like that...however, that provides no easy way of telling one light apart from another short of using the light's position as a key. As several key lights in the game will be moving this is just ugly and inefficient. Update I found the variable unity LightAtten in the Unity Shader Variables documentation. However, this is only used for Vertex Lit shading, which isn't exactly ideal, especially considering the lack of console support. Could there be a way to pipe this variable to Forward Rendering? Update 2 For clarification, shading should otherwise be 'flat' (ie no need for diffuse etc) Also, what I've currently got (albeit, not currently working as desired and currently using a workaround) Shader "Lantern Flat Pullup" Properties LitTex ("Lit (RGB)", 2D) "white" UnlitTex ("Unlit (RGB)", 2D) "white" Falloff ("Falloff", 2D) "white" Pullup ("Pull up Point", Range(0,1)) 0.7 SubShader Pass Tags "LightMode" "ForwardBase" LOD 200 CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" uniform sampler2D UnlitTex uniform float4 UnlitTex ST uniform sampler2D LitTex uniform float4 LitTex ST uniform float Pullup uniform float4 LightColor0 struct VI float4 vertex POSITION float4 tex TEXCOORD0 struct V2F float4 pos SV POSITION float4 tex TEXCOORD0 float4 posWorld TEXCOORD1 V2F vert(VI v) V2F o o.pos mul(UNITY MATRIX MVP, v.vertex) o.tex v.tex o.posWorld mul( Object2World, v.vertex) return o float4 frag(V2F i) COLOR float3 flatReflection LightColor0.xyz (1 length( WorldSpaceLightPos0.xyz i.posWorld.xyz)) float4 color Improve for light color etc if(length(flatReflection) gt Pullup) color tex2D( LitTex, i.tex.xy LitTex ST.xy LitTex ST.zw) else color tex2D( UnlitTex, i.tex.xy UnlitTex ST.xy UnlitTex ST.zw) return color ENDCG FallBack "Diffuse"
0
How can I stop transform.position from being modified when adding a child object? I suspect there is a well known and easy to explain reason for the behavior I'm seeing, but I am having difficulty explaining it (and likely not able to Google for the answer). When adding a child GameObject to a translated parent, the child's localPosition is modified so that the child's position stays the same after the parent's transformation is applied. Is there a way to not have this be the case? In the following example, I create a parent object and move it to (1,1,1), and then attach the child. I would like the child's position to be (1,1,1), that is (0,0,0) relative to the parent. However, the child's position is modified to be ( 1, 1, 1) so that it is (0,0,0) relative to the world. Here is a repro Create parent. GameObject parent new GameObject() parent.name "Parent GameObject" parent.transform.parent foregroundObject.transform Move the parent. parent.transform.Translate(1, 1, 1) Add a child under the parent GameObject. GameObject child (GameObject) GameObject.Instantiate(guildiePrefab) child.name "Child GameObject" child.transform.parent parent.transform PROBLEM localPosition is set so that the "global" position is (0,0,0). How can I add the child object and have its position be (1,1,1)? this.Assert(child.transform.localPosition.ToString() "( 1.0, 1.0, 1.0)") this.Assert(child.transform.position.ToString() "(0.0, 0.0, 0.0)") Is there a different way I should be adding child as a child of parent? Or, should I always zero out the position of parent before adding a child? If that is the case, any reason why I need to do this? What is the rational for this design choice?
0
Unity UNET, problems spawning and then destroying that instantiated prefab I am very new to networking, and have ran into an issue, read below. I have multiplayer system setup, where players can spawn, they can pick up weapons and drop them, there is an object representing a pickup with network identity component attached and local player authority enable, the player can come up to it and press "E", which will destroy the pickup object, then the player can press I to to "drop" that weapon, which instantiates it infront of the player, now this is what should happen, and it works on single player, but when there's 2 players, for second player(client only) it doesn't work as it should. I have 1 script weapon manager and another small, Pickup (on pickup object child with trigger). Below is the code and according description of my attempt so far Below is PickUp script (on 1st child of pickup object with trigger enabled) private void OnTriggerStay(Collider other) if (other.CompareTag("Player")) if (Input.GetKeyDown(KeyCode.E)) Call pickup function on player, passing the weapon id and parent gameobject other.GetComponent lt WeaponManager gt ().PickUpWeapon(weaponID, transform.parent.gameObject) Below is WeaponManager script (on player) public void PickUpWeapon(int id, GameObject go) CmdDestroyObj(go) ... (other code, not relevent) Command void CmdDestroyObj(GameObject obj) RpcDestroyObj(obj) ClientRpc void RpcDestroyObj(GameObject obj) HERE obj is NULL (!!ERROR!!) Destroy(obj) Above in RpcDestroyObj() obj is null void Update() if(isLocalPlayer) if (Input.GetKeyDown(KeyCode.I)) if (slots currentActiveSlot ! null) CmdDropWeapon() Then here's CmdDropWeapon() function Command void CmdDropWeapon() RpcDropWeapon() Here's RpcDropWeapon() function ClientRpc void RpcDropWeapon() GameObject drop (GameObject)Instantiate(drops currentGun.GetComponent lt WeaponStats gt ().id , transform.position transform.forward, Quaternion.identity) drop.GetComponent lt Rigidbody gt ().AddForce(transform.forward 25000f Time.deltaTime) CmdDestroyWeaponHeld() Destroy currently held weapon (don't pay attention, not relevent to current problem currentGun null if (isLocalPlayer) GetComponent lt PlayerSetup gt ().playerUIInstance.GetComponent lt PlayerUI gt ().SetInventorySlotFill(currentActiveSlot, 1) emptyHanded true On single player (so host amp client), everything works besides destroying the pickup prefab that is Instantiated. On multiplayer, second player (client only), can pick up and drop weapons as well as the originally spawned weapon is destroyed, but destroying the newly instantiated (so after player drops it) pickup object doesn't work. (In the console there are no errors when UnityEditor is the Lan host server, when 2 players are playing and I try picking up and dropping weapons several times from client side) Why is this not working? I would appreciate any help assistance in getting this right and sync over network for all players. My guess is that, rpc function Instantiates the drop prefab but it's kind of different on all clients, so the server or another client doesn't have exactly the same object in the scene which means it will not find it and return null. Let me know if you need any additional information. Thanks a lot in advance!
0
Unity 3D Have a Vector3 attribute on inspector that behaves as GameObject's Transform position Vector3 As the title suggests, I am looking to serialize on the Inspector a Vector3 that behaves just as the Transform's position Vector3 If you modify the position Vector3, the GameObject positions itself according to the World Position. If you move the GameObject on the scene by picking the handles, the GameObject moves, and the position Vector3 gets modified equal to the GameObject's position. So, is there a way I can constrain a serialized Vector3, so if I modify it on the inspector I can change the GameObject's position, like this ExecuteInEditMode public class LameExample MonoBehaviour public Vector3 transformPosition private void Update() if(modifyingVectorOnInspector) transform.position transformPosition else if(gameObjectIsBeingMovedOnScene) transformPosition transform.position I've tried an approach using Selection.contains(gameObject), but that does not take into account if it is dragged by the handles. Thanks in advance for your help.