_id
int64
0
49
text
stringlengths
71
4.19k
0
How to temporarily increase the speed of a character in a Unity game As the title would suggest, I want to give a character a speed boost for x amount of seconds, while increasing their Gameobject's mass. During this little speed boost, I also want to add a script to another player that disappears when the speed boost dies out I am new to C , and Unity in general, any help would be appreciated. using System.Collections using System.Collections.Generic using UnityEngine public class PlayerAddMass MonoBehaviour Start is called before the first frame update void Start() Update is called once per frame void Update() if (Input.GetKey(KeyCode.Q)) rb GetComponent lt Rigidbody gt () rb.mass 10 rb GetComponent lt Rigidbody gt () rb.speed 5 The code above was found on a unity website of some sorts, and I modified it to set the speed and mass numbers (I changed the 0s into a 10 and a 5) The errors I get are "rb does not exist in the current context" x 4
0
Unity Applying Global Light Settings fog to a non main camera Is it possible to apply fog to a non main camera?
0
Can I create realtime textures with text? I have a large number of items in my game, that will eventually have a texture associated with them. The problem is, for right now, I have nothing. I would really like to do something with, say, the first 2 letters of the object's name. As my main system will be pure textures, I really don't want to add a text object to the texture, I would really like to just create a texture with the object's first two letters. Is there a way I can create a texture, realtime, with font rendered on that texture? Preferably without a camera render texture, unless I can create them once. I really want to create a unique default texture for each item at runtime, preferably with some kind of font. Can I do this?
0
How do mobile games implement time gates unhackably? Is it possible in offline games? I'm thinking about porting my game to Google Play, and it would be free to play with time gates which are skippable if you watch an ad. What are the ways of implementing an unhackable time gating? Is it possible without internet connection? If yes, how? If no, is there a way to implement it without custom backend, using Google Play's services? Or should I care about this at all? Because... It doesn't affect other players... Most of the audience couldn't do it anyway, and if the game stays small, hacks couldn't really spread. Then maybe I should just let them hack those time gates, it's a marginal revenue loss. What do you think?
0
Do editor errors affect device performance? Do errors that come up in the Unity editor affect a game's performance on a device (on Android in particular)? I'm talking about errors that keep coming continuously during Update() such as NullReferenceException and "Debug.Log".
0
How can I make a level generator script run in Edit Mode? Description I've a script that takes in a PNG bitmap (e.g. 8x8) and, reading from that, populates the grid with cells where alpha gt 0. Problem The script runs in Awake(), so it can only be seen in Play Mode. I want it to always appear in the scene, even in Edit Mode. Potential Solutions I know of the ExecuteInEditMode attribute, as well as the OnValidate() callback. I don't know which is better to use, though, or what pitfalls to avoid. Additionally, in the past, I created a level generator that created a mesh, which I saved as an .asset with a custom editor button. The .asset was then loaded from inside the script. However, if possible, I'd like a more elegant and automatic solution. Other I'm using Unity 2018.4, and the grid is isometric. (I'm not using Unity's built in Tilemap.)
0
How do I make Unity halt on exceptions? I'm trying to debug a Unity project using the Unity Editor and Visual Studio. A runtime exception keeps popping up, but the debugger doesn't halt when an exception occurs, making it impossible to debug my code efficiently. In Visual Studio, I've gone into Tools Options Tools For Unity and set "Exception Support" to "True". I've also enabled all types of exceptions in the Exception Settings panel. I am connecting the debugger to Unity using the "Attach to Unity" button. Breakpoints are working, but the debugger isn't halting on Exceptions. What do I need to do to get Unity VS to actually halt on Exceptions? Note I've tried closing and re opening both Unity and VS many times but that doesn't make any difference.
0
Jerky Character movement after adding mouse orbit script I added a custom mouse orbit script to my project. When the right mouse button is clicked, the camera can be rotated around the player. The issue, after this change, is my player movement has become jerky choppy and not smooth. If I remove my mouse orbit script, player moment is back to normal i.e smooth. I can't seem to pin point what is causing this jerky movement withing MouseOrbit script Video demo Code This is where we initialize our script void Start() Initialize() This is where we set our private variables, check for null errors, and anything else that needs to be called once during startup void Initialize() h this.transform.eulerAngles.x v this.transform.eulerAngles.y cameraTransform this.transform cam Camera.main smoothDistance distance timerot TimeSignature((1 rotationDampening)) 100.0f NullErrorCheck() We check for null errors or warnings and notify the user to fix them void NullErrorCheck() if (!viewTarget) Debug.LogError("Please make sure to assign a view target!") Debug.Break() if (collisionLayers 0) Debug.LogWarning("Make sure to set the collision layers to the layers the camera should collide with!") This is where we do all our camera updates. This is where the camera gets all of its functionality. From setting the position and rotation, to adjusting the camera to avoid geometry clipping void Update() if (!viewTarget) return if (Input.GetMouseButton(1)) Cursor.lockState CursorLockMode.Locked h Input.GetAxis("Mouse X") horizontalRotationSpeed Time.deltaTime v Input.GetAxis("Mouse Y") verticalRotationSpeed Time.deltaTime h ClampAngle(h, 360.0f, 360.0f) v ClampAngle(v, minVerticalAngle, maxVerticalAngle) Debug.Log ("value of h " h) newRotation Quaternion.Euler(v, h, 0.0f) else Cursor.lockState CursorLockMode.None if (Input.GetKeyDown(KeyCode.D)) h transform.eulerAngles.y 90 newRotation Quaternion.Euler(transform.eulerAngles.x, h, transform.eulerAngles.z) if (Input.GetKeyDown(KeyCode.A)) h transform.eulerAngles.y 90 newRotation Quaternion.Euler(transform.eulerAngles.x, h, transform.eulerAngles.z) We set the distance by moving the mouse wheel and use a custom growth function as the time value for linear interpolation distance Mathf.Clamp(distance Input.GetAxis("Mouse ScrollWheel") 10, minDistance, maxDistance) smoothDistance Mathf.Lerp(smoothDistance, distance, TimeSignature(distanceSpeed)) We give the rotation some smoothing for a nicer effect smoothRotation Quaternion.Slerp(smoothRotation, newRotation, TimeSignature((1 rotationDampening) 100.0f)) newPosition viewTarget.position newPosition smoothRotation new Vector3(0.0f, height, smoothDistance) Calls the function to adjust the camera position to avoid clipping CheckSphere() smoothRotation.eulerAngles new Vector3(smoothRotation.eulerAngles.x, smoothRotation.eulerAngles.y, 0.0f) Vector3 dir new Vector3(0, 0, distance) cameraTransform.position newPosition cameraTransform.position viewTarget.position smoothRotation dir cameraTransform.rotation smoothRotation Time Signature with speed as input private float TimeSignature(float speed) return 1.0f (1.0f 80.0f Mathf.Exp( speed 0.02f))
0
can i show logs in unity with different colors or different icon signs? I'm working on a project that has a lot of logging messages that pass very fast. I can use error logs or warning logs but is there any way to log something with different colors so it is easier to find? Right now, I just use something like this Debug.LogError("show missing gold popup accepted")
0
Sea is higher than land when importing large real world terrain I am trying to import some real world terrain into Unity with the help of Global Mapper. The data I am using is download from CGIAR SRTM(http srtm.csi.cgiar.org ,http srtm.csi.cgiar.org srtmdata ). The land part works well but I am having trouble with the sea part. This is a larger view of that weird thing in the first image. This strange is actually the sea. This is happening because I am using the gradient shader. Lokks like The sea is represented with white, but when Unity reading the .raw file, the white means the highest part. Does anyone know how to deal with problems like this? Thanks very march.
0
How do I duplicate the functionality of ugui's onClick (button component) in inspector (Unity)? I'm trying to create the same functionality that occurs when you are working with a button in uGui in Unity. I know that I have to create a custom inspector, but i'm not sure where to go from there. Essentially the functionality allows you to drag and drop a script to it's on click portion in the inspector, and then it gives you a list of functions for that script to select. This may sound a little confusing, so here are a few pictures demonstrating the functionality i'm trying to replicate. As you can see above the functionality allows you to drag in a script, select a function to link, and do this for as many or as little scripts as you want by pressing the or buttons on the bottom right. Thanks for any help in advance!
0
Hide part of the GUITexture in Unity I have a Health Bar in my Unity game and it's implemented as a GUITexture with gradient image from red to green. Now I can reduce it's width from max width to 0, but is still scaled gradient. public void UpdateHealthBar(int hitPoints) healthBar.pixelInset new Rect( healthBar.pixelInset.x, healthBar.pixelInset.y, 3 hitPoints, healthBar.pixelInset.height) But I want to hide (make transparent) the right part of this health bar in game progress. How can I do this? Thanks!
0
Box2D Soft Body Wheel in Unity3D I was watching this video made with IForce2D, its about creating soft bodied wheels in box2D. http www.youtube.com watch?v F aDMZUVw0c I wanted help in being able to increase the Radius of the Wheel gradually. I tried increasing the natural distance of spring joint (Distance Joint) between central body and outer body. But since outer bodies are connected by revolute joint, which force the outer bodies to not change their positions. I then changed the Anchor Points of Revolute Joint to match the increase in Radius of Wheel. Now, the outer bodies start moving away from center body towards their natural Distance. But gradually some outer bodies rotate and move away from each other. Check out this video i made showing what i have done https drive.google.com file d 0B CQHvLBg5TQNlBEZXpRaVc5MDQ edit?usp sharing Note I am using Unity3D 4.3.4 with 2D Physics, Gravity is Off. Any ideas?
0
Get all supported resolutions for a monitor I've been receiving complaints from users that my game doesn't support the 16 10 aspect ratio. Currently I list everything in Screen.resolutions in a dropdown and allow the user to pick from that. I have since come to the understanding that the first element is not necessarily the native resolution of the monitor. I've found the Display class but this appears to only give the native resolution, not all scaled resolutions. E.g. if the monitor is 1920x1080 then I need a list of 1600x900, 1280x720, 640x360 etc. I thought about just multiplying by some scale factor but then I'm afraid I'll get something obscure like 885x497.8. And if I have a pre determined list of resolutions for a specific aspect ratio, how do I support obscure aspect ratios like widescreen for example.
0
Raycast a ray to the tip of another ray I'm using unity to raycast a line from the center of my camera viewport to a world position (yellow line). I also want to cast a ray from the center of my character to this same point (blue line). I have tried two methods to get this to work, however neither has worked. The two methods are the following if (Input.GetKey (KeyCode.Mouse0)) if left click is held down Ray crosshairPoint viewCamera.ViewportPointToRay (new Vector3(0.5f, 0.5f, 0.0f)) Vector3 crosshairEnd (crosshairPoint.origin crosshairPoint.direction 15) Debug.DrawRay (crosshairPoint.origin, crosshairPoint.direction 20, Color.yellow, Time.deltaTime, false) Vector3 intersect crosshairPoint.GetPoint (20) Debug.DrawRay (Vector3.zero, intersect, Color.red, Time.deltaTime, false) Debug.DrawRay( charFace.position, intersect, Color.cyan, Time.deltaTime, false) The red line being drawn is a line from the origin, which has no problem intersecting my camera ray line. The one from my character just refuses to point at the given point. The second method is the same as above, but using vector math (origin direction distance) to get the same point. Any ideas why the ray from my character won't point the right way, but one from the origin would? Something to do with world vs. local coordinates? Thanks 1
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
How to use the BillboardRenderer in Unity? Since version 5 (?) Unity has a new component type BillboardRenderer. Unfortunately the documentation is quite poor. It can be added in the inspector by clicking on "Add Component Misceallaneous Billboard Renderer" but apparently it requires a Billboard Asset to do anything. There doesn't seem to be any way to create one from the Unity interface. One of the few sentences from the equally poor documentation of BillboardAsset reads imageCount Number of pre baked images that can be switched when the billboard is viewed from different angles. My newest project will have sprite polygon mix graphics, so a component which renders a billboard with a different sprite depending on the view angle is something I could really make use of. But there doesn't seem to be any method to add such images. So I wondered if you could post an example how this component is used.
0
Unity3d Rigidbody movement along slope slowdown I have a Rigidbody character controller (Unity, C ) which I'm trying to make work seamlessly when walking on sloped ground. I've got it working fine walking up and down a slope by changing the forward direction to always be parallel to the ground (using the surface normal). But a strange thing is happening when walking sideways on that same slope (and not up and down it)...the character slows to a crawl. Anyone have any idea why this might happen, or how to solve it? private void Walk() isMoving false if (!inChatwithNpc amp amp !ledgeChecker.isGrabbingLedge) isMoving true playerRigidbody.AddForce(moveDirection moveSpeed multiplier Time.deltaTime) if (playerOnGround) playerRigidbody.velocity Vector3.Lerp(playerRigidbody.velocity, moveDirection playerRigidbody.velocity.magnitude, Time.deltaTime 0.5f) if (!isRunning) playerRigidbody.velocity Vector3.ClampMagnitude(moveDirection playerRigidbody.velocity.magnitude, 12f) if (isRunning) playerRigidbody.velocity Vector3.ClampMagnitude(moveDirection playerRigidbody.velocity.magnitude, 18f) if(!isMoving amp amp playerOnGround) playerRigidbody.velocity Vector3.Lerp(playerRigidbody.velocity, Vector3.zero, 0.2f) private void CalculateForward() if (!playerOnGround) forward transform.forward return forward Vector3.Cross(transform.right, touch.normal)
0
On key press, spawn a collider where my player is facing? I'm trying to create an attack mechanic to my player hero in my 2D Tower Defense game. When I press the Q button I want my hero to do an animation and spawn a temporary collider shaped as a cone at where the hero is looking at. If this collider collides with a GameObject called "Stone" it will decrease its hpValue with a script I made. If there is multiple Stones in the cone I want it to only effect one Stone, chosen either by random or and closest to the hero. How would I go about doing this and how can I detect the direction of where my hero is facing? This is my movement script public float speed Movementspeed Rigidbody2D rbody void Start () rbody GetComponentInChildren lt Rigidbody2D gt () rbody.freezeRotation true void FixedUpdate () Vector2 movement vector new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")) rbody.MovePosition (rbody.position movement vector speed Time.deltaTime) A picture visualising what I mean
0
Map video texture to a half sphere in Unity I'm new to unity3D. and am trying to play a 360 degree video. But instead of mapping the whole 360 degree (equirectangular) video to the whole sphere, I need to map the half video to a half sphere object. How can I do that? So basically we'll have two half sphere, tied together, each playing the half of 360 degree video, as if a single video is mapped to a whole sphere. An example or tutorial for a beginner would be great. e.g. So the top half of this 360 video should be textured on such mesh UPDATE No worries...we not cropping the video on the go! It is already cropped as two separate videos)
0
Customizing Unity WebGL index.html Hey everyone just some css and styling tips needed! i want to use a game as a 404 page. so i would need on top to be either text or a contact form then some spacing and then the actual game window. iframes dont work that good on mobile devices and by doing a simple div in unity index although on mobile it works rather crude but nice, on desktop the text is going behind the unity game window. any tips please? Note that im adding the style in the index.html and not using the separate css file in the template folder. So to sum up how can i make another div centered in the page and well responsive for mobile above the game container and add a margin on the bottom of that div! Thank you!!
0
Make platformer character stay in the air at the top of a jump I have a player who can jump. I want the character to stay in its position and not fall to the floor. This is the code I am using so far private void FixedUpdate() if(moveup) rigid.AddForce(new Vector3(0, 1f, 0) speed, ForceMode2D.Impulse) moveup false How can I stop the character from falling?
0
I try to make a Unity Curved Shader with shadow Effect? I try to make a curved shader with shadow effect I got a existing curved shader in github and it has no shadow effect i try to modify it but i couldn't find any appropriate solution. The shaderor helping script link https gist.github.com g0ody 5550039 Curved.shader Shader "Platogo Curved" Properties MainTex ("Base (RGB)", 2D) "white" QOffset ("Offset", Vector) (0,0,0,0) Dist ("Distance", Float) 100.0 SubShader Tags "RenderType" "Opaque" Pass Lighting Off CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" sampler2D MainTex float4 QOffset float Dist uniform float4 MainTex ST struct v2f float4 pos SV POSITION float2 uv TEXCOORD0 v2f vert (appdata base v) v2f o float4 vPos mul (UNITY MATRIX MV, v.vertex) float zOff vPos.z Dist vPos QOffset zOff zOff o.pos mul (UNITY MATRIX P, vPos) o.uv TRANSFORM TEX(v.texcoord, MainTex) return o half4 frag (v2f i) COLOR return tex2D( MainTex, i.uv) ENDCG FallBack "Mobil Unlit" CurvedAlpha.shader Shader "Platogo CurvedAlpha" Properties MainTex ("Base (RGB)", 2D) "white" QOffset ("Offset", Vector) (0,0,0,0) Dist ("Distance", Float) 100.0 Alpha ("Alpha", Range(0.0,1.0)) 1.0 SubShader Tags "Queue" "Transparent" "IgnoreProjector" "True" "RenderType" "Transparent" LOD 100 ZWrite On Blend SrcAlpha OneMinusSrcAlpha Pass Lighting Off CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" sampler2D MainTex float4 QOffset float Dist float Alpha uniform float4 MainTex ST struct v2f float4 pos SV POSITION float2 uv TEXCOORD0 v2f vert (appdata base v) v2f o float4 vPos mul (UNITY MATRIX MV, v.vertex) float zOff vPos.z Dist vPos QOffset zOff zOff o.pos mul (UNITY MATRIX P, vPos) o.uv TRANSFORM TEX(v.texcoord, MainTex) return o half4 frag (v2f i) COLOR return tex2D( MainTex, i.uv) float4(1,1,1, Alpha) ENDCG FallBack "Platogo Unlit Texture Alpha"
0
Unity "Convert To Entity" does not work (Render) with "Skinned Mesh Renderer" for Animations I'm trying to make a game with Unity's ECS and Job System. I came across the issue where, Convert To Entity does not support Skinned Mesh Renderer. It does not render the mesh. I need it for animations. On the bright side, Game Object Entity does render Skinned Mesh Renderer. The downside is that, it does not support Physics Shape and Physics Body. Convert To Entity does. I am using Physics Shape and Physics Body for physics. Would anyone mind telling me what options are open to me?
0
Unity Custom aspect ratio in build I have made a game that was supposed to be for mobile but now I need to build it for PC. I want the aspect ratio to be 2 3 but as you can see on the image that doesn't exist. How do I add a custom aspect ratio for the build?
0
GUI Layering (Enemy health bars appear above Inventory) I have set up an enemy prefab that gets instantiated during Start. Each enemy object has a health bar GUI object attached to a Canvas which is a child of these spawned enemy objects. So, when I spawn 10 enemies, 10 health bars get spawned as well. I have another GUI object for the inventory which I can open and close at the press of a button. When I open my inventory and there are enemies behind it, their health bars show on top of my inventory. I would like to layer the GUI objects such that these enemy health bars do not appear above my inventory. How do I do this? I have tried ordering them differently in the hierarchy as per someone's suggestion in a forum post, but that didn't seem to work. Again, every enemy object has its own Canvas of which the health bar is a child. The inventory GUI object is attached to a different Canvas which has no parent.
0
Do I have to use new keyword for unity single game object? I'm using Unity4. Do I have to use new keyword for single game object? look at the following code. 1. GameObject obj new GameObject() obj Resources.Load("Prefabs Ball", typeof(GameObject)) as GameObject 2. GameObject obj obj Resources.Load("Prefabs Ball", typeof(GameObject)) as GameObject is it the same?
0
How to make score counter independent of framerate I have a score counter, but I've noticed that the lower the framerate is, the slower it counts. How can I make it so it ignores the framerate? using System.Collections using UnityEngine using UnityEngine.UI public class Score MonoBehaviour private Text scoreText private static int score private static int finalScore private static bool count public static int scoreMultiplier private void Start() scoreText GetComponent lt Text gt () count false scoreMultiplier 1 public static void StartCounting() count true public static void StopCounting() count false public static void Reset() count false score 0 public static IEnumerator MultiplyBy(int scoreMultiplier) Score.scoreMultiplier scoreMultiplier yield return new WaitForSeconds(6f) Score.scoreMultiplier 1 private void Update() if (count) score scoreMultiplier Slice the score so the number doesn't get too big finalScore score 4 scoreText.text finalScore.ToString("00000") Edit Fixed by adding Time.deltaTime and putting it in FixedUpdate instead of Update private void FixedUpdate() if (count) score scorePerSecond Time.deltaTime scoreMultiplier finalScore Convert.ToInt32(score) scoreText.text finalScore.ToString("000000")
0
Restrict object movement inside irregular shaped container I want to restrict object movement inside an area. My object follows cursor position. I have already done that for the area border using Mathf.Champ to the translate because the borders are square shaped (got the idea from Unity Restrict movement inside a gameobject (2D)). The thing is that inside the box area there can also be other shapes (colliders) which I don't want my object to go over. I know people suggest using physic collisions, but my game needs a unit perfect positions so I can't use physics due to physics' default contact offset (the one physics use to detect collisions). Here is a short video of what I have https gfycat.com cookedsmartannelid As you can see, movement is restricted (clamped) inside the box area but I want the movement to also be restricted to not go over the black area. Is there a way to be able to do this with just clamping or do I need a raycast system or something like that?
0
Unity only rendering certian parts of 3d building model from certian angles So I made a couple modular building sections in blender, modular in the sense that I can insert build a floor at a time. I transferred them into Unity and then I got a rendering error that I have gotten many times before. I will put the object in the game world and then certain chunks of the building will only be visible from on direction and the other it will be completely invisible. I have been having trouble with this bug for a long time and I really would like if someone could point out what's causing this problem. I will include pictures below to help show my problem. Thanks, Nova
0
Stop animation playing automatically I've created an animation to animate a swinging mace. To do this I select the mace object in the scene pane, open the animation pane, and key it at a certain position at 0 00. I'm prompted to save this animation in my assets folder, which I do, as maceswing I then rotate the mace, move the slider through time and key it in a different position. I move the slider through time again, move the object to the original position and key it. There are now three things in my assets folder maceswing appears to be my animation, but I have no idea what Mace Mace 1 and Mace 2 are. (I've been mucking around trying to get this working so it's possible Mace 1 and Mace 2 are just duplicates of Mace. I still want to know what they are though) When I play my game, the mace is constantly swinging, even though I didn't apply maceswing to it. I can't stop it. People say there's some kind of tick box to stop it constantly animating but I can't find it. My mace object only has an Animator component Unticking this component doesn't stop the animation playing so I have no idea where the animation is coming from. Or what the Animator component actually does. I don't want this animation constantly playing. I only want it to play once when someone clicks a certain button var Mace Transform if(Input.GetButtonDown('Fire1')) Mace.animation.Play('maceswing') Upon clicking the 'Fire1' button, I get this error MissingComponentException There is no 'Animation' attached to the "Mace" game object, but a script is trying to access it. You probably need to add a Animation to the game object "Mace". Or your script needs to check if the component is attached before using it. There is no 'Animation' attached to the "Mace" game object, and yet I can see it swinging away constantly. Infact I can't stop it! So what's causing the animation if the game object doesn't have an 'Animation' attached to it? My maceswing animation object
0
Flexible and extendable system of level objectives (victory failure conditions) in Unity I'm trying to come up with a flexible system of level objectives for a Unity game. What I'd like to achieve is to have a system that on each level (scene) can accept a different set of (configurable) success failure conditions. Conditions can be repeated between levels but on every level a given type of condition should accept different parameters. For example on one level success conditions would consist of destroying all enemy units and on the other level success conditions would require destroying a specific enemy unit and escorting a friendly unit to a specific place on map. Failure conditions would for example be player death (on all levels) or not reaching a specific destination within a given time. First I've tried to approach this problem by using ScriptableObjects but abandoned this idea as it's not possible to save scene object references in a ScriptableObject. So I've come up with a kind of polymorphic system like this (pseudocode) public interface Condition bool IsFulfilled() public abstract class VictoryCondition MonoBehaviour, Condition public virtual bool IsFulfilled() public abstract class AllUnitsKilledCondition VictoryCondition public List lt Unit gt units public bool IsFulfilled() foreach (Unit unit units) if (unit.IsAlive) return false return true public abstract class FailureCondition MonoBehaviour, Condition public virtual bool IsFulfilled() public abstract class TimeOutCondition FailureCondition public float timeLeft void Update() timeLeft Time.deltaTime public bool IsFulfilled() return timeLeft lt 0 The idea here is to have a level manager that is given a set of victory failure conditions in the editor and have it continuously monitor all those conditions. In a simplest scenario a level is won if all victory conditions are fulfilled and lost if any failure condition is fulfilled. Unfortunately, I'm not sure how to create a LevelManager component that would expose those lists letting me add various conditions and configure them (for example letting me add a list of units from scene to AllUnitsDestroyedCondition). I think it would be doable with a set of custom property drawers for each type of condition but I'm wary of digging into this until I'm sure there is no other, easier way. I've come up with a way of adding various conditions by adding multiple condition components to a GameObject and then dragging those components to victory failure conditions lists in LevelManager. But this solution seems awkward and inflexible because it's not possible to dynamically add and configure new conditions in runtime and creating more complex conditions (for example some condition activating only after some other condition is fulfilled) seems like a sure way to create a huge pile of unmaintainable condition component mess. Please, let me know if I'm approaching this problem correctly and if not, what are other, simpler, more flexible solutions.
0
How to make an object destructible? I have some 3d models that I have downloaded from Unity asset store. Most of the time, these objects are not "separatable" so I can't apply a destructible effect. Is there a way to separate a model into small pieces, whether by using Blender, or a Unity script, or something else?
0
Unity Event Register Deregister and Scene Unload From what I understand in C , normally when you register an event, it maintains a reference to the object of the containing method, so in order for garbage collection to pick up an object, you need to first deregister it. My question In unity when one scene is loaded and another is unloaded, do I need to first clean up and deregister any registered events, or does the scene unload process destroy objects and remaining references?
0
A.I. dependencies based on components I'm working on a turn based game in Unity. I need to perform field grid analysis(2D grid) when i'm iterating trough each unit "entity". The A.I. should be able to plan ahead and therefor needs to consider the components each unit have. Not every unit will have the same ability. These abilities are defined as components. I want to make it flexible in the sense that I can plug in new abilities and my A.I. will take it into consideration. While user control is somewhat implemented, A.I. hasn't even been written. So I'm open to any suggestion. Q What is a way for the A.I. system to collect all abilities of one unit and make decisions depending on each component? edit I know there is the "null" checking method to see if the gameobject contains a component. But this is highly inflexible because you are hard coding a stack of if else. Something I want to prevent.
0
What's the scope of RPCs in unity? I can define several RPCs in unity and I can call them via the networkView component. But it seems that it gets the RPC called regardless where it is defined. So I was wondering to know how do the scope of RPC works in Unity. Am I able to call whatever RPC in whatever script which share the same networkView? Or is there any other logic behind? As a corollary can I define a unique structured file gathering every RPC in my project?
0
Impossible rooms in 3D games recently I was playing The Stanley Parable, and noticed that there are several impossible spaces in the game in this example, a pair of pillars in the middle of the room, which from each side appear to open onto a long corridor between them, which would have to cut the room in two if it were present in the same space. I hadn't seen this in a game since the Marathon Trilogy. The marathon games used a 2.5d engine that due to a quirk in its programming allowed for non Euclidean geometry. I was not aware it was even possible with fully 3D engines until I played The Stanley Parable. How does it work? how would I do that in Unity 5?
0
How is actual object size in a scene calculated? I've got stuck with 'pixel per unit' parameters and object scale. I've created two different sprites. A background picture, 1000x1000 pixels, and another one for a 'player', 200x200 pixels. I've added two empty game objects, with default transform, so positions are (0 0 0) and scale is (1 1 1). I added a sprite renderer to both of them, and assigned the required sprites. Both sprites have 1 pixel per unit. And the 'player' in the scene looks much more bigger than the background. I expect that if ppu 1, then the background would have a size of 1000 units, a player 200 units and it would be 5 times smaller. What am I doing or understanding wrong? What is an actual object size?
0
How to Get VR Controller's Velocity in Unity with SteamVR? Back when I used Unity 2017 and controller bindings weren't a thing, I simply attached a rigidbody to my Vive controller and read out the velocity of the rigidbody to know how fast the player was swinging the controller. Now, I've updated to Unity 2021.2.0a14, I went through all the effort of modifying my code to work with bindings, and it doesn't seem like I can get velocity anymore. The rigidbody always reports zero velocity. I can see the World Center of Mass vector changing so I know it registers motion, but it's just not reporting the velocity anymore. Is there a new setting in Unity I need to turn on to measure things that it doesn't personally control? Or do the new bindings options have a way to get velocity as an input? Am I forced to calculate it myself now? Thanks! Edit Base assumption was wrong, I did not get velocity from the rigidbody attached to the hand controller like I thought I did. I got it directly from SteamVR Controller. So Unity is probably acting like it ever did.
0
How can I prevent clicks from going through a GUI.Box? I have a GUI.Box that I slide in from the side of the screen. How can I prevent mouse interaction from going to any objects under it (another GUI.Button for instance, or for that matter an GameObject)?
0
Using a Compute Shader in Unity to convert a texture to a float array I have a fairly simple requirement for a compute shader (DirectCompute through Unity). I have a 128x128 texture and I'd like to turn the red channel of that texture into a 1d array of floats. I need to do this very often so just doing a cpu side for loop over each texel won't cut it. Initialization m outputBuffer new ComputeBuffer(m renderTexture.width m renderTexture.height, sizeof(float)) m kernelIndex m computeShader.FindKernel("CSMain") Here is the C method lt summary gt This method converts the red channel of the given RenderTexture to a one dimensional array of floats of size width height. lt summary gt private float ConvertToFloatArray(RenderTexture renderTexture) m computeShader.SetTexture(m kernelIndex, INPUT TEXTURE, renderTexture) float result new float renderTexture.width renderTexture.height m outputBuffer.SetData(result) m computeShader.SetBuffer(m kernelIndex, OUTPUT BUFFER, m outputBuffer) m computeShader.Dispatch(m kernelIndex, renderTexture.width 8, renderTexture.height 8, 1) m outputBuffer.GetData(result) return result and the entire compute shader Each kernel tells which function to compile you can have many kernels pragma kernel CSMain Create a RenderTexture with enableRandomWrite flag and set it with cs.SetTexture Texture2D lt float4 gt InputTexture RWBuffer lt float gt OutputBuffer numthreads(8, 8, 1) void CSMain(uint3 id SV DispatchThreadID) OutputBuffer id.x id.y InputTexture id.xy .r the C method returns an array of the expected size, and it usually sort of corresponds to what I expect. However, even if my input texture is uniformly red, there'll still be some zeroes.
0
Is it bad form to use singletons in unity I've heard a lot of people say singletons are bad practice and an 'anti pattern', like here, this answer this article and here. However, a lot of the reasons I've read about seem to be to do with dangers in their creation, them not being thread safe, difficult to destroy safely etc. But in unity where there are functions such as awake() and start() which are (as far as I'm aware) guaranteed to only be called once, are they unsafe to use?
0
why child class can access object while parent can't I have Block class which is the parent and StandardBlock the child , the prefab block have StandardBlock script attached to it, and according to my small knowledge in inheriting I though this would work public class Block MonoBehaviour HUD HUDscript Start is called before the first frame update void Start() HUDscript GameObject.FindWithTag("Canvas").GetComponent lt HUD gt () public void OnCollisionEnter2D(Collision2D col) HUDscript.addPoints() Destroy(gameObject) and child class public class StandardBlock Block some code but this is the error that i got NullReferenceException Object reference not set to an instance of an object Block.OnCollisionEnter2D (UnityEngine.Collision2D col) (at Assets Scripts Gameplay Block.cs 24) while writing OnCollisionEnter2D in the child class worked fine
0
Rotating game object without using localEulerAngles I'm building a player controller. While aiming, the player can rotate the chest bone. This looks as if the character aims in different directions. The chest bone should only be allowed to rotate within a certain range. If this range is exceeded (either to the left or to the right), the chest bone should stay at its current rotation, and the player should be rotated instead. I'm having problems applying the desired rotation to the parent game object instead. I'm trying to work with the localEulerAngles in order to applying an additional Y rotation to the gameobject, but the Y rotation value tells me for example "359.9" while I expected to work with a value of 0. private void pHandle LateUpdate Aim() Quaternion oldNeckRotation Neck.transform.rotation Fade old input before capturing new, so we don't dull the freshest data. float yawBlend Mathf.Pow(1.0f Aim yawInputFalloff, referenceFramerate Time.deltaTime) A Lerp toward zero is just the same as a multiplication by the blend factor. Chest yawRate yawBlend Accelerate by mouse movement over the past frame. (May need adjustment for display resolution). Chest yawRate Input.GetAxis("Mouse X") float yawDelta Chest yawSpeed Chest yawRate Time.deltaTime float offCenterYaw Chest currentYaw Chest yawCenter float fDesiredChestYaw Chest currentYaw yawDelta float fHeroRotation 0f if (fDesiredChestYaw gt Chest rotateRange) the allowed chest rotate range would be exceeded. Instead, move the gameobject the parent. fHeroRotation (fDesiredChestYaw Chest rotateRange) fHeroRotation this.transform.localEulerAngles.y this.transform.Rotate(0, fHeroRotation, 0) return else if (fDesiredChestYaw lt Chest rotateRange) fHeroRotation (Chest rotateRange fDesiredChestYaw) fHeroRotation this.transform.localEulerAngles.y this.transform.Rotate(0, fHeroRotation, 0) return else If we're moving away from the center, slow down as we approach the edge. if (yawDelta offCenterYaw gt 0) float extremityYaw offCenterYaw Aim yawMaxRange yawDelta 1.0f extremityYaw extremityYaw fHeroRotation yawDelta Ensure we never overshoot the allowed range. Chest currentYaw Mathf.Clamp(Chest currentYaw yawDelta, Chest yawCenter Aim yawMaxRange, Chest yawCenter Aim yawMaxRange) Vector3 nNewChestRotation new Vector3(Chest.localEulerAngles.x, Chest currentYaw, Chest.localEulerAngles.z) Chest.localRotation Quaternion.Euler(nNewChestRotation) Quaternion newNeckRotation Neck.transform.rotation the neck should not rotate with the chest. So I first counter rotate it against the new chest rotation, then rotate it a little towards the chest rotation Neck.transform.rotation Quaternion.Lerp(oldNeckRotation, newNeckRotation, neckFollowChest)
0
Unity Animation makes object spawn at x0 y0 z0 I was making an animation for a coin in my game in Unity, and when I was testing the full game, I saw that the coin is spawning at x0 y0 z0 and is doing the animation there. Then I realized that it was the animation, that increases and decreases y position and y rotation, starting at 0. So, I need to make the animation, that increases and decreases position y and rotation y, without affecting the actual position, because it will be different the position of the coins each time. In a while I will upload a screenshot for describing better the problem. Any clue?
0
2d ParticleSystem batching problem I have multiple ParticleSystems with TextureSheetAnimation pointing to the same texture, using different offsets rows to choose different textures. They seem to batch with each other, but they're also being split by Unity into multiple batches in a strange manner. Here's a Frame Debugger view These 4 Draw Dynamic are on the same atlas, using Mobile ParticlesAdditive shader. The reason of breaking batching is Objects have different batching keys. This is usually caused by using different vertex streams on ParticleSystems or by mixing Lines and Trails, or by mixing lit and unlit geometry. All of the ParticleSystems have a simple setup, some Color Over Lifetime, some Velocity Over Lifetime etc. The strange thing is that Unity breaks batching like it makes one batch, puts half of the stars and half of the smokes into that, and then, makes another batch from these two. So they do batch, and the don't o.O I couldn't find and help on the web about this issue. I'd be glad for help.
0
Why is my game object generated by a custom Unity editor script missing its sprite? I have a number of sprites that I generate outside of Unity. I'd like to automate the process of importing these sprites into Unity as fully configured game objects. I'm trying to do this through a Unity editor script, but I'm having some difficulty. When I run my script, my game object is saved as a .prefab as expected. However, the Sprite I'm assigning to my game object's SpriteRenderer component is missing In my script, I'm assigning my SpriteRenderer's sprite property to a Sprite object that I dynamically create in the script. Here's the relevant excerpt from my editor script GameObject gameObject new GameObject(fileName) SpriteRenderer spriteRenderer gameObject.AddComponent lt SpriteRenderer gt () texture size will be replaced during the LoadImage() call Texture2D texture new Texture2D(1, 1) texture.LoadImage(File.ReadAllBytes(Path.Combine(generatedOutputPath, fileName ".png"))) spriteRenderer.sprite Sprite.Create( texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.0f, 0.0f) ) PrefabUtility.CreatePrefab("Assets Prefabs " fileName ".prefab", gameObject) DestroyImmediate(gameObject) I can verify through logging that the image path to my .png is correct and that the Texture2D and Sprite objects seem to be instantiated correctly. For example, I can do this logs "580" as expected Debug.Log(texture.width) What am I doing wrong? How can I save this game object as a .prefab without losing its sprite information?
0
"Unfortunately game has stopped" error on Android device In Unity 2018.4.3f1, I am able to build my APK successfully, but when I try to launch it on my mobile device, it shows "Unfortunately game has stopped". I don't know the problem is. Here are the project settings I'm using
0
how to check mouse is not over any object in unity Im working on a way to check mouse is not over any object on scene to put my object in there. i know i can use OnMouseOver function but i have to add it on all objects script. Is there any other way to check my mouse position is not on any object collider? Its a 2d project. thank you for helping
0
Load Material from file path or parse .mat file to Material Unity Is it possible to load a material from a file path? Or, otherwise parse a .mat file saved on disk to a Material usable at runtime? I had naively thought it would be possible to assign the bytes from a .mat file, as read by File.ReadAllBytes to a Material object, but that does not seem to work.
0
Missing references in built bundles The following is a copy of our post in Unity Forum (https forum.unity.com threads missing references in built bundles.1103689 ) Hello, We have a bundle for our scenes and another one to store our prefabs (actually we have around 10 bundles but let's keep it simple). In every scene we have unpacked prefab instances. We have no problem in playmode using the AssetDatabase but once we use built addressables some unpacked prefab instances in our scenes are broken. Sprites and or scripts are missing in a inconsistent way in some scenes those objects are fine and sometime they are not. This comes along multiple warning messages quot The referenced script (Unknown) on this Behaviour is missing! quot . Note that the issue also happens when we fully deploy our player. Unity version 20193.3.13 Addressables version 1.16.1 Solution 1 We tried to remove addressable prefabs (A,B,C in the diagram) from their bundle since we don't really have to instantiate them at runtime for now and it worked. Solution 2 We also tried to put scenes and prefabs into the same bundle and it worked too. Solution 3 Switch to 1.18.2 and 1.15.1 version of addressable package and it didn't work. Solution 4 Finally we tried to use the Duplicate Bundles Dependencies analyzer multiple times in order to have no more issues of this type and it didn't work. Questions 1 As far as we understand, when addressable groups are built, Unity computes all dependencies and build them inside the bundle along the orignal assets (in my diagram quot Scenes quot bundles is packed with D'). What we don't understand is why having our prefabs in a separated bundle break references link in the scenes. Our guess is that Unity doesn't know which version of those dependencies to use (the one in the scene bundle or the one in the prefab bundle) and somehow fails to load them properly. Question 2 Is splitting our content is a good approach, we did it mostly for visibility but it appears to be more a problem in the long term, what are your guidelines regarding this matter ? Question 3 Why Duplicate Bundle Dependency rule has to be processed multiple times to properly fix every issue ? We think that running this rule creates duplication issues itself but we can't really tell.. Thanks.
0
DontDestroyOnLoad() doesn't work in Unity I have a problem with DontDestroyOnLoad() in Unity. It does not work! My code private static PlayerSpawningScript instance public void Awake() Debug.Log ("PlayerSpawningScript awake") Debug.Log ("Instance " instance) if (instance null) Debug.Log ("Initializing PlayerSpawningScript instance") instance this DontDestroyOnLoad (gameObject) if (instance ! this) Debug.Log ("PlayerSpawningScript instance exists. Destroying new copy.") Destroy (gameObject) Debug.Log ("PlayerSpawningScript instance " instance) public void OnDestroy() Debug.Log ("Destroying PlayerSpawningSceript instance " instance.ToString ()) Basing on the console output, I successfully create an instance in scene1, but when I change the scene, it gets destroyed I know this because I get "Destroying PlayerSpawningScript (...)" before the new scene is loaded, and the same script set up in scene2 does not find an existing instance (which held data saved in scene1) and sets up itself as the instance instead of getting Destroyed. What am I doing wrong?
0
How can i add a description of gameobject when click on the gameobject? I have this DetectInteractable working script attached to Player (FPSController). I'm using tag to detect interactable objects, each object i want to be interactable i change his tag in the editor to "Interactable". ( Maybe there is a better way to do it without using tag ? It's working but many told me not to use tag. ) I'm using Raycast to hit a gameobject detect if it's "Interactable" and if it does i display on the gameobject his name. For example "Security Door" or "Screen Monitor" or "Surveillance Camera" Now i want to do that if i hit a gameobject with the raycast and it's "Interactable" if i will click the mouse left button it will display a description text description about the gameobject. But this time i want to use some gui box so it will be in front of the screen in the middle and not on the gameobject. The problem is that i need to create a script for every "Interactable" gameobject and make that if i click on a button it will display a description. Then how do i make the script and how can i make that when i attach the script to each gameobject it will make in the inspector a box of text so i can enter and type there the description of the item(GameObject) ? using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class DetectInteractable MonoBehaviour public Camera cam public float distanceToSee public string objectHit public Image image public bool interactableObject false public Canvas canvas public Text interactableText private RaycastHit whatObjectHit private RotateObject rotateobj private void Start() rotateobj GetComponent lt RotateObject gt () private void Update() Debug.DrawRay(cam.transform.position, cam.transform.forward distanceToSee, Color.magenta) if (rotateobj.rotating false) if (Physics.Raycast(cam.transform.position, cam.transform.forward, out whatObjectHit, distanceToSee)) if (whatObjectHit.collider.gameObject.tag "Interactable") image.color Color.red objectHit whatObjectHit.collider.gameObject.name interactableObject true interactableText.gameObject.SetActive(true) interactableText.text whatObjectHit.collider.gameObject.name print("Hit ! " whatObjectHit.collider.gameObject.name) else image.color Color.white interactableText.gameObject.SetActive(false) print("Not Hit !") else image.color Color.white public class ViewableObject MonoBehaviour public string displayText public bool isInteractable
0
How to make a changeable color constant for editor materials? Due to the nature of a project I'm working on, the models I got have a bunch of redundant materials on them. I have to fiddle around with some of the colors, but every time I want to change the colors, I have to change each material to the exact same color. Is there any way to declare some kind of swatch that I can change and have those changes just apply to the materials or anywhere else? For instance, in code, you'd just make a readonly Color mainColor, that you'd use wherever you need and could change at will. I'm looking for this kind of behavior in the editor itself.
0
Render 2D textures on a 3D object's face I am not familiar with 3D graphics, and I'd like to know the right way to render some 2D figures on different points of a wider face of a 3D object. My 3D object is just a cube representing a poker table. I have a 2D png for players' placeholders, and I'd like to render these figures on the 3D object where needed. An alternative solution would be to render the whole face with a big picture containing all the placeholders figures. However, it would be a waste of memory and thus less efficient. What do you suggest?
0
Making a gameobject move back and forth in Unity So i have this enemy gameobject and i want it to move in a certain pattern like a patrol. So i want him to move from A to B to C then Back to B to A. The script I worked out makes him go from C to A directly but I dont want that. Can someone please help . The Length of PatrolPoint Array in 3 using UnityEngine using System.Collections public class EnemyPatrol MonoBehaviour public Transform patrolPoints An Array of path points to be followed private int currentPoint public float enemySpeed void Start() currentPoint 0 transform.position patrolPoints currentPoint .position Starting Point void Update() if(transform.position patrolPoints currentPoint .position) currentPoint if(currentPoint gt patrolPoints.Length) currentPoint 0 transform.position Vector3.MoveTowards(transform.position , patrolPoints currentPoint .position , enemySpeed Time.deltaTime)
0
Unity3D and Photon Networking RPG Good time of the day. My question might sound stupid, due to the knowledge you might have, but here it is. I've purchased Diablo 3 a long time ago and been enjoying it since then. Since many of my friend are playing other Blizzard titles, i tried to convince them to purchase Diablo and to play all together. However, they don't want to invest money in the game they don't understand (yet). So i've decided to write a game, which will be similar to the Diablo in the way of interaction and gameplay, but will (obviously) have some unique points in it (since i'm not only doing this for them, but also to educate myself in the game development area). Other this is, i've decided to take Masters in the Game Development (later this march, just got my bachelors in computer security) and wanted to have some basic knowledge about game development. I used to make "RPG" games before, tho only browser style ones using LAMP stack, and have some basic knowledge on storing retrieving data to from server. In order to implement multiplayer part of the game, i've decided to use free package PUN (Photon Unity Networking). Had no problem with creating my first room and spawning a player prefab for every new connection (tho they all move no matter on which client action is performed). Now to the question(s) By using PUN, i'm able to create new room for players (limited to 5), is it possible to set room names BEFORE they are actually initialized by the player? (set of rooms might be stored on MySQL server and retrieved by the API call) Is it possible to save progression of the player on the server, and later pass it back to the spawned player (by PUN). This is my main concern, since i've no actual access to the data processed by the server. (Solution is to create another connection to the "storage" server, and keep both of them "online"?) Does PUN allows you to select which scene should be loaded upon first player entering the room, if so, a bit of pseudo code might be helpful. What will happen to the player, if there is no spots left to join the server (this is just theoretical question, since i'm not going to publish this game, and amount of friends playing games is less than 20) How would one deal with the item equipped, which is received during the gameplay? (This one links to the second question) What i'm talking about is, is it possible to restore player object with the set of data received form the server (if possible, ofcourse) I know, the first suggestion will be to go and to read documentation (i'm in the process of reading it, don't worry). But i've decided to write here, since there are many skilled people out there in this area, who can give me basic understanding on how this whole PUN system works. I would like to thank you for all of the responses, which you are about to post (or maybe not), and again, have a great day.
0
How do I stop clicks on a button from also triggering my gameplay scripts? My character jumps when I press the right side of screen. The pause button is alsp in the top right corner. So when I press that button, the right side script always triggers and I don't want that to happen. Here the script if (Input.GetMouseButtonDown(0)) float xPosition Input.mousePosition.x if (xPosition gt Screen.width 2 amp amp isGrounded amp amp !isJump) mouse is on the right part of the screen, shoot right rb2d.velocity new Vector3(0, jumpForce, 0) isJump true JumpSoundSfx() if (Input.GetMouseButton(0)) float xPosition Input.mousePosition.x if (xPosition lt Screen.width 2 amp amp !isJump) mouse is on the left part of the screen, so shoot to the left crouch.SetActive(true) stand.SetActive(false)
0
How can I blend meshes together where they intersect? In a lot of my scenes I have things like this and this All the places I've circled are places where a prefab overlaps with another one or with the terrain. Is there any way to make those lines softer more natural and blend together more? When I can, I try and hide the lines with trees or other items, but that doesn't work in every case. I wonder if I can solve this with something like the soft particles effect. Soft particles in Unity help blur the line between a particle system and a rendered mesh. This keeps you from having jarring hard cut offs and straight lines in something that's supposed to be amorphous. (That's as far as my understanding goes) Can I use something like this to blend my prefabs together?
0
Unity override Coroutine Loop I have problem, when i override a Coroutine loop from the base code. But it seems that it only execute once. While on the base code it does what it suppouse to do and that is execute forever. protected virtual IEnumerator OnThink(float interval) while (true) yield return new WaitForSeconds(interval) protected override IEnumerator OnThink(float interval) Debug.Log("Execute") yield return StartCoroutine(base.OnThink(interval))
0
unity lag while moving a sprite I'm trying to build a 2D game for android and after I finished developing the game I noticed that there was lag present when moving objects around. I tested it on a phone much more powerful than my own Sony Xperia z2 and it had more lag, therefore I believe it's not related to RAM. I've disabled vsync using profiler putting the movement in fixedupdate, lateupdate, and even built a new project. This new project has only 1 scene and 3 scripts. One of scripts are attached to this sprite to move it. When running this project I still have lag both on my laptop and on my mobile phone! This is the script using UnityEngine using System.Collections public class PlayerMove MonoBehaviour public Vector2 movement public Vector2 speed private float myTimer Use this for initialization void Start () speed new Vector2(2,0) Update is called once per frame void Update () handleMove () public void handleMove() if (Input.GetKey (KeyCode.UpArrow)) speed.y 2 this.gameObject.rigidbody2D.velocity speed myTimer .3f if (Input.GetKey (KeyCode.DownArrow)) speed.y 2 this.gameObject.rigidbody2D.velocity speed myTimer .3f if (myTimer gt 0) myTimer Time.deltaTime else speed.y 0 this.gameObject.rigidbody2D.velocity speed this is results of profiler
0
How can I choose a pathfinding target for a unit group and move the group to that target? So I've got some units which should move to a specific position which is given by the player. Currently the units can move there by finding a path with the A algorithm (to be more precise A Pathfinding Library for Unity) I was wondering what the best way to move the units is? When the player has selected e.g. 20 units, some of them are near each other, some of them are far away from the others, what is the best way to navigate them to a single position defined by the user. Obviously they cannot just all have the same target since they would never reach it when the first unit moved to it. Thus what do I have to do? Do I have to assign different targets to each unit or do I calculate the target position relative to the position they were to each other before?
0
Unity separate shapes on a map into individual objects? Okay, I asked this question yesterday anonymously thus I couldn't edit it so I'm remaking it. Short version I have a transparent map with black borders (Colored map) and I want those shapes formed by these borders to become individual objects in Unity. Is it even possible and if it is, how? Long version I want to make a Grand Strategy type game with provinces and countries. However, I'm not really an experienced graphics nor Unity programmer. I already have a map drawn with the desired black borders with each province being defined by these very borders and each has an unique color (sort of an identifier). Having just this seems plain and complicated to use so I'd like for each province to emit a color corresponding with a selected map type (diplomacy, terrain, domains, etc.). Obviously, this would be hard to do with just a single plain texture therefore I need to make objects and this is where my inexperience blocks me from continuing. Is there anything I can do (in Unity and or Photoshop) that could make the provinces be objects without manually isolating, importing and matching (as a puzzle) each single one? I've already looked at countless questions and answers but still none fit my problem. I'm at my wits' end with this to the point where I'm actually thinking about scrapping the project.
0
Making the camera look at the player while keeping another object in view I'm working on a sorta football game where I need my player to always be at the center of the camera view while keeping the ball into view, without any vertical movement. The idea would be for the camera to act like the picture below. What I came up with was the following code that I'm using in a LateUpdate. I'm computing a directional vector between the player and the ball and placing my camera behind the player using that data, and then I look at my player. Vector3 ballPosition ballTransform.position Vector3 playerPosition playerTransform.position ballPosition.y 0.0f playerPosition.y 0.0f Vector3 directionVector (ballPosition playerPosition).normalized directionVector.y 0.0f Vector3 newPosition playerTransform.position directionVector 12.0f newPosition.y 9.0f transform.position newPosition transform.LookAt(playerTransform.position) The code itself is working, but the camera movement is a bit nauseous, and when I'm trying to smooth it I end up with the ball leaving the camera field most of the time. Plus when I get too close from the ball I end up with some really quick camera movements which makes the whole thing kinda hard to follow. I tried to use a totally different technique by working with a Cinemachine Camera, but there doesn't seem to be an easy way to achieve such a view. Does anyone have an idea of how to achieve such a thing?
0
3D Collisions Walking below a slope pushes me through the floor Here's a really short video (less than 30s) of this issue https www.youtube.com watch?v JrKbpTY8cMU When I move the player towards a slope (the player is below it), it pushes the player inside the floor Collider instead of blocking it. I've searched the Internet for a while but haven't found anything about it Do you have something in mind ?Thanks for your time Info I move the player using rigidbody.MovePosition() The collision of the player is a Capsule.
0
EnemyAI rotating on Y axis in opposite direction After a battle flag has gone off and the player has entered an enemy's battle zone I want to keep track of the player when it moves and make sure the enemy's Z axis is always pointing towards the player. Upon the player entering the battle zone, the enemy automatically marks the player as its target However there is a chance that the Z axis may not be pointing towards the enemy's target when the battle is first initiated. I decided to shoot a ray cast from the Z axis of the enemy when the battle flag goes off and rotate the enemy until the ray and the player intersect thus telling me that enemy's Z Axis is lined up correctly. the enemy always has a reference to its current target. My idea was that as once the enemy spots its target initially, it can save the position of the most recent spotting and then take the delta of the CurrentTargetPosition.x and the LastSpottingPosition.x If the delta is positive rotate right and if the delta is negative rotate left. THE ISSUE my math or logic must be flawed somewhere because although it works sometimes, other times the enemy will randomly rotate itself in the opposite direction and the ray cast will essentially take the long route to hit the player instead of the shortest route as intended. Also the Local Origin of the enemy and the player are at different height respectively but I dont think that should matter in my case Code Below. create ray from enemy position orgin and point it on the Z Axis Ray ray new Ray(CurrentEnemyTransform.position, CurrentEnemyTransform.forward) RaycastHit hit if (Physics.Raycast(ray, out hit, 50f)) Debug.DrawLine(ray.origin, hit.point) ray hits current enemy target if (hit.transform CurrentTargetTransform) check if enemy has seen its target before while in this battle or is it the first time if (enemy.hasTargetLastPosition) replace old last seen position with most recent spotting enemy.ReplaceTargetLastPosition(hit.transform.position) or add the first spotting of target while in this battle else enemy.AddTargetLastPosition(hit.transform.position) ray is not intersectiing with the enemy's current target so rotate to look for it if (hit.transform ! CurrentTargetTransform) check if enemy has seen its target once before in battle if (enemy.hasTargetLastPosition) since last spotting has my target moved more to the left or right? if (enemy.targetLastPosition.value.x gt CurrentTargetTransform.position.x) rotate right CurrentEnemyTransform.Rotate( Vector3.up, 5f, Space.Self) rotate left else CurrentEnemyTransform.Rotate(Vector3.up, 5f, Space.Self) never seen target yet during this battle so default rotation to right till you found it else CurrentEnemyTransform.Rotate( Vector3.up, 5f, Space.Self)
0
Unity Stuttering character rotation Am working on the controls and camera movement for my character. What I am trying to do is have the character head be able to rotate left and right and then when the head is rotated a certain amount, the whole character rotates around. I have kinda of done it, the head can move smoothly, but it stutters when it starts rotating everything. Hopefully it is visible in this GIF. You may be able to see that the head does rotate smoothly, but when the body starts rotating, it stutters. Here is the code that is in LateUpdate that handles all the rotations. this.current rotation Quaternion.Lerp(this.current rotation, Quaternion.Euler(new Vector3(this.pitch, this.yaw, 0)), this.mouse sensitivity Time.deltaTime) this.cam.transform.rotation this.current rotation this.head.transform.rotation this.current rotation if(this.head.transform.localRotation.y gt 0.3 this.head.transform.localRotation.y lt 0.3) Quaternion from Quaternion.Euler(0, this.player.transform.eulerAngles.y, 0) Quaternion to Quaternion.Euler(0, this.current rotation.eulerAngles.y, 0) Quaternion q Quaternion.Lerp(from, to, this.mouse sensitivity Time.deltaTime) this.player.transform.rotation q
0
Unity UI making it responsive I am attempting to create a simple Jeopardy game using the UI features of Unity However as im trying to change the size of the screen it does not seem that my UI is responsive Here is it in 16 9 Here it is in 600x900 My Question is. is there a way to make it responsive? Is it even nessary to do so in unity or am i thinking way to much web based? ) Hope someone is able to help me and guide me abit
0
Runtime Issues on 144Hz Monitors I've recently finished my first ever Unity game. The game runs okay in my end but two of my friends had issues with the game. They both have 144hz monitors and the issues are solved when they lower the refresh rate to 60Hz. The problems are that any object who has a velocity depending on Time.deltatime, it gets halved. Is there a way to fix this on code so that nobody has to reduce their refresh rate when playing? Here is an example code of a snowball projectile's behaviour. The snowball usually stays alive for 3f seconds and that allows him to go across the whole screen but in 144hz runtime, the snowball goes really slow and it does not last enough to even get across the half of the screen. using System.Collections using System.Collections.Generic using UnityEngine public class Snowball MonoBehaviour SerializeField private float speed 20f SerializeField private Rigidbody2D rb SerializeField private GameObject impactEffect Start is called before the first frame update void Start() Destroy(gameObject, 3f) void Update() rb.velocity transform.right speed Time.deltaTime 75 void OnTriggerEnter2D(Collider2D hitInfo) if(hitInfo.CompareTag( quot Player quot ) hitInfo.CompareTag( quot Enemy quot )) Destroy(gameObject) Instantiate(impactEffect, transform.position, transform.rotation) Here is my game if anyone is interested in further examination itch.io link
0
Player object's model starts to shake after some time I created a default scene in a new project and imported a model from Unity's asset store and then get this strange behavior of the model starting to shake for no reason after some time after starting the game. I also have a script to read keyboard input and then apply forces to the model when the player presses some keys but the shaking of the model starts to happen even when the player does absolutely nothing. I'm really confused and have no idea where to look for a problem and google doesn't seem to have a solution to this either.
0
Unity UV map, tint change color of texture I have an array of vertices with texture coordinates for a UV map in Unity newUV.Add(new Vector2 (0, 1)) FACE 1 newUV.Add(new Vector2 (1, 1)) newUV.Add(new Vector2 (1, 0)) newUV.Add(new Vector2 (0, 0)) newUV.Add(new Vector2 (0, 1)) FACE 2 newUV.Add(new Vector2 (1, 1)) newUV.Add(new Vector2 (1, 0)) newUV.Add(new Vector2 (0, 0)) mesh.uv newUV.ToArray() It textures my mesh just fine. How could I go around tinting FACE 1 to a darker color? Let's say the texture is just plain green and I wanted to texture only on FACE 1 to be a darker shade of green.
0
Level Selector with possible future levels? Unity I have a level select screen which is a simple grid layout of my levels. The level data comes from a scriptable object for each level. The problem I have is what is the best method for populating the grid of levels that use the scriptable object and is able to add more levels to the grid layout if let's say I add an asset bundle in the future? My thought was that I use a levelDB which holds a list of all of the scriptable objects. Then when an asset bundle is used then it adds the content to the levelDB. The UI would then just use this levelDB to populate the screen. NOTE I have very little to no knowledge of how asset bundles work and what you can, and cannot do with them.
0
How to Cease the Ragdoll Wiggle Dance When I instantiate a ragdoll object, it collapses nicely, but the movement never stops. It wiggles continuously. I'm using CharacterJoint components. None of the colliders (box and capsule) intersect. They are all spaced by at least a small amount. I tried playing with angular drag of the colliders, but that seems not to work. There do not seem to be any values in the CharacterJoint that affect this. But I'm probably wrong. How can I get the physics to stop quot wiggling quot after a certain threshold?
0
Show 3D elements on 2D background I'll make a navigation menu in my game and had the good idee to this the enemies to start games or go to the gun store. The problem is when I look in game mode, the enemy named ZomBear in hierarchy and gun are away. The ZomBear and the gun are 3D elements that I will show on a canvas named StartScreen in hierarchy. How Can I do that? (Click on image to see full size) Notes by the hierarchy Everything that begin whit Btn are button elements. StartScreen, PlayButtons and LevelButtons is a panel Gun and ZomBear are 3D elements form the Prefab folder. Here you have also a screen from aside
0
Unity3D Orbit around orbiting object (transform.RotateAround) The best way to explain this is I'm attempting to make a small model solar system (not to scale or anything complicated, just simple rotation as a learning exercise). There's a sun, a planet, and that planet's moon. The planet orbits like normal, however the moon orbiting around the planet shoots off and makes an extremely large and far away orbit. My code is as follows (where "target" is the object being orbited around, and "transform" is the orbiting object itself. Both are "Transform" objects.) public class RotateAndOrbit MonoBehaviour public Transform target public float RotationSpeed 100f public float OrbitDegrees 1f void Update () transform.Rotate(Vector3.up, RotationSpeed Time.deltaTime) transform.RotateAround(target.position, Vector3.up, OrbitDegrees) I'm not sure how to compensate for this or even what my mistake is called, but any help would be appreciated.
0
Customizing Unity WebGL index.html Hey everyone just some css and styling tips needed! i want to use a game as a 404 page. so i would need on top to be either text or a contact form then some spacing and then the actual game window. iframes dont work that good on mobile devices and by doing a simple div in unity index although on mobile it works rather crude but nice, on desktop the text is going behind the unity game window. any tips please? Note that im adding the style in the index.html and not using the separate css file in the template folder. So to sum up how can i make another div centered in the page and well responsive for mobile above the game container and add a margin on the bottom of that div! Thank you!!
0
How to keep two objects in the same zone when they collide? I made a zone out of a cylinder with zero height. When one sphere moves to that zone it is fine but if another one moves to the same zone it only shows one sphere. I tried to add a rigid body for each sphere but they collide inside the cylinder and both fly. I want both of them to collide but stay inside the cylinder zone with a distance between them like 2 units.
0
Add points to a prefab in Unity I have a prefab that looks like this I have created a couple of 'points' in the Hierarchy using 'Create Element' and I would like to attach them to the prefab, however drag and drop over doesn't work. Why is that?
0
Can running unity of a system with nvidia graphics card speed up the simulation? I have a nvidia GTX 1080 graphics card in my computer, I don't know if unity by default makes use of GPU. Does having a GPU helps to speed up unity simulations.
0
Bad quality of the sprite in Unity I need to import a few sprites (background platform and sky) into my game scene but it seems that their quality after importing into Unity is too bad (they are blurred). The original resolution of this two images is big enough (2048 X 400 for background) and they are looking very nice in standard Windows image viewer. Here are the settings for these two textures maxSize 2048 Format truecolor TextureType Sprite(2d) nGUI FilterMode point I am using Unity2D 4.5 Target resolution of my project is 1280 800. Can anyone help me to solve these problem? As you can see the grass on foreground looks very bloory (1 picture) Texture settings (2 picture) Original image (3 picture)
0
Translate position from 3D camera to 2D camera Currently I have 2 cameras, one for viewing the 3D objects (Perspective), and the other camera to view 2D objects (Orthographic). (Also, the view of the camera never intercepts each other.) I am trying to display a 2D object based on the position of a 3D object, like so What I have is the respective 2D and 3D Camera, as well as the Vector3 position of the 3D GameObject. What I have tried public Vector2 Convert3DPositionTo2DPosition(Camera camera3D, Vector3 position3D, Camera camera2D) var tempPos camera3D.WorldToViewportPoint(position3D) return camera2D.ViewportToWorldPoint(tempPos) The only problem is that the returned position is not completely aligned with the 3D position. Which results in this kind of results Also, I have made sure that both the 3D and 2D object have their pivot point are set correctly in the center, but it still does not work as intended. (I am currently using Unity 2019.1.14f1)
0
How to stop the RotateAround function to rotate after Keypress in Unity I have a camera follow script and I am rotating the camera with Q and E key to right and left. The Camera is a child of a camHolder object. I came up with this code, which rotates around the player to the right and left, but it's shaking as it tries to keep rotating around the player. I didn't come up with a solution to stop the RotateAround function, instead I tried setting rotateSpeed to 0 after I let go of the key, but that didn't work either. public Transform player public float smoothSpeed 0.125f public float rotateSpeed private Vector3 velocity Vector3.zero SerializeField private Vector3 offset Space public Transform camHolder void LateUpdate () CameraFollowPlayer() void Update() RotateCamera() void CameraFollowPlayer() camHolder.position Vector3.SmoothDamp(transform.position, player.position offset, ref velocity, smoothSpeed Time.deltaTime) transform.LookAt(player.position) void RotateCamera() if(Input.GetKey (KeyCode.E)) rotateSpeed 20f if(rotateSpeed gt 20f) rotateSpeed 20f transform.RotateAround(player.position, transform.up, rotateSpeed Time.deltaTime) else rotateSpeed 0f if(Input.GetKey (KeyCode.Q)) rotateSpeed 20f if(rotateSpeed gt 20f) rotateSpeed 20f transform.RotateAround(player.position, transform.up, rotateSpeed Time.deltaTime) else rotateSpeed 0f
0
How to launch a prefab at the mouse position I want to use Instantiate(item, new Vector3(...), Quaternion.identity) to land an item at the position that was clicked. My game is using a third person view (example). This is the code that I think I should be using if(Input.GetKeyDown(KeyCode.Mouse0) amp amp cur items gt 0) Instantiate(item, object pos, Quaternion.identity) cur items mouse pos Input.mousePosition object pos Camera.main.WorldToScreenPoint(mouse pos) What am I doing wrong?
0
Collision prediction of 2 moving objects I have to 2 objects with Collider2D. Both objects are moving, in the very next frame they will either overlap each other or not. How to predict if they would collide on the next frame? I'm thinking of instantiating a temporary object then use collider.Overlap(). But maybe there are better ways to do this.
0
How do you partition a level and create screen transitions out of these partitions? The levels in Castlevania games, you walk forward and then come to a point on the level where the screen stops scrolling but is not a deadend and there's no door either. They just wanted to transition to the next room for some reason (like a hallway transitioning to another room). I want to create something like this in Unity, using 2.5d (3d characters constrained in 2d plane) question is, do I separate each transition to a scene? But that seems kinda wasteful (I don't know, maybe). Or just one scene and develop the level as a whole and do some camera programming for the transition making sure everything lines up?
0
Why does the script stop working after respawning? I have a flying enemy that follows the player public class MoveTowardsPlayer MonoBehaviour public float moveSpeed, sightDistance public Rigidbody2D theRB public Transform target private void Start() theRB GetComponent lt Rigidbody2D gt () private void Update() Vector3 targetDir target.position transform.position targetDir targetDir.normalized float dist Vector3.Distance(target.position, transform.position) if (dist lt sightDistance) theRB.velocity targetDir moveSpeed And here is what happens when the enemy dies, and then respawns public void Die() Instantiate(enemyDieEffect, transform.position, transform.rotation) gameObject.SetActive(false) public void Respawn() gameObject.transform.position initialPosition gameObject.SetActive(true) currentHealth maxHealth The enemy respawns if the player dies and goes back to the last checkpoint. Interestingly, if the player dies before reaching any checkpoint, the MoveTowardsPlayer scripts still works after respawning. It only stops working after any of the checkpoints are reached. For the sake of completeness, here is the Checkpoint script, which has absolutely nothing to do with the enemies public class Checkpoint MonoBehaviour private Animator animator public bool isReached Start is called before the first frame update void Start() isReached false animator GetComponent lt Animator gt () private void OnTriggerEnter2D(Collider2D other) if (other.CompareTag( quot Player quot )) CheckpointController.instance.DeactivateCheckpoints() animator.SetBool( quot isActive quot , true) CheckpointController.instance.SetSpawnPoint(transform.position) public void ResetCheckpoint() animator.SetBool( quot isActive quot , false)
0
How to use a decal logo tatoo texture on a object or character? It appears I've misunderstood the purpose of Standard Shader's "Secondary Texture" options. If I wish to map temporary details to an object, what is the Unity appropriate way to do this? I am referring to effects like the following Tatoos Blood Spatters Logos Decals etc... I'm aware that I could have two materials, but this is render inefficient, and I avoid hackish workarounds when I can. Standard practice? EDIT Per the comment below, I will elaborate slightly In my specific case I'd like to have one of two scenerios 1 Areas where a logo can be inserted (player created), pre uv assigned. 2 Drag drop logo placement, similarly, but without constraints. This would mean of course passing UV boundaries.
0
VertexColor shader is not working correctly in built application I want to change the vertex colors of my mesh. The light sources must not affect the objects with this shader, its lighting must be determined only by its vertices colors, so I turned the Lighting Off. I use this simple shader Shader "VertexColored Simple" Properties MainTex ("Base (RGB)", 2D) "white" SubShader Pass ColorMaterial AmbientAndDiffuse Lighting Off SetTexture MainTex Combine texture primary Fallback "VertexLit" And this script using UnityEngine using System.Collections public class BehaviourScript MonoBehaviour void Start() Color exclrs new Color 11 new Color32(25, 25, 25, 255), new Color32(50, 50, 50, 255), new Color32(75, 75, 75, 255), new Color32(150, 150, 150, 255), new Color32(200, 200, 200, 255), new Color32(255, 255, 255, 255), new Color32(200, 200, 200, 255), new Color32(150, 150, 150, 255), new Color32(75, 75, 75, 75), new Color32(50, 50, 50, 255), new Color32(25, 25, 25, 255), Mesh mesh GetComponent lt MeshFilter gt ().mesh Vector3 vertices mesh.vertices Vector3 normals mesh.normals Color colors mesh.colors for(int i 0 i lt vertices.Length i ) for(int j 0 j lt 11 j , i ) colors i exclrs j i mesh.colors colors When the game is launched, in editor I can see this This is EXACTLY what I wanted to achieve! But in built for PC(x86) version I see this Why the results from the editor and from the built .exe differs? What should I do to see my effect in built version? Maybe I need to use an another shader?
0
Cube that turns every for example 5 seconds 90 degrees I want a cube to rotate 90 degrees every Second Counter should be setable Like in this video at 3.47 the spiky cube that turns 90 degrees https www.youtube.com watch?v bxWpsT4lKXU I have tried to do it but it will not turn 90 degrees smoothly or even 90 degrees, it just turns kind of 90 degrees but I need help I guess. Here is my script public class TurnCubeScript MonoBehaviour public Transform turnCube public float turnSpeed SETTING THE COUNTER FOR OBJECT TO TURN public float setCounter public float counter SETTING THE COUNTER TO SETCOUNTER AFTER COUNTER1 0 public float setCounter1 public float counter1 void Start () setCounter counter setCounter setCounter1 counter1 setCounter1 void Update () TurnTheCube() void TurnTheCube() counter 1 Time.deltaTime if (counter lt 1) SOME TRIES... turnCube.transform.eulerAngles new Vector3 (0, 0, 90 Time.deltaTime turnSpeed) turnCube.Rotate(0, 0, 90 Time.deltaTime turnSpeed) turnCube.rotation Quaternion.Euler(0, 0, rotation) counter1 1 Time.deltaTime GIVES THE CUBE SOME TIME TO TURN if(counter1 lt 1) counter setCounter counter1 setCounter1
0
How can I support many point light sources in a dynamically generated level in Unity? I'm currently working with a dungeon game which is similar to Dungeon Keeper by Mythic Entertainment. I'm using Unity and developing this game for Ipad 2 and above. Player can modify his dungeon, and I'd written a dungeon generator which creates it. In this case, I can't use lightmaps, because the dungeon has been created dynamically and player can tweak it. I also devised a way to combine separate game objects in a single mesh, so imagine that the entire dungeon (except special objects such as pillars, statues and mobs) is the single mesh. There's many point light sources (10 15 and above) on the stage, but Unity don't allow to use more than 8 light sources per object. So, if all dungeon cells are separated objects, I can use the diffuse or even vertex lit lighting, but if the entire dungeon is a single mesh, there's the hardware limit appears. Ways to solve this problem I'd divised Use separated geometry (tried) bad, because it harms berformance because there's many many many drawcalls (16 17 fps on Ipad 4). Use deffered shading (tried) bad, because it harms performance even more than separated geometry. Use a custom shader (haven't tried) I don't know how. Don't unite all cells in the single mesh but unite groups of cells to reduce the number of separated objects (haven't tried) Use the light manager (haven't tried) I don't know how. ??? How can I deal with it?
0
Can I run my own loading script during the Unity splash screen? Can I load data in the background while the Unity splash screen is up? If so, how? I am trying to run code during the splash screen, not just load assets. I have not been able to find any information on this in Google or the Unity Documentation.
0
Separating scene generation and scene starting in Unity? I'm working on a game, where the map is generated, and The map is generated in an Awake(), so when an object's Start() is called, the map should be fully initialized. But the scene's physics world won't be updated till the next FixedUpdate. So when Start() is called, there is a high chance, that physics operations are done in an incorrect world (like raycasting) I tried using Physics.SyncTransforms, but it didn't solve the issue for some reason. (Why?) My next approach was to start the objects with a delay. Precisely after a FixedUpdate. So I started a Coroutine in the Start() method, which waits for a FixedUpdate, then starts the object. But this caused that for example ObjectA's Update() is called before ObjectB's Start coroutine finishes. How could I achieve that scenes won't be started until the scene is fully initialized? Is there a way to tell Unity to call every Start() i.e. 1 frame later? Or how else could I fix this? What is the best solution?
0
A Pathfinding issues, player node is always off so I am using Sebastian Lague's second video on A pathfinding (https www.youtube.com watch?v nhiFx28e7JY amp list PLFt AvWsXl0cq5Umv3pMC9SPnKjfp9eGW amp index 2), and since he is using a 3d model, and I am using a 2d model, I need to convert some of the values to 2d. It is working fine, but the problem I ran into is that the node that detects the player is always off. Like in here, the cyan node is the node where my player is supposed to be, and the my cursor is where my player actually is. You can see that it is completely off. I am pretty sure this is because some error is produced while I tried to turn 3d into 2d, but I don't know how. Here is my grid script using System.Collections using System.Collections.Generic using UnityEngine public class Grid MonoBehaviour public Transform player public LayerMask unwalkableMask public Vector2 gridWorldSize public float nodeRadius Node , grid float nodeDiameter int gridSizeX, gridSizeY void Start() nodeDiameter nodeRadius 2 gridSizeX Mathf.RoundToInt(gridWorldSize.x nodeDiameter) gridSizeY Mathf.RoundToInt(gridWorldSize.y nodeDiameter) CreateGrid() void CreateGrid() grid new Node gridSizeX,gridSizeY Vector3 worldBottomLeft transform.position Vector3.right gridWorldSize.x 2 Vector3.up gridWorldSize.y 2 for (int x 0 x lt gridSizeX x ) for (int y 0 y lt gridSizeY y ) Vector3 worldPoint worldBottomLeft Vector3.right (x nodeDiameter nodeRadius) Vector3.up (y nodeDiameter nodeRadius) bool walkable !(Physics2D.OverlapCircle(worldPoint,nodeRadius,unwalkableMask)) grid x,y new Node(walkable,worldPoint) public Node NodeFromWorldPoint(Vector3 worldPosition) float percentX (worldPosition.x gridWorldSize.x 2) gridWorldSize.x float percentY (worldPosition.y gridWorldSize.y 2) gridWorldSize.y percentX Mathf.Clamp01(percentX) percentY Mathf.Clamp01(percentY) int x Mathf.RoundToInt((gridSizeX 1) percentX) int y Mathf.RoundToInt((gridSizeY 1) percentY) return grid x,y void OnDrawGizmos() Gizmos.DrawWireCube(transform.position, new Vector3(gridWorldSize.x, gridWorldSize.y, 1)) if (grid ! null) Node playerNode NodeFromWorldPoint(player.position) foreach (Node n in grid) Gizmos.color (n.walkable)?Color.white Color.red if (playerNode n) Gizmos.color Color.cyan Gizmos.DrawCube(n.worldPosition, Vector3.one (nodeDiameter .1f)) And here is my node script using System.Collections using System.Collections.Generic using UnityEngine public class Node public bool walkable public Vector3 worldPosition public Node(bool walkable, Vector3 worldPos) walkable walkable worldPosition worldPos
0
How to disable animation root motion I downloaded some animations with root motion from Mixamo and the corresponding character model. After created an animator with those animations and added it to the character game object, the root motion was causing the transform to move around, which was not supposed to happen. I tried to uncheck "Apply Root Motion", and set "Motion Root Motion Node" to "None", but neither of them worked. The only thing that worked is checking "Loop Time Loop Pose", but it doesn't make much sense to mess with root motion, someone even proposed it shouldn't disable root motion. So, how to disable animation root motion? Also I'm confused, is root motion optional? Must I get animations without root motion if it's not needed?
0
How can I separate gameview from UI most efficiently in Unity? Let me provide an image to illustrate what I mean. It is from a game called Runescape.
0
Enemy walks to the nearest player? I'm trying making my enemy goes to the nearest player to him but what i get is kind of hesitated or shaking. I think is from the first line on Update but i don't know how to solve it. Here is my script private Animator enemy anim private NavMeshAgent mAgent private GameObject player public GameObject dead point public int farPoint, dead point number,player number public float dist public bool enemt run, enemy atack false void Start() mAgent GetComponent lt NavMeshAgent gt () enemy anim GetComponent lt Animator gt () player GameObject.FindGameObjectsWithTag("Player") dead point GameObject.FindGameObjectsWithTag("dead point") 3 points enemy dirction() void Update() player number Random.Range(0,player.Length) dead point number dead point.Length dist Vector3.Distance(transform.position, player player number .transform.position) if (player ! null amp amp dist lt 5.1f) mAgent.destination player player number .transform.position if (dist lt 1.2f) enemy atack true else enemy atack false else if (dead point number gt 0) mAgent.destination dead point farPoint .transform.position else mAgent.destination player player number .transform.position if (mAgent.remainingDistance lt 1.5f) enemy atack true else enemy atack false enemt run true mAgent.speed 1.0f enemy anim.SetBool("run", enemt run) enemy anim.SetBool("attack", enemy atack) end update void enemy dirction() if (dead point number gt 0) farPoint Random.Range(0, dead point.Length) mAgent.destination dead point farPoint .transform.position else
0
Why am I unable to edit the Input Field object's script? When attempting to edit an Input Field object's script like so I get the following error Unable to open C Program Files Unity Editor Data UnityExtensions Unity GUISystem UnityEngine.UI.dll Check external application preferences. Why is Unity attempting to open a .dll, here?
0
Upper Lower angular limits on Y and Z axes My Task I'm trying to replicate this project. I'm using unity as my physics engine. Currently I'm still learning how to work with the different joints unity has to offer. The type of movement I'm looking for is where a body is connected to only one other body and its relative movement can be limited based on angles on different axes. My Problem I'm using Configurable joints for my movement restrictions. The Low Angular X Limit and High Angular X Limit does exactly what I'm looking for since it can have a different uppper and lower rotation limit. Looking at the documentation, it seems that this can only be done on the X axis. The Y and Z axes only have a Angular Y Limit or Angular Z Limit which set the upper as the opposite of the lower limit. My Question Is it possible for the Y and Z axes to have the same lower upper limit system that the X axis has? Is the use of configurable joint good for this task? Thanks in advance )
0
Tools or techniques for UV unwrapping texturing terrain with features such as roads? I'm trying to create a map similar to Outset island in Loz Wind Waker. Here is an example of what I'm trying to create As you can see, the roads more or less have dedicated tris. However, when I look at the UV data, it looks like a complete mess For reference, this is the texture without any overlays I have no idea how to go about creating a similar effect in my own game are there any tools I can use? What is this technique called?
0
Gravity well shader for Unity2D I'm trying to find or create a gravity well distortion shader for Unity. I've been looking around and all I can find are "lenses" which bend space around a black hole. I'd rather have a distortion that "pulls" or "bends" the image behind into a small hole. Essentially, what this would look like if viewed from above (ignoring the sphere) I can't seem to find any examples or a common terminology for it.