_id
int64
0
49
text
stringlengths
71
4.19k
0
Why does Unity's MeshCollider only use SharedMesh? For components like MeshRenderer, Unity uses two references to mesh through script mesh, and sharedMesh. My understanding as of yet that setting a "sharedMesh" will affect every GameObject that uses that component, whereas "mesh" alone will only affect a particular instance of that component. Same goes for "material" and "sharedMaterial". However, for MeshCollider, the only thing available is "sharedMesh". The field "mesh" does not exist. I can work with this, but from a policy standpoint it seems very strange to me. Is there a reason that MeshCollider is treated differently? I may be overlooking something obvious, but a Google search didn't help me.
0
Server and client showing different spawned object How do I unify them? I have overridden OnServerAddPlayer and put some custom logic in place to set the rendered prefabs color. Something like this var playerCount NetworkServer.connections.Count if(playerCount 1) player.GetComponentInChildren lt Renderer gt ().material.color Color.green When I test the code with two application instances, the server host shows the expect result (first character is green, second is red) but the client instance shows both characters as red (the default). Is my logic for setting the colour incorrect? or do I need to do something special to ensure that the my clients will see the colour I have set for the characters on the server?
0
Character Controller Lag Massive Teleportation Through Walls I'm working on a fairly robust game with another developer and we've been having a really serious issue with (I believe) the character controller. Specifically, if there's ever a large lag spike (as there are somewhat frequently the code's not well optimized in some parts) there's a chance that the character controller will wing right through all nearby colliders and fall out of bounds. It happens pseudo randomly, but I've noticed that it seems to be somewhat predictable, such as standing next to certain objects (nothing weird about them just tables with colliders). The lag often is a cause of large chunks of a level having SetActive(true) called on them in one frame or multiple objects being instantiated in one frame. These objects sometimes have colliders rigidbodies attached but don't seem to be in any direct contact to the character controller. I can very consistently make it happen by moving towards certain walls (again, very normal walls) and alt tabbing while my character is still moving also seems to cause the issue predictably, which is VERY strange. Has anyone ever experienced anything like this with the character controller? I'd give a code sample but honestly not even sure where from the codebase would be pertinent other than if (Time.deltaTime lt 0.15f) if (applyGravity amp amp noClip false) moveDirection.y gravity Time.deltaTime controller.Move(moveDirection Time.deltaTime) Which seems awfully straightforward to me. Obviously moveDirection gets changed elsewhere in the function too but it's all similarly bland. I'm pretty experienced with this sorta' stuff and it doesn't ring wrong to me at all. Some other stuff. Checked that moveDirection isn't a huge number Tried eliminating Time.deltaTime from the equation Fairly sure colliders aren't ending up inside of the player while a lag spike happens (again, alt tabbing will do it too) Geometry surrounding the player is clean (box colliders, mesh colliders on well developed meshes) Nothing strange like rapidly setting any components on or off is happening to my knowledge. Anyone have any experience with this sort of issue?
0
Flash animation or Sprite sheet animation good for Unity mobile games I would like to develop dress up and cooking kind of games. So it needs lots of animations. Our designers done the animations in the lash. I found the plugins callued GAF and UniSWF to convert flash animation to Unity or We can convert animations into sprite sheets and animate them in Unity, But i don't know which one is the best way to do animations for mobiles with better performance and lower game size. Any kind of suggestion is good. Thank you!
0
Custom shadow mapping in Unity. Works with preservative Light view but not with Orthographic So about a week ago I decided to make my own shadow mapping technique in Unity based on my understanding of the whole thing. The entire experience was somewhat successful. I learned a lot and I get to correct a lot of things such as the MVP matrix and the math behind it. One thing though didn't work as planned and I don't know why. First lets talk about what worked. I wrote a replacement shader that will show the depth of every object based on the Light Position perspective. Therefore I made a custom Light GameObject that act as a camera light with that replacement shader attached to it, and I record everything the Light sees into a render texture. Then I made a second Camera which is basically a child of the main camera, and sees what the main camera see with the exception of the replacement Shader that I attached previously to the Light gameobject. again I recorded everything from the camera to a render texture as well. After that, I wrote a basic Shader that does a basic light calculation and make a the shadow comparison between the two textures, and determines whether a fragment in a shadow or light. Also, I added a shadow Bias as well to eliminate any artifacts. struct appdata float4 position POSITION float3 normal NORMAL float2 uv TEXCOORD0 struct v2f float4 position SV POSITION float2 uv TEXCOORD0 float3 normal TEXCOORD1 float3 worldPos TEXCOORD2 float4 Tint sampler2D MainTex sampler2D SahdowMap Light, SahdowMap View float4 MainTex ST float4x4 WorldToCamera, WorldToLight float3 LightDir1 v2f VertexProgram(appdata v) v2f i i.position UnityObjectToClipPos(v.position) i.worldPos mul(unity ObjectToWorld, v.position) i.normal UnityObjectToWorldNormal(v.normal) i.uv TRANSFORM TEX(v.uv, MainTex) return i float Shadow Cal(v2f i, sampler2D DepthMap,float4x4 space) float4 projected2 mul(space, float4(i.worldPos, 1.0f)) float2 uv ( projected2.xy projected2.w) 0.5 0.5 float Shadow tex2D(DepthMap, uv).r if (uv.y gt 1.0) Shadow 0.0 return Shadow float4 FragmentProgram (v2f i) SV TARGET float LightDepth Shadow Cal(i, SahdowMap Light, WorldToLight) float ViewDepth Shadow Cal(i, SahdowMap View, WorldToCamera) float bias max(0.05 (1.0 dot(i.normal, LightDir1)), 0.015) float Shadow LightDepth bias lt ViewDepth ? 0 1 float4 Texture tex2D( MainTex, i.uv) float3 lightpos LightDir1 i.worldPos return saturate(dot(lightpos, i.normal)) Tint Texture Shadow The problem is when the Light is on perspective, this works perfectly fine as shown above, but when I switch the light camera to Orthographic this happen I tried many different things to fix it but I failed. I would love your insight in this whole thing, your thought, solution or even a suggestions. You are free to download the whole project as a package here Download Special thanks to DMGregory.
0
NavMesh Changing Mesh by Jumping upwards I have been playing around with the NavMesh and I have seen that there are different situations where an agent has to change meshes. When it works Everything seems to work alright with links, if I try to make the agent jump from a mesh to another one, tweaking the "Jump distance" paramenter Another scenario is when the agent needs to fall to another mesh to reach the target. This one also works, when I tweak the "Drop height" parameter. When it does NOT work But there are 2 different scenarios, where the agent cant reach the target. The first one is when the agent must jump upwards instead of dropping. And the other scenario is when the agent needs to fall to another mesh that is not directly below the one he is standing on. How could I do so that the agent jumps either to move upwards, or to land in a lower mesh?
0
Make health bar follow the player not the camera I wrote a script to create small bars of life amp mana on top of the character. So far it's following him and everything ok, but the problem is that it has a delay, for example the player arrives first and then the bars arrive shortly afterward. How can I keep the bars it fixed to the player? using UnityEngine using UnityEngine.UI public partial class UIMiniHealthMana MonoBehaviour public GameObject panel public Slider healthSlider public Slider manaSlider void Update() Player player Utils.ClientLocalPlayer() panel.SetActive(player ! null) hide while not in the game world if (!player) return healthSlider.value player.HealthPercent() manaSlider.value player.ManaPercent() Example of the error
0
How to get the correct Input direction based on the camera angle to use in a rootmotion based third person controller I move my character based on the rootmotion of their animation using a blend tree that uses 2D Freeform Cartesian input (Vertical, Horizontal) if Vertical 1, the character moves forward based on the direction he is facing if Horizontal 1, the character turns right based on the direction he is facing and the rest of the system follows, here is the current Blend Tree Currently, if i press forward, the character move forward no matter where the camera is facing But in this example, what i want is for the character to slightly make a turn left to face the camera direction and then start walking forward When working on a game that moves the character by code (without rootmotion), something like this would solve the issue inputAxis new Vector3(Input.GetAxis( quot Horizontal quot ), Input.GetAxis( quot Vertical quot ), 0) inputCam Quaternion.Euler(0, cam.transform.eulerAngles.y, 0) inputAxis And then use inputCam to move the character, but for some reason this isn't working, and these two variables are always equal to each other, what am i doing wrong ? also if there is a quot standard quot solution for this problem (am sure it is) please link it (doesn't matter if its Unity or not as long as the code is readable) Thanks!
0
How does the Unity coordinate system map to screen pixels? If I have a GameObject, say at x 0, y 0, and I want to move it for a 40 pixel to x how can I make that? In don't understand which is the unit of measurement in Unity. If I make something like this where mov is 40 the sprite goes out of screen! void Start() transform.Translate(new Vector3(mov, 0, 0)) it seems like the correct values must be very low, say 0.6, 1, 3, etc. But why?
0
Sprite with transparency Create box collider (ignoring transparent area) I have a sprite which has a transparent area in it. The non transparent area is a free form graphic (red). I would like to create a box collider around it (yellow), but ignoring the transparent area. Some notes to the image above Left This is what happens, if I apply a PolygonCollider2D. The yellow line represents the area covered by the PolygonCollider2D. This is not what I want. Middle This is what happens, if I apply a BoxCollider2D. The yellow line represents the area covered by the BoxCollider2D. This is also not what I want, as it includes the transparent area of the sprite. Right This is what I want Have a BoxCollider2D outside my free form graphic. Here's how I currently load my sprite data into the game during runtime My sprites are located in the Assets Resources SceneData ... folder structure of my project. The graphics are stored as .png files. When loading a level, I load the required graphics as sprites like this var sprite Resources.Load lt Sprite gt ("SceneData AfternoonAtTheBeach DragAndDrop Graphics Level1 ElephantWithIceCream") "ElephantWithIceCream" is the .png file (Resource.Load wants me to refer to this file without file extension) After that, I create a new game object and attach a SpriteRenderer component to it. The sprite is assigned to the SpriteRenderer by setting the sprite attribute of the SpriteRenderer component. My first thought on how to solve my problem was to do something like this Create a PolygonCollider2D and try to convert it into a BoxCollider2D. But I was not able to find code examples on how to do this. After that, I thought of trying it to do like this Create a PolygonCollider2D and try to extract some useful information out of it (such as bounds, center, extents, etc...). Delete the PolygonCollider2D and create a BoxCollider2D. Use the previously extracted info to create the BoxCollider2D. But I fail doing so. I am also a bit confused as sometimes they refer to world space or local space. Does anyone have a working recipe for doing something like this? I do not really understand how to work with center, bounds and extents. If there is any better way of doing this, I am highly interested. Thanks a lot for your help!
0
How could you use mirror in unity to network across multiple networks rather than only LAN (Port Forwarding?) I've been working on a game for my friends and I to play during quarantine but I can't figure out or find any information on networking using mirror. Everything I see gives vague answers to even vaguer questions that assume you have prior knowledge of networking. Could anyone give me any sort of direction on how to port forward using mirror or if there's a better solution?
0
How to implement GIF insertion in Unity? "XYZ App doesn't support image insertion here" I'm making an Android App with Unity, which has a chat service in it. And I would like to handle sending images or GIFs via Gboard. Currently when the user selects a TextField, his keyboard comes up, which is let's say GBoard. And now when I click on a GIF or a Sticker, it says XYZ App doesn't support image insertion here So how could I implement it? Or more precisely, how can I define what method will be be called in my application when the user tries to send a GIF? Because my first thought to implement it, is like it's done in all other apps every GIF would be in a separate message, and when the user clicks on a GIF it instantly sends a special GIF message, which will be rendered for example as an animated texture. But how could I subscribe to this event in the first place? Thanks in advance!
0
How to make a part of an object with navmesh agent rotate separately? I have a game object (a Humvee jeep) and it has a turret gun on top of it. What i want to do is while the vehicle is moving in a line the turret look at player. I tried rotating the turret gun with "Transform.rotation" and "transform.lookat()" but nothing happened. Is it possible to move rotate some part of an object with navmesh separately?
0
Why is my TextMesh always on top? I have a 2 d game that I am making, using 3 d assets, including TextMeshes for text. I have decided that in some instances, I would like to have the TextMesh appear behind objects in the foreground. The below is one such example. It seems that the TextMesh is always in front. I have tried a number of things to get the text between the map and object layers, with no success. These include Moving the text between the map and object. Changing the SortingLayers and SortingOrder. The map, objects, and labels are on 3 different layers, with the Objects being the highest layer, the map the lowest, and default and label in between. Using a perspective camera, not orthographic. Any ideas as to what else could be going on? Thanks! How can I make the TextMesh appear that isn't on the top layer? Thanks!
0
Creating a smooth transition between materials on large models using Unity and or Blender I'm not sure if this is possible or not but I would like to create a smooth transition (cross fade) between two textures on a 3D model made in Blender that can be imported to Unity. For example if I have a model with two materials, the edges where the materials meet is an abrupt change. How would I go about creating a smooth transition across the edge where the materials meet? I've seen some tutorials on using cycles in Blender to achieve this, but to the best of knowledge the cycles rendering cannot be brought into Unity. Projection painting in Blender using an image as the brush is also a possibility, but the models I'm trying to do this on are rather large and would lose resolution in their textures because of this. Is something like Substance Painter by Allegarithmic what I need?
0
Displaying Trajectory Path How can I display trajectory path exactly as in this image? I have used void OnDrawGizmos, but that only displays trajectory in the editor and without any arrows like shown below. Trajectory with void OnDrawGizmos Script public Transform someObject object that moves along parabola. float objectT 0 timer for that object public Transform Ta, Tb transforms that mark the start and end public float h desired parabola height Vector3 a, b Vector positions for start and end void Update () if ( Ta amp amp Tb ) a Ta.position Get vectors from the transforms b Tb.position if ( someObject ) Shows how to animate something following a parabola objectT Time.time 1 completes the parabola trip in one second someObject.position SampleParabola( a, b, h, objectT ) void OnDrawGizmos () Draw the parabola by sample a few times Gizmos.color Color.red Gizmos.DrawLine( a, b ) float count 20 Vector3 lastP a for ( float i 0 i lt count 1 i ) Vector3 p SampleParabola( a, b, h, i count ) Gizmos.color i 2 0 ? Color.blue Color.green Gizmos.DrawLine( lastP, p ) lastP p region Parabola sampling function lt summary gt Get position from a parabola defined by start and end, height, and time lt summary gt lt param name 'start' gt The start point of the parabola lt param gt lt param name 'end' gt The end point of the parabola lt param gt lt param name 'height' gt The height of the parabola at its maximum lt param gt lt param name 't' gt Normalized time (0 gt 1) lt param gt S Vector3 SampleParabola ( Vector3 start, Vector3 end, float height, float t ) float parabolicT t 2 1 if ( Mathf.Abs( start.y end.y ) lt 0.1f ) start and end are roughly level, pretend they are simpler solution with less steps Vector3 travelDirection end start Vector3 result start t travelDirection result.y ( parabolicT parabolicT 1 ) height return result else start and end are not level, gets more complicated Vector3 travelDirection end start Vector3 levelDirecteion end new Vector3( start.x, end.y, start.z ) Vector3 right Vector3.Cross( travelDirection, levelDirecteion ) Vector3 up Vector3.Cross( right, travelDirection ) if ( end.y gt start.y ) up up Vector3 result start t travelDirection result ( ( parabolicT parabolicT 1 ) height ) up.normalized return result
0
How can I find if a GameObject is not exist in the Hierarchy? var selections Selection.objects.OfType lt GameObject gt ().ToList() if (selections.Count gt 0) tempSelections selections for (var i selections.Count 1 i gt 0 i) var selected selections i transformSelection.Add(selected.transform) TransformSaver.SaveTransform(transformSelection.ToArray()) transformSelection new List lt Transform gt () for (var i tempSelections.Count 1 i gt 0 i) var selected tempSelections i if (GameObject.Find(selected.name) null) GUI.enabled true else GUI.enabled false if (GUILayout.Button("Undo last selection if deleted")) transformsCount TransformSaver.LoadTransform().Length PlayerPrefs.DeleteKey("transform") For testing I'm deleting one of the GameObjects in the tempSelections List But then I'm getting exception in the editor on the line if (GameObject.Find(selected.name) null) Since the GameObject have been deleted it can't access the GameObject. MissingReferenceException The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.
0
Generating Mesh using Compute Shaders I am working on a game project in unity which has a procedurally generated terrain made up of 16 128 16 chunks of blocks. The map size is going to be finite (Possibly up to 100 100 chunks). Currently the data for the chunk is stored in a 1D Array, and takes a couple milliseconds to generate. But generating the mesh takes longer, averaging 30 40ms. So generating terrain as it enters the range of the camera isn't feasible as it's too slow, and generating all the meshes on load up would take a lot of memory as well as a long time. I've thought about attempting to try it on the GPU through Compute Shaders (although I don't have any experience with them). Would generating the mesh for each chunk in a Compute Shader be viable efficient? (The chunks could be made smaller if would be more performant)
0
2.5D UI, perspecitve view, distort objects by angle but not position Instead of thousand words, a few pictures to explain what I want to achieve How do I get the merit of UI objects rotation in perspective projection, but ignore the position of an object(as in Overlay Canvas)? UPDATE 1 Can you include an example of what your full UI or scene would look like? A usual bar which is used to hold stuff like score. Same base prefab is used for mana health and any other UI parameter on screen. But bars have different rotations, so here is one solution have a unique sprite for every special rotation and have a bunch of prefabs(nah). Or have one sprite, one prefab and set the rotation in scene(that's the way). Is there a reason you are asking for this in perspective projection? Just because I want to be able to rotate UI objects in scene and show the "depth" of rotated object. I'm not particularly stuck onto perspective projection, as long as I can achieve the "want" look without actually redrawing sprites for every unique angle. so I'm not sure what you are asking for. Are you asking how to skew an image in 2D, so that it looks like a 3D perspective projection? I know it sounds crazy, since it's obvious that in perspective looking at object which is above camera you get that "looking from down" look. And yet I feel you are onto something(and now am I), one way of thinking is actually to skew a 2D image to simulate rotation as in perspective view!
0
Unity Help with RaycastHit2D.hit.normal I'm working on a little pong clone and trying to implement collisions using triggers. I have a ball which OnTriggerEnter sends out a raycast from the ball's position towards its velocity. I then take the .normal of the raycast hit and use that to figure out bounce angle. most of the time this is working, but in a few cases (I can't quite figure out the common element between them) It doesn't work and gives a completely wrong number. Video example, https webmshare.com xAe7X Full code, using System.Collections using System.Collections.Generic using UnityEngine public class BallScript MonoBehaviour public Vector2 velocity public float angularVelocity private Vector2 collisionNormal void FixedUpdate() transform.Translate (velocity.x, velocity.y, 0) Debug.DrawRay ((Vector2)transform.position velocity 2, velocity 5,Color.red) void OnTriggerEnter2D(Collider2D other) FindCollisionNormal () ReflectVelocity () public void FindCollisionNormal() RaycastHit2D hits Physics2D.RaycastAll ( (Vector2)transform.position velocity 2, velocity 5) foreach (RaycastHit2D hit in hits) if (hit.collider.GetType () typeof(BoxCollider2D)) collisionNormal hit.normal collisionNormal new Vector2 (collisionNormal.y, collisionNormal.x) public void ReflectVelocity() print (collisionNormal) velocity velocity 2 (Vector2.Dot (velocity, collisionNormal) collisionNormal)
0
Is there any way to automaticaly rig a sprite? I'm making an AR test where the player takes a photo, them i get the bones from the pose and set a t shirt sprite's bones position to match the ones from the photo. I was wondering if there's any way to make the sprite rigging process, with just the main bones like LRshoulder,LRelbow and LRHip, automatic in Unity.
0
Why game window automatically scale itself when I press play? When I am in the editor and I press play to test my game something weird happens, the game window is like zooming in.. and I am not touching anything, the scale slider just goes from x0.41 to x1. What may cause the problem? Bug in the editor? Thank you in advance. PS I noticed that the problem is only with my custom game windows, their initial scale is 0.41 and not 1, why is that?
0
What is the actual formula to find the vertices of an animation frame in using a BVH file? I've read this tutorial and tried many formulas to build the skeleton. I am able to build it without the rotations, but those break everything. This, for example, is a simplified code for one of my attempts Pseudocode using overloaded operators for illustration purposes var build skeleton function(motion,frame number) positions deg to rad Math.PI 180 (function travel tree(node,old pos) pos node.offsetX, node.offsetY, node.offsetZ frame node.frames frame number x rotation quat from axis angle( 1,0,0 ,frame 2 deg ro rad) y rotation quat from axis angle( 0,1,0 ,frame 1 deg ro rad) z rotation quat from axis angle( 0,0,1 ,frame 0 deg ro rad) rotation x rotation y rotation z rotation pos old pos apply quaternion(rotation, pos) positions.push(pos) node.children.map(function(a) return travel tree(a,pos) ) )(motion.root, 0,0,0 ) return positions I've tried many variations of this, switching axes, signals etc. Nothing seems to work. So what is the formula to find the positions of the vertexes of an animation on the BVH format?
0
How do I make Unity use UTF 8 and LF characters for new script files? By default, when you make a new script in Unity on Windows, it will use UTF 8 with BOM and CRLF. How do I change this to be regular UTF 8 without BOM, and LF (Unix style)?
0
How can I apply a mesh collider in Unity to an entire imported model rather than a single piece? I have a series of models from Blender I'm importing to Unity as .blend files and I need mesh colliders applied to each one. What I'm finding is that with any model that is constructed of multiple primitives, applying the mesh collider to the object is unsuccessful. The mesh collider can't find the mesh. Unity seems to treat each shape inside the model as a separate object. I've even noticed that the Unity editor will allow me to select a single piece of a model and drag it away if I'm not careful. This is unexpected behavior and somewhat alarming. I've discovered that if I apply a separate mesh collider to each individual piece inside the model, the colliders will find the sub meshes and the collision detection will work. My primary concern at the moment is that this is monotonous. For example, if I have the following model of a road intersection, then I'll need to individually select each of the seven pieces and create a mesh collider for each one. How can I apply a mesh collider to the entire model in one move? UPDATE Based on some feedback and some thoughts on my own, I'm redesigning the road pieces to simply be solid road on the bottom with the sidewalks on top. This way, I'll only need one collider for the bottom, for now (if I don't care about testing collisions with the sidewalk edges yet). I'm hesitant to merge the meshes into a single mesh at this time, though, since I'm potentially not done modelling street pieces yet. This also doesn't address the long term question of what to do in the final version of the game. Unity primitives have automatic collision detection, but simulating hills this way and still having the pieces meet seamlessly is difficult. They also won't do curved surfaces as far as I know. I'd rather not use box colliders, since that will involve a lot of painstaking zooming in and tweaking of tiny values to get them perfect. It also seems that box colliders will only rotate with a model and not to a model that's already sloped. What I'm trying to avoid is spending almost as much time messing around with the colliders as I did modelling these bits in the first place. Sticking with the mesh colliders is looking like the best option for now, since most of these shapes are simple, 6 sided objects and it's only a couple of clicks to add a mesh collider to each shape. It sounds like if I do it this way, it might be smarter to keep the meshes un merged, since I would then be using a mesh collider on a concave object.
0
Backup virtual goods to survive game reinstalls I'm developing a game using Unity3D (for Android and iOS). I would like to save all user's virtual goods, so they are available even if the user remove and reinstall the app, or even if the user install it on a new device. AFAIK an approach would be to authenticate the user, and save all the data on my backend server. But, to not reinvent the wheel, can you share your approach? i.e. how do you authenticate users? are you using your own server, or any BaaS? EDIT After reading your answers, I think the best approach is to use "Google Play Game Services Saved Games" on Android, using the official plugin for Unity3D. For iOS, there is a similar feature for GameCenter, but I can't find any official plugin for Unity3D. But this plugin may work https www.assetstore.unity3d.com en ! content 11626 Soomla plugin can be useful https www.assetstore.unity3d.com en ! content 6103 Also, this plugin can be useful too https www.assetstore.unity3d.com en ! content 20152
0
Unity free look camera on two axes. How do I do it? I'm new to Unity and c but have programming experience... I have a a simple "game" in Unity that shows one sphere orbiting another. How do I allow the camera to be moved by the user in a "free look" dynamic? I want to be able to press the right mouse button and adjust the camera on two axes. I'm using Unity 5.0. Whenever I run the following Unity freezes when I press the right mouse button. Here's the camera control script using UnityEngine using System.Collections public class CameraControl MonoBehaviour private float horizontalSpeed private float verticalSpeed void Update () while (Input.GetMouseButtonDown(1)) horizontalSpeed Input.GetAxis ("Mouse Y") verticalSpeed Input.GetAxis ("Mouse X") transform.Translate(verticalSpeed,horizontalSpeed,0.0f)
0
Unity shader to pick 1 of 2 base colors for individual instances (picture) I am building this scene in 3D using Unity 2019.3.13's Universal Render Pipeline. I have a block prefab that I want to instance, but I want to choose which are yellow and which are blue (you can see the materials are basically the same). How can I write a shader that will allow me to pick either yellow or blue in the editor for each one? Is this possible? What is the most optimal way to make dozens of identical blocks where the color is different for specific instances? (I would prefer a script to a graph, something with a simple switch boolean input and hex values yellow e4c658 blue 32676a
0
Unreal Engine 3 vs id Tech 3 vs Unity I'm trying to decide which engine I should start using to try to start building a game in. I had chosen Unity, but upon hearing that Unreal Engine 3 had just become kinda free to use, I found myself questioning my decision. Technically Unreal is still the most expensive commercially, then Unity, then id Tech 3 (free). But, it also could be the fastest to work in? Or is just the most powerful, but Unity actually does so much for you, that it makes the most sense to work with this, and take a hit on performance tuning (like Java C ). Thoughts please, can anyone speak from experience of all three? I have experience with modding since the doom days, then in Quake 1 and Half Life. I also have experience in 3DS Max. I don't have a desire at this point my life to really get into the nitty gritty of C animation and rendering issues, I'd rather get something up and running quickly, to see if it's possible. But Unreal experience tempts me greatly.
0
Play Stop All Animations in a Project I see that there's a way to get each animation clip like the following, but is there a way to get all of the animations in a given project and play stop them at the same time? public class Anim MonoBehaviour protected Animation anim Use this for initialization void Start () anim GetComponent lt Animation gt () void PlayAnimation if () some sort of condition anim.Play ("Roll Dice") else anim.Stop()
0
Making a scriptable dynamic Distance Joint in Unity I have 2 2D RigidBodies that are connected together using a Distance Joint 2D... I update the distance of said Distance Joint 2D (using a script) expecting the distance between the two RigidBodies to change, but nothing actually happens. I'm guessing this is to do with the Physics engine not updating the positions of the RigidBodies?
0
unity onCollisionEnter does not work I know this question has been asked several times but none of the answers solved my problem. I made an sphere and gave it rigidbody. then I draged the sphere on to a new made prefab. on mouse click Instances of this prefab are made and shot. the spheres collide with things in the scene but the onCollisionEnter function is not called. all things in the scene have colliders. I would be grateful if you could tell me what's wrong edited it works if either the sphere or the other object's collider is trigger and I use onTriggerEnter.
0
How do I keep a rigidbody from making unnecessary collisions on smooth surfaces in Unity3d? I have been having trouble with a custom character controller I am making. The root of the problem lies with collisions. I am trying to make movement code, but I have a problem with ground movement. Pay attention to this gif. It might be hard to notice due to the low frame rate, but the collider registers collisions with objects (in red) that do not point out of the ground. They share the same y position as the ground. I've printed the normals of the collisions, and there are a lot of normals that are perpendicular to the normal of the ground (which is causing the rigidbody to get stuck). The problem lies with collisions in unity. If I were to print the y position of the bottom of my collider, it would be just a tad lower than the y position of the ground. The collider actually rests below the ground by an almost negligible amount (which is why it doesn't always collide with these objects). Here is what I have tried I created a function that runs at the beginning of every FixedUpdate() that uses current collisions to change the y position of the rigidbody. It only runs on collisions that would ground the player (meaning that they are below the collider). The problem with this approach is that the same issue can occur with walls, meaning that the collider can get stuck on walls. I cannot create another function that would do the same for walls for various reasons. Here is what would fix the issue I need help figuring out how I can make collisions more discrete in unity. Colliders rest slightly below objects when ontop of them. They can also "sink" just a little into walls. In other words, colliders can rest into other colliders, and I need this to stop. Any help is appreciated. Thank you.
0
Problem when importing fbx in Unity made in Blender First I will explain how do I make my object in Blender I want to make an object with a texture that have transparecies (png image). I unwrap my object and then apply the image to it in the UV editor. Then I export my object as fbx. To try the transparecy first I imported a PNG image as a plane on Blender and adjusted the necessary things in order to make work the transparency. You can appreciate the settings I used in the following image Until there is all fine. The problem appears when I import the fbx in Unity. The material that I created with the png image is not well visualized. When I import the fbx object in Unity, this messages appears in the Materials tab What do I have to set here in order to visualize well the image with its alpha channel working? Furthermore, if I try to change the material settings it is impossible because I cannot click the different options as they are disabled Can anybody tell me what I'm doing wrong? I don't know if my error is when creating the material in Blender or when I import the fbx in Unity.
0
World Canvas InputField cursor precision control from RenderTexture output in Overlay UI How do you have a world canvas input field cursor be controllable from the input being mapped from a UI overlay with its raw image supplied from render texture from a render camera? Described another way World Canvas Input Field gt Render Camera creates renderTexture for gt Screen Overlay UI Raw Texture gt Main Camera How do you have the cursor position be mapped from the Screen Overlay UI Raw Texture?
0
Multiplayer Synchronization I am developing multiplayer game in unity. For multiplayer i am using photon networking library. I created room and join client successfully. But Problem is I am doing gameobject movent by this code public GameObject player IEnumerator Moving (String temp) for (int i 0 i lt 3 i ) player.transform.DOMove (CurrentPositionHolder, 0.5f).SetEase (Ease.Linear) yield return new WaitForSeconds (0.5f) DoMoveis library here. Problem is player movement is not synchronized. For Synchronization I add photonview component to player gameobject. And i call coroutine though RPC like this. player.GetComponent lt PhotonView gt ().RPC ("Moving", PhotonTargets.All, "temp") Accordingly i changed coroutine like this PunRPC IEnumerator Moving (String temp) for (int i 0 i lt 3 i ) player.transform.DOMove (CurrentPositionHolder, 0.5f).SetEase (Ease.Linear) yield return new WaitForSeconds (0.5f) I got this error Illegal view ID 0 method Moving GO player UnityEngine.Debug LogError(Object)
0
UNET Performance of (many) Kinematic Rigidbodies I am building a game in Unity in C using the UNET networking elements. I am trying to figure out what is the performance cost of kinematic rigidbodies? My understanding is that, when kinematic, rigidbodies are outside the physics system and therefore are not as resource heavy as non kinematic rigidbodies. For my game, I will need to use a lot of kinematic rigidbodies in the scene, because they are used to detect collisions between player placed objects (with box colliders) and the rigidbodies. All the objects instantiated in the scene will therefore need a kinematic rigidbody to allow this collision checking to take place. Thanks very much for your help.
0
How to enable disable GameObject I have child object with ParticleSystem component. I want to have particles disabled until I press button. I unchecked child object to make it disabled but when I press play it enables automatically(with no scripts attached). Then I made this script below (with .SetActive(false) part only) and it worked. But then I needed to activate it somehow, which I did, but now when I press play, object is automatically enabled activated again. Is there another way of doing this because I need it haha. var particle1 GameObject var particle2 GameObject var particle3 GameObject public var triggered boolean false function OnTriggerEnter() triggered true function OnTriggerExit() triggered false function Start() particle1.SetActive(false) particle2.SetActive(false) particle3.SetActive(false) function Update() if (triggered amp amp Input.GetKeyDown(KeyCode.JoystickButton1)) particle1.SetActive(true) particle2.SetActive(true) particle3.SetActive(true)
0
Dragging UI element lags behind the cursor Have been at this for 2 days straight trying different ways to solve this, and I can't. I'm simply dragging around a UI panel using PointerDown and Drag events. I set the transform.localPosition inside the Drag handler. It works as expected, only problem is, the UI element seems to lag behind the cursor. I created a GIF to show the issue in a build version to rule out the Editor. Not sure how well you can see the issue, but the faster you move the cursor the worse it is. Any ideas of what the issue is and how can I solve it? Thanks
0
Keep the timer counting after changing scenes In my game you have 2 minutes to finish the whole game and after searching for an answer to my problem I think I should use DontDestroyOnLoad but I can't understand how to use it correctly. Here's the code public class countdownTimer MonoBehaviour public float myTimer 120 public Text timerText private bool timerIsActive true void Start () timerText GetComponent lt Text gt () void Update () if (timerIsActive) myTimer Time.deltaTime timerText.text myTimer.ToString ("f0") print (myTimer) if (myTimer lt 0) myTimer 0 timerIsActive false SceneManager.LoadScene ("lose")
0
How can I fix zig zagging UV mapping artifacts on a generated mesh that tapers? I am creating a procedural mesh based on a curve and the size of the mesh gets smaller throughout the curve as you see below. And the problem is UV gets zig zagged as the size changes (it works perfectly when the size of the mesh is same throughout the curve). Vertices.Add(R) Vertices.Add(L) UVs.Add(new Vector2(0f, (float)id count)) UVs.Add(new Vector2(1f, (float)id count)) start Vertices.Count 4 Triangles.Add(start 0) Triangles.Add(start 2) Triangles.Add(start 1) Triangles.Add(start 1) Triangles.Add(start 2) Triangles.Add(start 3) mesh.vertices Vertices.ToArray() mesh.normals normales mesh.uv UVs.ToArray() mesh.triangles Triangles.ToArray() How can I fix this?
0
How can I create and load models with additional information? I want to create game similar to original DOOM in Unity (using 2017.2). I'd like to make it possible to load entire levels from file, but I don't really want to write my own level editor that would serialize and deserialize Unity objects. I'd like to allow the player base to create new levels using blender, without them needing to use Unity all the logic and shapes should come from that single blender file. I'm wondering how it could be possible to create levels in blender with some additional data, that could be processed from the Unity game. Just simple markers, for example stepping on platform A will open door B.
0
Split the camera into sections? I have a layout for my game similar to this Where the light gray area is reserved for HUD elements and the dark gray area is reserved for the actual game. One function I want to offer in the dark gray area is the ability to zoom and move around, which works independently from the light gray area, meaning that no matter how far I zoom in out or how far I move, the light gray area remains unaffected. How can I do this without always taking the offset center into account? How can I completely separate the game play part and the HUD?
0
Unity's Quaternion.Lerp slows down when target is directly behind turret Software Unity v5.2.1f1 Personal I am trying to achieve the effect of a turret in Unity. For this I have a turret consisting of 3 parts as well as a target. The problem is that whenever the target my turret is targeting has a z of lt 0, the lerp speed is extremely slow. However, the further away the target is from x 0 (both positive and negative), the faster it will move. This effect only occurs when my target has a transform.position.z of lt 0. When z 0 the transform.position.x has no effect on the lerp speed. My setup is as follows The 3 turret parts are the base, turret and barrel. The base is nothing more than a block for the turret to rest on. The turret is a block holding the barrel in place with base as his parent. The turret rotates around its y axis to always face the target. The barrel has turret as his parent. The barrel rotates around its x axis to always face the target. See the picture below for the end result. Base Blue Turret Red Barrel Green The turret has the following code public class turretRotation MonoBehaviour public Transform target void Update() Vector3 relativePosition target.position transform.position relativePosition.y 0 Quaternion rotation Quaternion.LookRotation(relativePosition, new Vector3(0, 1, 0)) transform.localRotation Quaternion.Lerp(transform.localRotation, rotation, Time.deltaTime) The barrel has the following code public class barrelRotation MonoBehaviour public Transform target public float speed 1 Vector3 relPos Quaternion rot void Update () Position of target relative to my position relPos (target.position transform.position).normalized rot Quaternion.LookRotation(relPos, new Vector3(0,1,0)) Lerping localRotatiot gt rot with speed Time.deltaTime speed (set to 1 by default) transform.localRotation Quaternion.Lerp(transform.localRotation, rot, Time.deltaTime speed) Resetting y and z EulerAngles to 0 This way only the x EulerAngle will be affected. The y rotation is inherited from the parent (turret turret) transform.localEulerAngles new Vector3(transform.localEulerAngles.x, 0, 0) In this picture the Lerp is working as intended Note target.transform.z 0 In this picture the target has a z 5 and x 0 pay particular attention to the Lerp speed It eventually gets there, but it takes a very long time. For some reason, the further away the target is from x 0, the faster the Lerp speed. Note Still slower than intended In this picture the target has a z 5 and x 10 So for some reason when target.transform.z has a negative value, the higher the distance from target.transform.x to x 0 the higher the Lerp speed. I've done a fair bit of searching and came across a post on answers.unity.com describing a similair problem Unfortunately, no reply. http answers.unity3d.com questions 1084067 lerp problem when target is behind.html So my question is "Why is this happening and more importantly, how can I fix this?" Any help would be much appreciated!
0
Can I give prizes based on sharing a WebGL game link on Facebook? I made a share to Facebook link for my WebGL Unity game and depending on when you share you get extra points. This is tied to a button which once pressed opens a new page to Facebook for sharing the link but at the moment when you press the button you get the extra points either way. Is there a way to actually know when the content has been shared or not?
0
In Photon, What happens networked GameObject's ownership when master client disconnects? I'm creating multiplayer game with Photon. When player disconnects, especially master client does, every GameObject instantiated from Master client is gone, so I can prevent with this PhotonNetwork.autoCleanUpPlayerObjects false Now GameObjects are still there even Master is gone, but what about their ownership? I needed to destroy some of enemies when they dies, but if master is gone and other player got selected as Master, is he automatically receive ownership of them too? If not, is there a way to do that automatically? Any advice will very appreciate it!
0
Delay Pause game while displaying countdown 3,2,1 go I have already a running script of countdown and it works fine , the problem is that I want to pause or delay the game while the countdown is displaying, the moment countdown finished the player is already dead. Here is my code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class jb MonoBehaviour private string countdown "" private bool showCountdown false public AudioSource noise1 public AudioSource noise2 public Sprite sprite2 public Vector2 jump new Vector2 (0,300) private SpriteRenderer spriteRenderer void Start () GetComponent lt Rigidbody2D gt ().velocity Vector2.right speed StartCoroutine(getReady()) spriteRenderer GetComponent lt SpriteRenderer gt () noise1.GetComponent lt AudioSource gt ().Play() Update is called once per frame void Update () if(Input.touchCount gt 0 amp amp Input.GetTouch(0).phase TouchPhase.Began) Vector2 touchPosition Input.GetTouch(0).position GetComponent lt Rigidbody2D gt ().AddForce(jump) noise1.GetComponent lt AudioSource gt ().Play() Vector2 screen position Camera.main.WorldToScreenPoint (transform.position) if(screen position.y gt Screen.height screen position.y lt 0) noise1.GetComponent lt AudioSource gt ().Stop() noise2.GetComponent lt AudioSource gt ().Play() StartCoroutine(Die()) void OnCollisionEnter2D(Collision2D det) noise1.GetComponent lt AudioSource gt ().Stop() noise2.GetComponent lt AudioSource gt ().Play() StartCoroutine(Die()) IEnumerator Die() PlayerPrefs.SetString( "previousLevel", SceneManager.GetActiveScene().name ) spriteRenderer.sprite sprite2 yield return new WaitForSeconds (2) SceneManager.LoadScene("score") IEnumerator getReady() showCountdown true countdown "3" yield return new WaitForSeconds (1) countdown "2" yield return new WaitForSeconds (1) countdown "1" yield return new WaitForSeconds (1) countdown "GO" yield return new WaitForSeconds (1) showCountdown true countdown "" void OnGUI () if (showCountdown) GUI.color Color.red GUI.Box ( new Rect (Screen.width 2 100, 50, 200, 175), "GET READY") display countdown GUI.color Color.white GUI.Box (new Rect (Screen.width 2 90, 75, 180, 140), countdown) what can I do to pause the game? I tried invoke (by creating another function and copying everything over there) in update call but it didn't work.
0
Why when a certain boolean variable is true, the Unity editor crashes? In my game I've got a timer script, which counts down unless the game is paused, but whenever the variable for pausing is true, something in the timer script makes the editor itself crash, and I have to pull out the task manager to close unity because it freezes up completely. Timer.cs using UnityEngine using System.Collections public class Timer MonoBehaviour public LevelManager levelManager Use this for initialization void Start () levelManager FindObjectOfType lt LevelManager gt () StartCoroutine ("timerUpdate") Update is called once per frame void Update () IEnumerator timerUpdate () while (levelManager.levelTimeSeconds gt 0) if (levelManager.isPause false) yield return new WaitForSeconds(1) levelManager.levelTimeSeconds 1 levelManager.isOver true Anyone have any idea what's causing the editor to crash once isPause is true?
0
Built in Terrain analogs search is it worth to use imported 3d model? I think 3d model is better than the built in terrain component in Unity when it comes to optimization. But when it comes to texturing terrain made in 3rd party 3d modeller, how to apply resulting texture in Unity? If the terrain is too big you can't bake it in UV map. Otherway you should split it in many UV's and each one is separate material, which kills performance in the game. Other decision that i see is to use generated type of material and just tile it across the terrain mesh, but you can't draw the details like roads on it... So i'm confused is it really worth it to use Unity's terrain analogs or there is no way to do so efficiently?
0
Trying to find a solution for instant knockback in multiplayer game I'm making a server authoritative fast paced multiplayer game. I'm trying to implement wack hammers, they are a melee weapon that knocks close players, in other words, that sets their velocity to inverse of their mass to the direction aimed at the force of the hit. Even if the enemy player is only seen getting knocked after the client input gets processed on the server and after the enemy's position and velocity get sent back, I want to make it seem like your action appeared instantly. I've tried one thing when you knock a player, that player gets predicted for a short amount of time instead of being interpolated. That way, players appears to have been knocked out instantly, but there's an issue with that. When should I stop predicting? And how? When you think about it, the prediction is done on your own client time. The positions and velocities of other players are a few millisec old, so when you try to interpolate between your local quot futur quot predicted player position to the quot old quot server player position, you essentially move the other players back in time, and it looks real bad. I'm not quite sure what to try to hide this issue. I can't possibly predict the enemy player's position forward in time, its movement can get too chaotic. I've already watched the GDC talk from Overwatch's and Rocket League's netcode a million time, I'm not sure if they can help me with my issue. Edit I still haven t found the best solution yet but there s some useful information over at https forums.unrealengine.com development discussion c gameplay programming 1455487 responsive knock back in multiplayer game
0
How to have 3d multiple planet gravity in unity c ? Im using unity and I want to make a game where you can walk around small planets and the further away you get, the weaker the gravity, so you can go to other planets. All the tutorials so far only work with one planet, how do I code this? Is there anything I can download that does it for me?
0
Unity 2D Object following target instead of moving towards it I'm making a 2D game with Unity that's based on avoiding evading enemies. The problem i'm facing right now is i can't get the enemies to move towards the target player, but instead they follow it. So they never actually "attack" because they only follow it around and don't even come close to it. Also if the target player stops moving, they stop moving. I'm wondering if it could be something in my scene, since i've asked this question on multiple forum threads in the unity forums section and everyone seems to answer with the same lines of code. Extra information My enemy has a box collider on it with no rigidbody 2D. My player has a box collider on it with a rigidbody 2D. Kind regards. using UnityEngine using System.Collections public class BeeBehaviour MonoBehaviour public Transform target public float moveSpeed 3 void Start () target GameObject.Find("MainObject").transform void Update () Chase() void Chase () Vector3 targetDirection target.position transform.position transform.position targetDirection moveSpeed Time.deltaTime
0
How to put labels at a specific point on any resolution I am working on a project in Unity 4.6.1 and I put the label at the top But when I put the Scene in full view this happened I made a Development Build and when I select my resolution (1366x768) the label goes behind the buttons. Is there any way to put the label at a specific point no matter what resolution?
0
Ensuring a Recursive method completes in one update tick? OK so I have a method that calls itself as this was the only way I could think to get the behaviour I needed. Its a tetris clone i am making and this method is for checking for full lines across X axis. void CheckForFullLine(int starting Y) for (int y starting Y y lt frozenCells.GetLength(1) y ) for (int x 0 x lt frozenCells.GetLength(0) x ) if (!frozenCells x, y .isFilled) CheckForFullLine(starting Y 1) return if (x CELL COUNT X 1) tetrisLinesThisTick Debug.Log("lines this tick " tetrisLinesThisTick "on tick " tick) ClearLine(y) but when i test the game, most of the time (more than 9 10 times) when you get multiple lines, the debug log says we only got 1 line in that 'tick'. Here is the update method where at the top I set tetrisLinesPerTick to 0 at the start of each frame. private void Update() tick reset the tetris lines this tick value tetrisLinesThisTick 0 ClearScreen() CheckForFullLine(0) HandleMovementAndBlockCreation() DrawFallingPiece() DrawFrozenBricks() For example if I get 2 lines in one go, I get the debug log saying '...linesPerTick 1' twice in quick succession. Strangely , occasionaly I do get the 2 or even 3 lines and it says the correct amount, but this is rare and i don't know how i reproduce that yet. Another very strange thing (the relevant code might not be here for this part..) ...quite rarely one of the frozen blocks will turn grey after falling, then I can still 'use' it in game to make more lines, but it doesnt disappear like the others, then make a couple more lines using this grey block and it disappears as normal S (well just in case you feel like helping me with this part, he is more code P) void ClearLine(int line) TODO Add score remove complete line for (int x 0 x lt frozenCells.GetLength(0) x ) frozenCells x, line .isFilled false shift all lines down todo figure out if its a multi line tetris to give better scores... for (int y line y lt frozenCells.GetLength(1) y ) for (int x 0 x lt frozenCells.GetLength(0) x ) if (frozenCells x, y .isFilled) if (y gt 0) frozenCells x, y .isFilled false frozenCells x, y 1 .isFilled true For some reason, I feel it may be the recursive method i made and the fact that 'linesPerTick' value is getting set back to zero prior to the other lines being removed (in the same move), is what is causing my problem but i could be completely wrong about it! The whole project is just one .cs file and a block texture i made in GIMP, I could paste the whole script here if you want to try it please let me know. Cheers for any help!
0
save a particular area of the scene as screenshot in unity I need to save a particular part of the scene as screenshot. I have done a sample to show the particular part of the scene. When I click on the rectangular area the selected area will being shown on the screen on a texture (marked in red rectangle) But when I save, the whole scene is getting saved but not the selected part Here is code Texture2D screencap Texture2D border bool shot false public string path void Start () screencap new Texture2D(300,200,TextureFormat.RGB24,false) border new Texture2D(2,2,TextureFormat.ARGB32,false) border.Apply() Update is called once per frame void Update () if(Input.GetKeyUp(KeyCode.Mouse0)) StartCoroutine("Capture") string fileName(int width, int height) return string.Format("screen 0 x 1 2 .png", width, height, System.DateTime.Now.ToString("yyyy MM dd HH mm ss")) void OnGUI() GUI.DrawTexture(new Rect(200,100,300,2),border,ScaleMode.StretchToFill) GUI.DrawTexture(new Rect(200,300,300,2),border,ScaleMode.StretchToFill) GUI.DrawTexture(new Rect(195,100,2,200),border,ScaleMode.StretchToFill) GUI.DrawTexture(new Rect(500,100,2,201),border,ScaleMode.StretchToFill) if(shot) GUI.DrawTexture(new Rect(50,10,60,40),screencap,ScaleMode.StretchToFill) Application.CaptureScreenshot(myFolderLocation myFilename) IEnumerator Capture() yield return new WaitForEndOfFrame() screencap.ReadPixels(new Rect(198,98,298,198),0,0) screencap.Apply() shot true byte bytes border.EncodeToPNG() string filename fileName(Convert.ToInt32(screencap.width), Convert.ToInt32(screencap.height)) Application.CaptureScreenshot("D " filename) How can I save only the particular part in unity,can anybody please help me out.
0
How can I create a custom PropertyDrawer for my Point struct? I created a Point struct System.Serializable public struct Point public int x public int y I am trying to create a property drawer for it, so that when it shows in the inspector, it is shown in a Vector2 field. I have the following script in the "Editor" folder using UnityEditor using UnityEngine CustomPropertyDrawer(typeof(Point)) public class PointEditor PropertyDrawer public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) EditorGUI.Vector2Field(position, label, property.vector2Value) It shows up in the inspector the way I want, but the values are locked at 0. Basically, I am trying to access the Point instance from inside the OnGUI method, but this could be the completely wrong approach. How can I make this so that when the values are changed in the inspector, the respective Point is also changed?
0
MonoBehavior Script that uses UnityEditor Best practice for Location? I've created a script which helps me auto generate a GameObject prefab. It uses some UnityEditor, so it can't be used at runtime (and its not meant to be). Normally, a script like this I would put in the "Editor" folder. However, since it needs to be attached to a GameObject as a Component to do its thing, I'm not sure where I should put it. I can't store it in the Editor folder, because Unity yells at me and says I'm not allowed. Are there any best practices defined for things like this?
0
Move an object with other objects connected (via joints) the right way What is the best way to move an object with other objects connected to it via joints? Let's assume we have the following setup A player that can move on the x and the z axis "Normally configured" RigidBody Moving like this void FixedUpdate() Vector3 movement new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical")) movement movement.normalized 2f Time.deltaTime m rb is the RigidBody of the player m rb.MovePosition(transform.position movement) Another object that should be moving with the player as it were its child Connected to the player via a fixed joint "Normally configured" RigidBody When moving the player without any object connected the movement looks as expected Now moving the player with the object connected results in some kind of dragging effect as seen here One way to solve this behaviour would be to also move the connected object m otherRb is the RigidBody of the connected object (m other) m otherRb.MovePosition(m other.transform.position movement) Is there a better way to solve this? Shouldn't the joint handle the movement of the other object? Moving the connected object like this results in many problems like to high impulse forces when colliding with something as both elements get pushed towards the collider. Also handling the rotation of the connected object isn't as easy as the position.
0
Connecting varying tilemap layouts at possible connection points? I'm building an isometric 3D ARPG in Unity3D, and I have a tilemap, for example a dungeon. I have tiles marked where a door could be placed. I select a random "could be a door" tile from the tilemap. I "receive" an any shaped room, which could be a prefab, or a generated one as well. This room got tiles marked for door placement as well. Without editing anything how could I easily determine whether this room could be connected to the existing dungeon via the selected connection point? (and of course find the solution if it could be) by (valid) connecting I mean only their doors and walls can overlap, but nothing else. (and removing the duplicates, creating the door itself, etc) (Of course rooms can differ from rectangles)
0
Objects do not stop when colliding each other while using mouse drag I work on a 2D game and I have multiple objects that the player can control. The objects each have a RigidBody2D and a Collider, and a method OnMouseDrag() with which I can drag the objects. I want the dragging to stop when the objects hit each other. I tried by using this rigidbody2d.velocity Vector3.zero rigidbody.isKinematic true But the objects do not stop. I want exactly like this video. I tried this but it isn't work too. https www.youtube.com watch?v ZfjVR 0ZFHU amp t 270s using UnityEngine using System.Collections public class NewBehaviourScript1 MonoBehaviour bool allowDrag true void OnCollisionEnter(Collision collision) allowDrag false void OnMouseDrag() if(allowDrag) float distance 7 Vector3 mousePosition new Vector3 (Input.mousePosition.x, Input.mousePosition.y , distance) Vector3 objPosition Camera.main.ScreenToWorldPoint (mousePosition) transform.position objPosition if ((transform.position.x lt 0)) Vector3 tmp transform.position tmp.x 0 transform.position tmp if ((transform.position.x gt 4.5f)) Vector3 tp transform.position tp.x 4.5f transform.position tp void OnMouseUp() if ((transform.position.x gt 0) amp amp (transform.position.x lt 0.375f)) Vector3 tr transform.position tr.x 0 transform.position tr if ((transform.position.x gt 0.375f) amp amp (transform.position.x lt 1.25f)) Vector3 fs transform.position fs.x 0.75f transform.position fs if ((transform.position.x gt 1.125f) amp amp (transform.position.x lt 1.875f)) Vector3 tr2 transform.position tr2.x 1.5f transform.position tr2 if ((transform.position.x gt 1.875f) amp amp (transform.position.x lt 2.625f)) Vector3 tr4 transform.position tr4.x 2.25f transform.position tr4 if ((transform.position.x gt 2.625f) amp amp (transform.position.x lt 3.375f)) Vector3 tr6 transform.position tr6.x 3 transform.position tr6 if ((transform.position.x gt 3.375f) amp amp (transform.position.x lt 4.125f)) Vector3 tr7 transform.position tr7.x 3.75f transform.position tr7 if ((transform.position.x gt 4.125f) amp amp (transform.position.x lt 4.875f)) Vector3 tr8 transform.position tr8.x 4.5f transform.position tr8 void Start () void Update() Please help!
0
How do I draw a world rectangle as a GUI I would like to draw a perspective green rectangle that glows ( it constantly changes its alpha between 0 an 1). I already achieved this, but not as a GUI element, but as a real 3D object. In order to show this rectangle in front of everything else, I have to turn this into a GUI element. And I don't know how I would draw a perspective rectangle that constantly changes its alpha on the GUI. I do not only mean the math behind it, but also how to do it exacetly Do I use actual materials, or do I use an image in the size of the green box? Thank you. Edit This is what I'm trying to rebuild
0
Shooting at mouse in unity I'm using unity and trying to get my bullet to shoot at a target. I am clicking the mouse and I'm wanting to fire my bullet in that direction. I have gotten the coordinates of the mouse click and tried to compute the vector. Then I've tried instantiate the bullet prefab (which has rigidbody component and is in front of the scene) at my position and then fire it in the direction of the mouse. I can see that my objects being instantiated in my Hierarchy Pane but can't see anything on the screen! Not sure if I'm doing the vector thing right (newb here), but if I click on Yoshi's head, I'm getting ( 2.0, 0.4). Does this sound right? Code void fireBullet(float mousePositionX, float mousePositionY) Vector2 position new Vector2(mousePositionX, mousePositionY) position Camera.main.ScreenToWorldPoint(position) GameObject bullet Instantiate(bulletPrefab, transform.position, Quaternion.identity) as GameObject bullet.transform.LookAt(position) Debug.Log(position) bullet.rigidbody2D.AddForce(bullet.transform.forward 1000)
0
How can I make all the objects to move between the waypoints? using System.Collections using System.Collections.Generic using UnityEngine public class MovementSpeedController MonoBehaviour public List lt Transform gt objectsToMove new List lt Transform gt () public List lt Vector3 gt positions new List lt Vector3 gt () public int amountOfPositions 30 public int minRandRange, maxRandRange public bool randomPositions false public bool generateNewPositions false public float duration 5f public bool pingPong false private void Start() if (generateNewPositions (positions.Count 0 amp amp amountOfPositions gt 0)) GeneratePositions() StartCoroutine(MoveBetweenPositions(duration)) private void GeneratePositions() for (int i 0 i lt amountOfPositions i ) if (randomPositions) var randPosX UnityEngine.Random.Range(minRandRange, maxRandRange) var randPosY UnityEngine.Random.Range(minRandRange, maxRandRange) var randPosZ UnityEngine.Random.Range(minRandRange, maxRandRange) positions.Add(new Vector3(randPosX, randPosY, randPosZ)) else positions.Add(new Vector3(i, i, i)) IEnumerator MoveBetweenPositions(float duration) for (int i 0 i lt positions.Count i ) float time 0 Vector3 startPosition objectsToMove 0 .position while (time lt duration) objectsToMove 0 .position Vector3.Lerp(startPosition, positions i , time duration) time Time.deltaTime yield return null objectsToMove 0 .position positions i Now only the first object in objectsToMove is moving between the waypoints but I need all of the elements of objectsToMove to move between the waypoints. If I try this objectsToMove i .position Vector3.Lerp(startPosition, positions i , time duration) I will let out of bound index exception because the size of objectsToMove is not the same the size of positions i
0
transform.Rotate needs to change axis of rotation So I'm making a game in Unity. After many failed attemps from either being bored of the idea, or something going wrong and me giving up I think (hope) that will be the good one. I have made a simple racing game with a track and a car. I am using transform.Translate to move it, but when I use transform.Rotate to turn it goes around the x axis. How do I change the axis it goes around? I cant find anything online. if (Input.GetAxisRaw("Horizontal") gt 0.5f) transform.Rotate(Vector3.right Time.deltaTime handling) if (Input.GetAxisRaw("Horizontal") lt 0.5f) transform.Rotate(Vector3.left Time.deltaTime handling) if (Input.GetAxisRaw("Vertical") gt 0.5f Input.GetAxisRaw("Vertical") lt 0.5f) transform.Translate(new Vector3(0f, Input.GetAxisRaw("Vertical") moveSpeed Time.deltaTime, 0f)) Thanks for any help you can give me.
0
Box2d on authoritative server for Unity client I'm creating a multiplayer platform and shooting game in unity, using unity2d's own physics system (box2d). But the truth is that I am quite lost in the creation of an authoritative server in c . I have quite clear and experience in the use of socket for communication between client and server, I do not know how to approach the issue of simulating the physics of my game on the server so that it decides the positions movements of the clients. Can anyone guide me to use box2d on the server, as I simulate the game on the server? Is this a good option or would it be better to implement my own game physics than to use the non deterministic engine? Thank you very much and sorry for my level of English
0
Why is there a white border around my app icon? EDIT This is because Unity did not support Android's adaptive icons. As of Unity 2018, it is supported natively. For Unity 2018 , see this question. For Unity 2017 , see Jimmy's answer. I am developing an Android app in Unity. I have two versions of the app on my phone, both with identical icons. The white border is only on the newer version of the app. I am using a Google Pixel. Why is this there, and how do I get rid of it? Is this tied to my phone or my app? If it is tied to my phone, why is it on one icon, but not the other (they are same icon)? I don't want other users to have this pointless border around the app, as my icon already has a border.
0
How should I setup my sprites for 2D combat? I was painting pixel sprites of a goblin (the enemies in the game). I first thought of making sprites of it for each different scenario facing camera, moving toward camera 1, moving toward camera 2, facing camera with sword, moving toward camera with sword 1, moving toward camera with sword 2, facing left, going left 1, going left 2 facing left with sword etc. (for a total of 18 sprites) Then I wondered, how will I make the sword hit the player ? What if I want the goblin to have a different type of sword ? Do I have to make different sprites of it holding different weapon ? I realised doing sprites for every scenario wasn't ideal. So my question is, how do I make this ? Should I keep the sprites I have but remove the sword from them and then add a sword sprite attached to the player sprite and animating it so it matches the players movement ? Is that the way to go ?
0
Response to form triggers creation of zero or more duplicate scenes I've got two scenes, one with room 1 and one with room 2. In room 1 I've got one table with two 3D assets on top of it. This room also has a door that connects to room 2 through a door but it's closed. Once going near the 3D assets a dialog pops up saying to click "E". This pops up a 2D form one needs to fill. Only after filling both forms I'm able to go into room 2. Now what I would like to do is, depending on the response in the form, one or more duplicate room 2 scenes should be created and dynamically added to the scene. If with scenes isn't possible, what's the way to do such thing? Know about SceneManager.CreateScene but this creates an empty scene, not exactly what I want to.
0
How To Display a friend list Using Play fab? I m making a multiplayer game using playfab. One player send a friend request Second player then not display a player name?? I want the access(display) a player name??? see the referance, Code ListingPrefab.cs public class ListingPrefab MonoBehaviour public static ListingPrefab Instance public Text playerNameText FriendRequest.cs public class FriendRequest MonoBehaviour public GameObject listingPrefab btn public Transform panel parent Display Friend void DisplayFriends(List lt FriendInfo gt friendsCache) foreach (FriendInfo f in friendsCache) I think problem is here GameObject listfriend Instantiate(listingPrefab) ListingPrefab templisting listfriend.GetComponent lt ListingPrefab gt () templisting.transform.SetParent(panel, true) PlayerPrefs.GetString("PlayerName", ListingPrefab.Instance.playerNameText.text.ToString()) PlayerPrefs.SetString("PlayerName", ListingPrefab.Instance.playerNameText.text.ToString()) Debug.Log("playername " templisting.playerNameText friendsearch) Debug.Log("helloone" f.TitleDisplayName) templisting.playerNameText.text f.TitleDisplayName TitleDisplayName PlayFab unique username for this friend. void DisplayPlayFabError(PlayFabError error) Debug.LogError(error.GenerateErrorReport()) void DisplayError(string error) Debug.LogError(error) Getfriend List lt FriendInfo gt friends null public void GetFriends() you can call button click PlayFabClientAPI.GetFriendsList(new GetFriendsListRequest IncludeSteamFriends false, IncludeFacebookFriends false , result gt friends result.Friends DisplayFriends( friends) triggers your UI , DisplayPlayFabError) Debug.Log("Inside GetFriends") Add friend enum FriendIdType PlayFabId, Username, Email, DisplayName void AddFriend(FriendIdType idType, string friendId) var request new AddFriendRequest() switch (idType) case FriendIdType.PlayFabId request.FriendPlayFabId friendId break case FriendIdType.Username request.FriendUsername friendId break case FriendIdType.Email request.FriendEmail friendId break case FriendIdType.DisplayName request.FriendTitleDisplayName friendId break Execute request and update friends when we are done PlayFabClientAPI.AddFriend(request, result gt Debug.Log("Friend added successfully!") Add a friend , DisplayPlayFabError) string friendsearch SerializeField GameObject friendpanel public void InputFriendID(string inputfriendid) friendsearch inputfriendid public void SubmitFriendRequest() AddFriend(FriendIdType.PlayFabId, friendsearch) public void OpenCloseFriends() friendpanel.SetActive(!friendpanel.activeInHierarchy) Prerequisites SDK Unity The title ID is set in the PlayFabSharedSettings object (alaready i have) The project can successfully log in a user (alaready i have) The title has at least two registered users (alaready i have) image I have 15 Player. How To access a PlayerName??
0
Object destroyed when applying WebCamTexture across Photon This script turns the texture from WebCamTexture into a byte array to send across Photon as an RPC. However, when it is called, it displays the WebCamTexture for 1 frame before destroying the entire GameObject it is applied to. The gameobject is this case is a prefab with a cube that is instantiated after joining a room. edit I should add that it only crashed when called on a prefab. When applied to an in scene object, it works. using System.Collections using System.Collections.Generic using UnityEngine using Photon.Pun using Photon.Realtime using System.Text using ExitGames.Client.Photon using System using UnityEngine.Timeline using System.Security.Cryptography public class CameraTry6 MonoBehaviourPunCallbacks WebCamTexture backCam public Texture2D CamThing public Texture2D TextureFromCamera Start is called before the first frame update void Start() if (backCam null) backCam new WebCamTexture() if (!backCam.isReadable) Debug.Log( quot Unable to read camera. quot ) return if (!backCam.isPlaying) backCam.Play() if (backCam.isPlaying) InvokeRepeating( quot Starter quot , 2.0f, 2.0f) else Debug.Log( quot the webcam is not working. unable to send. quot ) Update is called once per frame void Update() void Starter() StartCoroutine( quot Camsend quot ) Destroy(CamThing) IEnumerator Camsend() if (backCam.didUpdateThisFrame) yield return new WaitForEndOfFrame() Debug.Log( quot Frame is over quot ) Texture2D TextureFromCamera new Texture2D(backCam.width,backCam.height) int frame new int 3 frame 1 backCam.width frame 2 backCam.height TextureFromCamera.SetPixels(backCam.GetPixels(0,0,backCam.width,backCam.height)) TextureFromCamera.Apply() GetComponent lt Renderer gt ().material.mainTexture TextureFromCamera byte bytes TextureFromCamera.GetRawTextureData() Destroy( TextureFromCamera) int id photonView.OwnerActorNr Debug.Log( quot Local camera bytes quot bytes.Length quot from quot photonView.OwnerActorNr) this.photonView.RPC( quot NetMess quot , RpcTarget.Others, quot rcving the texture from quot , id) photonView.RPC( quot CamRcv quot , RpcTarget.All , bytes, id, frame) PunRPC public void CamRcv(byte bytes, int pid, int frame) yield return new WaitForEndOfFrame() if (photonView.OwnerActorNr pid) StartCoroutine( quot LoadTexture quot ) LoadTexture() Debug.Log( quot Recieved byte from quot pid quot array length quot bytes.Length) yield return new WaitForEndOfFrame() Texture2D CamThing new Texture2D(frame 1 , frame 2 ) CamThing.Apply() CamThing.LoadRawTextureData(bytes) CamThing.Apply() GetComponent lt Renderer gt ().material.mainTexture CamThing CamThing.Apply() IEnumerator LoadTexture() yield return new WaitForEndOfFrame() Debug.Log( quot Recieved byte array length quot bytes.Length) Texture2D CamThing new Texture2D(backCam.width, backCam.height) Debug.Log( quot Recieved byte array length quot bytes.Length) CamThing.LoadRawTextureData(bytes) CamThing.Apply() GetComponent lt Renderer gt ().material.mainTexture CamThing Destroy(CamThing) PunRPC void NetMess(string mess, int pid) Debug.Log(mess pid)
0
RTS Pathfinding without collision between units Options Ever since I made my units move to a certain location a problem has popped up that of course if I try to make two or more units go to the same place they fight for the same spot. Am I just being stupid and unity already has a way around this or do I need to do something specific? I have looked into flow field path finding but no way on how to implement it. I dont want to have to use a ready made script but some pointers and other options are more than welcome.
0
Render Texture shows opposite view of camera when rendered? I am using render texture (cube) to render what camera sees into it. However, the render texture shows me opposite side of cameras view (flipped) instead of what camera sees. Any solution for this? void Update() renderTexture.isPowerOfTwo true Graphics.SetRenderTarget(renderTexture, 0, CubemapFace.PositiveZ) renderTexture.dimension TextureDimension.Cube camera.RenderToCubemap(renderTexture, 63) What camera sees What Render Texture shows What happens when I rotate Render Texture manually by hand 180 degrees So, instead of rotating per hand, what I want is for the render texture to be rotated via code so that what is in camera view is shown exactly the same in render texture view.
0
Determine facing direction mecanim 2d movement I'm using this script to move my character in my 2d world public float speed Movementspeed public Rigidbody2D rbody Animator anim void Start () rbody GetComponentInChildren lt Rigidbody2D gt () anim GetComponent lt Animator gt () void FixedUpdate () Vector2 movement vector new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")) if (movement vector ! Vector2.zero) anim.SetBool("iswalking", true) anim.SetFloat("input x", movement vector.x) anim.SetFloat("input y", movement vector.y) else anim.SetBool("iswalking", false) rbody.MovePosition (rbody.position movement vector speed Time.deltaTime) What I want is to somehow register where my character is facing walking towards to be able to Instansiate a gameobject infront of it. How do I do that?
0
Moving object along X and Z plane relative to camera Using keys, I'm trying to move a cursor object across the X and Z plane, keeping it relative to a camera that I can orbit around the playfield. This is my code so far, and apologies...I'm about 2 days into learning Unity. This code is on my cursor object. if (Input.GetAxis("Horizontal") gt 0f) transform.position transform.position Camera.main.transform.right moveSpd Time.deltaTime if (Input.GetAxis("Horizontal") lt 0f) transform.position transform.position Camera.main.transform.right moveSpd Time.deltaTime if (Input.GetAxis("Vertical") lt 0f) Vector3 dir Camera.main.transform.forward dir.y 0.01f dir.Normalize() transform.position transform.position dir (moveSpd 1.5f) Time.deltaTime if (Input.GetAxis("Vertical") gt 0f) Vector3 dir Camera.main.transform.forward dir.y 0.01f dir.Normalize() transform.position transform.position dir (moveSpd 1.5f) Time.deltaTime transform.position new Vector3(transform.position.x, 0.01f, transform.position.z) It works, but the vertical axis affects the Y plane so I had to do another transform at the end. What is the best way of doing this? I'd also like the cursor to snap to grid co ords. I've tried turning them to int but it doesn't do what I want.
0
Old tv effect in shader graph I am trying to use Unity's shader graph to create this old tv effect I thought about using a noise node, and somehow randomize the noise's seed. Can anyone help me?
0
How do I correctly set up a Unity animation to move? I downloaded a custom .fbx model from the asset store, imported it to my project and placed it in my scene. I then created an animator controller and added it to the object. To get the animations (that came with the model) into the animator tab, I dragged them onto the model in the hierarchy. I then set the one animation to default and pressed play, but in the game window, the model didn't move. What might be going on? The only time it did something was when I set it to "play from start" but that made it go through all the animations. I'm quite new to Unity 4. If you need any extra information, please ask.
0
When I pause my game scene in unity editor by keyboard ctrl shift P Assertion failed ... appears in console window I am using Unity 2017.2.0f3. When I pause my game scene by use mouse click on pause button amp play it frame by frame, it works OK. Instead, pause by use ctrl shift P keys down, an error will play once in console window at the time I press frame by frame button. Assertion failed Assertion failed on expression '!dest.m MultiFrameGUIState.m NamedKeyControlList' UnityEngine.GUIUtility ProcessEvent(Int32, IntPtr) This would happens even in the new created empty scene! Any help will be appreciated!
0
Using Unity built in sprites programatically I'm trying to figure out how to use the "Panel" built in resource in a game I'm making. I've been able to figure out some potential solutions, but I can't quite figure out how to put all of the pieces together. panelImage.sprite UnityEditor.AssetDatabase.GetBuiltinExtraResource lt Sprite gt ("UI Skin InputFieldBackground.psd") panelImage.sprite Resources.GetBuiltinResource(typeof(Sprite), "Resources unity builtin extra Background.psd") as Sprite The first produces the button sprite, which is almost what I want, but not quite. The second doesn't work at all. I'm missing some small piece of what it takes to make this work, but I can't quite figure it out. How can I use the panel background programmatically?
0
Follow 3D Path Around Sphere I have currently have a path that wraps around a Sphere from one side to another this is basically a 3D highway in the sky type object that is a textured road. I have an Aircraft model that I can get to follow this path, however I'm having trouble getting it to rotate correctly so that it is parallel to the surface of the globe Using the following code this.transform.forward Vector3.RotateTowards(this.transform.forward, this.transform.position TargetWaypointPos, Airspeed Time.deltaTime, 0.0f) this.transform.position Vector3.MoveTowards(this.transform.position, TargetWaypointPos, Airspeed Time.deltaTime) This gets the plane to correctly face the next waypoint and follow the path, however I cannot get it to rotate correctly in the Z space to be parallel to the path globe. I can compute the correct angle by Vector3 yAxis this.transform.position yAxis.Normalize() Vector3 zAxis nextPoint this.transform.position zAxis.Normalize() xAxis Vector3.Cross(yAxis, zAxis) xAxis.Normalize() float angleZ Vector3.Angle(Vector3.right, xAxis) However attempting to apply this to my model in any way appears to ruin the Vector3.RotateTowards logic. I must be missing something simple to combine these two. Any ideas? I'm new to Unity, still figuring out all the available options.
0
Can Cloud Functions be used for a multiplayer game server? I'm building a turn based online multiplayer game with Unity for both desktop and mobile. Traditionally, I would build a Java socket server, host it in Google Compute Engine or similar, and have players connect to it. Since this works with sockets I can easily notify players of relevant events, such as matchmaking, chat, enemy turn, etc. I've been curious about Serverless Functions for a while, such as Google Cloud or Amazon Lambda. However, at first glance it doesn't seem to me like that would work for my game because there ins't a constant connection (with sockets), I can't notify players of relevant events in realtime or can I? For mobile I realize I could probably use something akin to push notifications (so the serverless code may push messages to the relevant player's phone). But that doesn't seem as simple for desktop games. Well, what if the players poll for messages? Like every second, call a Cloud function and ask them if there's anything for them. I'd image that would work, but that seems rather overkill with as little as a couple thousand players, calling the same function every second for prolonged times (the game's matches are long) sounds like it would easily increase expenses. Is there something I am missing? A coding practice that would make serverless code feasible for a cross platform online multiplayer game? I want to make it work, but it would seem like a socket server is still my only option.
0
How to select top most gameObject in a stack of gameObjects? I'm stuck trying to figure out how I can select the top most GameObject in a stack of GameObjects. In the picture below, I have a Green and Yellow circle stacked on top of each other. If I try to select the top most gameobject (the green one), it selects the yellow circle. Is there a way that I can make sure that when I go to select a circle, it selects the top most one? I'm currently using the OnMouseDown() function built into unity. Update Sorting the colors on the z axis did not solve the problem. I'm still trying to figure out a solution
0
How to Bring the Scene View Camera Controls into Game View I've got a scene with a big sphere in the centre (the Earth) and a lot of smaller spheres around (the stars). Above is a screengrab in Scene View with the camera in the Front View position. I really like the controls in Unity's Scene View when moving around the viewport and I was wondering whether it can be brought into the Game View. How can I do this?
0
How do I check user's unlocked achievement and leaderboard scores via GPG plugin I need to load user's achievement and their scores from leaderboard in my game. But the Social.LoadScore() and Social.LoadAchievements() both returns a 0 size array in callback. When I checked the implementation in Google Play Gaming's PlayGamePlatform.cs, both the method has this summary Not implemented yet. Calls the callback with an empty list. So my question is How do I get this data in Unity? Has anyone tried any other method to get the data?
0
I found out how to rotate both Sphere and Cube (1) like a Turret facing a target but why is it so hard? I just added 3 objects to my scene to a new project. To be sure where the problem is I created a new project. Then added to the scene 2 Cubes and 1 Sphere 1 empty GameObject. Cube is the target. Sphere and Cube (1) are the Turret and both are childs of the empty GameObject. The script is attached to the empty GameObject. The logic say if I will rotate the empty GameObject both Sphere and Cube (1) will rotate at the same time. But I found that if I'm not setting both Sphere and Cube (1) same direction before running the game they will never face to the target only the Sphere. I had to figure out where is the Sphere facing direction before running the game and change the Cube (1) to face the same direction of the Sphere on the Z Blue axis. I can't figure out yet and understand why is it so hard to rotate two objects at the same time to be facing the same direction (target). Now it's working once the sphere and the cube (1) are facing same direction before running the game. It didn't work if I made them childs or parents or changed the Cube (1) position to 0,0,0 nothing. They were both rotating but never faced the target only the Sphere faced the target. So now each time I want to rotate two objects at the same time to face another gameobject like a turret, or cannon or anything that is built of two parts I need first to make them facing same direction ? I guess I did something wrong but not sure what. The script using System.Collections using System.Collections.Generic using UnityEngine public class Rotateturret MonoBehaviour public float speed 3.0f public GameObject m target null Vector3 m lastKnownPosition Vector3.zero Quaternion m lookAtRotation private void Start() Update is called once per frame void Update() if (m target) if (m lastKnownPosition ! m target.transform.position) m lastKnownPosition m target.transform.position m lookAtRotation Quaternion.LookRotation(m lastKnownPosition transform.position) if (transform.rotation ! m lookAtRotation) transform.rotation Quaternion.RotateTowards(transform.rotation, m lookAtRotation, speed Time.deltaTime) bool SetTarget(GameObject target) if (!target) return false m target target return true Here is a link for a short video clip I recorded showing what I mean Video clip of the problem
0
Unity or Monogame or Gamemaker 2 for an experienced application developer? So i know this question has been hammered down several times but please bear with me. I used to be a C .Net application developer but i am no longer employed, i am pretty good at C . I want to get into serious game development and i dunno where to start, i used to work with unity occasionally which is a very little and i kinda find it clunky, like it works but somehow it does not feel right and feels kinda clunky. But it works with tiled map editor without much of a hassle. I Remember using Game maker studio when i was back in college and i found it very good, its a breeze to work with and even have its own tiled map editor, even seems to have some good tutorials, the only con is its price. I was initially inclined towards Monogame cause of my C background, but i neither have time nor money and resources to support me for long enough time to be able to code every single thing from scratch and i am kinda in a pretty bad situation overall right now. It just takes too much time to do anything even to make it work with a tiled map editor, and there are very few tutorials or documentation to start with. It seems like the only option for me is Unity at the moment, cause of ease of access and how easy it is to work with tiled map editor and lots of tutorials. which one do you guys think is good overall? Please keep in mind that i am currently unemployed and have very little resources to support myself, and i am a programmer so i don't even know how to compose music and do art for the game and i'd prefer if it provides some asserts to be used so i wont waste time in learning stuff when i cannot afford to spend time. I will eventually learn them but not now, its not happening now so i prefer something that comes with some sorta free asserts that can be used (mainly music and art), I mean does it even matter if all i am trying to do is earn a decent minimum living? I just want to make simple 2D NES Snes style games with multiplayer support. Thank you.
0
Unity Passing an array in a shader I want to pass my array (which is inside my c code) to my shader. Shader "custom shader4" Properties myArray("Array", Float 256 ) SubShader Pass CGPROGRAM public float myArray 256 code... this is obviously not working. Is anyone here who knows how to solve this? (also in c ) myMaterial.MyArray anotherArray It has to be something like this right? Or do I need a workaround?
0
Difference between GUILayout and EditorGUILayout? Is it matter if I use GUILayout or EditorGUILayout for my custom editor? I need to use one of them in the OnInspectorGUI function. which one should I use? What are the differences between the two? Thank you in advance.
0
Persisting Player Prefs On Build in Android Can I ask for help guide where I can build 2d game on android device includes the players prefs that I defined already, for example I have an quot int quot PlayerPrefs (PlayerPrefs.Getint ( quot mysavenumber quot )), the data quot mysavenumber quot has already a saved integer value in it. How ever upon building my game and installing it on my android device it seems does not hold any value. How can I build my game with the Playerprefs data that I have defined upon building and installing it on an android device?
0
After using Unity's Destroy() function, I see the Prefab Clones are now called "New Game Object" is this a problem? I use a prefab to generate several gameobjects which I then get rid of with the Destroy() function. I noticed the clones, when destroyed are replaced with "New Game Object". Because of the nature of the game there would be thousands of these created throughout the course of the game. Is this expected behavior, or is there something I'm perhaps doing wrong where the Destroy isn't really getting rid of it completely?
0
Change Time.timeScale during an animation event Unity I have an animation. A few seconds after this animation starts I set an animation event that is correctly being triggered. This animation event calls a method where I am trying to modify Time.timeScaleand set it to 0.05f. This event is calling the following method public void Slowmotion() Time.timeScale 0.05f Time.fixedDeltaTime Time.timeScale 0.02f But this Slowmotion method is not working. Any ideas on what may be happening?
0
Object reference not set to an instance of the object using System.Collections using System.Collections.Generic using UnityEngine public class PlayerMovement MonoBehaviour public CharacterController2D controller public float runSpeed 40f private float horizontalMove 0f Update is called once per frame void Update () horizontalMove Input.GetAxisRaw("Horizontal") runSpeed void FixedUpdate() controller.Move(horizontalMove Time.fixedDeltaTime,false,false) error is somewhere here Though all the classes are defines it throws the error please help!!!!!
0
Getting Directions from player I have a camera player in a scene. Scene contains a fixed north which i want to indicate on my compass with needle but how can i do it? I tried this code using a tut so far but its north is not right public void ChangeNortDirection() northDirection.z player.eulerAngles.y 10 northLayer.localEulerAngles northDirection
0
Why aren't my Unity rotations working properly? I'm experiencing a rather annoying bug and I was hoping someone could offer some help because this just isn't making sense to me. I have a Ballistic script that tells the bullet to move in its local forward direction, which should be whichever way the gun is pointing. I have a PlayerAttack script that calls for a bullet to spawn with OnShootEnter(). It sets the bullets position to that of a bulletSpawn transform, which is a child of the gun. OnShootEnter() is being properly called and bulletSpawn is properly assigned and yet, when the bullet spawns, its facing Vector3.forward, instead of it facing bulletSpawn.forward. These are the only two scripts affecting the bullets spawn, rotation, and direction. Everything looks in order to me what am I missing? public class PlayerAttack MonoBehaviour public GameObject bulletPrefab public Transform gun public Transform bulletSpawn public float damage void OnShootEnter() GameObject bullet Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation) public class Ballistic MonoBehaviour public GameObject model public float range public float accuracy public float speed Vector3 dir Vector3.zero void Start () model.transform.SetParent (this.transform) dir transform.forward void Update () transform.GetComponent lt Rigidbody gt ().velocity dir.normalized speed range Time.deltaTime if (range lt 0) Destroy (this.gameObject)
0
Unity RTS Multiple Selection Approacah I've recently solved the single selection problem but now I want to do multiple selections. I know I need to find two points with the mouse position to draw a box but it just won't work for me. void Update() if (Input.GetMouseButtonDown(0)) bool dragging true Debug.Log("Multiselect active") MultiSelect(dragging) private void MultiSelect(bool dragging) mouseDownPoint Input.mousePosition if (Input.GetMouseButtonUp(0) amp amp dragging) mouseUpPoint Input.mousePosition Debug.Log("First pos " mouseDownPoint " Second pos " mouseUpPoint) dragging false What is a better way to achieve what I'm trying? If someone can tell me a way that can also detect any units inside the area that'd be nice too.
0
Problems exporting animations to Unity 5 I've finished a model in SpeedTree Cinema v7.1.1 and the model exports correctly, but I can't figure out how to export the wind animation to Unity 5. The only problem is that the wind animation itself doesn't export. I think that the problems are one of the following The way I export the mesh (.FBX ascii). The settings in the export process. I'll add some images so you understand better. (Image 1.) In here you can see the export settings, the important aspects, regarding the animation, are in the 'Extra Data' tab, in there I included Wind, there are other options which I will describe in the next paragraph. (Image 2.) In the 'Include' section, in the 'Extra Data' tab I can choose from a variety of things, but I don't know which one will work for exporting the wind animation to Unity 5. In the 'Extra Data' tab there is also a sections where it says 'Format', under Include, in the 'Format' section the options are FBX MC, FBX PC2 and MDD. In the 'Files' sector the options are One or Per Frame. If you know or think you know how to do this, please tell me, any help will be appreciated. Thank you.
0
How to enable the option "edit physics shape" in the Sprite Editor? I can successfully import .png files, create tilesets, and use them in my tilemaps in Unity. Thanks to DMGregory, I just learned that there exists an option to customize the Tilemap Collider 2D in the Sprite Editor, which allows me to set a custom collider for every tile instead of going through them one by one. The steps I follow while creating a tileset in Unity is as follows. Import the .png file. Open the Sprite Editor. Select the option Multiple for Sprite Mode. Select Slice from the Sprite Editor. Then, I create a Tile Palette in a folder, drop and drag my created tiles, and start creating my level. I have never encountered the option to modify the colliders tile by tile. What am I doing wrong?
0
Should I code game logic separately from game engine scripts I'm developing a game in Unity3d, economic strategy. I wonder if I should code logic inside unity scripts, or write it as an external module library? By game logic I mean game model, which describe game entities, they relation with each other, their methods. And this logic has nothing to do with and doesn't need to know anything about networking, rendering, representation etc. If I do it inside unity scripts, then logic is tied to unity engine and I don't see a way to implement multiplayer(client server) without rewriting whole logic for server side, where unity cannot be used. I would like to define logic outside of scripts, and later, reference it inside some "main" unity script. This way I could implement multiplayer easily. Is this a common practice, or should I avoid it, or maybe there is some alternative patterns?
0
Loading images using their bytes in Unity If you import an image into the Unity inspector, the image will be encoded in Unity's own format. Usually the resulting image is much bigger than the original (from 100kb to 1MB). Of course, you can do stuff like compress and change the texture max size to reduce the image's size, but at the end it will almost always be bigger. I noticed that you can create a Texture2D if you got the necessary bytes. As an experiment, I took my 100kb image and imported it to Unity as a .bytes file. Then I read the bytes and created my Texture2D Texture2D texture new Texture2D(100, 100) texture.LoadImage(myTextAsset.bytes) Sprite sprite Sprite.Create(texture, new Rect(0,0,350, 288)) And it works. And it is smaller (100kb). So my question is what's the difference between Unity's builtin way of handling images and my way of loading them using their bytes? Because I'm saving tons of memory with this method. I imagine that it is a bit slower. But if that's the only difference, I can live with that.
0
Preload multiple scenes at the same time and activate them on demand in Unity. Unity, async, simultaneous Preload scene in unity this question tells us about how we can pre load a scene in Unity and load it on demand. What it doesn't tell us how do we pre load multiple scenes at the same time and also keep the other scenes in memory waiting to be activated when we load another scene? Use case pre loading multiple scenes at the start of the application, so they are ready when required. Example You have a Scene Intro which takes 20s to complete where you start pre reloading Scene Main Menu that takes 10s to load. When Scene Main Menu has finished pre loading, you still have 10s to spare, those could be used to pre load Scene Main Game. You have a Scene Main Menu. Depending on user choice you load Scene Main Game or Scene Sandbox. You pre load both scenes while user is still in Scene Main Menu. When user makes their choice, chosen pre loaded scene is loaded.
0
Changing colour of multiple prefab instances when dragging over them So I am having some issue trying to get it so that when I touch mousedown that an instantiated prefab changes color and then with mouse down still any other prefab that mouseenters, that prefab should change color as well. the bit of code that i have is shown below. Nothing happens though, other than the one prefab that received the OnMouseDown changes color, but not the others OnMouseEnter. If i remove the if statement though, they do change color OnMouseEnter. Any suggestions on how to do this or what i may be doing wrong? Thanks using System.Collections using System.Collections.Generic using UnityEngine public class Letter MonoBehaviour Color clkColor Color.red private bool clicked void Start() clicked false void OnMouseDown() clicked true this.GetComponent lt SpriteRenderer gt ().color clkColor private void OnMouseEnter() if ( clicked true) this.GetComponent lt SpriteRenderer gt ().color clkColor