_id
int64
0
49
text
stringlengths
71
4.19k
0
Reusing tilemap segments I'm wondering how I can incorporate reusable tilemap segments in my workflow. For example I construct a room out of my tile palette, and I want to reuse this room in multiple places. Is there some way to "prefab" a section of a tilemap? I haven't found such a thing. Or perhaps I should just prefab the whole tilemap, and use multiple tilemap objects within one grid? Won't that introduce significant overhead? What if I want to prefab a section of a tilemap with some additional, non tilemap objects?
0
Unity Game objects in scene load incrementally and not at the same time I am using Unity in my Android app. When the app opens, I show the user data in the Unity scene. User data contains texts and images. In order to load this data in the scene, I make a lot of UnityPlayer.UnitySendMessage(GameObject,Function,Params) calls to many C scripts in Unity from Android. Each of these calls performs a specific task like loading an image, creating a text, applying the text font etc. Problem is that the loading of this data right now looks incremental (if that's the right word). So the text is visible first and after a fraction of a second the image shows. Some text effects show later. This looks ugly. How can I make all the UI elements load at the same time even if it takes some time? Is there a way to freeze the scene before each game object is ready to be drawn?
0
Creating a game with in game programmable AI I am looking to make a game where the player can access an in game terminal and then use this terminal to write AI logic in a programming language such as C or C , then they can compile the code and apply the AI to NPC characters. Of course if the code failed to compile error free then it would not be applied to the NPC. Mostly the code would be function calls with a few basic constructs available like int, float, bool etc. My question is how could I achieve this in say Unity or another game engine. Would I need to use a scripting language such as LUA or Python to create the AI or could I be done in real time on a separate thread in Unity somehow?
0
Material is flickering in Unity I'm trying to make a grid like, light up floor using Unity's Shader Graph. However, I am having an issue where the lines are flicking after a really short distance when the camera is moving. The shader graph is below. How can this issue be prevented and what is causing it?
0
In the new InputSystem of Unity, how to detect the keyboard and the mouse "as the same input device"? I'm trying to use the PlayerInputManager of the new InputSystem (preview 7) and my keyboard and mouse are being detected as separate devices. I'm not saying that it is wrong, but it is not useful at all and I would like to know how to fix it. As shown in this video, the PlayerInputManager has the ability of Instantiating new players when they press a button of their controller. This is almost exactly what I need, but it is not perfect. All works fine using controllers but if someone wants to join using the keyboard mouse, "they won't be able". When a key is pressed in the keyboard, a player joins, and when the mouse is used, another player joins (despite the fact that in that game youn need both to control a character and neither one of the spawned characters would be playable). So my question is how can I configure the InputSystem so that only one player joins when either a keyboard or mouse is used and it reads the input from both devices? Maybe it is simply a missing feature, but I think that it would be nice if you could achieve what I want because a lot of times the keyboard is used alongside a mouse. Thanks in advance!
0
Unity Pixel Perfect Camera Adjusting the Viewport Rect? I am trying to make a pixel perfect Tetris style game. I have the pixel perfect component attached and have tried playing with settings such as Crop Frame and Stretch Fill. It seems to override any setting made to the 'Viewport Rect'. The problem here is I want to control where the play area is shown on the screen. For example I want the single player game to be somewhere near centre (although preferrably slightly off to the left). But when they play 2 Player mode I want the P1 playarea to be near left, and P2 area at the right. The screens below shows some of the settings I tried. The 3rd screen shot shows the play area approaching what I want, but I am unable to move it left to right for example (Im unable to move it at all). (Also note, if I try leaving CropFrame and StretchFill unchecked my Camera Size value is also overridden). I even tried to 'extend' the Pixel Perfect Camera class but haven't been able to do that, I'm starting to wonder if this is just a limitation of using this component and perhaps I would need to write my own implementation of the pixel perfect camera to achieve the full control I need. UPDATE Actually I am able to extend the Pixel Perfect Camera class by 'using UnityEngine.U2D'. So far this is what I am trying whilst I wait in hope of further help (It seems like a lost cause extending the class, because I am not sure I can override much from it and cannot see the code. I can't find a way to set the Viewport X or similar). All the best everyone! Thanks for any help.
0
Unity is losing track of changes to Resources I have a Unity project, where I recently changed the names of a few files in my Resources folder. This is relevant because I have code that looks like this internal void LoadItems(string names) var items Resources.LoadAll lt TileBase gt ("Tiles Items") var itemMap items.ToDictionary(m gt m.name.ToUpperInvariant()) items.Clear() items.AddRange(names.Select(n gt itemMap n.ToUpperInvariant() )) The AddRange call is currently throwing an exception, because the incoming data is expecting the new names to be present, but itemMap for some reason still contains the old names. I've verified this in the debugger, and I've verified in Unity's file search that no file matching the old version of the name that's causing trouble here exists anywhere in the project anymore. And yet, when I run the project, (using the Attach To Unity And Run option from Visual Studio,) the old names still show up. If I go into Build Settings and tell it to rebuild the project, this code works correctly... once. Subsequent runs cause it to fail, going back to the old names again, so it kind of feels like Unity is actively trolling me at this point. The old data has to be cached somewhere, but I'm not sure where or how to fix it. Anyone know how I can resolve this?
0
Cost of Unity Local Multiplayer VS Unity Online Multiplayer I know that making multiplayer games in Unity costs money because of the servers that are used in connecting the players. So basically its free upto 20 CCU and then it increases as per the CCU. Its true for the online multiplayer games. But for local multiplayer games(LAN), should it cost the money for using it? Because we converted one of the devices in the local as the server and we don't need their servers. So am I thinking right ?? Or I am going wrong somewhere? Just wanted to be clear about how to make a local multiplayer and not an online multiplayer. Also wanted to ask if Photon supports local multiplayer? Basically I am confused about how to make offline local multiplayer game.
0
SceneManager.GetActiveScene() return 1 when Debugging active scene in editor I'm trying to use the new SceneManagement since Application.LoadLevel is obscelete and I've read that we need to put it like this. using UnityEngine using System.Collections using UnityEngine.SceneManagement public class UI MonoBehaviour private Scene activeScene SceneManager.GetActiveScene() Use this for initialization void Start () Debug.Log (activeScene.name) Update is called once per frame void Update () public void restartLevel() SceneManager.LoadScene (activeScene.buildIndex) The Debug.Log show " 1" and it should be "0" and throw this error in console Scene '' ( 1) couldn't be loaded because it has not been added to the build settings or the AssetBundle has not been loaded. The Scene is added in the build setting too by the way. Seems that it can't return me the good index and even with the activeScene.name, still returns NULL. I miss how Application.LoadLevel was easier and more robust that this new way...
0
Glow shader limited by the texture area I'm working on a glow shader (for 2D engine Futile relying on Unity). It works OK but the effect is limited by the texture area. Except from adding a lot of empty pixels around the textures (which would result in un optimized too big texture atlases), is there a better solution to cope with this problem? I'm quite new with shaders so maybe this is a classic problem with some well known solutions, maybe I'm not searching with the right keywords.
0
Unity UI, how to hide on play I have created a menu on Unity using the built in UI components,I can't create this on a seperate scene because I used the toggle button, which basically when you click it, it spawns a specific object (I have 4 of these toggle buttons). I have completed making the menu on the my current scene. My problem is that when I start on runtime, the menu appears in front of the first person character controller, and when I move the mouse to click the toggle, the camera controller follows the mouse movement. How do I fix this? Also when I click all of the toggle buttons, I want the UI to dissapear, so it isn't shown when I am playing the game because atm when I click the toggle buttons, the actual buttons stay on the screen whilst I am navigating around the scene, is there any way to make this invisible?
0
Directional light causes an FPS drop I have only one object in the scene and it is lit with a directional light. It uses the mobile diffuse shader. The issue is that on iPhone 4 the FPS drops from 42FPS to 11FPS when the directional light is enabled. Rendering is set to forward rendering and there are no other light sources. Shadows are not enabled. Scene stats give a total of five draw calls, 3k tris and 2.6k verts. Having a single directional light should not have that kind of effect on FPS. What could cause this FPS drop?
0
How can I randomly generate objects inside of a Complex Area? In my game, I want to generate randomize enemies inside of this green area that I made with a custom editor tool.
0
Hide move the Particle Effect panel on the Scene view window The problem for example is if I want to drag the particle system object to the bottom right corner of my view, then it goes behind the Particle Effect panel. Is there any way to do hide or move this panel in editor mode and or in runtime mode?
0
camera.render reads a file in the middle of a gameplay Why does camera.render read a file in the middle of a gameplay? This causes a lag in my game
0
How do I make a game object appear on the other side when it leaves the screen? I'm doing an assignment for a course and what's required is to include a moving asteroid in the game that starts moving in a random direction and when the asteroid leaves the bottom of the game window it should re appear at the top of the game window ,so I wrote the script for warping and I applied it to the asteroid and a ship in my game ,then built it to WebGl game. the warping worked fine in the editor for both the ship and the asteroid, while it only worked for the ship in the built game, and I can't figure out what's wrong this is the script (ScreenUtils gives the borders of the screen) float Radius void Start () Radius GetComponent lt CircleCollider2D gt ().radius void OnBecameInvisible() Make the ship wrap Vector3 position transform.position if (position.x Radius gt ScreenUtils.ScreenRight position.x Radius lt ScreenUtils.ScreenLeft) position.x 1 if (position.y Radius gt ScreenUtils.ScreenTop position.y Radius lt ScreenUtils.ScreenBottom) position.y 1 transform.position position
0
How to implement 3d maneuver gear physics in unity? I am trying to create a attack on titan styled game for a school project. I am not new to programming, but I am new to game development. I couldn't find any resources for this, hence I am posting it here. How do I go about implementing 3d maneuver gear physics from attack on titan anime? What is it? In case you don't know, here's a brief link about 3d maneuver gear. A brief commentary about 3dMG It's basically a grappling hook based system (similar to what you would find in a spiderman game), but it has different components to it, which makes it quite complex to think about. My Approach so far I have seen tutorials on how to use hooks in unity and stuff, but it would be great if someone could give me a general idea as to how to even start with this kind of thing. I would appreciate your answer, even though it is not unity specific. The idea is to have two points on the character, from where we fire the ropes. These ropes could simply be graphics (or unity's RaycastHit). And then we would also need information about the hook "hit point". Once we know that, we just reel in ourselves towards that. However the problem is that I don't know how to use momentum etc to effect the character's movement. Also since it's not just one rope(like a spiderman's game), but two, it's even difficult to think as to how would the movement be if user uses only left hook, or right hook or both. Also there is this gas aspect, which would propel you further and it should also be taken into account, along with momentum that we would carry. So any general idea would be greatly appreciated.
0
Should I package and sell my game on the unity3d asset store? I'm trying to figure out if I should refurbish and refactor a game I and some friends have made. It's released on kongregate and wasn't a super hit but I feel there's a lot of interesting techniques and solutions going on that new or intermediate developers would like to see. The only thing that's holding me back is that I don't know if people are interested in it at all. Would you be interested in buying the source code and assets for this game? Check it out and you'll see that there's a lot of things happening in the game. If we packaged it and sold it, we would of course tidy it up a bit which would involve more work so I would really appreciate your honest opinion. We've looked around and haven't found actual released games in the unity3d asset store. Maybe we just didn't look enough though. We're thinking of setting a price tag of between 150 and 200 . What's your opinion on this price? And in general, what's your opinion on selling assets and source code? Should I be wary of any legal implications (like my customer licensing my stuff and then forbidding me from selling it)? I posted this over at UnityAnswers as well but I know I rather go here for gamedev questions so I'm hoping other unity devs will drop by here too. Edit Reconsidering after getting some great advice we'll probably rip out the assets only and market those as space stuff or something. We'll then market the assets with the help of some free classes of code showing off some of the examples that were hard for us to do when we were (more) beginners. The unify wiki might benefit from having some of the code that we've done and that isn't all that hard but a bit tedious. If we actually "finish" the game (it is indeed an asteroids spinoff and was never intended to be anything else, apart from some sandbox modes we've been experimenting with) we'll probably sell it with a decent price tag for an indie game like this.
0
How can I use websockets in a Unity WebGL project? There are plenty of good Websocket APIs for C , but I run into trouble when targeting Unity WebGL due to this restriction described in the Unity documentation No direct socket access Due to security implications, JavaScript code does not have direct access to IP Sockets to implement network connectivity. As a result, the .NET networking classes (ie, everything in the System.Net namespace, particularly System.Net.Sockets) are non functional in WebGL. The same applies to Unity s old UnityEngine.Network classes, which are not available when building for WebGL. If you need to use Networking in WebGL, you currently have the options to use the WWW or UnityWebRequest classes in Unity or the new Unity Networking features which support WebGL, or to implement your own networking using WebSockets or WebRTC in JavaScript. How can I work around this restriction for networking in my Unity WebGL game?
0
Fragment shader coordinates Displacing pixels and texCoord problems I'm trying to create a shader that creates a displacement on an object, slicing horizontally the sprite. These is an example of the atlas I'm using and the effect I'm trying to achieve I tried to achieve this creating a fragment shader, that would read the Y coordinate of the texcoord, and depending on the height, displace it horizontally. But I found two main problems 1) If my atlas had more rows of sprites, I can't really tell at what height I'm drawing the sprite in the fragment shader. Since values of texcoord go from 0 to 1 relative to the atlas being use, the more rows I have, the smaller values should I choose to create the horizontal cut. Is there any way to know the position inside the drawn? 2) The problem is similar to the previous point. When displacing the pixels horizontally, if the displacement is too big, I end up sampling the sprite next to the one being rendered. The idea is for it to loop back the the begining of the sprite. If I had the width of the sprite, I could tell how to do so, but using texcoord alone is just not posible. How can I do this?
0
How to search for a visible player? I've an enemy static tank with a "rotable" cannon turret. I would like to rotate it in the player's direction . How to implement it ? I've thought something like void Update SearchForPlayer() RotateTurret() I don't know how to implement a sort of radar function. Thanks
0
Unity2D Don't Destroy On Load UI button I have a UI button as a child under my background canvas. What I want to do is to save the button through out scene, I tried using DontDestroy OnLoad but It saved ay canvas and everything under my canvas, rather than saving just the button. Anyway this is my DontDestroyOnLoad script void Awake() DontDestroyOnLoad(transform.root.gameObject) Thank you. )
0
Layers in Unity won't drag I'm trying to rearrange my layers in Unity but I can't seem to drag them. When I try to do this I'm in edit layers under the heading sorting layers and I click on the symbol and try to drag it but it won't move. I also tried restarting Unity twice but it won't resolve the problem. Could someone help me with this?
0
Unity IVRRenderModels 006 SteamVR Error I get this Error in Unity when I imported SteamVR "Failed to Load IVRRenderModels Interface Version IVRRenderModels 006" I looked after on it but nothing really solved the problem. Why is this happening and what could be the solution?
0
How do you use SoundManager for multiple player games over the network? I have created a basic sound manager according to this unity tutorial (https unity3d.com learn tutorials projects 2d roguelike audio). However, I need it to work for multiple players over the network, and it doesn't make sense for them all to be playing the same sounds. E.g. If a player loses, it should play the gameover sound, but the other player(s) should remain in the game and continue playing the game sound. But the current behavior is that once a player loses, everyone gets the gameover sound. By the tutorial, I currently use a single instance within the SoundManager class. I think I need multiple SoundManager instances, each associated with a client. What's the best thing to attach the SoundManagers too? Or is there a different best practice for managing sounds for multi player games? Here's the code for my sound manager using UnityEngine using System.Collections public class SoundManager MonoBehaviour public static SoundManager instance null public AudioSource effects public AudioSource music void Awake () if (instance null) instance this else if (instance ! this) Destroy (gameObject) DontDestroyOnLoad (gameObject) public void playSoundEffect(AudioClip clip) effects.PlayOneShot (clip, 1f) public void setBackgroundMusic(AudioClip clip) music.clip clip music.Play ()
0
Raycasting from 3D object to UI canvas! I have a world space canvas in front of the player and I want to shoot a ray towards an enemy (in the direction of the enemy) and create and object where Raycast hits the UI canvas. I know that the physics engine doesn't interact with UI elements and event system is not the answer for me since it depends on pointer events and their position. So how can I do this? If possible, I would like to draw the ray or the line as gizmo to see if it's working. My Current Code is this void OnDrawGizmos() foreach (AeroplaneAiControl item in GameObject.FindObjectsOfType lt AeroplaneAiControl gt ()) Gizmos.color Color.magenta Gizmos.DrawLine(transform.position, item.transform.position) Vector3 Direction transform.position item.transform.position RaycastHit rch Ray r new Ray(transform.position, Direction) Physics.Raycast(r, out rch) if (rch.collider ! null) Gizmos.color Color.cyan Gizmos.DrawLine(transform.position, rch.point) Gizmos.DrawSphere(rch.point, 0.1f) it draws the magenta line but not the cyan line and no spheres.
0
Handling RPG (rocket launcher) launcher and rocket In my game, the player has an RPG (rocket launcher). Using this launcher, he can shoot a rocket. When shown in the inventory, the rocket is stuck in the launcher. Also, when the user walks, the rocket is stuck in the launcher, and the RPG (the combination of launcher and rocket) is placed on his back. Now when the user shoots, the rocket leaves the launcher, and the launcher pulls the player into a little spin to simulate a recoil. Since the rocket and the launcher are stuck together most of the time, I was thinking that I should have a main game object named "RPG" with the 2 meshes "launcher" and "rocket". Most of the time, they would be stuck together. When the user launches the rocket, I would change the position of the rocket in order to simulate it flying away. When it has exploded, I would make the rocket mesh invisible. I was really proud of that plan until I noticed that the recoil will move the rotation and position of the RPG (launcher). Imagine the recoil of a pistol The recoil will cause the pistol (and the hands) go up a bit. Now when I do this with the launcher, the rocket will change its flight path. That would look unrealistic. Can somebody tell me how this is commonly dealt with? Thank you!
0
How to orient hands(or spine) to always look at some target? I am building an FPS game in Unity 3D everything was going cool but when I tried to implement aiming for the rifle everything just broke. 1) I have an IK setup which triggers when you equip weapon, this IK only calculate the hand position and orientation needed to hold the gun and after that the IK system disables itself, basically I am using IK for getting the proper hand position on different guns. 2) Once hands are positioned correctly on the gun then I rotate the hands(or spine, which will rotate hands and head with it) with the mouse to look up, down, right and left. 3) Handgun is very easy to handle, equip it and rotate the arms, arms are almost straight along the z axis so I just rotate them on the y axis to aim upward and downwards. 4) With the rifle, I can calculate the hand position and rotation to hold the rifle easily but (because static animation pose of holding he rifle is little oriented to make the player little realistic) when I rotate arms they rotate weirdly. I checked in the editor by changing the y axis of the rotation and found that only y axis can't rotate the arm the way I want and to rotate it that way other axis must change their values. I searched a bit and found that it is a situation called as Gimbal Lock which is very common with euler rotations, I tried many things but still can't fix it. Original Code leftArm.transform.localEulerAngles new Vector3(leftArm.transform.localEulerAngles.x, leftArm.transform.localEulerAngles.y (currentCamRotX offset), leftArm.transform.localEulerAngles.z) rightArm.transform.localEulerAngles new Vector3(rightArmFPS.transform.localEulerAngles.x, rightArmFPS.transform.localEulerAngles.y (currentCamRotX offset), rightArmFPS.transform.localEulerAngles.z) It works great with Handgun but not with Rifle. I read about and tried following but in vain Method 1 Failed var target camera.GetChild(0).GetChild(0) var direction target.position rightArmFPS.position var toRotation Quaternion.FromToRotation(rightArmFPS.up, direction) rightArmFPS.rotation Quaternion.Lerp(rightArmFPS.rotation, toRotation, Time.deltaTime 5) Method 2 Failed var targetForward target.position spine.position targetForward.Normalize() var rotAxis Vector3.Cross(Vector3.forward, targetForward) var angle Mathf.Acos(Vector3.Dot(Vector3.forward, targetForward)) Mathf.Rad2Deg spine.eulerAngles rotAxis angle What I am looking for now is if someone can point me what topic I should be looking in(because my poor maths skills are really getting me and I often use very poor workarounds for what could be solved easily with maths or physics), pseudo code to get me started or anything that might help me resolving this issue. I know there are bunch of other ways to achieve what I am looking for and I have tried many of them like using IK to position hands and then moving the guns up or down or having animations for each gun aiming up or down but honestly each method has it's own drawback(or its just me who is too noob for these things). I followed this solution Orienting a model to face a target and many others, you might find it duplicate but none of the post on the internet has solved my problem(it is second day and I still can't figure this out). Hope you understood the question and thanks for reading this )
0
Is it possible to use true Blinn Phong lighting on Unity Android IOS? I've noticed that the Unity's Legacy Shaders Specular shader does not work on mobiles due to the lighting model being incompatible. I then tried using the Mobile Bumped Specular shader, but this shader does not support non directional lights. So I tweaked the mobile specular shader to remove the noforwardadd argument, but I noticed that specular highlights are improperly positioned for non directional lights, even after removing the halfasview interpolateview argument. Does Unity even support non directional specular highlights on mobile devices?
0
How to make a fade effect on the Unity's scrollView? I have a basic ScrollView, with some additional scripts so it snaps to the nearest element (focusing on it). When I perform the scroll, it looks like this What I need to achieve is to fade the part which is currently going off the screen. Like when I'm scrolling left, the right panel is coming in, and the left one fading out Is there any built in option for this? I'm opened for any ideas!
0
Hotkeys to toggle draw view in Unity Using Unity (2109.1.3f1) is there a way to switch the scene view's Shading Mode Draw Mode from Wireframe to Shaded? (eg. press 4 for Wireframe, 5 for Shaded) I've looked in the Shortcuts Editor, but "Wireframe" doesn't appear in any list of commands, and I don't see anything under the Scene Visibilty or Scene View Categories that look appropriate either. The docs only describe how to toggle this through the Scene view control bar, but it seems silly that it wouldn't be possible to map that operation to a key combination.
0
Changing CharacterController's height causes jittering issue in Unity As title said changing height of Character Controller causes jittering issue. For example when I reduced the height of CharacterController, it seems CharacterController was floating at each frame and it keeps falling to the ground. Opposite situation has same issue, different is collider is actually already passing the ground so it just push up the object by physics engine. (I saw some similar issue with Terrain, in this case it's worse, it just falling through the terrain) Anyway someone told that I have to change center of CharacterController too, with foot offset(I don't know what exactly that is), so I tried to change the center of CharacterController when resizing height but it still have same problem, nothing different. This is the code that I'm using void Update() if(Input.GetKeyDown(KeyCode.LeftControl)) isCrouched !isCrouched float newHeight isCrouched ? crouchingHeight originalHeight controller.height Mathf.Lerp(controller.height, newHeight, Time.deltaTime smooth) Vector3 newCenter isCrouched ? new Vector3(0, 0.2f, 0) Vector3.zero controller.center Vector3.Lerp(controller.center, newCenter, Time.deltaTime smooth) float newCamPos isCrouched ? origCamPos.y 0.2f origCamPos.y Vector3 newPos new Vector3(cam.localPosition.x, newCamPos, cam.localPosition.z) cam.localPosition Vector3.Lerp(cam.localPosition, newPos, Time.deltaTime smooth) Is there a way to rid off that jittering issue while changing height of Character Controller? Any advice will very appreciate it.
0
Unity AR Ground Plane Detector I need to check a "ground plane" to put objects over it without a marker, using Unity. Right now I'm using Vuforia, but the Ground Plane on Vuforia only works on some devices, I tested on mine and my mother's Android phone, both modern and from different brands, didn't work. So it's not an option, because many many people couldn't use it. Same with ARCore, asked me to install some sort of Google Services AR, which the download is locked for my phone. Is there any way to use Unity with some kind of ground plane detector that many phones can "read" it? Any API, code, anything different that I didn't try yet? Thanks!
0
Does it make sense to export and use skeletal animation as sprites? As tools like Dragonbones, Spine lets you export animations as both sprite atlas and skeleton data (JSON binary), I'm not sure which format to use when importing to Unity. I have few concerns Will there be any differences between the quality of the animations, when imported as atlas vs skeleton data? Any other pros and cons, using one over the other? If I use a sprite atlas, I don't have to depend on a third party runtime though. It is for mobile, so performance is also a concern.
0
Converting shader to ShaderGraph Is there a way to convert the below piece of shader code to shader graph? I am not sure how to find float2(i, i) in shader graph. fixed4 frag (v2f input) SV Target float2 res MainTex TexelSize.xy float i offset fixed4 col col.rgb tex2D( MainTex, input.uv ).rgb col.rgb tex2D( MainTex, input.uv float2( i, i ) res ).rgb col.rgb tex2D( MainTex, input.uv float2( i, i ) res ).rgb col.rgb tex2D( MainTex, input.uv float2( i, i ) res ).rgb col.rgb tex2D( MainTex, input.uv float2( i, i ) res ).rgb col.rgb 5.0f return col
0
Ease Rotate RigidBody2D toward arbitrary angle I'm trying to make a rigidbody2D circle return to an orientation after a collision. But there is a weird behavior I do not expect it always orients to the same direction. This is what I call in FixedUpdate() rotationdifference halfPI rigidbody2D.rotation rigidbody2D.AddTorque (rotationdifference ease) I would expect this would rotate 90 degrees (1 2 Pi Radians) off of the neutral axis. But it does not. In fact it performs exactly the same as rotationdifference rigidbody2D.rotation rigidbody2D.AddTorque (rotationdifference ease) What is going on? How would I be able to set an angle I want it to ease towards, and then have it ease towards it when its not colliding with some other force? Edit For those who want to try this themselves, here is a MonoBehavior. Apply it to a sprite with a rigidbody2D. I have a boxcollider going througha field of pegs like in pachinko. using UnityEngine using System.Collections public class MarchingMovement MonoBehaviour public Vector2 speed new Vector2(50, 50) public float ease 0.01f private float rotationdifference private float halfPI 1.57079632679f Use this for initialization void Start () rotationdifference 3.0f Update is called once per frame void Update () void FixedUpdate() 5 Move the game object rigidbody2D.velocity speed rotationdifference halfPI rigidbody2D.rotation rigidbody2D.AddTorque (rotationdifference ease)
0
Getting the rightmost point of gameobject How do i determin the point on a gameobject that is most to the right (highest x value).
0
How to fold a view from 2 3D cameras in Unity? I need to combine view from 2 or more 3D static cameras. Let's say I have 3 humans standing in line side by side. The first camera is viewing the left person and the left half of the middle person. The second camera is viewing the person on the right and the right half of the middle person. Now I need to see the whole middle person. Any ideas how I can do this? I don't need to see code or some finished implementation, I just need some ideas, because I can not find anything on this.
0
How to get what button was clicked on? Other contexts in which this was done I'm sure have been answered for this kind of problem before. But this has thus far been a 2 week long impasse of wittling down all the other suggestions I've seen and not one has worked. I've got a prefab GUI with a singleton instance based script, which automatically disables itself at the start (I've tried commenting that out to see if that was it). The gui has a title text, body text, and 8 buttons. The script is meant to allow other scripts for interactive objects to safely access it and "start a conversation", using a coroutine. I created a script for the buttons that I attach to each, that when called should set a public bool to true, indicating it was clicked, this bool is polled among the buttons to see which button the user clicked. This is then return to the script which called the GUI, and the GUI closes or waits for the next piece of the conversation. I've set everything to be enabled, and removed anything that disabled the components. I've made sure that the buttons are higher in the hierarchy than everything else, to make sure nothing else was intercepting the clicks. I'm unable to get OnClick, OnMouseOver, OnMouseDown to be called. Debug messages never show. I've tried setting OnClick as part of the GUI where you select a function from the list, and inside of the button's code by adding a listener manually to the button. I've tried IPointerExitHandler, IPointerDownHandler, etc, also never seen anything come back from the methods. I've tried several other methods to date to get which button I clicked, such as ray casting when the mouse button is down and checking the name for the button's name, however it always passes through to the terrain. I've tried getting the button's rect and using Rect.contain with the mouse position to see if the mouse was over the button when clicked, but this never returns true. I'm really interested in seeing a working example where something like this has been done, so that perhaps if that doesn't work, I could at least start hunting down what might be causing a functioning example to fail, as I've no idea what's wrong at this point. Not to vent but this is very frustrating, and I feel it could be made so much simpler. Thank you all for any help you can give, you guys have been very wonderful with my short time here.
0
Why am I getting this "tag not defined" error? In the log, it says UnityException Tag car is not defined. at PlayerController.OnTriggerEnter (UnityEngine.Collider other) 0x00000 in lt filename unknown gt 0 I'm checking against the tag car when colliding, why does this happen? I have tagged the object, see picture below heres some code void OnTriggerEnter(Collider other) if (other.gameObject.CompareTag("car")) error here more code
0
How to make a script's Gizmo toggleable in the Gizmos menu in Unity3D? I've implemented Gizmos for a few behaviours, and I'd like to make them toggleable in the Gizmos menu, just like the built in ones. Is this achievable?
0
How to iterate through the frames of an AnimationClip in editor mode I'm working on a 2D game, using spritesheets as the basis for four AnimationClips. (Every frame from the spritesheet is a keyframe in the animation.) I'm trying to step through the frames of these AnimationClips and programmatically create Collider2Ds which fit the dimensions of each frame. The problem is, I'm having an impossible time actually iterating through the frames. My character has an Animator component, with 4 different states. I've tried various inputs to my editor script, but the closest I've gotten has an AnimationClip as input private AnimationClip clip set in inspector private GameObject targetForColliders set in inspector void createColliders() Animation animation new Animation() AnimationUtility.SetAnimationClips(animation, new AnimationClip clip ) foreach (AnimationState state in animation) do useful things here Unfortunately, somehow the animation local variable is null, crazy as that sounds. I've confirmed that by both logging it and attempting to use it, which causes a NullReferenceException every time. I can't access the Sprite containing the spritesheet directly, because I've made manual adjustments within Unity to the keyframes (removing some, duplicating others) and I don't want to have to manually sync my colliders with the modified assets. Has anyone attempted to do something similar to this before? tl dr What's the easiest way to iterate through the frames of a 2D animation in an editor script?
0
Delete EdgeCollider issue In this program, When i draw a hill, a car can road on it's surface, and when I draw another one, the previous hill should remove. but unfortunately the previous edge collider looks still there. this is what i've done for delete this collider if(col) col.Reset() col null Destroy(col) unfortunately nothing works ) col.enabled false is also doesn't work this is the code i don't know what i have to do to disable the previous collision using UnityEngine using System.Collections using System.Collections.Generic public class LineFreeDraw MonoBehaviour private LineRenderer line private EdgeCollider2D col private bool isMousePressed private List lt Vector2 gt pointsList private Vector2 pointsArray private Vector3 mousePos Structure for line points struct myLine public Vector3 StartPoint public Vector3 EndPoint void Awake() Create line renderer component and set its property line new GameObject("Line").AddComponent lt LineRenderer gt () line.material new Material(Shader.Find("Particles Additive")) line.SetVertexCount(0) line.SetWidth(0.9f, 0.9f) line.SetColors(Color.green, Color.green) line.useWorldSpace true isMousePressed false pointsList new List lt Vector2 gt () void Update() If mouse button down, remove old line and set its color to green if (Input.GetMouseButtonDown(0)) if(col) col.Reset() col null Destroy(col) isMousePressed true line.SetVertexCount(0) pointsList.RemoveRange(0, pointsList.Count) line.SetColors(Color.green, Color.green) else if (Input.GetMouseButtonUp(0)) isMousePressed false Drawing line when mouse is moving(presses) if (isMousePressed) mousePos Camera.main.ScreenToWorldPoint(Input.mousePosition) mousePos.z 0 if (!pointsList.Contains(mousePos)) pointsList.Add(new Vector2(mousePos.x, mousePos.y)) line.SetVertexCount(pointsList.Count) line.SetPosition(pointsList.Count 1, (Vector3)pointsList pointsList.Count 1 ) CarIsCollide() private void CarIsCollide() col new GameObject("Collider").AddComponent lt EdgeCollider2D gt () Collider is added as child object of line col.transform.parent line.transform if (pointsList.Count lt 2) return pointsArray new Vector2 pointsList pointsList.Count 2 , pointsList pointsList.Count 1 col.points pointsArray
0
Unlock levels using coins Unity I'm creating a game that has multiple levels. The first three levels are free but the others can be unlocked either using coins (collected during the game) or through IAP. For the coins, I'm using a binary formatter to store the number of coins. The reason I'm using BF is because it persits through all levels(so far this seems to work as the coin score is carried through to other levels). Here is code I have so far in the coinSystem public class CoinSystem MonoBehaviour public TextMeshProUGUI coinScoreText public int coinScore void Start() LoadScore() public void Save() coinScore coinScoreText.text coinScore.ToString() BinaryFormatter bf new BinaryFormatter() FileStream file File.Open(Application.persistentDataPath quot TotalCoinScore.dat quot , FileMode.Create) CoinContainer coinContainer new CoinContainer() coinContainer.coinScore coinScore bf.Serialize(file, coinContainer) file.Close() public void LoadScore() if (File.Exists(Application.persistentDataPath quot TotalCoinScore.dat quot )) BinaryFormatter bf new BinaryFormatter() FileStream file File.Open(Application.persistentDataPath quot TotalCoinScore.dat quot , FileMode.Open) CoinContainer coinContainer (CoinContainer)bf.Deserialize(file) file.Close() coinScore coinContainer.coinScore coinScoreText.text coinScore.ToString() Serializable public class CoinContainer public int coinScore This is code that I use to add to the coinScore. public class Player MonoBehaviour Rigidbody rb public CoinSystem cs public bool dead true void Start() rb GetComponent lt Rigidbody gt () . . . . void OnTriggerEnter(Collider col) if (!dead amp amp col.gameObject.tag quot Enemy quot ) die() if (!dead amp amp col.gameObject.tag quot Coin quot ) cs.Save() So now in the level select menu, I want to add a button that once clicked should enable the user to unlock a particluar level if he has enough coins. For example, if a level requires 500 coins and the user has 600, then on clicking this button the level is unlocked and the total coins now available are 100. And if the number of coins are less than what is required to unlock a level then the user should not be able to unlock that level. I'm not sure how to implement this.
0
How to set ortho projection model view matrix without a camera? I'm trying to create the correct projection and model view matrix for rendering without a camera. orthoCamera is a camera I set up in the scene view. Using the orthoCamera projection matrix and modelView matrix works but I don't know exactly how to recreate these. My attempt is the commented code. not correct var projection Matrix4x4.Ortho( 512, 512, 512, 512, 0.3f, 1000) var modelView Matrix4x4.LookAt(new Vector3(512, 512, 5), new Vector3(512, 512, 0), Vector3.up) inverse? correct result var projection orthoCamera.projectionMatrix var modelView orthoCamera.worldToCameraMatrix GL.LoadProjectionMatrix(projection) GL.modelview (modelView) This is how I set the camera up in the scene.
0
How can I play an animation in response to an event? I've written a script to play an animation, but it starts immediately as my level loads. Instead, I want it only to start when triggered by some event or after a given timeout. How can I do this?
0
How to find asset by it's number? Don't know what this number means I need to find the asset that is displayed by this number inside my project. I guess this number means "GUID" but it's hard for me to understand what is it. Can you help me guys?
0
I accidently changed the cursor image in Unity In the Unity Editor I accidently changed the image for the mouse cursor in project settings player How can I restore it to the default, preferably not through programming?
0
How do I set the Jump distance and height of my sprite in C I have been able to make my sprite jump for a platformer I am making in unity. I can't seem to be able to make him jump a certain height or distance though, every time he jumps it's like he's jumping on the moon, any suggestions? Here's my code using UnityEngine using System.Collections public class playerScript MonoBehaviour public bool grounded true public float jumpPower 190 public float jumpSpeed 100f private bool hasJumped false Use this for initialization void Start () Update is called once per frame void Update () Do something if(!grounded amp amp GetComponent lt Rigidbody2D gt ().velocity.y 0) grounded true if (Input.GetKey(KeyCode.Space) amp amp grounded true) hasJumped true GetComponent lt Rigidbody2D gt ().AddForce(Vector3.up jumpSpeed) void FixedUpdate () if(hasJumped) GetComponent lt Rigidbody2D gt ().AddForce(transform.up jumpPower) grounded false hasJumped false Any help would be greatly appreciated )
0
Having the same camera in all scenes I have 100 scenes, each scene has a camera, but I want only the camera from scene 1 to exist in each scene that I appear in. I use the function DontDestroyOnLoad() to make the camera exist in each scene but I always find my self with another camera that I don't want. Any ideas? thank you in advance.
0
Unable to Set Up unity remote? I have installed Android Studio and set the path in unity. And I am able to build apks with no problem. But when I try to test in unity remote unity gives an warning as Set up Android SDK path to make Android remote work I don't know what is happening. If Android SDK path is not set then how am I able build the apks. I tried to solutions like enabling usb debugging mode , running unity editor first then opening Unity Remote , installing Google USB driver component of Android SDK but none of them worked for me.
0
How to securely retrieve game stats from clients in a p2p game network? I'm working on a P2P game and I know I should never trust the clients. I my architecture, there is a "Master Server" that stores game room (host) informations. Players can create their own rooms (hosting) and play with together. There is another server that is "Info Server", it stores character informations like inventory, level etc. Now, I need to make a stats table with kills deaths and I have to get these kill death events from host player (host player event master server). But I think host player can send a lot of kill events because it is authoritative, so master server will process handle all events from the host player. How can I trust these events? Can't a server just send fake kill death events?
0
Changing alpha of Sprite I'm using OnGUI to draw a rect when I "box select" or "drag select". The texture that gets drawn is a PNG file made in Paint.Net with the opacity alpha channel set quite low. In Unity however, when I go to box select, the texture is completely opaque. How do I get Unity to honor the alpha set in Paint.Net? I also wouldn't mind using Unity itself to adjust the opacity, but I haven't found such an option in the import texture part of the inspector.
0
Questions about Jrpg NPC events (Unity C ) So, I'm trying to wrap my head around something. I've got my basic quest system up and running for my rpg style game. Right now I'm taking a look at NPC events and triggers that as I see it have two distinct styles The classic floor panel trigger that rpg maker uses or have a listener class for quest active event active My questions are thusly what's the best way to go about activating the event and what's a good way to define the event? Like set movement patterns etc would it be feasible in json? Or should I use scriptable objects?
0
How can the Server send a message to a single Client? I'm trying to send an Rpc, or any sort of message, to a specific client instead of to them all. I'm completely at the loss trying to associate a NetworkConnection with its own authoritative spawned player (from playerPrefab). If I let the NetworkManager auto spawn it, then I don't know how to get the connection from the player object. If I override OnServerReady and I spawn it myself, then it has no authority on the client and I don't know how to give it. I've browsed all sort of documentation but I couldn't find anything useful. Obviously there must be a way to do that, but I really can't find it.
0
How can I make an object move in a certain direction depending on its spawning point? I'm currently developing a 2D game and I couldn't find a way to figure this out. In the game, I have 4 different balls and 4 different spawning points. Every 2 seconds, a random ball spawns at a random spawning point. What I want to achieve is, as I tried to describe above, lets say a ball spawns on right side, I want it to move towards left, if it spawns upside, I want it to go downwards etc. Here is my spawner code using System.Collections using System.Collections.Generic using UnityEngine public class Game MonoBehaviour public Transform spawnPoints public GameObject balls public float timer 2.0f void Update() timer Time.deltaTime SpawnBalls () void SpawnBalls() int spawnPoints num Random.Range (0, 4) int balls num Random.Range (0, 4) if (timer lt 0) Instantiate (balls balls num , spawnPoints spawnPoints num .position, spawnPoints spawnPoints num .rotation) timer 2.0f And here is my ball movement code using System.Collections using System.Collections.Generic using UnityEngine public class Balls MonoBehaviour public Game game public float speed 0.25f void Start () game FindObjectOfType lt Game gt () void Update () Some if statement transform.Translate (Vector3.left Time.deltaTime speed) else if transform.Translate (Vector3.up Time.deltaTime speed) else if transform.Translate (Vector3.right Time.deltaTime speed) else if transform.Translate (Vector3.down Time.deltaTime speed) I've tried giving spawnpoints tags and creating if statements with gameObject.tag and stuff but couldn't find a way to work it. How can I make it check which spawnpoint the ball spawned at so I can make it move accordingly? Thanks for help.
0
Have several classes with a common interface, but still able to access MonoBehaviour methods through that interface? In our project we used to have a PlayerObject class and then Unit and Building derived from that class. We recently started taking a look at Bolt, which requires classes that define objects that may have different states to inherit directly from a Bolt class. So Unit and Building can no longer inherit from PlayerObject. This turns out to create a few problems, a significant portion of our game uses PlayerObject rather than Unit or Building to perform actions that are the same for both. Separating them would really throw a wrench into the program, since you now have to have methods that use both Unit and Building instead of just PlayerObject. I thought making a common interface IPlayerObject, and defining common properties and methods in the interface and making Building and Unit both derive from IPlayerObject would do the trick. I did not think it through enough and came to find out that if I use IPlayerObject I can no longer access MonoBehaviour methods and fields (such as transform, or render). Can I make this in such a way that I can use the IPlayerObject type, with a Unit or Building type and still have access to MonoBehaviour through that interface? If not, is there a proper way to do this, past just adding in extra methods to handle Unit and Building types separately.
0
RTS Unit AI When to let the unit stop (due to local avoidence) I am developing an RTS like game, that have units that move and attack. I implemented path finding and local avoidance. One problem is when multiple units being ordered to the exact same position, they can never reach the position due local avoidance and collision. Only this will make the units scratch each other, this will also cause the unit not able to STOP, as the unit might be still far from the target position. And whether stopped or not is important for battle (unit can only attack when stopped). I studied how SC2 handles this, it appears that the units will stop after a few seconds of scratching. PS, I have used group formation to avoid the situation, but it can not be avoided, when the group are ordered to goto some impossible position, and they would cluster at the edge of the valid navmesh.
0
How to handle assets in Unity? Here's what I have in our little Unity game If an asset (mostly a prefab or a texture) has to be accessed (e.g. to instantiate a game object), it is often passed as SerializeField to the script component. Scripts that are not components get their assets through the constructor so the assets are passed down until the class where they are needed. It's ugly. If a lot of assets are needed (like textures of an animation), they are moved into a folder called "Resources" and accessed through the Resources class. The documentation explicitly says "don't use it". What I want To access assets through a name or path to create objects at run time. What I found The AssetDataBase class looked promising until I couldn't locate it and found out it is deprecated (and the documentation does not tell how to replace it). Nothing on Google but a lot of outdated things Asset bundles look promising too, but they are quite complicated and there are no really good migration tutorials and I don't know how to use them. Any suggestions? How do small mid sized bigger Unity games handle their resources?
0
How can I create a precise touch in Unity Is there a way so that I can touch an object precisely? I have these aerial cars and there pretty tiny like 32 by 32 and it's hard to touch them using a raycast. I thought I'd spawn an object with a circle collider on it on the first touch and destroy it after the touch.
0
How do I pause play animation in Unity without the animation getting cut off I'm trying to achieve a common game behavior that when you hit an enemy, then whatever the enemy's action (animation) is, when the hit happens, the enemy pauses a bit, then continues with the animation. So everytime you hit the enemy, the enemy pauses for a bit. I currently have this code IEnumerator StopStartMotion() animator.speed 0 yield return new WaitForSeconds(.2f) animator.speed 1 Problem is, sometimes, when I hit too early in the enemy's animation (like at the beginning of a punch), the enemy pauses, and then doesn't continue the animation where he paused for a bit. Is there a better way of doing this? I tried animator.enabled as well, but the animation also jumps.
0
Artifacts in unity shading I created block of 3x3x3 cubes, disabled shadows, set directional lighting color to white and ambient to black. And I'm getting this Any idea what is going on and how to fix it? Effect is visible when object isn't moving but with a lot less artifacts. It doesn't matter what is moving, camera or cubes. I would guess that this is precision problem but is there anything that can be done about it? EDIT Here is a screenshot of cubes Also this is how it looks after static batching (this happens because of Lightmap Static in Mesh Renderer is on)
0
Is the Microsoft recommendation to use C properties applicable to game development? I get that sometimes you need properties, like public int Transitions get set or SerializeField private int m Transitions public int Transitions get return m Transitions set m Transitions value But my impression is that in game development, unless you have a reason to do otherwise, everything should be nearly as fast as possible. My impression from things I've read is that Unity 3D is not sure to inline access via properties, so using a property will result in an extra function call. Am I right to constantly ignore Visual Studio's suggestions to not use public fields? (Note that we do use int Foo get private set where there is an advantage in showing the intended usage.) I'm aware that premature optimization is bad, but as I said, in game development you don't make something slow when a similar effort could make it fast.
0
How can I reduce the size of bundled Unity DLLs on Android? I have created a simple project (I am a Unity beginner) for Android but the apk size is around 18 MB! I checked the documentation. One way to decrease the apk size is to check the editor log. Then I discovered that imported DLLs have a size of 3.9MB. I only used UnityEngine and Collision packages. So how can I avoid to import the other big DLLs?
0
Generate 4 vectors rotated in cardinal directions from a central vector There is some unit vector, which is a coordinate in a spherical space. It is necessary to obtain from it 4 vectors diverted in different directions (right, left, forward, backward) by a certain number of degrees. For these actions I use the following code Vector3 center point Vector3 left Quaternion.Euler( 30, 0, 0) center Vector3 right Quaternion.Euler(30, 0, 0) center Vector3 back Quaternion.Euler(0, 0, 30) center Vector3 front Quaternion.Euler(0, 0, 30) center The problem is that this works when point is equal or close to Vector3.up. When deviating from the vertical position, the lateral vectors begin to "stick together". Here is a visualization of what I need Test code is attached using System.Collections using UnityEngine public class Test MonoBehaviour public GameObject centerGO public GameObject leftGO public GameObject rightGO public GameObject backGO public GameObject frontGO ArrayList list new ArrayList() void Start() SetCenterPoint(Vector3.up) void Update() DrawDebugRays() Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit)) SetCenterPoint(hit.point) void SetCenterPoint(Vector3 point) Vector3 center point Vector3 left Quaternion.Euler( 30, 0, 0) center Vector3 right Quaternion.Euler(30, 0, 0) center Vector3 back Quaternion.Euler(0, 0, 30) center Vector3 front Quaternion.Euler(0, 0, 30) center centerGO.transform.position center leftGO.transform.position left rightGO.transform.position right backGO.transform.position back frontGO.transform.position front list.Clear() list.Add(center) list.Add(left) list.Add(right) list.Add(front) list.Add(back) void DrawDebugRays() for (int i 0 i lt list.Count i ) Color color Color.red switch (i) case 0 color Color.green break case 1 case 2 color Color.blue break Debug.DrawRay(Vector3.zero, (Vector3)list i , color)
0
How to pass an argument with ref keyword to a local funtion how to work around it? Unity 2019.3 I am writing a few extension methods to make my life a little bit easier, but this one is bogging me down. I am loading stuff with Unity's Addressable system, and I would like use it by extension methods. I am passing in my variables (reference type amp value type, doesn't matter) to my extension methods, hoping to set them and and hide some complexity and source of bugs, and errors. It seems to me they are passed by value, because when I am trying to use them outside the extension methods, they are not set, null, etc. Not working. There is a callback called Completed, and I am subscribing with a lambda expression... I tried with the ref keyword, but obviously the compiler is yelling, that she doesn't want to pass my ref, out whatever parameters to local functions... ( I tried it out with no local functions, and it did not work without the ref keywork, but it did with it! You get the idea! Please see my code below! This is the one that I can't get to work... Trying to set the generic variable data from the Addressable assetref public static void TryLoadData lt T gt (this AssetReference assetref, T data) var handle assetref.LoadAssetAsync lt T gt () handle.Completed loadedresult gt T result loadedresult.Result if (result null) return data result This one does, but only with ref... Setting the generic data parameter to the parameter g. public static void SwapTest lt T gt (this T g,ref T data) where T class gt data g I am not sure if there is a workaround, I thought of pointers, or global variables, but not sure which one is the right way to go. Thanks
0
How to make UI image bounce back and forth inside another UI image? I've been trying to create a battle system for my game, and I've been trying to get a UI image to bounce back and forth inside another image, but for some reason, the UI image goes out of the other UI and bounces back, like so Here's the script I add to the moving arrow image, in order to make it bounce using System.Collections using System.Collections.Generic using UnityEngine public class JumpSystem MonoBehaviour private Vector2 startPosition public int speed Start is called before the first frame update void Start() startPosition transform.position Update is called once per frame void Update() transform.position new Vector2(startPosition.x Mathf.Sin(Time.time speed), transform.position.y) Is there any way I can prevent this incident from occurring? Please help me understand this and thank you in advance.
0
Can I use trilinear filtering for my sprites, but keep their outlines unfiltered? Suppose that I have two images of equal size. They both contain a square https i.stack.imgur.com BI62X.png https i.stack.imgur.com Nev5Z.png When overlapped, both squares will appear next to each other. If both images use Point (no filter), they will contact without issues regardless of the amount of zoom or scale If you use either Bilinear or Trilinear, there will be an artifact visible in certain zoom scale levels Of course, that is to be expected from the very nature of the filters. As much as I would like to just leave it at Point (no filter), my game looks far better using Trilinear instead except of course, for the "borders" or points of contact. The ideal scenario for me as bizarre as it may sound, is to be able to use Trilinear filtering generally, but force the "outlines" of my sprites to stay as if they were Point (no filter). This way, my game looks painterly when zoomed in out (the game isn't pixel art), and I also avoid the "glitch" in specific contacts. Yes, the glitch is only noticeable if you use a scale zoom that is higher than 100 . Unfortunately, due to the nature of the game, the player should be able to zoom in out if they desire, so I can't just pick "the" ideal camera size or sprite scale because it can't be constant. I've tried using Canvas and its Pixel Perfect checkbox to no avail. I didn't really expect that to work though. What can I do to achieve the desired effect, then?
0
LineRenderer sorting order lines always in front of everything I have 3 cameras and 3 canvases. Back Camera depth 5, Back Canvas Sorting layer BackLayer, Camera depth 0, Middle Canvas Sorting layer MiddleLayer, Camera depth 10, Front Canvas Sorting layer FrontLayer, Orders in canvases are also set (for SpriteRenderers, images, ui etc.) Back is for a background image and stars, middle for mountains and front for the UI. Everything is working perfectly with one exception No matter where I draw lines with a LineRenderer they're always at the front of everything (each canvas). The one situation where the line moves deeper is when I set it's points Z to some huge values like 30000 and then they're just behind everything. My goal is to place these lines along with the background image and stars on the BackLayer or BackCanvas. What I've already tried Setting LineRenderer sorting layer and it's order from the code. I read somewhere on Unity forums that lineRenderer has to have a special material for this to work but I tried most of them not working. I also tried setting their positions manually, from the inspector, from the code, incrementally in the Update() method they're always in front or complately hidden (with huge numbers mentioned above). I tried assigning them to different canvases (back, middle, front) as children didn't work too. On Unity forums I also read a post which says that we shouldn't use sorting layers with linerenderer and use only Z positions. If someone has any experience with this, I would be grateful. I really have no idea if I'm doing something wrong or what.
0
How do I blink a sprite a few times before it disappears? I need the 3d poop emoji model in the chest on the right to blink, visible invisible visible, several times This is a 3d gameObject oriented to face the camera, shaded with an unlit material. I need the object to "blink flash" to indicate that the item has been obtained. The object needs to be generated the moment the lid opens (done), stay unchanged until the lid pops all the way up (0.2 seconds), and flash 3 times during the 0.6 seconds the lid is up. The object is destroyed the moment the lid starts to come down again. My code (blinking flashing is not working) using System.Collections using System.Collections.Generic using UnityEngine public class ItemBox MonoBehaviour bool disabled false private Animator anim public GameObject item null void Start() anim GetComponent lt Animator gt () if (!disabled) anim.Play("ItemBoxIdleState") Update is called once per frame void Update() void OnTriggerEnter (Collider other) if (!disabled amp amp other.gameObject.tag "Player") anim.Play("ItemBoxGetItemState") GameObject itemClone Instantiate(item, transform.position new Vector3(0, 0.5f, 0), Camera.main.transform.rotation Quaternion.Euler(0,180,0)) Blink(itemClone) Destroy(itemClone) disabled true IEnumerator Blink(GameObject obj) Renderer objRenderer obj.GetComponent lt Renderer gt () objRenderer.enabled true yield return new WaitForSeconds(0.2f) for (int i 0 i lt 3 i ) objRenderer.enabled false yield return new WaitForSeconds(0.1f) objRenderer.enabled true yield return new WaitForSeconds(0.1f) Instead of blinking flashing, the object is just there, doing nothing.
0
Is database necessary? Hi I have studied c for good few months and I'm at intermediate level at the moment. And few days ago I decided to make simple 2D Games like "Mr Jump" after studying Unity. So my question is as follow 1)Should I study database to make simple mobile games? and if so what would be good language to study? 2)And if you have played "Mr.Jump", can you tell me if that game required complicated database coding and a lot of knowledge? 3)Also when we play the game, our best score and new characters get saved in our phone. Is that something to do with database? 4)Could tell me examples of database in games? 5)Should I study database as much as c ?
0
How to check if gun may shoot again (because animation has stopped playing)? When the user presses the fire button, I set a trigger animator.SetTrigger( quot HG Shoot quot ) This trigger causes a quot pistol shoot quot animation to be played. The gun should only be able to shoot again as soon as the shoot animation has finished. I could check at each Update() if that certain animation is still being played like this bool isAnimationStatePlaying(Animator anim, int animLayer, string stateName) if (anim.GetCurrentAnimatorStateInfo(animLayer).IsName(stateName) amp amp anim.GetCurrentAnimatorStateInfo(animLayer).normalizedTime lt 1.0f) return true else return false But I don't like the frequent checks. I would rather like to have a variable to would be set by the animator. Or I would set it at the beginning of the shoot animation. Because there are other animations that I have to check that would disallow shooting of the gun, too, like reloading the gun. This would make everything even more complicated. How can I solve this problem?
0
prefab editor not working for NGUI in unity2018 i just updated my project from unity5 to unity 2018. my project uses ngui as UI solution. eveything works fine in updated version but when i want to edit prefabs in prefab mode i get this message is there any idea about cause of this problem and how to solve it? i looked for updating ngui for unity 2018 but because of many changes ngui has, it causes lots of problem in project that takes lots of time to solve the mall
0
How would I find the SDK folder for Android Studio so I can build my Unity project? So I've been trying to build my unity project for android, but my problem is that I don't know how to find the Android SDK. I have the old developer bundle installed, when it was still the one with eclipse, but this version is not supported by Unity. So, I installed the latest version of Android Studio, the new official Android IDE, but the SDK folder is not in the same place as the rest of the program. How would I find the SDK folder for Android Studio so I can build my Unity project?
0
Specify the size of the points when building a mesh based on a point cloud I create a mesh in Unity3D based on a point cloud in this way The standard sequence for creating a mesh Mesh mesh new Mesh() Vector3 points new Vector3 numPoints int indecies new int numPoints Color colors new Color numPoints Fill in points, indecies, colors mesh.vertices points mesh.colors colors mesh.SetIndices(indecies, MeshTopology.Points, 0) I learned that it is possible to set the size of points in PSIZE through Vertex Shader. Applied such a Shader, but without result. Shader "VertexColor" Properties PointSize("Point size", Float) 5.0 SubShader Pass LOD 200 CGPROGRAM pragma vertex vert pragma fragment frag uniform float PointSize struct VertexInput float4 vertex POSITION float4 color COLOR struct VertexOutput float4 pos SV POSITION float4 col COLOR float size PSIZE VertexOutput vert(VertexInput v) VertexOutput o o.pos UnityObjectToClipPos(v.vertex) o.col v.color o.size PointSize return o float4 frag(VertexOutput o) COLOR return o.col ENDCG Tell me, please, how to set the size of points correctly?
0
I need to keep music playing but still be able to mute it between games, how? I have a game built in Unity. The game plays music continuously, which can be muted on button press on the scene. This works fine using the below code MuteButton.cs using UnityEngine using System.Collections using UnityEngine.UI public class MuteButton MonoBehaviour public GameObject audioObject private AudioSource audioSource void Start() Button b gameObject.GetComponent lt Button gt () b.onClick.AddListener(Pause) void Pause() Debug.Log("mute toggle") audioSource audioObject.GetComponent lt AudioSource gt () if(!audioSource.isPlaying) audioSource.Play() else audioSource.Pause() However, when the player loses the game restarts by reloading the scene, using this code public void Restart() SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex) In order to keep the music running I have attached the following script to my music game object using UnityEngine using System.Collections public class Music MonoBehaviour static Music instance void Start() if(instance null) instance this DontDestroyOnLoad(gameObject) else if (instance ! this) Destroy(gameObject) All working fine up until now. Once the scene is reloaded when the user tries to mute the music I get the following 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. I understand that the error is that I'm trying to mute a now non existent game object, but how can I pause the music if this is the case?
0
How do i move a 2D object with angle and speed variables in unity? I want to move an object with a certain angle and speed, is there a was to set this as an initial velocity so that it is still possible for the object to collide and bounce of other objects using its rigid body?
0
Creating outline from a collection of points following the concavity I am trying to create an outline from a collection of points. I found this solution for Convex Hull. I specifically picked this implementation https en.wikibooks.org wiki Algorithm Implementation Geometry Convex hull Monotone chain Edit I can't find an algorithm that will find the concavity of the region specified in green. The yellow line is the Hull from the algorithm amove I have the point is defined as Serializable public struct Point IComparable lt Point gt , IEquatable lt Point gt public int X public int Y public static int Cross(Point o, Point a, Point b) return (a.X o.X) (b.Y o.Y) (a.Y o.Y) (b.X o.X) Here is the implementation of the algorithm public static List lt Point gt ConvexHull(List lt Point gt points) if (points null points.Count lt 3) return points var size points.Count var k 0 var hull new Point 2 size points.Sort() build lower hull for (int i 0 i lt size i) while (k gt 2 amp amp Point.Cross(hull k 2 , hull k 1 , points i ) lt 0) k hull k points i build upper hull for (int i size 1, t k 1 i gt 0 i) while (k gt t amp amp Point.Cross(hull k 2 , hull k 1 , points i 1 ) lt 0) k hull k points i 1 var result new List lt Point gt (hull) if (k gt 1) result.Resize(k 1) remove non hull vertices after k remove k 1 which is a duplicate return result
0
Unity Ambient Occlusion artefacts When I create two cubes from Unity Component menu. And turn on AO the bottom cube is not shaded properly. I mean the upper cube is alright but the bottom cube does not have any shadow present. What am I doing wrong ? Lighting setup Result
0
How can I add array of components to a new gameobject? I use Getcomponents to get all components from existing gameobject Component components go.GetComponents(typeof(MonoBehaviour)) And I want to add them now to another gameobject for (int i 0 i lt components.Length i ) var comp components i newObject.AddComponent lt comp gt () components is type Component But when I try to type components inside the AddComponent lt the variable components not exist. Tried then to make the comp variable but can't type it inside the lt either.
0
Animation imported from Blender into Unity via FBX doesn't play? I started building this model in Blender and gave it a simple animation that rotates the board about the axel. ...I exported it as FBX and imported it into Unity. I can see the animation is stored in the file when I import, but I can't find an animation file after I drop it in the scene, and there is no controller for the Animator controller it generated, either. I can watch the animation play in the FBX preview thumbnail but nowhere else. How can I get my animation working?
0
Quaternion.slerps resets camera rotation to (0,0,0) when i go to play mode help! i am building a camera rotation script like in fps. Everything is setup and working except that camera rotation resets to zero at the start of game which i dont want. This is the camera rotation i have set This is rotation of character my script is attached to And after hitting play it resets camera rotation to (0,0,0). i want it to remain how i have set it in inspector. i am using quaternion.slerp to rotate camera around to rotations on the basis of touch inputs. After reset to (0,0,0) everything works fine.please help, i have always had a hard time understanding quaternions. this is the script public class ScreenCharacterController MonoBehaviour private Camera mainCamera private CharacterController character private int leftFingerID 1 private int rightFingerID 1 private Vector2 leftFingerInput private Vector2 rightFingerInput private float xAxisRotation private float yAxisRotation SerializeField private float minXRotation SerializeField private float maxXRotation SerializeField private float minYRotation 25f SerializeField private float maxYRotation 25f SerializeField private float cameraRotationSpeed 20f void Start() mainCamera Camera.main void Update() for touch TouchInput() for calculating rotation vaues CalculateAndClampRotation() RotateCamera() void TouchInput() foreach (Touch touch in Input.touches) if (touch.phase TouchPhase.Began) Left Touch if (touch.position.x lt Screen.width 2) leftFingerID touch.fingerId Right touch else rightFingerID touch.fingerId else if (touch.phase TouchPhase.Moved) Left Touch if (touch.position.x lt Screen.width 2) if (leftFingerID touch.fingerId) Right touch else if (rightFingerID touch.fingerId) rightFingerInput touch.deltaPosition Time.smoothDeltaTime else if (touch.phase TouchPhase.Ended touch.phase TouchPhase.Canceled) if (touch.fingerId leftFingerID) leftFingerID 1 else if (touch.fingerId rightFingerID) rightFingerID 1 rightFingerInput new Vector2(0, 0) void RotateCamera() Quaternion currentRotation mainCamera.transform.localRotation Quaternion targetRotation Quaternion.identity targetRotation Quaternion.Euler((mainCamera.transform.localRotation.x yAxisRotation), (mainCamera.transform.localRotation.y xAxisRotation), 0f) mainCamera.transform.localRotation Quaternion.Slerp(currentRotation, targetRotation, 0.5f) void CalculateAndClampRotation() xAxisRotation rightFingerInput.x cameraRotationSpeed yAxisRotation rightFingerInput.y cameraRotationSpeed xAxisRotation Mathf.Clamp(xAxisRotation, minXRotation, maxXRotation) yAxisRotation Mathf.Clamp(yAxisRotation, minYRotation, maxYRotation)
0
Unity editor, horizontal line in inspector How to draw a horizontal line in the inspector like on the reference image? Kind of separation line.
0
Unity Ragdoll Colliders don't collide I have a humanoid character with Ragdoll setup in Unity. However the box capsule colliders on the various parts of the body don't collide with other static geometry. They do collide with the ground but not with any other static meshes. Is it possible to use them as colliders towards static meshes and what do I need to do for it to work?
0
Is it legal to sell or monetize games created with the Unity 3D free edition? Is it okay to use Unity 3D programming and gaming software to create mobile game apps for Android and iOS? I am using a free version of Unity 3D and planning it to sell my current game app I've created by publishing it to Google Play. I also use this method for earning money by setting as a free app with ads on it. I saw some developers relied on using free version of Unity 3D to create games and published it via App Store or Google Play. If it does, should I have to pay or share contribution to the Unity development team for earnings since I use the free version in order to rely for producing several game apps for business?
0
Unity3D terrain object's textures flickering on long distances I'm making RTS project on Unity3D. I created terrain with Unity's standard Terrain tool, and added textures of grass, mood etc. on it. Then, for creating "man made" objects of terrain (roads, sidewalks, road curbs etc) I'm created this objects in separate assets, and placed on terrain. And I have one issue with this solution. On moving camera away from the terrain, terrain's texture(e.g. mood) are flickering under roads, sidewalks and other objects. AFAIK, this bug caused by insuficcient accuracy of floating point coordinates in Unity3D engine (?). Now, as I concerned, my approach to creating terrain objects is not correct. I must create one mesh with terrain, and all manmade objects in 3D modeling software, and then create UV map for texturing all of it. Is this approach correct? If "yes", is any special approach for modelling and texturing so large and complex object as terrain?
0
How to put virtual hands in front of player? I want to have the VR hands always in front of the player. This works while walking forwards backwards, once I rotate the camera they stay in the same place. I know that I need to take the camera facing into account, but I am missing the math here. Here is the code for hand translation rotation void Update() if (UnityEngine.XR.XRDevice.isPresent) GameObject player GameObject.Find("PlayerGameObject") if (hand WebVRControllerHand.LEFT) transform.position UnityEngine.XR.InputTracking.GetLocalPosition(UnityEngine.XR.XRNode.LeftHand) player.transform.position transform.rotation UnityEngine.XR.InputTracking.GetLocalRotation(UnityEngine.XR.XRNode.LeftHand) if (hand WebVRControllerHand.RIGHT) transform.position UnityEngine.XR.InputTracking.GetLocalPosition(UnityEngine.XR.XRNode.RightHand) player.transform.position transform.rotation UnityEngine.XR.InputTracking.GetLocalRotation(UnityEngine.XR.XRNode.RightHand) Update Having no movement implemented, looking around will make the hands always appear in front of the camera. If I add this code to the camera object, it will break so the hands never leave their original space(they still move when I rotate the controller but they stay in the same place) Script is attached to the parent of the hands public class SimpleMovement MonoBehaviour void Update() var x Input.GetAxis("Horizontal") Time.deltaTime 150.0f var z Input.GetAxis("Vertical") Time.deltaTime 3.0f transform.Rotate(0, x, 0) transform.Translate(0, 0, z) Update 2 It seems like I got it partially working. At least for translation movement. I set the position only according to what comes out of the XR framework, now I add the player's position on top(previously I did this at the wrong spot). What is missing now is rotating the camera with the sticks seemns different than rotating the camera with the headset. So the hands still do not respond to rotation movement of the sticks.
0
How can I get Unity to do letterbox pillarbox to maintain aspect ratio? I'd like my game to have the same aspect ratio at all cost, including keeping all UI elements fixed in the same place. I'm totally ok with losing screen space in the interest of fixing the aspect ratio.
0
How to set up the camera for a PS Vita game? I am starting my first project for Unity and I want to start a new game for PS Vita. This console has a resolution of 960x544 pixels. How do I have to set up my camera so that it adapts to this aspect ratio?
0
Unity2D Floor tiles moved or missing I'm following the 2D Roguelike tutorial, which can be seen here. I don't want to get fancy, just follow the existing steps. I've reached the part where all it's supposed to do is draw the playfield. But it looks like this and I don't know why. Some of the floor tiles are appearing beyod the outer wall, and others are missing (or maybe they're stacked on top of other tiles). (EDIT I discovered that the "missing" tiles are because I had the sprites in the wrong layer, and fixed them. I still have several appearing to the left of the outer wall, though.) I tried to debug it in Visual Studio. The plan was to step through it line by line to see how the tiles are put down, but the debugger doesn't show the playfield until the whole thing is complete.
0
Mip Maps on 2D Sprite causing black line above. Why is this? I am new to Unity. I'm trying it out and using Futile for a code first approach, but still importing textures using the Unity system. The problem I'm having is that when I use mip maps to scale large sprites down to smaller sizes without jagged edges, I'm getting a black line artefact above said sprites. A little hard to see, but they're there. If I turn down the resolution, you can clearly see them These are my texture settings My question is, why are these black lines here? Is it a mistake I've made? Is it just a common side effect? How can I reduce these? Also, if this is the wrong approach, how can I use smooth sprites in a game with the ability for them to scale up smoothly? Thanks!
0
How can I my homing missile avoid walls (2D)? Okay, I have the homing missile implemented. It will follow the player, but I want it to avoid the walls. I tried out A but I want to make my own. I need some help plzz.
0
Quat.AngleAxis broken on one axis I have a scene in my game where you create your own designs by placing static meshes and manipulating their scales, positions, and rotations. For the rotations I'm using Quaterion.AngleAxis as so if (toolMode PositioningTool.Rotate) switch (grabbedCollider.transform.name) case "X" focus.localRotation Quaternion.AngleAxis(delta.x 90 Time.deltaTime, transform.right) break case "Y" focus.localRotation Quaternion.AngleAxis(delta.x 90 Time.deltaTime, transform.up) break case "Z" focus.localRotation Quaternion.AngleAxis(delta.x 90 Time.deltaTime, transform.forward) break where delta is the mouse movement for that frame, focus is the object I am manipulating, and transform is the transform component of the ToolArm that the player interacts with. toolarm.position is set to focus.position every frame my problem arises when I try to do a rotation on my x axis. my other axis will spin 360 and beyond, spinning in circles endlessly. when x axis is used, it only rotates from 90 to 90 (as seen in the unity editor). What am I doing wrong?
0
Setting up a shader for RTS construction grid visibility (around cursor) I've set up a shader, thanks to the good help of DMGregory over at Draw animating grid with terrain deformation and variable colors here's what I got so far here's what it's supposed to look like here's what my shader code looks like as it stands forgive my non 2K screen it's only a 1080p but this is the full shader. here's each bit in isolation here's the main options for the node If I set surface to transparent... I get a much better result yet still not what I want because the grid area fades out immediately instead of staying at the center of the cube also the corner clearly has a green and red line overlap when line should only ever be red or green. this is the mock file that I'm currently using for buildable and non buildable area it's 256x256 (the size of my map) for now because I want to start small (where 1px maps to one unity square on the terrain of 1 unit) before I move on to the real deal which should be a 3584x3584 Texture 2D (where 1px corresponds to 1 14th of a unity unit). I want my grid to be 1 14th of an digit. eg cell one is (in diagonal) from (0.0f, 0.0f) to (0.14f, 0.14f). I've got preliminary code which will serve to generate this texture 2D programmatically editable2DconstructibleMap new Texture2D(256, 256, TextureFormat.RGBA32, false) constructionGrid GameObject.FindGameObjectWithTag( quot GridViewer quot ).GetComponent lt MeshRenderer gt () fill texture color corresponding to navMesh for (int x 0 x lt editable2DconstructibleMap.width x ) for (int y 0 y lt editable2DconstructibleMap.height y ) NavMeshHit hit if (NavMesh.SamplePosition(new Vector3(x 1.0f, 0f,y 1.0f), out hit, 1.0f, NavMesh.AllAreas)) editable2DconstructibleMap.SetPixel(x, y, Color.white) else editable2DconstructibleMap.SetPixel(x, y, Color.black) constructionGrid.sharedMaterial.SetTexture( quot BuildableMask quot , editable2DconstructibleMap) Here I'm using the navMesh which itself is automatically generated based on terrain slope. I target each point of the map and see if it falls in or out of the navmesh. Instead of redrawing this texture 2D when a building is placed and placement becomes impossible. I think I'll simply programmatically edit the 2D texture to add the new black pixels whilst the navmesh will be updated independently. Anyways, I guess the green red overlap issue comes from my texture2D being currently too small, but if I don't know yet what one pixel corresponds to, I'll have trouble getting this right. Update so changing the texture to one of 3584x3584 did not help. I still have the exact same behavior. So basically what did I get wrong in following the instructions from the other answer?
0
Is it possible in Unity to Flip a 2D Sprite Without Flipping the Object it is Assigned to? I 'built' (followed a tutorial) on a collision detection system, and when I flip the object to go left and right the collision messes up. So I have three options find a way to modify the collision detection, have sprites for all animations for left and right or to flip the sprite but no the object. if anyone has used RaycastHit2D, and has figured out a way to do it correctly, that would also be great.
0
How can I make several 2D objects move in complex pre defined patterns? I will be making my mobile 2D game in Unity and the objects in the game will have complicated movement. For example, there will be lots of squares (around 10 15 tiny squares) in the middle of the screen which will move in pre defined patterns like in the shape of an X or an M or O. The tiny squares forming the pattern M will be constantly moving within that X symbol and will be constantly instantiated at one end and destroyed at the other to achieve the effect (or just allowed to move within a pattern if the patterns shape permits). Unity tutorials explain the basics on how to work with the transform component, etc but I have been looking for a resource that tells you how to achieve the above. How can I implement it?
0
Build Unity3D project from source without Unity Editor I am trying to create an installer which will download the source of the latest release of a Unity project from a repository hosted on Github and then build it into an executable file. I have tried looking online for a solution, but, they all require the Unity Editor to be installed. Is it possible to build a Unity project from the source code into a .exe file or a .dmg file without the Unity Editor? EDIT From DMGregory's answer, it seems that using an external tool to build Unity Projects will violate Unity's Terms of Service. Therefore, I am updating the question. Does Unity provide a lightweight (installer) tool that can allow clients to build and install Unity projects from source rather than requiring the client to install the entire Unity Editor?
0
Set Parent to Instantiated Objects in Unity i am having problem in attaching parent to the instantiated objects. I have attached the code below. please tell me where i am doing wrong. Thank you. public GameObject brick public Transform BrickHolder public GameObject Bricks void Start() for (float y 2.16f y lt 4.88f y 0.34f) for (float x 2.125f x lt 2.125f x 0.85f) GameObject Bricks Instantiate(brick, new Vector3(x, y, 0), Quaternion.identity) as GameObject if (Bricks ! null) Debug.Log("Hello") Bricks.transform.SetParent(BrickHolder)
0
Making a new instantiated prefab as a child for existing GameObject I've been searched about how to make these fruit to move as the basket movement if it collided with it, and I've been found that if I want to perform this I've to let these fruit to be a child to the basket game object .. for example banana.transform.parent basket.transform banana and basket each of them of type "GameObject" ... BUT unfortunately this way didn't work !! and I don't know why ?? So now I need to know if it is possible to destroy the banana if a collision with the basket happened and instantiate a new banana in the basket as a child at run time ?!! I need to try this stupid way because I've tried all the other ways and nothing worked (
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)