_id
int64
0
49
text
stringlengths
71
4.19k
0
How can I create Portrait game assets to have same with gap for both iPhone 7 Plus and iPhone X? In my Unity game I made changed my Pixel Per Unit value to 243 since the height of a Portrait game for iPhone X is 2436. The game looks great and the asset sizes look just right on the iPhone X simulator. But when I change to iPhone 7 Plus I get considerable space on the sides and it gets worse when I change to the iPad. How can I make my game have the same width gaps for iPhone 7 Plus and iPhone X without making assets look stretched horizontally or vertically? UPDATE The images below give an idea of my game on both 1080x1920 (for iPhone 7 Plus) and 1125x2436 (for iPhone X). It's not a match3 game. All the game objects below are static and have colliders. The gaps between are quite significant for other dynamic objects to move between. Reducing the gaps significantly would alter the movement of the dynamic objects and their sizes too, making the ratio in object sizes look wrong. I haven't started worked on scores or menus yet, so I haven't added a UI canvas yet.
0
Can I reset the DisallowMultipleComponent attribute in child classes in Unity somehow? Can I reset the DisallowMultipleComponent attribute in child classes in Unity somehow? I want to create my base class DisallowMultipleComponent public class MyCompanyClass Monobehaviour I want all my component scripts to inherit from the MyCompanyClass. So, I will be able to add only one instance of my component script to a game object at a time. I need it for most of my classes. But for some classes I still want to preserve the ability to add a few class instances to a game object, while still inheriting from the MyCompanyClass (because I am going to put some custom behavior into it, which is going to be used by all my component scripts). So, I was trying to search for something like AllowMultipleComponent , but found nothing. Is there maybe another way to achieve what I want?
0
How do I make the PS4 controller vibrate in Unity3D on mac? I am currently working on a 2D game in Unity3D with an option to play with a gamepad controller. I would like the PS4 dualshock 4 controller to vibrate. I am on mac. I have looked into Xinput but I think it is only for Windows, I may be wrong.
0
faster compile and editor update in unity sometimes for some small changes, I need to recompile the code In the editor and it causes some time to be testable in the editor(sometimes more than 20, 30 seconds). I know when loading shows on the bottom right side of the editor in means that it's compiling the code and when it doesn't move it means that it's updating the editor or checking for possible updates. I need to know is there any way to make it faster? I mean, is there any option to tell unity don't recompile unchanged classes or don't consider all editor classes for changing the editor? or any other technique that makes the process faster? as I use unit tests in the editor, most of the time is consumed by updating the editor for any added function or changes on them.
0
Unity2D Proper way to implement ladder climbing with a raycast controller? I originally posted this on Stack Overflow, but was told I might have more luck here I've been slowing grinding out programming features for my character controller, and one of the last things to implement is ladder climbing. The code I've come up with over the past 2 days mostly works, but presents some issues Sometimes the character bounces after climbing while holding the up arrow, at the point with which a 1 way platform meets the end of the ladder. Once the character is all the way up, resting on the 1 way platform, it cannot go back down. This can be remedied with a longer ladder collider, but that makes issue 1 worse. If the character is on the ground near a ladder and jumps, but presses the up arrow at the very last second, it gets flung considerably far in a certain direction. If the character is on a rope and jumps off the rope, but holds the up arrow before doing so, it goes slightly higher, but is noticeable. Not holding the up arrow, but rather just pressing the left or right arrow and jumping, yields a regular jump. Perhaps this has something to do with the x or y input axes? The way my classes work is that I have a Controller2D class which handles most of the raycasting stuff and movement methods, a Player class for input that calls the movement methods, and a parameters class that sets default world parameters, like gravity and jump height, but can be overridden if the character is in a certain volume, such as water or a ladder collider (this allows me to set gravity to 0 while climbing so the character can move properly). Almost all of my ladder code is contained in the OnTriggerEnter Stay Exit functions, and I'm just not sure if this is the best way to do it. I tried making a ClimbUp ClimbDown method, and shooting a raycast from the center of the player, which would allow him or her to climb up, but this was not overly successful (there were too many issues compared to using OnTriggerStay). I'm wondering if someone who has successfully implemented ladder climbing in a raycast controller, or anybody who might have advice, would be willing to point me in the right direction for this task. Here's some of the script public void ClimbLadder(float y) ClimbingOnLadder true SetVerticalForce(y) public void JumpWhileClimbing(float x) if (ClimbingOnLadder) ClimbingOnLadder false overrideParameters null AddForce(new Vector3(x, Parameters.jumpVelocity .70f, 0)) JumpAfterClimbing true print(Parameters.jumpVelocity) private void OnTriggerEnter2D(Collider2D other) if (other.tag "Ladder") CanClimb true private void OnTriggerStay2D(Collider2D other) if (other.tag "Ladder") if (ClimbingOnLadder) var newParameters other.gameObject.GetComponent lt ControllerPhysicsVolume2D gt () if (newParameters null) return overrideParameters newParameters.NewParameters Debug.Log("overriding") if (ClimbingOnLadder amp amp State.IsCollidingBelow) ClimbingOnLadder false overrideParameters null private void OnTriggerExit2D(Collider2D other) if (other.tag "Ladder") CanClimb false ClimbingOnLadder false JumpAfterClimbing false var newParameters other.gameObject.GetComponent lt ControllerPhysicsVolume2D gt () if (newParameters null) return overrideParameters null
0
How can I verify that a Steam key is legit? I am developing a game that has online multiplayer. It will be available on Steam. However, I do not want to use Steam authentication to use the online capabilities. I will use my own account system, so you must register with your email and password. Which brings me to the next problem how can I verify if this newly created account is a legit owner of the game in Steam? I can ask the player to provide their license key, but how could I verify that this key is valid? Does the Steam web API have a way to check if a key is valid, regardless of having been used to redeem the product or not?
0
How to assign an index to different node clusters? (for pathfinding) Hellow So for a bit of context i'm currently working on a RTS (way above may league) which already has a level editor and a node grid which maps the terrain, i previously make a navigation system with A as explainned by Sebastian Lague in his tutorial series about the topic, but then i run into a problem when running with multiple units (not the point here but never manage to find each unit cluster within the selection), so i change it into a navmesh mapping which if made dynamic by assigning navmesh obstacles to the unwalkable nodes (the frame after the creation of the node grid) Now i want to use the node grid basically to check if the target node and the start node share the same node cluster. But here is the thing i can't assign the needed index to the nodes as i expected. I've been trying adapting code from this post, but didn't quite make it. Now i have this one, which i think could achieve something but still gets me a invalid operation exception public const int UNWALKABLE ISLAND 999 public static void SetIslands(ref WorldGrid worldGrid) int width worldGrid.nodeGrid.GetLength(0) int height worldGrid.nodeGrid.GetLength(1) bool , visited new bool width, height int clusterCount 0 for (int x 0 x lt width x ) for (int y 0 y lt height y ) if (visited x, y ) continue else List lt Node gt cluster new List lt Node gt () worldGrid.nodeGrid x, y foreach (var node in cluster) if (node.isWalkable) visited node.X, node.Y true node.SetIslandIndex(clusterCount) cluster.AddRange( worldGrid.GetNeighbours8D(node)) else cluster.Remove(node) clusterCount The error InvalidOperationException Collection was modified enumeration operation may not execute. System.ThrowHelper.ThrowInvalidOperationException (System.ExceptionResource resource) (at lt 437ba245d8404787b9fbab9b439ac908 gt 0) System.Collections.Generic.List1 Enumerator T .MoveNextRare() (at lt 437ba245d8404787b9fbab9b439ac908 gt 0) System.Collections.Generic.List1 Enumerator T .MoveNext() (at lt 437ba245d8404787b9fbab9b439ac908 gt 0) Pathfinding.SetIslands (WorldGrid amp worldGrid) (at Assets Pathfinding.cs 25) WorldGrid.CreateNodeGrid() (at Assets WorldGrid 80) WorldGrid d 12.MoveNext() (at Assets WorldGrid.cs 42) UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, Sustem.IntPtr returnValueAddress) (at lt 437ba245d8404787b9fbab9b439ac908 gt 0) UnityEngine.GUIUtility ProcessEvent(Int32, IntPtr) My node class contains an int that should hold the cluster index, which will be using for the request check. (the code its based from this youtube video) Right now i'm trying to understand the spectral clustering stuff, i've been told it could help. I hope you can help an animator in need with some pointers. Cheers 3 Oh!, I also tried reading the nav agent path end coordinate for comparison, but it ended up becoming a huge mess for me.
0
Text not instantiating under a canvas (unity) Below is my code for a text I want to spawn under a canvas. Both spawn and I no longer get errors, but the text isn't spawning under the canvas. Instantiate(canvasparent) Text savescore Instantiate(score) as Text savescore.transform.SetParent(canvasparent.transform, false)
0
Unity's new Input system does not work after building the game I've made a test project to test the new Input system pointers (touch and mouse), in the editor, everything works perfectly however when I build the game they don't. it's like there is not an input system. I'm not sure if I'm missing a setting or something. I've made simple sean where the Ui displays the available devices, whether they're enabled or not, and if a touch or mouse click detected it will display general information about it. this is how it works in the editor And this is the android version, note that button press still works I did not record the PC standalone version but it still does not respond. this is the link to the build https github.com Venay Input test this is the code I used and couple of screenshots of my settings using UnityEngine using UnityEngine.UI using UnityEngine.InputSystem namespace Testing.InputDebugger public class InputDebugger MonoBehaviour PointerInput pointerInput public Text inputText public Text deviceText public Text buttonText private void Awake() pointerInput new PointerInput() pointerInput.General.Pointer.performed ctx gt OnPointer(ctx.ReadValue lt myCompositData gt ()) pointerInput.General.Pointer.canceled ctx gt OnPointer(ctx.ReadValue lt myCompositData gt ()) string text "" foreach (var S in InputSystem.devices) text S.device " " S.enabled " n" deviceText.text text private void OnEnable() gt pointerInput.Enable() private void OnDisable() gt pointerInput.Disable() public void OnPointer(myCompositData data) string n " n" string Press "Press " data.Press.ToString() n string PressCount "Press Count " data.PressCount n string Position "Position " data.Position n string Delta "Delta " data.Delta n string Radius "Radius " data.Radius n string Tap "Tap " data.Tap n string StartPosition "Start Position " data.StartPosition n string StartTime "Start Time " data.StartTime n string Scroll "Scroll " data.Scroll n inputText.text Time.time n Press PressCount Position Delta Radius n Tap StartPosition StartTime n Scroll public void OnButtonPress() gt buttonText.text "Pressed at n" Time.time
0
How can I create a precise touch in Unity Is there a way so that I can touch an object precisely? I have these aerial cars and there pretty tiny like 32 by 32 and it's hard to touch them using a raycast. I thought I'd spawn an object with a circle collider on it on the first touch and destroy it after the touch.
0
SerializeField vs GetComponent Efficiency As far as I know, there are two built in ways to get an instance of a component in Unity. 1 Serialize the field and drag in the component manually in the editor SerializeField private MyScript script 2 Using MonoBehaviour's GetComponent method script GetComponent lt MyScript gt () I would think that it is more efficient to drag the component in the editor lest making the engine illiterate through every component in the GameObject to find the component. Is it more or less efficient to drag the component in the editor compared to using GetComponent? Or does Unity find components in a different way or dragging components in the editor is handled in a different way such that it would be more efficient to use GetComponent? Would using one over the other have any impact on performance in the real world? A similar question would also be raised regarding GameObject.FindGameObjectWithTag() vs dragging in the editor. As far as optimization go, should you use one method over another?
0
Switching between meshes vs Loading only specific mesh I am currently developing an online multiplayer game on Unity. In the game, the character of each player will be assigned its mesh after the game receives parameters (their meshes' names) for each character from the server. Assigning each character's mesh can happen after the main scene is loaded. I am wondering whether I should make each character's object the same by having every mesh possible loaded into it and only activate the corresponding mesh for that player. I should create a class that holds every mesh possible (like, mesh manager) and tell each character to use its mesh from that class. I should delay the characters' meshes loading to wait for the parameter from the server first. Then, load the mesh after the scene has been loaded. I am not sure if specific assets can be loaded outside of its scene in Unity. If anyone has any different solutions, feel free to suggest. Thanks in advance.
0
How to vary the initial velocity of a jump based on hold time? What I want to do is, the longer player holds the screen, the longer distance the object will jump when they release the hold. Here is my code private float timeBeginTap switch (touch.phase) Finger start touching the screen case TouchPhase.Began print("Start tapping") timeBeginTap Time.time break Finger leaving the screen case TouchPhase.Ended when finger release,the object jump float timeHolding Time.time timeBeginTap Debug.Log( "The player1 touched the screen for timeHolding seconds.") Vector2 jumpVelocity new Vector2(timeHolding, timeHolding) rb.velocity rb.velocity jumpVelocity break So with the code above I can get the value like 0.6324167, or 0.423567 for timeHolding, which is the amount of time that user hold the finger on screen. And I able to make the object jump by using this code below Vector2 jumpVelocity new Vector2(timeHolding,timeHolding) rb.velocity rb.velocity jumpVelocity But the distance traveled or "force" with which the object jumps is very small and it doesn't make sense. Therefore I make an attempt with the code below float right 5 float up 10 Vector2 jumpVelocity new Vector2(right timeHolding,up timeHolding) rb.velocity rb.velocity jumpVelocity With the code above, the distance is of course longer. But it feels constant and not dynamic, because the relationship between the Vector2's X and Y value is always constant. Therefore my question is, What is the correct way to define the values of X and Y for a Vector2 object based on the value of Time? If I missed anything, please guide me in the right direction. Desired Outcome For example,the velocity added to the box is to let the box jump from pole to another pole and stand on it. The velocity is define by using the time user hold on the screen,the longer the user hold on screen,the greater the velocity,means the x,y value of Vector2 is define by the timeHolding. Now when I hold the screen for the long time,the box will jump to the 3rd or 4th pole,and it not guarantee will reach the pole.Like everything is by chance. What I want is,the box will jump from 1st pole to 2nd pole,from 2nd to the 3rd and continuously.At the same time,the velocity to go higher or lower and the distance is depends on the time user hold the screen. This is what I want and my limited understanding of the problem.
0
Box collider rigid body eventually moves through static collider I found this question, but I'm not sure if it applies to my problem. I'm hacking together a Pong style game, and my problem is with the walls (box collider, no rigid body) not completely stopping movement of the player paddle (box collider, yes rigid body.) Sufficiently fast mouse movement eventually moves the paddle through the wall. There is initial resistance, but I would expect Player Paddle to stop moving abruptly at the wall. How can I make this happen? I'm new to Unity colliders game dev. My player paddle simply moves up and down (Z axis) with up down mouse movement public class MouseMovement MonoBehaviour public float speed 10f Update is called once per frame void Update () var translation Input.GetAxis("Mouse Y") speed translation Time.deltaTime transform.Translate(0, 0, translation) I exported an asset package that reproduces the problem. My problem objects are Player Paddle, Upper, and Lower https www.dropbox.com s yx9svb51nywdvgg pong export.unitypackage?dl 0
0
Unity GameView Differrent with CameraView Dont have 3D environments Now on my existing project, if i create new scene, automatically i got my gameview like below above game does not have 3d environments outlook, i'm expecting like below (my old existing scene) Any Idea to solve this ? thanks
0
Nuget in Unity with Mac OS I have moved over to Mac for Unity development, and am aware you can still use Windows .dll files in your project. I use NuGet as a secure method of getting specific dlls, and have usually done this on Windows by manually downloading the .nukpg and extracting the .dlls using WinRAR, then putting the dlls in Unity. So far, I have thought of two ways to do this on Mac 1.) Doing the same thing, but with a WinRAR alternative that can open .nukpg 2.) Using Visual Studio for Mac that has a NuGet interface built in with Unity Has anyone done this, or found a solution for getting package from NuGet in Unity for Mac?
0
Invoking a common method after a button press I want to implement a common method that handles several numeric values and performs and action based on those values. So I have buttons with specific methods to change this values without affecting the rest. However I want to link them all to a final method that runs right after the press of a button, so this way the game will change only when the player chooses to change it and changes according to the players decisions. How can I implement this in my script? Most of my methods are like this public void "ButtonIDGoesHere" (int "SpecificVariable") Add, Sub, Multiply, etc. What can I add so that it goes to a common method right after it executes its instructions?
0
How would I find the SDK folder for Android Studio so I can build my Unity project? So I've been trying to build my unity project for android, but my problem is that I don't know how to find the Android SDK. I have the old developer bundle installed, when it was still the one with eclipse, but this version is not supported by Unity. So, I installed the latest version of Android Studio, the new official Android IDE, but the SDK folder is not in the same place as the rest of the program. How would I find the SDK folder for Android Studio so I can build my Unity project?
0
Animation workflow between Blender and Mecanim I've recently started learning Unity. Not being able to add custom animations to the standard FBXs you get from Unity's app store is really really slowing me down. When I import one into Blender, it brings none of the animations with it. I also purchased 3D Studio Max and, while a little better, it's still a steep learning curve. Can I create an animation in Blender or 3D Studio Max and apply it to an existing Mecanim model? Do I need to manually create and rig a basic model, import it, then move its animation to another character, or is there an easier way?
0
Unity OnRenderImage hides UI I have a component which renders a few different cameras and the images. However, this obscures my UI when in Screen Space Overlay mode. I can put the canvas in WorldSpace mode, which works, but then the UI is affected by the image effect I've built and is, of course, not locked to the camera. Suggestions? Update additional details At design time, the OVR camera rig contains a single camera centered between the "eyes." This component is attached to the camera rig's centerEyeAnchor. At run time, the rig creates two additional cameras one for each eye. These aren't supposed to be modified by user code. (Among other things, their projection matrices are pretty weird.) I need to modify the image per eye. I created a new component which create two additional cameras per eye. One renders a low res version of the entire scene, the other renders a high res image of a portion of the screen, each to a dedicated RenderTexture. Pseudocode void Update() called once per frame called twice per frame once per eye void OnPreRender() called twice per frame once per eye void OnRenderImage(RenderTexture source, RenderTexture destination) low res render of entire scene var camOuter m cameras ... hi res render of part of the scene 10 20 of original image area var camInner m cameras ... update cameras to match current eye camera camOuter.copyFrom(Camera.current) camOuter.targetTexture m outerTexture render scene to low res texture camOuter.Render() camInner.copyFrom(Camera.current) camInner.targetTexture m innerTexture target texture that the Oculus wants to render to var ovrTexture Camera.current.targetTexture save projection matrix var originalProjectionMatrix camInner.projectionMatrix var scale new Vector3(m innerTexture.width 1.0f ovrTexture.width, m innerTexture.height 1.0f ovrTexture.height) zoom pan matrix to clip to part of the scene var gazeMatrix Matrix4x4.Scale(scale) offset projection gazeMatrix.m03 (1 2 gaze.x) scale.x gazeMatrix.m13 (1 2 gaze.y) scale.y camOuter.projectionMatrix gazeMatrix amp originalPRojectionMatrix render hi res portion of the scene centered at gaze pixel camOuter.Render() restore projection matrix cam.projectionMatrix originalProjectionMatrix composite images m material.SetTexture("InnerTexture", m innerTexture) m material.SetTexture("OuterTexture", m outerTexture) Graphics.Blit(null, destination, m material) (I'm also worried that there may be additional scene renders happening in the background.) The problem is that the UI does not render if set to Screenspace Overlay or Screenspace Camera. I can get it to render in Worldspace, which may be the only way to do this, but then it seems I'd need to create yet another hi res texture matching the viewport dimensions and render the UI layer to that, and keep it locked to the current eye's camera position. Alternatively, I could re use one of the current cameras, I guess, and just tweak its settings. Is there a better way to do this? Ideally, I'd like to have the engine just render the UI as it does in other applications without having to jump through hoops. However, at this point, I'll take anything I can get that works and looks good. Update the 2nd Okay, it looks like the UI is rendered perfectly if I use a regular camera instead of the OVR rig. ( Having the rig in the scene, though, prevents it from drawing at all.
0
How do I make my plane appear 3D like in the "Roll a ball" tutorial? I am following the first tutorial on the Unity website, which details making a 'Roll a ball' game. I am stuck at a point where I need to make a 3D plane object it looks flat, to me, and unlike how it looks like in the tutorial. How do I make my plane look 3D? This is what I see This is what I see in the tutorial
0
How to build a hidden 3D snapping grid effect? Looking to build a 3D grid similar to the image below taken from Google Blocks. Seems like it consists of these main components A set of spheres that can go transparent. A stencil that follows the controller's location. When stencil overlaps with spheres, they show up, otherwise, alpha fades to zero. Any advise on how to approach building this?
0
Unity2D Scaling and Locking Image to anchor points I have a script that uses Index to change an objects sprite using OnClick to move through the sprites, like a slideshow. I want the image to scale to the size of my anchor points, because I've notice that when I stretch the game or put the game on maximize play the image stays the same size and doesn't scale to the size of my anchor points. How would I do that? This is my script public Sprite Images Index starts at one because we are setting the first sprite in Start() method public int Index 1 void Start() Set the image to the first one this.gameObject.GetComponent lt SpriteRenderer gt ().sprite Images 0 public void onClick() Reset back to 0 so it can loop again if the last sprite has been shown if ( Index gt Images.Length) Index 0 Set the image to array at element index, then increment this.gameObject.GetComponent lt SpriteRenderer gt ().sprite Images Index Thank you. )
0
How can I change some tree's radius and length in C script in Unity3D? So, I have this little tree stem. It only has its initial node. All I would like to do is make it grow in length and radius in Update(). How can I do that?
0
Unity Access to svPosition in fragment shader I am trying to access to the svPosition in my fragment program in Unity but I keep having this error. invalid input semantic 'POSITION' Legal indices are in 1,15 invalid ps 3 0 input semantic 'POSITION' Here are some information about my whole shader. struct float4 pos SV POSITION vertex o.pos mul(UNITY MATRIX MVP, v.vertex) fragment col.rgb i.pos.xyz Any idea how to access this value?
0
How do I stop movement from being mirrored on the X and Y axis with Unity Kinect? I have made a scene and avatar in the scene, put all of the correct joints on the Open NI Skeleton, but the outcome is not only mirrored on the x axis, it is also on the y axis. So, when I lift my arms, the avatar's arms move downward. How can I fix this?
0
what is best iap unitypackage (Asset) for support google play amazon in unity 2019.1.9? I need a unitypackage easy and easy for In app purchasing in googleplay and amazon (for Android) Which unitypackage is best in unity 2019.1.9?
0
How to know the size of object in Unity in world units? Suppose I have some external package with objects. Suppose I place some of these object to the scene. Now how to know actual size of object in world units? I found no any rulers or something in Unity. The I thought I can place primitive cube and compare it, but then I realized that I don't know the size of cube too. Is is possible to "measure" arbitrary object in Unity somehow?
0
How can I change the color of an object at runtime? I wish to have the shader effect as in the game 'The stack' by ketchapp https play.google.com store apps details?id com.ketchapp.stack amp hl en As you can see, the color of the objects as well as the skybox keep changing. I'm completely c noob and trying my best to find shaders to replicate the effect. But I can't find anything. How can I change the color of an object at runtime?
0
Workflow to animate character rig with an already animated model How should I go about animating character rigs (walking, running, ducking, ...) with already animated assets? Do I load the animated asset into the project file of my character rig or do I attach the animated asset to the rig in the engine? I am using Blender for the models and Unity3D as the engine.
0
Is there a way to convert shader graph to shader code for older version? Editing Shader in a graph is brilliant feature, however it's only works in Unity 2018 with Lightweight RP template. So I want to use the shader made from shader graph in Unity 2018 to older versions, such as 2017 or 5.x. There is a button to compile the shader to code but unfortunately when I drag into 2017 it gives me syntax error so I can't use it. Is there a way to use the shader made from Unity 2018's graph editor to older versions of Unity?
0
Gizmos.DrawMesh does not render anything I would like to draw a procedural mesh as a gizmo Gizmos.DrawMesh(mesh) however this does not render anything no matter what. I can confirm that the mesh in question is a correct one by both GetComponent lt MeshFilter gt ().mesh mesh assigning it to Renderer and rendering it using default material and Gizmo.DrawLine drawing it edge by edge. No error are logged in debug window, setting position or flipping triangle orientation has no effect neither. Version of Unity is 5.6.2f1. Am I missing something? void Start () GetComponent lt MeshFilter gt ().mesh mesh renders without any problems void OnDrawGizmos() Gizmos.color Color.red Gizmos.DrawMesh(mesh) nothing rendered renders without any problems for (int i 0 i lt mesh.triangles.Length 3 i ) Gizmos.DrawLine(mesh.vertices mesh.triangles i 3 2 , mesh.vertices mesh.triangles i 3 ) Gizmos.DrawLine(mesh.vertices mesh.triangles i 3 , mesh.vertices mesh.triangles i 3 1 ) Gizmos.DrawLine(mesh.vertices mesh.triangles i 3 1 , mesh.vertices mesh.triangles i 3 2 )
0
How can I trigger an event each time the rotation of my rigidbody2D is at a given value? I would like to trigger an event each time my rigidbody2D is at a particular value. The event should only be triggered once for each given value per complete object revolution. Initial attempts at achieving this have resulted in the following method which checks against an array of values, logging an event and incrementing an index when the value has been passed. static readonly float angles new float 90f, 180f int angleIndex 0 void CheckForTrigger() if (rigidbody2D.IsSleeping()) return var rotation Mathf.Abs(rigidbody2D.rotation) if (rotation 360f gt angles angleIndex ) Debug.Log("Fire") angleIndex if (angleIndex angles.Length) angleIndex 0 This suffers from a couple of issues Floating point inaccuracy means that values close to 360f will often be missed (e.g. 359f) Fire will be logged each frame between the last and first value (i.e. between 180f and 90f) Does anyone have any advice for approaching this problem and improving the above method?
0
Create Mesh in gap between tiles (in Unity3D) I am loading two kinds of tiles (meshes in tile format) in Unity, both are placed in the environment correctly but there is a gap between these two tiles (see the picture below). I want to fill this gap automatically either through scripting or a shader. With scripting, there is an algorithm I thought of, but its first step is taking too much time. Get each tile and get the outer edges of the mesh (it's taking too much time to calculate with each tile, as there are thousands of tiles) Then raycast from the outer edges of the mesh and get intersection points of outer tiles Take vertices and draw the mesh. I get stuck in the first steps, as it's taking so much time to calculate the outer edges of a tile. Maybe there is a solution available in form of a shader that works in the gaps of two meshes? Here is visual representation
0
Unable to check Cardboard XR Plugin in Unity I tried to create a project for Cardboard VR. I imported the git VR package from the Google Cardboard XR Plugin for Unity repository on GitHub. Then, in Project settings gt XR Plug in Management I tried to check Cardboard XR Plugin, The package is not installed, I got the error message which is shown the below screenshot.
0
Unity 5.5 Android scaling The questions I've seen are outdated, explained, not to my liking, or just don't work. Problem I want to be able to create a game that can scale on all mobile devices with ease and with no pixelation. Extra Info I'm very new to unity and tackling the the software with all my might I'm sorry for being a noob. I already paired unity with my phone and set the build to android (Nexus 5). Aspect ratio is 10 16, The game is going to be portrait. I have no scripts or anything, Its legit a blank game with a camera that has a blue background. I have some pictures, if you need anything else for my assistance don't hesitate I'm here to learn and take, GULP, Constructive Criticism. PC Android
0
How can I get OnMouseEnter to trigger on a 3D Text in Unity3D? I've just started to learn Unity3D. I want to create a simple 3D menu with just two 3D Text instances. I've created and named them, then dropped this script function Awake() print("MenuItem " gameObject.name " init!") function OnMouseEnter() print("OnMouseEnter " gameObject.name) function OnMouseDown() print("OnMouseDown " gameObject.name) I only see the init awake message printed in the console. What am I missing ? EDIT Sorry, I forgot to add the BoxCollider(Physics Box Collider) to my object, so no events were triggered.
0
Using XBox 360 controller in Unity game game doesn't recognize axis movement I have a problem with the usage of XBox controller in Unity game. I connected the controller to the PC and it works fine, I also managed to use it in the game itself I'm using "A" button to fire and Start to start the game and they work properly. However the game doesn't recognize the x axis movement. I'm not sure if the problem is in the input settings or my code. This is how the Horizontal movement is defined in the game This is the code that handles the movement float x Input.GetAxis("Horizontal") Vector3 newPosition new Vector3(transform.position.x x playerXMoveSpeed, 0, 0) newPosition.y transform.position.y newPosition.z 0 transform.position Vector3.Lerp(transform.position, newPosition, playerXMoveSpeed Time.deltaTime) var limit animator.SpriteRenderer.bounds.extents if (transform.position.x limit.x lt leftBorder) var capped transform.position capped.x leftBorder limit.x transform.position capped else if (transform.position.x limit.x gt rightBorder) var capped transform.position capped.x rightBorder limit.x transform.position capped OnMove(gameObject) All variables are more or less self explanatory, the OnMove is a delegate that just applies the transform to the gameObject in question. The entire code is inside a void method called Move(). That method is called inside an if statement if ((Input.GetAxis("Horizontal") ! 0.0f Input.GetButtonDown("Horizontal")) amp amp !IsContinueDisplayed) FollowTouch() Like I said, the game recognizes the other buttons, but not the x axis, it doesn't move the character. The Input.GetButtonDown is there just so keyboard input would be supported also (and it works properly). Can you see the problem with this code or settings? Please advise.
0
Unity 5 Occlusion culling at runtime I am creating a game in Unity where the game is rendered while playing. The game is made in a voxel style, and has thousands upon thousands of objects rendered while playing. Of course, this causes a huge amount of lag. Therefor I need to use occlusion culling, to make sure only the objects needed are rendered. For occlusion culling, you need to bake the area, but I'm planning on creating a huge world. So, any tips on how I could do this?
0
Flash animation or Sprite sheet animation good for Unity mobile games I would like to develop dress up and cooking kind of games. So it needs lots of animations. Our designers done the animations in the lash. I found the plugins callued GAF and UniSWF to convert flash animation to Unity or We can convert animations into sprite sheets and animate them in Unity, But i don't know which one is the best way to do animations for mobiles with better performance and lower game size. Any kind of suggestion is good. Thank you!
0
Can geometry grass shaders be painted to a terrain or are they limited to meshes? So I was follow the roystan grass shader tutourial and although it works well I don't understand the use for it. From what I understand the shader is basically just a flat plane that calculates grass on top of it. If I wanted to apply this grass to a terrain and place it on uneven ground would I have to manually add in a quot grass plane quot all over the environment and at different angles or am I missing something? Thanks.
0
Why doesn't the Camera.pixel(Height Width) match the Canvas size? I am making an app that has a custom viewport Rect like so When I check the sizes of this viewport rectangle in pixels with Camera.pixelHeight Camera.pixelWidth, I get the following values 743px, 770px. This looks correct. Now when I check my canvas in the Editor, I see the following values for the width and height Now I have a script that gets the width and height of the canvas. This is correct I get again the 743px and 770px. But when I position my UI element, it is outside because the positioning refers back the the incorrect values displayed in the canvas rectangle transform properties. What is happening here and how do it make the canvas use the correct values?
0
Getting dynamic objects to match baked lighting on nearby static objects Here's how the hallway in my game looks now You might notice the dark section near the centre of the screen This is, in fact, a pair of cupboard doors which are not set to static and so don't get included in the baked lighting. The problem is, since all of my house lights are baked only, it looks like the only light these doors are getting is the ambient light so quite dark. Is there an alternative, best practise to ensure non static objects get lit sufficiently when lighting is baked?
0
Why do I get white highlights at the edge once light build complete? Whenever I build my lights in Unreal, why do I always get white highlights at the edges? I can't seem to solve this. I get this problem with both static and stationary lights. Can someone please help? I have also seen this problem in Unity and I could not solve it. Kumsan
0
How do I slowly decrease a float from 0.5 to 0? I have a 2D racing game with a track, and the track is repeated with vector2. When I die, I want to slowly stop moving the track, but I do not know how. Here is my code . using UnityEngine using System.Collections public class trackMove MonoBehaviour public static trackMove Instance get private set public float speed Vector2 offset Use this for initialization void Start () Instance this Update is called once per frame void Update () offset new Vector2(0, Time.time speed) GetComponent lt Renderer gt ().material.mainTextureOffset offset Here is my current Inspector view
0
How can I make a trail renderer flat with the normal of the nearest face? I'm making a basic skid system for a car model using a trail renderer. I have everything setup and working properly except that the trail renderer always faces the camera. I want the trails to be perfectly flat with the ground. So I thought if unity can make the faces all rotate towards the camera, then would it be able to rotate towards the normals of the nearest faces?
0
How can i scale a cube on one side on x only? I have in the Hierarchy a empty GameObject and a cube as child of it. The cube the child is at position 0,0,0 and scale 1,1,1 But when running the game the scaling is on both sides of the cube. I put the cube as child of the empty gameobject and scaling the empty gameobject but still it's scaling the cube on both sides. The script is attached to the empty GameObject using System.Collections using System.Collections.Generic using UnityEngine public class Walls MonoBehaviour Vector3 originalScale Vector3 destinationScale void Start() originalScale transform.localScale destinationScale new Vector3(100.0f, 0, 0) private void Update() if (transform.localScale.x ! 100.0f) transform.localScale new Vector3(1, 0, 0) This is a working solution using System.Collections using System.Collections.Generic using UnityEngine public class Walls MonoBehaviour public Transform objectstoScale private void Update() if (objectstoScale 0 .localScale.x ! 100.0f) objectstoScale 0 .localScale new Vector3(1, 0, 0) But i want to make that the same cube will also scale one side on the z. So the cube will be scaled on both x and z but without filling it one be like frames. So i tried this using System.Collections using System.Collections.Generic using UnityEngine public class Walls MonoBehaviour public Transform objectstoScale private void Update() if (objectstoScale 0 .localScale.x ! 100.0f) objectstoScale 0 .localScale new Vector3(1, 0, 0) objectstoScale 1 .localScale new Vector3(0, 0, 1) And i have now two cubes childs of the empty gameobject one cube position is 0.5,0,0 the second is 0,0,0.5 but what i'm getting is What i want to do is to create automatic a rectangle scaling a cube on 4 sides at the same time not filled rectangle. For example like this
0
How can I make the loop only once when it's inside OnGUI? The script is EditorWindow type. private void OnGUI() var selections Selection.objects.OfType lt GameObject gt ().ToList() if (selections.Count gt 0) for (var i selections.Count 1 i gt 0 i) var selected selections i transformSelection.Add(selected.transform) TransformSaver.SaveTransform(transformSelection.ToArray()) tempTransformSelection transformSelection transformSelection new List lt Transform gt () When I select with the mouse a object in the Editor Hierarchy it will keep making the loop nonstop since selections.Count is large then 0. I tried to add after the loop selections new List lt GameObject gt () But it didn't help. I want that it will make the loop and the whole code inside the if (selections.Count 0) only once each time when selecting one or more objects in the editor. If I select one object make the whole code once if I then selected another more object make the whole code over again for the two selected objects and so on but make it once. Now it will keep making the loop over and over again even if I didn't select more other objects. Since in the editor the first object is still selected it will keep making the code the loop over and over again. This is what I tried var selections Selection.objects.OfType lt GameObject gt ().ToList() if (selections.Count gt 0 amp amp isSelected false) for (var i selections.Count 1 i gt 0 i) var selected selections i transformSelection.Add(selected.transform) TransformSaver.SaveTransform(transformSelection.ToArray()) tempTransformSelection transformSelection transformSelection new List lt Transform gt () isSelected true The flag boolean isSelected is global variable and set to false as init. UPDATE what I tried var selections Selection.objects.OfType lt GameObject gt ().ToList() int currentSelectionCount selections.Count if (currentSelectionCount ! lastSelectionCount) lastSelectionCount currentSelectionCount for (var i 0 i lt currentSelectionCount i) var selected selections i transformSelection.Add(selected.transform) TransformSaver.SaveTransform(transformSelection.ToArray()) tempTransformSelection transformSelection transformSelection new List lt Transform gt () Selection.objects new UnityEngine.Object 0 But when I select object in the editor in hierarchy it's immediately unselecting the object since the line Selection.objects new UnityEngine.Object 0
0
Strange momentum on projectiles shot out of "parent" object I'm trying to shoot a projectile out of a moving quot parent quot object. Both objects move off of rigidbody physics, so I'm using addforce for the projectile. Whenever I move the quot parent quot object and turn while it's moving and shoot the projectile, I instantiate the projectile, copy the projectile spawn position to the projectile's position, copy the rotation of the quot parent quot to the projectile, then add force to the projectile. It'll shoot but I notice it moves in the direction of the momentum of the quot parent quot rather than straight forward from where it was created. I'm pretty sure this is just me not understanding how rigidbody physics works for adding force but if anyone has any suggestions as to how to make the projectile move straight forward from where it's created rather than copying the momentum of the parent I'd appreciate it greatly. My code for moving and creating a projectile looks like this void FixedUpdate() if (Input.GetKey(KeyCode.W)) player.transform.Translate(Vector3.forward 10f Time.deltaTime) this.GetComponent lt Rigidbody gt ().AddForce(transform.forward 15) if (Input.GetKey(KeyCode.S)) this.GetComponent lt Rigidbody gt ().AddForce(transform.forward 15) if (Input.GetKey(KeyCode.A)) transform.Rotate(Vector3.up 15 Time.deltaTime) if (Input.GetKey(KeyCode.D)) transform.Rotate(Vector3.up 15 Time.deltaTime) void ShootBullet() create bullet GameObject bullet Instantiate(bulletPrefab) set location where bullet will spawn from bullet.transform.position bulletSpawn.position set direction of the bullet bullet.transform.rotation bulletSpawn.transform.rotation add force to the bullet bullet.GetComponent lt Rigidbody gt ().AddForce(bulletSpawn.forward bulletSpeed, ForceMode.Impulse) destroy bullet after x time Destroy(bullet, lifeTime)
0
Should I code game logic separately from game engine scripts I'm developing a game in Unity3d, economic strategy. I wonder if I should code logic inside unity scripts, or write it as an external module library? By game logic I mean game model, which describe game entities, they relation with each other, their methods. And this logic has nothing to do with and doesn't need to know anything about networking, rendering, representation etc. If I do it inside unity scripts, then logic is tied to unity engine and I don't see a way to implement multiplayer(client server) without rewriting whole logic for server side, where unity cannot be used. I would like to define logic outside of scripts, and later, reference it inside some "main" unity script. This way I could implement multiplayer easily. Is this a common practice, or should I avoid it, or maybe there is some alternative patterns?
0
How to make switch work with enum? C Unity I'm working on a script to fade UI elements in Unity, similar to a selector, where you can select the type of fading, and duration, and image to fade I found that enum is the best option to achieve that result, but I have a problem, when I run the code only element of the enum work and the other don't, no matter if I use switchor if just the first statement run, I don't know what's wrong with the code Please explain your answer Please explain why the code is wrong Please give feedback on how to improve I'm using Unity version 5.3.5f1 and Visual Studio Community 2015 Goal Make the enum work properly using either switch or if Be able to use the variables inside the FadeOperations class to make the calculations inside the Test class Select from an array the type of desired operation Select an UI element from Heriarchy and fade it Steps Create new Unity project (2D or 3D) Create UI Image Create Empty game object Create new C script (I called it Test) Attach new script to empty game object Code Here's my code so far... using UnityEngine using UnityEngine.UI public enum FadeManager fadeIn, fadeOut System.Serializable public class FadeOperations Tooltip("Type of fading") public FadeManager fadeType Tooltip("Duration time of the fading") public float duration Tooltip("Select the image to fade") public Image fadeImage public class Test MonoBehaviour Tooltip("Select your type of fade") public FadeOperations fadeOperations Reference to the class FadeOperations private FadeOperations fo new FadeOperations() Loop for debug private void Update() switch ( fo.fadeType) Debug.Log( fo.fadeType) This statement works case FadeManager.fadeIn Debug.Log("Fadein") Only this piece of code works break This statement doesn't work case FadeManager.fadeOut Debug.Log("Fadeout") break The result of the Log ( fo.fadeType) before the switch fadeIn UnityEngine.Debug Log(Object) Test Start() (at Assets Scripts Test.cs 34)
0
Matte reflection effect in Unity? I'm trying to achieve that kind of scene but in real time using Unity. It's basically composed of some primitives, a skybox, and a plane. I'm intrigued on how to do this effect in particular The plane acts like a mirror, but tainted and matte (and it appears to be less blurry at the bottom of the buildings... but I'm not quite sure). I have found some shaders to create mirrors in Unity but nothing about the matte effect like in this picture. Could you guide me on how to achieve this kind of effect (knowing that I'm pretty lame when it comes to write shaders but I want to learn). Thanks.
0
Check which object triggered another Two animated car object both contain a rigid body, a box collider and a script with an OnTriggerEnter event. I want to check which car started the collision event, by hitting the other car. Consider two cars regardless of whether carA hits carB or carB hits carA, both cars contain the same script with the same event. So both cars become the trigger. How do I identify which car started the collision? I wish to do so without the use of raycasting, as it is too expensive for what I am wanting to do.
0
How can i change the Camera component height in FirstPersonCharacter? The player looks very short. I changed his scale to 2,2,2 but the camera is in the middle it's like the player head is in the middle and not near the top. In the screenshot in the Hierarchy i have a FPSController and the FirstPersonCharacter with the Camera is child of it. The FPSController scale set to 2,2,2 like the two soldiers. But you can see when i'm getting closer to the soldiers it looks like i'm looking at them from the ground. I need to move the camera only up somehow. And this is the camera and the firstpersoncontroller before running the game
0
How can I "smoothen" my path finding on a map with big tiles? I've just implemented A in my "game", but as I finished it this came to my mind This is fine for a turn based game, but it would be really annoying for a real time one. For example look at the picture below. In an action rpg the character would move to its goal in a straight line, but this is impossible here because the tiles are too big to make a that straight line. So my question is How do they solve this in action games? (I don't think that they have miniature tiles because that's too inefficient. But maybe I'm wrong.) Edit Or should I remove those tiles from path, which aren't necessary? So there will be a only a few points left, which are connected by straight lines? Like this go through the path from the Start. When I find a X. tile which can't be accessed with a straight line from start Remove every tile from the path between Start and (X 1). tile. Repeat this from the X. tile, till I find the End. Interpolate through straight lines between the remaining points.
0
Head rotation according to weapon sight I have a 2D game and I'm working on head rotation with my newbie coding skills. My Player has child sprite object called DefaultPistol (which is the whole arm and pistol attached to it) and it has a Weapon script. The arm turns 360 (centered from the shoulder) in the scene. What I need is for my player turn his Head wherever arm turns (the Head is also another child sprite object attached to Player like DefaultPistol) but not like rotating the head, I just simply want to mirror the head to face left or right. I tried setting the head's x scale to 1 or 1, but it didn't work and I couldn't find what is the problem. (I also checked the inspector if I didn't attach anything, but everything is in order as far as I can see) Here is my Weapon. You can see where I tried to implement this in Flip. How can I fix this? public class Weapon MonoBehaviour public GameObject projectile public Transform shotPoint public float timeBetweenShots private Animator cameraAnim private float shotTime private bool facingRight public GameObject head private void Start() cameraAnim Camera.main.GetComponent lt Animator gt () private void Update() this code paragraph here is calculating the shotPoint player rotation Vector2 direction Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.position float angle Mathf.Atan2(direction.y, direction.x) Mathf.Rad2Deg Quaternion rotation Quaternion.AngleAxis(angle 90, Vector3.forward) transform.rotation rotation if (Input.GetMouseButton(0)) if (Time.time gt shotTime) Instantiate(projectile, shotPoint.position, transform.rotation) cameraAnim.SetTrigger( quot shake quot ) shotTime Time.time timeBetweenShots private void Flip(float horizontal) if (horizontal gt 0 amp amp !facingRight horizontal lt 0 amp amp facingRight) facingRight !facingRight Vector3 theScale transform.localScale head.transform.localScale new Vector3() theScale.x 1 transform.localScale theScale
0
How to make a 'Picture book Cutscene' in Unity 2D with simple 2D images? I'm trying to implement a simple cutscene system in my Unity game, preferably one that allows cutscenes to play at the start and end of each of the levels. What I was imagining was pretty similar to A Hat in Time's 'storybooks' from it's time rifts, but full screen and advanced with a single key. The images are simple and comic like, and I was wondering how to implement such a feature since it feels like it's a bit different to Unity's pre existing Timeline system, as there isn't many moving parts. How do I go about approaching this problem? At least, I don't know how to get the project to a state where a person can press a key to turn to the next page (whether or not there's a visual transition to the next is optional) and once it's done, to start the actual level scene. Do I still use the Timeline for this? I know I could potentially use an empty game management prefab in order to set up when to play the cutscenes, however.
0
Disadvantages of using a singular scene in Unity In my previous experience with Unity, I have had an organized level structure where each level instance was easily separated into a different scene. For my current project, it would be much more natural to avoid such transitions, and instead disable or remove GameObject instances far from the player's position, and of course loading them in when necessary. It strikes me that this must be how titles like Gone Home amp Firewatch must have been made, and while my game won't be huge in scope, it will be bigger than those ("distance" wise). Basically, I don't want to get halfway down this road and realize I've made a terrible mistake, so any input is appreciated. Are there disadvantages to using a singular scene in Unity?
0
Unity facebook SDK. Cannot login I want to show a leaderboard of facebook friends scores in a game. So I need access to the user friends permission. In order to get that permission I have to send a working build using that permission to facebook that they can review. So I need to keep my app on facebook in development mode, and test it with test users so I can build this feature and get it working. However when I build the game and try and login to facebook I get this... It did not give me a chance to login as a test user or anyone else. I didnt log in at all, it just went straight to this screen when I requested login. Now the solution for this error that I have found many instances of, is to set your app 'live'. But that wont work in my case.. I need the app the be in development mode so I can test this feature.. If the app is live no one will have access to the user friends permission including test users. So this seems like a paradox. What can I do?
0
Is it possible to add touch screen functionality to a Windows Standalone build for a Surface Pro? I have an application which is currently PC Windows Standalone, however I need it to be able to work with the touchscreen on a Surface Pro tablet when the same build is run on here. The interaction the user has is that of clicking buttons to open and close windows etc (all buttons use the OnClick() functionality), so any input required would just be simple button taps. I simply need this to work on a Surface Pro touchscreen display when it is run on there, so mouse clicks to be replaced with taps of the buttons. I've read many posts on the subject, but many are from Unity 4.6 and nothing conclusive for Unity 5. Many posts I found stated that this feature was introduced for Unity 5, but others suggest it is not supported and third party plugins are needed. I don't currently have access to a Windows touch screen device, so am unable to do a quick check. I therefore want to make sure it is possible before I purchase a device and commit to the update. From what I gather, the 'Standalone Input Module' has now replaced the 'Touch Input Module' which apparently had a checkbox to tick if you wanted to have it work in Standalone. As such a checkbox does not exist in the former, I am unsure whether this feature is still supported. So I would like to know Is it supported in Unity 5? If so Does it 'just work' automatically or does extra work need to be done to tell it to use touch screen if it is running on a Windows touch screen device? Many thanks in advance
0
Unity dictionaries having duplicate keys EDIT Restarting Unity solved the problem! ) I don't know if Unity and GameObjects have anything to do with this, but I am getting a strange duplicate Key error while scripting in Unity. static void LoadPartyDataIntoBattle() foreach (PartyMemberData partyMemberData in ins.TheParty) PartyMember partyMemberToAdd new PartyMember(partyMemberData) BattleManager.BattleParticipants.Add(partyMemberToAdd) GameObject PartyMemberUI Instantiate(ins.PMBattlePrefab, ins.PartyFrontRow.transform) PartyMemberUIDisplay display PartyMemberUI.GetComponent lt PartyMemberUIDisplay gt () display.Name.GetComponent lt Text gt ().text partyMemberData.Name display.Level.GetComponent lt Text gt ().text partyMemberData.Level.ToString() display.HPValue.GetComponent lt Text gt ().text partyMemberData.HP.ToString() display.TPValue.GetComponent lt Text gt ().text partyMemberData.TP.ToString() BattleManager.PMLinkDict.Add(partyMemberToAdd, display) In the line PartyMember partyMemberToAdd new PartyMember(partyMemberData) , the new keyword should create a different PartyMember on the heap, correct? Yet when I run the debugger, attach it to Unity and play, the second time the foreach loop runs I get a duplicate Key error. For reference, I set the values of ins.TheParty (my list of party members) in the Inspector there are three partyMembers in TheParty as of now. They have different names, attack, defense, etc. But that doesn't matter, does it? Isn't it the memory location that matters? I made a test file to mimic the problem I had. It worked fine, no surprises here. using System using System.Collections.Generic class Cow class MainClass static void Main() Dictionary lt Cow, object gt meDict new Dictionary lt Cow, object gt () List lt Cow gt myCows new List lt Cow gt () new Cow(), new Cow() foreach (Cow c in myCows) meDict.Add(c, new object()) Console.WriteLine("Yay nothing broke") this prints just fine I feel like I'm overlooking something obvious, but I can't for the life of me figure out what the problem is. Help appreciated!
0
How to change a sprite via script at runtime when using an animator? I am making a simple 2D shooter. I have my character's body and head as different objects, as I want him to look up down regardless of the movement. So, I basically use the following script public class PlayerHead MonoBehaviour public static PlayerHead instance public SpriteRenderer theSR public Sprite netural, down, up private void Start() instance this public void Up() theSR.sprite up public void Down() theSR.sprite down public void Netural() theSR.sprite netural However, the head is also used in the player animations This is because head must move with the body during the idle animation (breathing and moving up amp down slowly). I suspect that because of this animation, the sprite of the head is somehow fixed. It does not change in runtime even though I change it manually inside Unity. How can I make the Animator let me change the sprite?
0
Is it possible to have a GUI in world space in Unity3D game? I'm trying to make a tank shooter game for learning purpose and I want to have it viewed in first person, is there a way to make it so that the GUI seems projected onto the interior of the tank chamber so that I can look around without the GUI following the camera along with having the perspective change effects (i.e. the edge of the GUI further away from the camera appears smaller than the edge closer to the center of the camera)?
0
Sprite doesn't change material or picture I am quite new to unity and currenty I'm practicing with a 2D topdown game. I created a tile map with "tiled", imported it in Unity with "TiledToUnity" and changed some things like player movement, camera and so on. Now I wanted to create collectible coins. So I created a new 2D Sprite and added the picture of the coin I had to it. But the picture of the coin did not change. I tried the same with adding a material with the coin as picture but it did not work out either. To check if the object is even there I added a collide box to the coin and my player body did indeed collide. What did I do wrong while adding a picture to the sprite? Thanks in advance! (Sorry fotgot the pictures. ) Edit
0
Auto generate optimal direction for Unity Raycast with specifications How can I have a Physics.Raycast auto generate a direction for itself to try to hit a given target through a restricted window of space? Update After much work, my problem has slightly morphed into one about mesh colliders given a (convex) mesh collider, how can I detect all of the points intersecting with the collider? Or, if this can be done easily, can I get one Vector3 per object that is within the mesh collider? Update This is kind of a long question, so I'll try to explain it the best I can I have 3 GameObjects a source, a target, and a "window". This window sits between the source and target. I want the source to make a raycast that points in the direction of the target (not necessarily it's transform.position, just a direction that will make it hit the target) and this raycast must pass through (collide and continue through) the window GameObject I would like to automatically generate this direction for the raycast to follow such that 2 happens I would like this algorithm to also recognize if the above is not possible As an added item, I would like this raycast to pass through (collide and continue through) any objects that may be in it's way between it and the window Here's an image describing my issue in more detail How can I accomplish this? Thank you for your help in advanced!
0
How to draw lines with fountain pen effect in Unity? I'm working on drawing lines in Unity, I've already implemented smooth line drawing with LineRenderer. But I need lines have effect of fountain pen or gel ink pen, just as the picture showed below, I have no idea about this, may shaders make the effect ?can anyone help? Now I can draw common lines with Unity Effect needed
0
What are the steps in creating app icon for ios? I have completed developing my game (iOS) and now preparing it to submit to the appstore. However, i have some confusion regarding app icon. 1 In Unity build player settings, there are various sizes mentioned. Largest size is 180x180 px. But i read somewhere apple requires 512x512 px icon. 2 Is the build player settings the only place where i provide app icons or are there more steps involved in xcode? If there are, please provide link to some documentation. Thanks.
0
Realistic 2D air friction in unity I want to make an evolution games similar to this old games that was generating cars. Except I want it to be more realistic. So I want air friction to impact the speed of my cars, but how do I do that? wind will always be blowing at the same speed and in the same direction. But my car chassis are random and their angle of attack can change due to the terrain shape (which is also random) So I cannot apply a drag value, because this drag value change for the angle of attack. instead I must compute a new drag value for each frame. Using real world physics might be to much to let the game run smoothly (10 20 cars running at the same time) How would you do it? Thanks.
0
What does NavMesh.AllAreas specify in Unity? I'm trying to calculate the path to a point in my game using NavMesh.CalculatePath, it takes an argument NavMesh.AllAreas. I read the Unity Manual and couldn't clearly understand what it meant.
0
Player disappears when it collides with a tagged object I am working on a simple game where the goal is to help a Player catch specific objects with a tag "Present". After taking care of the models, animations I am now working on the collisions and counting UI. For the collisions, on my Player Controller (I am using the ThridPersonUserController from the player Unity Standard Assets which simplified the whole animation process), I added the following functions void OnCollisionEnter(Collision other) if (other.gameObject.tag "Present") Destroy(gameObject) count count 1 SetCountText() void SetCountText() countText.text "Count " count.ToString() if (count 0) winText.text "Thanks to you the Christmas will be memorable!" However, like this, when the Player hits an object with the tag "Present", even though the counting is working properly, the player disappears. I have tried to change the OnCollisionEnter to an OnTriggerEnter, like this void OnTriggerEnter(Collider other) if (other.gameObject.CompareTag("Present")) Destroy(gameObject) count count 1 SetCountText() However when the Player hits the objects with the tag "Present", they don't disappear. My Player has a Capsule Collider and a Rigidbody. The objects with the tag "Present" have a Box Collider and a Rigidbody. Any guidance on how to make my Player stay in scene while removing the other objetcs and reducing the count is appreciated.
0
Best way to handle events for a turn base game? I'm looking for the best way to handle events for a tactic game in Unity. Every unit may need to react to different events (turn start, end, on damage to self, on damage to other, on kill, etc...). At the moment I'm just cycling all units for any event from a central manager class, but I'm looking for a more elegant and easy to extend solution. I'm not worried about performance since the involved number of units will be low. Any advice?
0
Limit Quaternion vector3 axe in a certain interval I have some trouble to understand, and handle Quaternion and Vector3. I'm improving the tutorial Tank of Unity EDIT Because a video explain so much better, there is a link to the 30 secondes video I made https www.youtube.com watch?v nNrmlfbHNTI amp feature youtu.be In the first part, the turret turn with restriction made with the both line newRotation.z 0.0f and newRotation.x 0.0f (see code bellow). In the second part, I just comment this two line. My probleme is i want to be able to look up and down (like in the second part of the video, but with a DEPRESSION LIMIT (don't look too much high and too much down) I try soo manny case and can't manage the thing i want to do... there is the code of the script in ref to the Tank turret public float m TurnSpeed 8f private Transform m Transform private int floorMask private float camRayLength 100f void Awake() floorMask LayerMask.GetMask ("Ground") m Transform GetComponent lt Transform gt () void FixedUpdate() Turning () void Turning() Ray camRay Camera.main.ScreenPointToRay (Input.mousePosition) RaycastHit floorHit if (Physics.Raycast (camRay, out floorHit, camRayLength, floorMask)) Vector3 playerToMouse floorHit.point transform.position Quaternion newRotation Quaternion.Slerp(m Transform.rotation, Quaternion.LookRotation(playerToMouse), Time.deltaTime m TurnSpeed) EDIT 2 probleme solved with the following line block totaly Z and X quanta newRotation.z 0.0f newRotation.x 0.0f m Transform.rotation newRotation float tmpX m Transform.localEulerAngles.x if (tmpX gt 20.0f amp amp tmpX lt 90.0f) tmpX 20.0f else if (tmpX lt 315.0f amp amp tmpX gt 280.0f) tmpX 315.0f m Transform.localEulerAngles new Vector3(tmpX , m Transform.localEulerAngles.y, 0.0f) Thanks !
0
How can I find if a GameObject is not exist in the Hierarchy? var selections Selection.objects.OfType lt GameObject gt ().ToList() if (selections.Count gt 0) tempSelections selections for (var i selections.Count 1 i gt 0 i) var selected selections i transformSelection.Add(selected.transform) TransformSaver.SaveTransform(transformSelection.ToArray()) transformSelection new List lt Transform gt () for (var i tempSelections.Count 1 i gt 0 i) var selected tempSelections i if (GameObject.Find(selected.name) null) GUI.enabled true else GUI.enabled false if (GUILayout.Button("Undo last selection if deleted")) transformsCount TransformSaver.LoadTransform().Length PlayerPrefs.DeleteKey("transform") For testing I'm deleting one of the GameObjects in the tempSelections List But then I'm getting exception in the editor on the line if (GameObject.Find(selected.name) null) Since the GameObject have been deleted it can't access the GameObject. MissingReferenceException The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.
0
Mesh getting offset on combine because of worldmatrix When I try to combine my mesh, it get offset to an other position, but the collider is still at the same place (because i dont delete and add it again). I saw a fix on internet that is to do Matrix4x4 myTransform transform.worldToLocalMatrix combine i .transform myTransform meshFilters i .transform.localToWorldMatrix which worked in one of my script, but I just cant get it to work in this one. How can it be fixed ? Vector3 cb Vector3.zero Vector3 n hit.normal Vector3 p hit.point if(n new Vector3(1.0f,0.0f,0.0f) n new Vector3( 1.0f,0.0f,0.0f)) cb new Vector3((n.x 0.5f) p.x,Mathf.Round(p.y),Mathf.Round(p.z)) if(n new Vector3(0.0f,1.0f,0.0f) n new Vector3(0.0f, 1.0f,0.0f)) cb new Vector3(Mathf.Round(p.x),(n.y 0.5f) p.y,Mathf.Round(p.z)) if(n new Vector3(0.0f,0.0f,1.0f) n new Vector3(0.0f,0.0f, 1.0f)) cb new Vector3(Mathf.Round(p.x),Mathf.Round(p.y),(n.z 0.5f) p.z) GameObject cub Instantiate(cube,cb,Quaternion.identity) GameObject dupli Instantiate(hit.collider.gameObject,hit.collider.gameObject.transform.position,Quaternion.identity) MeshFilter meshFilters new MeshFilter cub.GetComponent lt MeshFilter gt (),hit.collider.gameObject.GetComponent lt MeshFilter gt (),dupli.GetComponent lt MeshFilter gt () CombineInstance combine new CombineInstance meshFilters.Length Matrix4x4 myTransform meshFilters 2 .transform.localToWorldMatrix combine 0 .mesh meshFilters 0 .sharedMesh combine 1 .mesh meshFilters 1 .sharedMesh combine 2 .mesh meshFilters 2 .sharedMesh combine 0 .transform meshFilters 0 .transform.localToWorldMatrix combine 1 .transform meshFilters 1 .transform.localToWorldMatrix combine 2 .transform meshFilters 2 .transform.localToWorldMatrix meshFilters 2 .mesh new Mesh() Vector3 sP meshFilters 2 .gameObject.transform.position meshFilters 2 .gameObject.transform.position Vector3.zero meshFilters 2 .mesh.CombineMeshes(combine) meshFilters 2 .gameObject.transform.position sP Destroy(meshFilters 0 .gameObject) Destroy(meshFilters 1 .gameObject)
0
Why I have to press the button twice to deactivate the GameObject for the first time? game engine unity3d scripting language unityscript code var setmenu GameObject var settings menu boolean function Start() settings menu false function settingButtonClick() if(settings menu false) setmenu.SetActive(true) settings menu true else setmenu.SetActive(false) settings menu false The problem is I have to click the UI button twice to SetActive to become false for the 1st time. But after that when I again activate and then press to deactivate it works fine with single click.
0
2D isometric game with 3D prefabs Is it possible to have a 2D isometric game in Unity, but also have 3D prefabs in the scene? Will that work or should I make the game in 3D with an isometric camera?
0
Is making a sandbox feasible in Godot Unity (w o open world)? I want to make a 3D multiplayer game. It will inherit the basic principles of the MOBA genre players choose from the variety of characters each having 4 8 unique abilities, then battle it out. I also want some abilities to affect terrain. I try to keep the concept simple to be able to make this game alone. It would be good if I manage to finish the first playable prototype in no more than 6 months (keeping in mind that I'll be able to work on the game mostly on weekends). Multiplayer AND 3d in themselves make things much harder, so deciding which mechanics to implement and how is essential. Thus I want to make sure I won't have to redo much after I start programming. To implement the destructible terrain I decided to stick with a Minecraft ish approach, where everything consists of blocks. The sandbox is a very hard genre in terms of game development, but after doing quick research, I concluded that most difficulties arise from the fact that the game is open world. This isn't my case. I won't need too many blocks to construct the arenas. Now I need to come up with the engine I'm gonna use. I like Godot due to its development paradigm, but I'm not sure whether it is a good choice for a game like this. Maybe Unity is the better choice in my situation. Or something else. Maybe I need to remove some mechanics from the concept to make the development a lot faster. Can you comment on it? Thanks! P. S. I have 7 years' programming experience (with Haxe and Python being my main languages) and a good mathematical background. I have been developing my multiplayer game for 3 years now (but it is a 2D game, I have no experience in 3d gamedev beyond the Godot tutorial). It is okay if I need to learn different things before starting to make a game, but I want to make the learning process as effective as possible.
0
Linq with Unity Select One from Many I'm using Linq to select the objects closest to the player that have the usable tag thusly GameObject usables GameObject.FindGameObjectsWithTag("Usable") .Where(t gt Vector3.Distance(t.transform.position, playerT.position) lt useDistance) .ToArray() This works as I intended, but I'd like to further narrow it down to the closest object in that array so the Linq query returns only the single closest GO. Linq is, however, a serious weak spot for me. Any thoughts on how that would look? Thanks!
0
player movement variable is not being set to false i have a player with a basic movement. when i press W he just keep on going this my code private void fixedupdate rigid.AddForce(new Vector3(0, 0, 10) speed, ForceMode.Impulse) moveup false
0
Issue picking the closest vector in a unique circumstance I have a list of targets that can be picked depending on the magnitude from the vector created using for(int i 0 i lt targetQueue.Count i ) 2 loops to cycle through targets for(int j 0 j lt targetQueue.Count j ) if two targets are the same, then skip them if(targetQueue i ! targetQueue j ) getting the direction using the source and destination vectors Vector3 iDir targetQueue i .transform.position transform.position Vector3 jDir targetQueue j .transform.position transform.position comparing i with j, if i is less than target at j then match found if(iDir.magnitude lt jDir.magnitude) LockedTarget is a gameobject to show what target the turret is locked on to LockedTarget targetQueue i if match found then set locked target to target at i break This code compares every target to each other, however it does this twice, once on each side( target i becomes target j ). When the magnitude is compared, if the target i is smaller, then this is now the locked target as this target is closer to the turret. This works every time except for one instance and I can't figure out why its happening here When both targets are inside the collider, the target on the right should still be highlighted, yet I get the target that is farther away being selected, this also occurs with more than two targets, with even stranger results. These being that the original target chosen for 'DEADLOCK' what i'm calling it, stays locked. Even when I move the other targets above, below, left and to the right of it. This only occurs with this target, i've tried with 2 other targets (south of the turret) and it works as intended by properly switching based on size of magnitude of the direction vector between the target and the source. I have ruled out the possibility being that it is an issue to do with adding target's to the gameobject list as it works everywhere else. When measuring the lengths of the magnitudes, the wrong target is chosen as the locked target. It does show that the closest target on the images does actually have the smallest vector magnitude. UPDATE the magnitudes of the vectors are increasing and decreasing by tiny amounts, 1 to 2 for a major movement. this makes sense as its worldPos. What doesn't make sense is the target on the right having a magnitude of 49 and the target above having a magnitude of 82, when according to world space they are pretty close to eachother. Can anyone help me with this issue? its been driving me nuts for days. It must be to do with the magnitudes of the direction vectors not being calculated properly.
0
How to make rhythm game long notes in Unity? I'm making a rhythm game for a university course and I can't figure out a way to make the long sustained notes. For reference, this is what I mean taken from Guitar Hero I already have a system working for regular notes. The way I do it is that the notes are stored in an external file as numbers which represent the absence or presence of a note as well as what type of note it is, separated into musical bars 000 010 020 001 There are three lanes for the notes to be, and this means that in this particular bar there are notes wherever it's not 0 (with the numbers being different types of notes). I had thought of using this system to create long sustained note start and end markers (say 3 and 4) and that create another game object which would be the line between the start and end markers. But the way my note generator works is that the notes are not all generated at once because that'd be pretty heavy. Instead, the notes are generated at a certain time taking into account its speed so that it's instantiated and will reach the player's activator when it's supposed to. The following is a part of my note generator code, put in the Update method if current song time time offset is greater than time taken for all executed bars so far spawn the next bar's notes if (songTimer timeOffset gt (barExecutedTime barTime)) StartCoroutine(PlaceBar(noteData.bars barCount )) barExecutedTime barTime And here is the PlaceBar coroutine go through all notes in a bar creates an instance of note prefab depending on which note is meant to be spawned private IEnumerator PlaceBar(List lt SongParser.Notes gt bar) for (int i 0 i lt bar.Count i ) if (IsThereNote(bar i .bottom)) GameObject obj (GameObject) Instantiate(GetNotePrefab(bar i .bottom, true), new Vector3(bottomLane.transform.position.x distance, bottomLane.transform.position.y, bottomLane.transform.position.z 0.3f), Quaternion.identity) if (bar i .middle ! 0) GameObject obj (GameObject) Instantiate(GetNotePrefab(bar i .middle, false), new Vector3(middleLane.transform.position.x distance, middleLane.transform.position.y, middleLane.transform.position.z 0.3f), Quaternion.identity) if (bar i .top ! 0) GameObject obj (GameObject) Instantiate(GetNotePrefab(bar i .top, true), new Vector3(topLane.transform.position.x distance, topLane.transform.position.y, topLane.transform.position.z 0.3f), Quaternion.identity) yield return new WaitForSeconds((barTime bar.Count) Time.deltaTime) So if I were to make start and end markers, the start marker would not know where the end marker is because it doesn't exist. Could anyone help please?
0
How can I apply a Camera Shader to UI? I am trying to make a shader that applies a black image with 50 transparency to the entire screen, with the exception of a designated area. I am starting by just trying to apply a shader to the entire screen. So I am using the default ImageEffect Shader. This is my before and after when applying my shader, which should invert everything. It inverts everything except for the Balmer's Peak, which is a Unity Image Before After Example of what I am going for I attached a script using OnRenderImage to the Camera, and the attached material is being applied to everything in sight, except the UI. What can I do to make my material applied to everything on the screen, including the UI? I am new to shaders, so this may seem like a bit of a dumb question. But I am not sure what direction I should be headed. Here are my scripts, although I did not really change anything from what Unity provided me Script attached to camera using UnityEngine public class ButtonHighlight MonoBehaviour Tooltip("Material which is to be applied") SerializeField private Material material private void OnRenderImage(RenderTexture source, RenderTexture destination) Graphics.Blit(source, material) Shader attached to material above Shader "Magic Magic Shader" Properties MainTex ("Texture", 2D) "white" SubShader No culling or depth Cull Off ZWrite Off ZTest Always Pass CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" struct appdata float4 vertex POSITION float2 uv TEXCOORD0 struct v2f float2 uv TEXCOORD0 float4 vertex SV POSITION v2f vert (appdata v) v2f o o.vertex UnityObjectToClipPos(v.vertex) o.uv v.uv return o sampler2D MainTex fixed4 frag (v2f i) SV Target fixed4 col tex2D( MainTex, i.uv) just invert the colors col 1 col return col ENDCG What is the correct approach to apply a shader to the entire screen? (Keeping in mind, that the purpose is to add a filter to most, but not all, of the screen.)
0
Could use some help figuring out bouncy physics material in this PhotonEngine game So I'm trying to prototype a primitive 1v1 fighting game where the goal is to push the opponent off of the platform rather than actually fight. This is working great in a local multiplayer setup using a physics material on the "belly" of the Rigidbody2d players (the circle collider gameobject nested inside of the square gameobject has the bouncy material). But I'm toying with the idea of making it a network game and it seems the physics material doesn't get communicated too well over the Photon Realtime connections? Here is a video showing how it seems like sometimes the position is updated but sometimes a player runs into another player and its like a brick wall https imgur.com QYWH178 Any ideas of what to try or if this is even possible? A bit about how things are currently setup Each player object has the nested collider with a high bounciness material on it. Each player moves via the Rigidbody2D component via .AddForce(direction Speed) I have a Photon View component on the player prefab and a Photon Rigibody 2D View component that is checked to Synchronize Velocity and Angular Velocity, as well as a Photon Transform View component synchronizing Position. Both the transform view and Rigidbody2dView are Observed Components in the Photon View. I also found a script someone posted where they were manually sending the position velocity data via OnPhotonSerializeView() I've tried adding that script and making that observable as well, but no luck, but it looks something like this public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) if (stream.IsWriting) We own this player send the others our data stream.SendNext(transform.position) stream.SendNext(transform.rotation) stream.SendNext(r.velocity) stream.SendNext(r.angularVelocity) else Network player, receive data latestPos (Vector3)stream.ReceiveNext() latestRot (Quaternion)stream.ReceiveNext() velocity (Vector2)stream.ReceiveNext() angularVelocity (float)stream.ReceiveNext() valuesReceived true Update is called once per frame void Update() if (!photonView.IsMine amp amp valuesReceived) Update Object position and Rigidbody parameters transform.position Vector3.Lerp(transform.position, latestPos, Time.deltaTime 5) transform.rotation Quaternion.Lerp(transform.rotation, latestRot, Time.deltaTime 5) r.velocity velocity r.angularVelocity angularVelocity
0
Animation conversion failed transform for bone not found? I'm trying to animate my first humanoid, and the animations in the Standard Assets pack (HumanoidIdle etc) work really well right out of the box. However, when I try to use other fbx files, like those in Unity's "Raw MoCap Data" pack, I get errors. I import the animations, select one, go to "Edit " and go to "Rig", select "Humanoid", copy the avatar definition from the character I'm trying to animate (e.g. Robot Kyle), and under "Animations" I will get an error like "Imported file RunBackward conversion failed Transform 'Left Thigh Joint 01' for human bone 'LeftUpperLeg' not found". When I compare the avatar of the character I'm trying to animate with the avatar that comes with the animations, they have the same bones defined, just with different names (which shouldn't matter, right?), so it's not that bones are missing. Using the animation with the default avatar also doesn't work, I get no error but my character goes into the first frame of the animation but then freezes. I've tried this with the standard models Ethan and Robot Kyle to the same effect. Does anyone know how to handle this import error?
0
Get GameObject which instantiated me in Unity How can I get a GameObject from another GameObject? If I know, that the GameObject I want to get instantiated(using function Instantite()) the GameObject from which I want to get it. If there is no solution, how can I get the direction in which should move the instantiated bullet? I mean should it be 1 or 1.
0
Accessing a UI Image that is a child of a GameObject? I'm sure there is a very simple solution to this issue. I am creating a UI for a 2D RPG in Unity. I have a Canvas with a two GameObjects DialogManager amp MenuManager The Dialog Manager has a child "DialogBox" which is a UI Image. And the Menu Manager has three children for each part of the menu, so three UI Images. How the heck do I access these UI Images in a script attached to a different gameObject? Since they're technically not gameObjects, I can't just use the old gameObject.Find(). I've seen some things about Transforms and Children, but I just can't wrap my head around it.
0
How to randomly generate biome with perlin noise? I want to generate a procedural world using perlin noise. As expected, my terrain is generating with a repetitive patern. I'd like to add biomes, zones separated with higher or lower amplitude to simulate mountains or plain. I first thought I could randomly select rectangles of verticesof random sizes and then give them bigger amplitude to simulate mountains. The problem with that is that It wont seem natural, since I will only have rectangle biomes and also I don't know how to make it so the mountains would connect with the plain to avoid things like this Here is my script public int size 10 public float amplitude public float frequence void GenerateTerrain(float amp, float freq) Mesh meshy MeshRenderer meshRenderer GetComponent lt MeshRenderer gt () meshRenderer.sharedMaterial new Material(Shader.Find( quot Standard quot )) MeshFilter meshFilter gameObject.GetComponent lt MeshFilter gt () List lt Vector2 gt uv new List lt Vector2 gt () Vector3 vert new Vector3 size size List lt int gt tri new List lt int gt () List lt Vector3 gt norm new List lt Vector3 gt () meshy new Mesh() for (int i 0, x 0 x lt size x ) for(int z 0 z lt size z ) float y Mathf.PerlinNoise(x amp, z amp) freq vert i new Vector3(x, y, z) i for (int i 0 i lt vert.Length i ) norm.Add( Vector3.forward) for (int x 0 x lt size 1 x ) for (int z 0 z lt size 1 z ) int i size x z tri.Add(i) tri.Add(i 1) tri.Add(i size) tri.Add(i size 1) tri.Add(i size) tri.Add(i 1) for (int i 0 i lt vert.Length i ) uv.Add(new Vector2(vert i .x, vert i .z)) meshy.vertices vert meshy.triangles tri.ToArray() meshy.uv uv.ToArray() meshy.normals norm.ToArray() meshFilter.mesh meshy void Update() if (Input.GetKeyDown( quot u quot )) GenerateTerrain(frequence, amplitude)
0
Filling of a multidimensional array with string I'm trying to fill a dropdown with a lis,t if some input is correct. now when trying to create the list from a text file (to save the program) i should split the line on a comma so i have 3 settings for one asset For ex asset1,colour,used,broken. the list should show the asset if the item is broken (0 is not broken, 1 is broken). public string ,,, UsedAssetList string lines System.IO.File.ReadAllLines( "" Application.persistentDataPath " assetlist.txt") cmbAssetNumber.ClearOptions() for (int i 0 i lt lines.GetLength(0) i ) UsedAssetList lines i .Split(',') if (UsedAssetList i,0,0,1 "1") list new Dropdown.OptionData(UsedAssetList i,0,0,0 ) cmbAssetNumber.GetComponent lt Dropdown gt ().options.Add(list) The lines i .Split(',')gives me the error Error CS0029 Cannot implicitly convert type 'string ' to 'string , , , ' I think everything is on point, except the filling of my list. any idea on how i can get this right? EDIT I was thinking the list should look like this "asset1","Gold","1","0" , "asset2","Green","0","1" , ... EDIT While the text file looks like asset1,Gold,1,0 asset2,Green,0,1 ...
0
Avoiding GC when rebuilding Mesh.uv and Mesh.vertices Since unity will not allow users to iterate over mesh.uv and mesh.vertices, I am stuck having to use GC intensive calls when applying an array of uvs and vertices to a mesh. I run into high GC allocation because every time I rebuild a mesh, the uv and vert arrays will be a different size due to the mesh being modified. In turn, this results in having to resize or create new uv vert array and that is where the garbage collection comes in to be a problem when the old array or list is discarded as well as when applied to the mesh. Example 1 List For example, building a List UVList for a mesh that is built frequently will require calls of UVList.Add(Vert), this creates garbage for the GC whenever the List is resized with List.Add because when the list is resized, it creates a new copy and the old copy goes into GC. Also, to apply this list to a mesh.uv requires the call UVList.ToArray() which is a nasty call that creates huge GC if you have a long list of vertices because again, to convert to array, that array after it is copied mesh.uv UVList.ToArray() the UVList array created goes to GC. Example 2 Array I've instead tried using fixed array sizes but then learned that you cannot iterate over vertices or uv array of a mesh. For example, using a for loop to directly apply a vertices array to mesh.vertices will result in no mesh showing (i.e. for(i 0 ...) mesh.uv i uvArray i ) If I cannot do this, then I run into the same problem as example 1, because the only way is to create new array every time you want to update your mesh that has diff uv vert length. Resizing array requires creating a new copy of it, and then you have the same issue with GC. I tried reading through this example of someone else dealing with Unity GC when frequently updating meshes http gamasutra.com blogs RobertZubek 20150504 242572 C memory and performance tips for Unity.php He doesn't really explain his helper method in applying the UVs to the mesh and when trying from his example, it also results in GC. I guess my question is, how can I frequently update a mesh with diff uv vert array size without running into GC Alloc slowing down my project?
0
Line renderer in 3D sorting order I'm using a line renderer as a laser aim for my character. If the aim hits an object it ends at that object. If the aim doesn't hit an object it continues a predefined distance. If I aim at an object it works fine, if I stand behind the object it also works, but if I stand in front of it, the line is rendered behind the object creating the illussion that the character stands behind the object. If I change the sorting order for the line I can make it to be in front of the object, but this is a bit tedious because then it will be in front of this object when it is in fact behind it. In the screenshot below a line is drawn from the picked up C4 which is in front of the pillar, but the line is drawn behind the pillar. Is there any way to solve this issue with a line renderer? I've been thinking of just using a cube and stretch it instead. Thanks in advance! Update 1 I made a cube solution instead, but soon realized that the issue is with a shader that is set to fade transparent and that this is due to sorting order. How can I dynamically change the sorting order in code so that my moving transparent object always appear in the correct place? Update 2 I noticed that my own answer below isn't working 100 . It works for most scenarios but if I'm standing at origo and aiming behind a pillar the sight is rendered in front of the pillar. In the image below it is clearly visible from the top view that I'm aiming behind the pillar. (This is done with a deformed cube, the line renderer had even more issues).
0
Gravity not being applied to character, using character controller So I just copy and pasted the unity example class to use with my character controller. public float speed 6.0F public float jumpSpeed 8.0F public float gravity 20.0F private Vector3 moveDirection Vector3.zero void Update() CharacterController controller GetComponent lt CharacterController gt () if (controller.isGrounded) moveDirection new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")) moveDirection transform.TransformDirection(moveDirection) moveDirection speed if (Input.GetButton("Jump")) moveDirection.y jumpSpeed moveDirection.y gravity Time.deltaTime controller.Move(moveDirection Time.deltaTime) The code seems to work okay if I comment out the isGrounded check statement (which means that gravity isn't being applied). So what could be the reason that the gravity is not being applied to my character controller?
0
Why aren't the Physics2D.Raycasts reliably colliding with the 2D Box Collider walls? I've got this NPC walking around and I'm trying to create a cone to represent their line of sight, including how it would be blocked by buildings, similar to how Nicky Case has implemented it as described here https ncase.me sight and light My main problem with this, right now, is that it seems like I'm not detecting collisions between my 2D box colliders and Physics2D.Raycast when I would expect to much of the time. The green rays in the image below are NOT colliding (this is fine on the corners, I don't really care, but when the rays are going straight through walls, that's a big problem for me). Red rays are colliding. Why aren't the Physics2D.Raycasts reliably colliding with the 2D Box Collider walls? I believe everything is in the same z plane and has the correct collision matrix in place. ! image of my NPC and raycasts from them at various points along their path List lt UnityEngine.Vector2 gt endPoints new List lt UnityEngine.Vector2 gt () GameObject corners GameObject.FindGameObjectsWithTag("verticies") corners MUST BE WORLD ORIENTED! for(int i 0 i lt corners.Length i ) UnityEngine.Vector2 corner new UnityEngine.Vector2(corners i .transform.position.x, corners i .transform.position.y) RaycastHit2D endPoint Physics2D.Raycast(this.transform.position, corner) if(endPoint.collider ! null) endPoints.Add(endPoint.point) Debug.DrawLine (this.transform.position, endPoint.point, Color.red) else Debug.DrawLine (this.transform.position, corner, Color.green)
0
How do I select my platform and move them in a specific place in gameplay? I saw this game called TaniNani and I was amazed by the concept of the game and I would like to try to replicate it! My goal is to let the player hover on the available grid (somehow like hovering on an inventory) and when the player finds its desire the player will select the platform and when it is selected it could move in a specific location inside the box only! How do I code this using C in Unity2D? The example I want to achieve! MEANING OF THE COLORS Red The platform Light Blue Where the platform can be moved either from left up right Purple The platform can be switched by another platform
0
Only StartCoroutine of Update on child prefab functions I have a script attached to a prefab. That prefab attached to a child and I want it to rotate the root transform. The Update of the script executes nothing but the Coroutine of a class I wrote. Attached is the hierarchy of the outside and inside of playmode as well as the script on the prefab and the class. From the Editor, Not on Playmode. and in Plamode uiTurnTileScropt.cs THIS SCRIPT IS CURRENTLY ON THE CCW PREFAB using UnityEngine using System.Collections public class uiTurnTileScript MonoBehaviour public float rotSpeed 7.0f public float degree 36.0f public float waitTime .3f private bool rotate false private Quaternion newRotation Quaternion.identity BlockButton clickTapBlocked void Start() clickTapBlocked gameObject.AddComponent lt BlockButton gt () clickTapBlocked.bttnName "clickTap" clickTapBlocked.setFalse() void Update () Debug.Log (transform.name) if(Input.GetButtonDown (clickTapBlocked.bttnName) amp amp (!clickTapBlocked.blocked) ) Debug.Log("MouseDown") StartCoroutine(clickTapBlocked.forTime(waitTime)) newRotation Quaternion.AngleAxis (transform.root.rotation.eulerAngles.z degree, Vector3.forward) rotate true RotateSetAmount () void RotateSetAmount() Debug.Log ("In Rotate function") if (rotate) this.transform.rotation Quaternion.Lerp(transform.root.rotation, newRotation, Time.deltaTime rotSpeed) if (transform.root.rotation.eulerAngles.z lt newRotation.eulerAngles.z) transform.root.rotation newRotation rotate false and the referenced class BlockButton in uiTurnTileScript.cs using UnityEngine using System.Collections This class is more intuitive if you name thie instance created ("buttonValue" blocked) Example for a button in the Input Project settings with a string of Fire1 I would name the instance fire1Blocked Declare with your other variables BlockButton fire1Blocked void Start() Fire1Blocked gameObject.AddComponent lt BlockButton gt () Fire1Blocked.bttnName "Fire1Blocked" Fire1Blocked.setFalse() public class BlockButton MonoBehaviour public string bttnName public bool blocked false public bool setFalse() blocked false return blocked public bool setTrue() blocked true return blocked public IEnumerator forTime(float duration) Debug.Log ("I was called") float dur duration blocked true yield return new WaitForSeconds(dur) blocked false In my output,no matter what I click, I get nothing but the code from the BlockButton Instance. No debug from the Update() happens but the coroutine happens. I am not understanding how that happens and how to implement this properly. Any help is appreciated.
0
How to make a Sprite be displayed always behind everything else? What I am in need to achieve is to have a Sprite always facing the camera identically to what happens with any simple game UI object, but instead of always displayed above everything else, it should be always displayed behind everything else. How can I achieve that in Unity using C ? Regarding the always behind rendering, I tried setting the Sprite's "Order in Layer" to 0 or to negative values, with no success. I also tried setting all game objects to a greater value than the sprite's go.GetComponent lt Renderer gt ().sortingLayerName "Test" go.GetComponent lt Renderer gt ().sortingOrder 1 That did not work as well. What would be the correct way of making a sprite to be always displayed behind everything else (other sprites, GUI and 3D meshes) preferably not having to resort to shaders, if possible? PS regarding the effect of the Sprite always facing the camera as in a game UI, I suppose it will be only a matter of updating its rotation towards the camera but I would be happy to find out if other approaches are avialable more suited to the task.
0
How can I edit a float that is in another script? (In C ) So basically, I have one script for the UI, which holds the float, score. Then I also have another script on my coin that detects when the player collides with it. What I want it to do is change the value of score, but I don't know how to change it, as it is in the UI script. How can I do this?
0
Unity prevent force apply on re enable Physics2D.IgnoreCollision I'm making 2d platformer game. My player and enemies are rb with body type Dynamic. I choose dynamic for enemies because enemy need physics ( jumping, colliding with ground, etc) I'm using Physics2D.IgnoreCollision for disabling and again enabling collision between Player and Enemies. When player lost life shield is applied on player.Here is code Disabling collision private void OnCollisionEnter2D(Collision2D collision) Player player collision.gameObject.GetComponent lt Player gt () if (collision.gameObject.tag quot Player quot ) Physics2D.IgnoreCollision(collision.collider, gameObject.GetComponent lt Collider2D gt (), true) StartCoroutine(EnableCollision(player.timeShildActiveFixed, collision.collider, gameObject.GetComponent lt Collider2D gt ())) if (player.playerState ! Player.PlayerState.SHIELD) playerLostLife() player.ActiveShield() Enabling collision again private IEnumerator EnableCollision(float delay, Collider2D collider1, Collider2D collider2) yield return new WaitForSeconds(delay) Physics2D.IgnoreCollision(collider1, collider2, false) This work well but I my problem is that some force is applied on enemy before ignoring collision and enemy is changing its position ( on enemy because mass is set to 0.01 , but on Player mass is 1). This force is more visible when player not moving and shield is disabling and collison between player and enemy occur again and player get shiled again. I can't work with different layer with disabled physics for Player and Enemy because I need collision between them. Can someone help me with this? How can I fix this ? Thanks
0
Changing Animation Sprites At Runtime Once I am designing a 2d platformer with pixel 32x32 sprites, right now I m using the method that s utilized at 20 minutes in this video. I m pretty much creating a main player parent object and adding the players equipment (helmet, breastplate, leggings) sprites underneath. But obviously when the player animates and starts running the pixel equipment needs to move and shift with the player. The solution provided by the video seems to work fine, but why can t this just be called once at the start and be set until changed? Basically why can t I set the sprites at the different frames of the animation when the game starts and leave it. I basically redrew all of equipment to fit the character during each frame of the run animation etc. If I equip a specific helmet, I just want to set all the sprites in the animation once, and if I replace the equipment, a new sprite sheet is used that contains the breastplate and its animations during the run animation for example. Is there any way to not repeatedly set renderer.sprite for each sprite in an animation via the late update function? I m just worried that the function I attached will cause animation lag or lag to the game in general. (I do not wish to piece and part the character together, especially not a 32 pixel drawing, and boning the character and stretching the pixels is definitely not a good option either)
0
Wandering motion in Unity I am trying to come up with a smooth wandering motion for my game object using Unity. What I currently doing is rotate the object by some random angle calculated every 1.5 second delay. But I am aiming getting a smooth rotation whenever it transitions to a different randomly generated angle. Below is my script attached to my character. void Update () if (canWander amp amp (currTime delay lt Time.time)) changeAngle() currTime Time.time if(canWander) Wander() private void changeAngle() float prevPosY transform.position.y Vector3 waypoint Random.insideUnitSphere new Vector3(10,prevPosY,10) waypoints are generated based on random unit sphere ( bounds of the plane they are on ) Vector3 relative transform.InverseTransformPoint (waypoint) float angle Mathf.Atan2 (relative.x, relative.z) Mathf.Rad2Deg transform.Rotate (0, angle, 0) private void Wander() transform.position transform.forward Time.deltaTime acceleration if (acceleration lt maxSpeed) acceleration 0.5f So the character wanders with newly generated random angles every time but its not a smooth transition. It suddenly transitions to the new angle and it does not feel realistic at all. What could I possibly change with my current code to make it more smooth and realistic?
0
How to synchronize damage with attack animation in a RTS game? I have been working on a RTS game in unity and did damage deal through code and a timer but it does not fit with the animations quet well. The damage is dealt in the beginning of the animation and about 4 attacks it fits perfectly and after more 4 attacks the damage is dealt delayed after the animation. My big question is if hitboxes would be a good answer to solve this problem or is it to preformance heavy?