_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | Smooth rotation Unity3d I have an animation and I modified some rotations of some bones in the animation at a certain frame. What I want to do is how to make the animation in the next couple of frames interpolate smoothly so that the changes I made looks smooth? Like for example, if I have an animation of a game object, and in frame number 100 it rotated 90 degree in the x direction. So now frame 100 has a modified rotation angle of the object, but frame 101 has the original animation. I want to smooth the rotation so that the transition of the obect from the modified frame back to the original animation looks smooth. |
0 | Unity Running code on the "Create Other" menu? Right now I am trying to create a TextMesh GameObject from code. The graphics primitives are accessible through PrimitiveTypes, I'm thinking there must be something similar, and if not, I could at least run whatever static function is bound to the menu if only I knew the name. The more general question is "how one get at all the other items on the "Create Other" without using the menu itself?" |
0 | Should I calculate in meters or pixels In my car sim I am doing my calculations in Standard Units, except for the distance which is in pixels. Is this still correct (my guess is no) or should I use Meters ? If I should use meters what is the best way to go about it? should I just pick a scale 10px 1m or is there a better way to do this ? thanks in advance. Some additional info I'm using Unity3D and using its physics engine. |
0 | Combat System Class Objects as Package and Listener So I've been trying to map out a combat system and I have an idea I'm laying out that I'm looking for a sanity check on, as well as suggestions. The idea is that all things that can do damage (weapons, spells, environmental traps, monsters that deal damage sans weapon) will have a CombatTalker() object attached that will contain information about the amount of damage and damage types (fire, frost, physical, magical, etc.), modifiers that it might have, and any special effects (apply DoT, blind, slow, etc.). Everything that can take damage will have a CombatListener() object that takes that information and transmogrifies it with the receivers resistances and any special properties it may have. The CombatTalker() will create a CombatPackage() from a collection class any time there is a collision, and send it to the CombatListener() on the collided objects, supposing it has one. The CombatPackage() is basically the raw data about the damage and effects. The CombatTalker() is a wrapper of sorts that generates the CombatPackage() based on the weapon (or whatever) base damage, then the specific details of that individual weapon, and sends it (like a network packet) to the CombatListener(). The CombatListener() unwraps the package, and in reverse applies the resistances then applies any relevant damage and effects. I know some of that was slightly repetitive, but I was trying to outline the idea completely, which apparently took two paragraphs. I know this might be slightly complex, but the creatures and players and weapons and spells can change over time, so there isn't just a pool of static data that can be attached to the item. It needs to be able to read stats from JSON, apply specific information about the damage and send it. The same goes on the other side in reverse. Is there a reason that this is "too complex"? Am I considerably overthinking it, or is this a reasonable method for a combat system? Thanks! |
0 | Loop in coroutine stops after going halfway I have a very weird problem with a particular loop in a coroutine public IEnumerator DestroyCubesGameOver() var startingCubeHolder GameObject.FindWithTag("StartingCubeHolder") DestroyOutOfCameraCubes() Debug.Log(cubeGroup.transform.childCount) for (int i 0 i lt cubeGroup.transform.childCount i ) Debug.Log(i) Destroy(cubeGroup.transform.GetChild(i).gameObject) yield return new WaitForSeconds(0.001f) Destroy(startingCubeHolder) The loop starts doing its thing and it needs to do it 100 times for example. However it stops after going about halfway and after destroying about half of the objects. Even if I increase the delay for each repeat it still does the same exact thing needs to repeat itself and destroy 100 objects, ends after destroying just 50. What is causing this? Edit If I make it just a void method it destroys all of the objects. Edit 2 This loop was initially a foreach but I rewrote it to try the other way same thing. |
0 | Why can't I expose a Plane variable in my unity script? I've got a script which creates raycasts. I wanted to use the (presumably less expensive) Plane.Raycast rather than the GameObject.Collider.Raycast (because the gameobject one has a distance parameter so that's one more check) I can expose the plane gameobject in my scene easily by simply making a public gameobject variable like this public GameObject floor however when I turn it into this public Plane floor It doesn't expose in the scene. Why is this? |
0 | Unity Problems with scene object orientation and rotation after updating my project from 5.0.0 to 5.2.2 Last year I made a large project on Unity 5.0.0, today I re opened it on 5.2.2 to do some work on it. I was given the message that the project needed to be updated, I allowed it to do the update. Now when I open up my scenes, many of my scene objects are misplaced, the rotation is completely wrong and positioned in the wrong place. My scenes are of a refinery and the most commonly broken object is the pipework, something that would take hours to correct manually. My pipework is created this way... All pipes are made in blender and each scene's pipes are saved as a single blender model (with each pipe make from a bezier curve and left as a separate object). Once imported into Unity (as a single .blend file), I've then dragged and dropped coloured materials onto all the individual pipes, so they are all coloured correctly. This has all been fine until updating the project to 5.2.2 now some of the pipes are in the right place, but many are rotated in completely the wrong direction, leaving it looking a mess. If I delete the pipes from Unity and reimport the pipe model back in, this would solve the problem, but then all the materials colours will be gone. Due to the sheer amount of pipes throughout the whole project, to re colour them all again would be an extremely problematic task, especially as it's critical that the pipes are the right colour. I am confused how some of the pipes within the same pipe model are fine and the others are wrong, it would be so much easier to sort if they had all changed rotation together, then I could just switch them all back in 1 go. I have a total of 13 scenes and so far all of them have suffered the same problem. Nothing whatsoever has been changed on any of the scenes, assets or indeed anything in the project folder. In fact I haven't touched a single file within the project since October last year, so it is certainly to do with updating to 5.2.2. Is there anything I can do to fix the problem without having to re import the models back in or manually rotate everything back? I have attached some screenshots to show the issue See how in the blender image, all the pipework is placed correctly and then in the Unity image, half the pipes have flipped and are facing the wrong way. I have removed the ground so this can be seen clearer. Any help would be much appreciated. Many thanks |
0 | How can I make the camera to rotate from side side but in static movement range? I mean for some reason now the camera is rotating to the left and to the right but sometimes it's rotating to one of the sides a lot I mean a very sharp angle and sometimes less rotation. How can I control how much rotation will be from side to side by degrees ? using UnityEngine using System.Collections public class scr camera MonoBehaviour public float rotate amount Use this for initialization void Start () Update is called once per frame void Update () transform.rotation Quaternion.Euler(transform.eulerAngles.x, (Mathf.Sin(Time.realtimeSinceStartup) rotate amount) transform.eulerAngles.y, transform.eulerAngles.z) Sometimes cam14 make almost 240 even close to 300 degrees rotation to one of the sides sometimes less. The rotation is not equal to both sides. I want simple rotation to both side just to see the room and not the walls behind the camera. In this case I set the rotate amount to 7 so it will rotate faster. |
0 | Unity Blend tree weird transition I have duplicated the blend tree from the ThirdPersonCharacter (Ethan) which comes with the Standard Assets package. In the duplicate I went into the blend tree and swapped out the walk animation "HumanoidWalk" with my own animation named "walk", but now I get a weird transition from the animation "walk" to "HumanoidRun". Both animations, my walk animation and the original "HumanoidWalk" are root animated and look similar they have around 1.5 velocity both and same frame length. Animation Settings I created the animation in blender, you will see in my video below that the animation itself runs smooth and as it should, but the transition to HumanoidRun is very weird for unknown reasons. I am using a custom metarig armature which comes with the blender add on "rigify", I deleted some bones on the finger, but the avatar has a check and is ok (no warnings either). Rig Settings Player settings I basically "copied" all the components from Ethan (ThirdPersonController) and only changed the Animator Controller and the Capsule Collider settings to match the model. I made some short videos where you clearly see the problem, it happens if the parameter Forward is at about 0.6 0.8. https youtu.be Q T7FplDxLE https youtu.be nrJNeo1ltsg NOTE First I am demonstrating how it looks with the normal animations, then I add my own. What am I doing wrong? More Infos I just baked the walk animation in blender and exported it to unity again, but this made no difference. I tried to export it from blender as FBX, it made no difference. However, I noticed that the import is happening much faster and applying in unity importer is very fast now. |
0 | How to make player stay on a moving object I've made an obstacle course with various moving parts to test out movement of a player. In the obstacle course there is a section where there are multiple cubes moves from side to side, and you have to jump from one to the other. But regardless of their speed, I can't seem to get the player to stay on top of any of the moving cubes. I have no clue how to fix this my only guess would be to use materials, but I can't apply any to the character controller. I appreciate any suggestion that you can give. Also the movement is done as an animation that I created in unity in the animation window. Thanks, Nova |
0 | Can a UIKit application co exist with a Unity game as a single application? I have a typical UIKit application with three buttons one opens an RSS feed in a UITableView, the second opens some kind of gallery view, and the third opens a Unity 3D game. Is it possible and how easy it is to support both in one application? |
0 | Having trouble making game time pause and unpause I've been trying to make it where when the player does a certain task, the game's time will pause. When the player does another action, the game's time would unpause and continue. I had my code like so using UnityEngine using System.Collections using UnityEngine.UI public class timeScript MonoBehaviour uGUI Items public Text date public Text playerCash Times public static int week public static int month public static int year 1980 amount of cash public static int myCash 10000 public AlertBox alert public Text timeText bool timeActive true int time int day void Start() InvokeRepeating("Timer", 0, 1) public static void Timer() timeText.GetComponent lt Text gt ().text "W" week.ToString() "" year.ToString() playerCash.GetComponent lt Text gt ().text " " myCash.ToString() region YEAR Check if month equals 13 (allows for 12th month to be counted) if (month 13) year month 0 endregion region MONTH Check if week equals 5 (allows for 5th week to be counted) if (month 5) month week 0 endregion region WEEK Check if day equals 8 (allows for 7th day to be counted) if (day 8) week day 0 endregion region DAY Check if Time equals 5 (allows for 4 seconds) if (time 2) day time 0 else time endregion I tried using CancelInvoke(timeScript.Timer()) in another c file but all it did was give me an error that stated I couldn't convert from string to void. |
0 | System.Runtime.Serialization.SerializationException while trying to deserialize List I'm trying to serialize deserialize a class that holds inventory items. The code is attached below. First I call AddOne() void a few times, then I call SaveFile(), then I call LoadFile(). In LoadFile() the following error occurs ex "System.Runtime.Serialization.SerializationException End of Stream encountered before parsing was completed. r n at System.Runtime.Serialization.Formatters.Binary. BinaryParser.Run () 0x00288 in lt 1f0c1ef1ad524c38bbc5536809c46b48 0 r n at System.Runt... Does anybody see my mistake? Thank you for the help! using System using System.Collections using System.Collections.Generic using System.IO using System.Runtime.Serialization.Formatters.Binary using UnityEngine public enum Type undefined 0, Pistol 1, Magnum 2, Grenade 3, BlendGrenade 4, FireGrenade 5, PistolAmmo 6, MagnumAmmo 7, Rifle, RifleAmmo, System.Serializable public class Inventory MonoBehaviour public class InventoryItem public int Amount 0 public int Row 0 public int Col 0 public int Rotation 0 public Type ItemType Type.undefined public List lt InventoryItem gt Items public void Start() Items new List lt InventoryItem gt () public void AddOne() InventoryItem n new InventoryItem() this.Items.Add(n) public void SaveFile() string destination Application.persistentDataPath " save3.dat" if (File.Exists(destination)) File.Delete(destination) using (Stream stream File.Open(destination, FileMode.Create)) BinaryFormatter bin new BinaryFormatter() bin.Serialize(stream, this.Items) public void LoadFile() string destination Application.persistentDataPath " save3.dat" using (Stream stream File.Open(destination, FileMode.Open)) BinaryFormatter bin new BinaryFormatter() try this.Items (List lt InventoryItem gt )bin.Deserialize(stream) catch (Exception ex) Debug.Log(ex.ToString()) |
0 | Editor Window How to create this? I am trying to create this in my editor window but not sure how. Basically a drop down arrow, next to a C icon, next to a toggle, next to a Label with a cog at the end |
0 | How can I use Body tracking in Android using ARCore or some other libraries? I know that ARCore on Android doesn't support Body Tracking like ARKit does. But is there some alternative or workaround to achieve it? Some other SDKs or Libraries or maybe even if there is some way to do it through ARCore itself? To make it clearer I plan to use something like this in an AR game for Android. I plan to develop it in Unity 2019.4.x. My search result in Google didn't yield a useful result as it gets mixed with ARCore Motion Tracking (which isn't what I am talking about here) or implementation with ARKit. But I got a little hope that there might be some way out after reading this post on Unity Forums. |
0 | Unity's Animator.GetBehaviour always returning null I have the following line As you can see "transitionOutAnimator" is null before the line runs. transitionOutAnimator is a StateMachineBehaviour of type ThoughtBubbleTransitionOutAnimator. We can check that the StateMachineBehaviour of the correct type is actually stored in the run time animator Yet when the line runs Am I doing something obviously wrong? Is this a bug? I have another identical instance in the code where I do this, and it works perfectly. EDIT Immediate window EDIT This is still a problem as of Unity 5.3.5f1. |
0 | Camera not following ragdoll in unity I have made a ragdoll and attached (as child object) the main camera to it, but the camera doesn't follow the ragdoll. Why is this happening? And how do I fix this? |
0 | Why do my trees share the same health? My trees keep on falling at the same time and I am not sure why! I am new to Unity3D javascript. Here is my script pragma strict INTS var health 5 GAMEOBJECTS var tree GameObject var log GameObject function Start () tree this.gameObject function Update () if(Input.GetKeyDown(KeyCode.Mouse0) amp amp Player script.axehave amp amp health gt 1 amp amp Camera script.tree) health 1 if(health 0) tree.GetComponent. lt Animation gt ().Play() Destroy() function Destroy() yield WaitForSeconds(2) Destroy(tree.gameObject) |
0 | How can I change the splash screen for a standalone game in Unity3D? I want to change the normal Unity splash screen to be customized for my game and every time I change the splash image in the player setting it does not appear. So how can I do that please? |
0 | How do I enable and disable objects with a certain tag in C ? I have a script that is supposed to find every active object with a certain tag and on the push of a button enable and disable it's meshrenderer and collider. but the script only tries to enable and disable the previous on the object the script is attached to. what am i doing wrong and is there any feasible way to do this? I've checked all tags, but the script keeps trying to reach this unrelated object. i even tried adding a mesh renderer and a colider. but nothing here is the script private bool on true public void Update() GameObject gameObjectArray GameObject.FindGameObjectsWithTag("buildnode") if (Input.GetKeyDown("b")) on !on if (on false) foreach (GameObject go in GameObject.FindGameObjectsWithTag("buildnode")) go.GetComponent lt MeshRenderer gt ().enabled false go.GetComponent lt Collider gt ().enabled false if (on true) foreach (GameObject go in GameObject.FindGameObjectsWithTag("buildnode")) go.GetComponent lt MeshRenderer gt ().enabled true go.GetComponent lt Collider gt ().enabled true Thank you and have a good day. |
0 | Surface Depth Intersection Shader I recently asked a question about the creating an accurate Depth Intersection Shader. When creating this in a fragment vertex shader it could be achieved by the following code SubShader Blend SrcAlpha OneMinusSrcAlpha ZWrite On Tags "RenderType" "Transparent" "Queue" "Transparent" Pass CGPROGRAM pragma target 3.0 pragma vertex vert pragma fragment frag include "UnityCG.cginc" struct appdata float4 vertex POSITION float2 uv TEXCOORD0 float3 normal NORMAL struct v2f float2 uv TEXCOORD0 sampler2D MainTex float4 MainTex ST sampler2D CameraDepthTexture fixed4 Color fixed4 GlowColor float FadeLength v2f vert(appdata v, out float4 vertex SV POSITION) v2f o vertex UnityObjectToClipPos(v.vertex) o.uv TRANSFORM TEX(v.uv, MainTex) return o fixed4 frag (v2f i, UNITY VPOS TYPE vpos VPOS) SV Target float2 screenuv vpos.xy ScreenParams.xy float screenDepth Linear01Depth(tex2D( CameraDepthTexture, screenuv)) float diff screenDepth Linear01Depth(vpos.z) float intersect 0 if(diff gt 0) intersect 1 smoothstep(0, ProjectionParams.w FadeLength, diff) return fixed4(lerp(tex2D( MainTex, i.uv) Color, GlowColor, pow(intersect, 4))) ENDCG However, when I try to put the same logic into a surface shader, the result does not show any depth intersections. SubShader Blend SrcAlpha OneMinusSrcAlpha ZWrite On Tags "RenderType" "Transparent" "Queue" "Transparent" CGPROGRAM Physically based Standard lighting model, and enable shadows on all light types pragma surface surf Standard fullforwardshadows alpha fade Use shader model 3.0 target, to get nicer looking lighting pragma target 3.0 sampler2D MainTex struct Input float2 uv MainTex float4 screenPos float eyeDepth half Glossiness half Metallic sampler2D CameraDepthTexture fixed4 Color fixed4 GlowColor float FadeLength Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader. See https docs.unity3d.com Manual GPUInstancing.html for more information about instancing. pragma instancing options assumeuniformscaling UNITY INSTANCING CBUFFER START(Props) put more per instance properties here UNITY INSTANCING CBUFFER END void surf (Input IN, inout SurfaceOutputStandard o) float2 screenuv IN.screenPos.xy ScreenParams.xy float screenDepth Linear01Depth(tex2D( CameraDepthTexture, screenuv)) float diff screenDepth Linear01Depth(IN.screenPos.z) float intersect 0 if (diff gt 0) intersect 1 smoothstep(0, ProjectionParams.w FadeLength, diff) fixed4 col fixed4(lerp(tex2D( MainTex, IN.uv MainTex) Color, GlowColor, pow(intersect, 4))) o.Albedo col.rgb o.Alpha col.a o.Metallic Metallic o.Smoothness Glossiness ENDCG |
0 | How to start in animating my model? I got a model from TurboSquid. Which is an archer and when i imported the model I got all the textures to be put on properly. The thing is the actual character has no children nodes, is it possible to still animate this model. I have looked throughout the files and there are a bunch of textures, but I don't happen to see any animations. Along side that the asset comes with an Avatar, I looked on the docs and still a little confused as to what that is about. If I cannot animate this model how could I force it to animate somehow or how could I make my own model. I am not a artist at all and just focus on the gaming logic and and programming, and I am working solo. Just wondering what are some options to get a game up and running with some decent graphics. So, far I use the model to get the game play down, but now I want to make it visually appealing. |
0 | How can I write a dots effect shader when the character is behind an object? I watched an interesting effect while I was playing Super Mario Odyssey when Mario or another character was behind an obstacle (walls, etc), a tiny gray silhouette mesh appears. I tried to build something similar using an amplify shader with Unity but I could not achieve it. How could I write this? Here is an example from the game |
0 | What would be the easiest way to define actions of multiple buttons So I'm creating a game that involves lots of different areas that involve pushing buttons to do certain things. Anyway, I'm trying to figure out how to let each button do its own separate thing, like open a door or things like that. I already know how to setup a Raycast between the player's mouse to the button, but now I'm just figuring out how to make each button trigger a separate action. Basically, should I set up a new tag for each button? Or create different scripts, even? I haven't tried anything yet and I need help. Thanks D |
0 | How To Have My Character Turn When The Camera View Moves So I have recently finished animating my character, having it move with key presses and have applied a camera to it. But I am stumped on how to have the player turn when the camera view moves, and have them both in sink. I want to have this instead of using keys to turn because that can be very awkward and hard to control. I would really appreciate any help I can get on this, as it will allow me to finally finish my character. Thanks, Nova |
0 | Unable to open project from a scene.unity file The tutorial I'm following has provided its project files, and I'm trying to open them in Unity. Here is the project download link. You can also go to the tutorial webpage and scroll down to download. I can't figure out how to do it. Here is what I've done. a) Extract zip to my Unity Scenes folder. b) Open Unity, create a new project called tutorial c) File Open Scene navigate to Unity Scenes voxeltut3 scene.unity d) Click Open It opens.. but then I don't see any of the tutorial's files in my project. There's none of the c scripts, no art, no prefabs... It's just the original empty project that I created. I also tried importing it as a new package e) Assets Import New Asset... select Unity Scenes voxeltut3 scene.unity f) Click Import And nothing happens. The Import New Asset dialogbox is still open with the scene.unity selected. It's like it's telling me that I've selected an invalid file. So I guess this is wrong? How do I open this tutorial project? I'm using unity 5.3.2 This is the folder structure the new Unity project that it created for me C Users me Documents Unity Scenes tutorial Assets Library ProjectSettings I unzipped the tutorial files in C Users me Documents Unity Scenes voxeltut3 Materials tiles.mat tiles.mat.meta Block.cs BlockAir.cs BlockGrass.cs scene.unity ... (other files) |
0 | Season system Implementation system in unity So I am planning on implementing a seasons system for a 2D top down game. Each season will have a characteristic terrain feature e.g. summers will have patches of grass spread out .. which I wanna reproduce by green bloat spread around on a 2D plane or quad... These features will need to generate dynamically for every season. The implementation will be simplistic nonetheless... using green bloats for grass patches, blue bloats for waterholes.. Can you guys give me like pointers to solve this problem? Some Reference images Notice how the backdrop background changes for each season Green Patches denotes grass Light blue denotes unfrozen water, dark blue denotes frozen water These bloats are to be generated dynamically, with some conditions like frozen water and unfrozen water need to spawn next to each other Summer Season Monsoon Season Winter Season |
0 | Unity change sprites to something that uses less memory I have a game that uses only silhuette textures, but they take up waay too much memory (360 MB overall and this is a mobile game) so I plan to avoid using sprites with alpha punchouts (1 bit alphas). From what I gathered, I could use an asset from Unity store like SVG importer, but I have no financial means to do so. So I plan to make low poly 3D (in fact 2D) planes that somewhat cover my textures. Now, I have a lot of sprites already. I saw that Unity can create a 2D mesh collider around my sprites. Can I use that to create my meshes and then apply a single colour unlit material to them? How would it roughly effect memory usage as opposed to my generally 500x600 sprites? If I'm going in the wrong direction, is there a way to create Shapes, just like in Photoshop or GIMP? |
0 | Unity Shader blending colors and color values above 1 I have source images where each pixel is one of exactly 4 colors red (1,0,0) green (0,1,0) blue (0,0,1) black (0,0,0) I'm trying to modify Unity's default sprite shader to use those colors (besides black) as a key to change to other colors. For example, any pixel that's red should become RedColor. My first attempt was fixed4 RedColor fixed4 BlueColor fixed4 GreenColor fixed4 frag(v2f IN) SV Target fixed4 c SampleSpriteTexture (IN.texcoord) IN.color fixed4 modColor modColor.rgb RedColor.rgb step(1, c.r) modColor.rgb BlueColor.rgb step(1, c.b) modColor.rgb GreenColor.rgb step(1, c.g) modColor.rgb c.a return modColor This worked. The problem was it was very jagged. In exporting the image and being compressed in Unity I think some pixels had multiple colors but the shader simply would set the color to the last matching color. So I tried to modify it to not reset the color if the next color matches, but instead blend between any colors present in the pixel weighted by their contribution. Here was my second attempt fixed4 frag(v2f IN) SV Target fixed4 c SampleSpriteTexture (IN.texcoord) IN.color float total c.r c.b c.g we set the total to 1 if it's 0 so that we don't divide by zero when the color is black total step(total, 0) c.rgb RedColor.rgb c.r BlueColor.rgb c.b GreenColor.rgb c.g c.rgb total c.rgb a return c This also worked and the jaggedness went away everywhere except the border of black and nonblack colors. So then I tried getting rid of the total and it was perfect fixed4 frag(v2f IN) SV Target fixed4 c SampleSpriteTexture (IN.texcoord) IN.color c.rgb RedColor.rgb c.r BlueColor.rgb c.b GreenColor.rgb c.g c.rgb c.a return c It's perfectly blended between any of the pixels. But I don't get why. I was dividing by the total so that the color values wouldn't go above 1 and it would blend between them. For example if a pixel had both red and blue present it would be adding the 50 of RedColor's rgb value and 50 of the BlueColor's rgb value. So when I didn't divide by the total it appears nothing changed besides blending between black and other colors. This implies to me that I never had any pixels that actually had more than one nonzero color component to them (or else I could would be getting white colors at those pixels). But if that's the case, why did switching from the first step function approach to a blend approach even do anything? This is my first foray into shaders so it's entirely possible I'm doing something terribly, but I just want to wrap my head around what's going on and why. So I definitely appreciate any help ideas. |
0 | Do I need a server if I only want to upload data to a DB? I'm currently creating a game where people get some kind of reports for their game performance on a website. Let's say, you log in, play the game, the system gathers your performance data and this is being sent to a database so that it can be read and interpreted by an external website later. For this, I'm using a firebase real time database and it's working fine by now. I'm pretty noob with unity and I have read and watch tutorials on the internet where people actually create a server to achieve this but do I really need a server when the only thing I need to do is to post data to a database based on users? This isn't really a multiplayer game, but there is some kind of information which is shared for example sometimes I need to get those data in order to get high scores and that kind of small information, but that's it. I'm using unity webgl and firebase for the moment, and everything is working fine, but then why people always create a server for this? PS sorry for my bad english |
0 | Using a Wii remote as main controller? I would like to use a Wii remote to control my player in my 3D game. So far I have the arrow keys and mouse to move and look but I want the Wii d pad to move and accelerometer data to look around. I have downloaded Unity Wiimote 1.1 and the demo works fine. In my game I have imported the Unity package for the Wii remote but I'm not sure what script goes where, attached to what, how to call particular functions. They are mostly C scripts. There is no documentation with the Unity Wiimote 1.1 and as I'm a newbie, I'm clueless on what to do. Or is there a simpler method to getting the Wii remote to be the main controller? |
0 | How to change Unity's display settings resolution? Unity displays in poor quality on my computer (the software itself), I was wondering how to change resolution display settings? |
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 | Bullet physics C script Is imparting force on rigidbody objects I have recently made the simplest gun and bullet script that I could and it works amazingly, except for one problem that I've found. When I attach it to a game object with a rigid body the force of the bullets move the object back with quit a bit of force. But what I can't seem to figure out is why the bullets are imparting force on the object at all. The bullets do not have a rigid body component. The way my guns work is with two scripts, one which acts as a simple spawning point when a key down event is given and what ever object you give it to spawn. The second script is applied to the bullet itself which causes the bullet to have motion through transform.Translate with a speed variable. The best example I can give of this is when I attached two guns to the default unity jet and when I fired, it had enough force to move the jet back against its thrust speed. I really would appreciate any help with this so I can move on with my project. I will provide the code bellow for the two scripts. Thank you public class Shoot MonoBehaviour public GameObject bullet void Update () if (Input.GetKey (KeyCode.Mouse0)) Instantiate(bullet, transform.position, transform.rotation) public class MoveBullet MonoBehaviour public float speed 1f void Update () transform.Translate (0, 0, speed) |
0 | Character doesnt move along with his rotation Decided to change my character movement from transform.Translate to a rigidbody movement, the only problem is that my character is not moving to where he is facing, also it falls really slowly in the Y axis. Heres the code related to the movement float moveHorizontal Input.GetAxis("Horizontal") rotSpeed float moveVertical Input.GetAxis("Vertical") speed rb.velocity new Vector3(0, 0, moveVertical) transform.Rotate(0,moveHorizontal, 0) |
0 | Unity How to manage a large amount of prefab variations? The project that I'm working on demands the ability for game designers to be very flexible when balancing, customizing items, etc. The most difficult requirement to meet at the moment is that they want to drag drop, say, a weapon prefab onto a weapon field in some game entity component and from there be able to tweak the prefab's parameters. If I provide some tools that create derived prefabs at such moments, then we'll end up with possibly hundreds of pretty much same prefab variations and also loose the ability to edit the initial prefab and transfer the changes to derivatives. What I'm starting to consider is introducing a "Data Map" structure in every entity that requires high level of parameter customization. Every parameter would be set through methods like Set GetFloat("key", "value"), Set GetFloatArray, Set GetInt, etc. So basically a dictionary that maps a string to a predefined set of data types. When a prefab of such entity would be drag dropped into a field of another component, an editor tool would separate the "Data Map" from the prefab, allow the game designer to tweak the values of the keys and eventually serialize it to json. During runtime uppon instantiation of a prefab with a "Data Map" a manager would check the deserialized overrides and override the "Data Map" with the tweaked values if needed. Though to me this sounds overly complicated and maybe some of you had a similar situation and came up with a simple solution? Maybe it's worth trying the ECS approach? Thanks. An example Let's say there are prefabs Axe, Sword, Bow with a bunch of parameters configured, say Damage, Durability, etc. There are many other components that can accept a weapon prefab and once it's dropped, the designers want to have "on the spot editing" say, okay, for this situation here the Axe prefab needs to be a little different and have Damage 3. Creating a new prefab means that the link to the initial Axe prefab is lost and there are now two Axe prefabs that need to be managed this is the problem we're trying to address. |
0 | How to avoid overwriting a value in Unity? I'm working on a Tower Defence style game, and wondering how best to handle the quot resources quot part. I have multiple enemies on screen at a time, and when an enemy dies, it updates a resource that allows the player to build more towers var tower Instantiate(buildables 0 , center, Quaternion.identity) var controller tower.GetComponent lt TowerController gt () controller.OnKilledEnemy (sender, args) gt int.TryParse(goldAmount.text.Replace( quot , quot , quot quot ), out var curr) curr args.gold goldAmount.text quot curr n0 quot But if 2 enemies die in the same frame, wouldn't the value there miss an update? What ways are there in Unity C to mitigate this problem? |
0 | can't make my unity character move so I'm starting with Unity , I followed the john lemon tutorial , and I wanted to apply what I learn on a model on my own coming from blender. Everythings works , animation , rotation , but not translation . For some reasons my character doesn't move at all . It might have to do something with root motion since I have apply root motion in grey with written just after "handled by script" . Not sure what to do .. I found something about character in place, I think I'm in this case but I'm not sure how to use it in my script .. https docs.unity3d.com Manual ScriptingRootMotion.html If you ask I'll give you my project . EDIT ok so I made some advances void OnAnimatorMove() m Rigidbody.MovePosition(m Rigidbody.position m Movement m Animator.deltaPosition.magnitude 10000) m Rigidbody.MoveRotation(m Rotation) Debug.Log("m Animator.deltaPosition.magnitude " m Animator.deltaPosition.magnitude) m Animator.deltaPosition.magnitude is actually always equal to 0 , explaining why my charachter doesn't translate but why is it always equal to zero ? |
0 | Stop player following cameras cameras direction Okay I'm not going to go to much into it but this is what I need my script to do. The way I have my controller set up is that the camera looks to the side of the player a little bit. I use this for aiming attacks, bullets and what not. The problem is that it follow the camera when it looks up causing my character to slightly jump ever time I aim and look up. So i want the player to move with the camera while ignoring its y axis. and i need my character to jump so i cant just make the players y movement 0. Here's the code I've been using transform.position Time.deltaTime cameraMain.forward Input.GetAxis("Vertical") speedWilAim and I am trying to avoid separating the mouse look script into x and y pivots but if there is no alternative I will do that. |
0 | How do you exactly implement a Semi Implicit Euler type of movement in a 2D platformer? So I've been following along Sebastian Lague's 2D platformer tutorial, and to understand exactly how the physics of how a jump is done, I dug into the subject and noticed a lot of people, from GafferonGames and Kyle Pittman, all mention using Semi Implicit Euler in making an accurate jump. Now my problem is How do you exactly implement this type of integration scheme in a game? Specifically a platformer. A comment on the tutorial I was following said that the code below uses the Explicit Euler type of integration. Though I'm not exactly sure myself on whether or not this is true another tutorial I found on the topic, specifically Jorge Rodriguez's Math for Game Developers uses the Semi Implicit Euler integration to make a spaceship simulator, but the code used was C and I only have some limited C and I was not able to fully understand parts of the code that went into implementing the integration. Specifically auto v vn, gravity (Vector x, float h) gt Vector return vn gravity(x) h auto a xn, gravity (Vector v, float h) gt Vector return gravity(xn) gravity(xn v h) h from what I understand, this function returns a Vector2, but I don't know if the auto a xn, gravity is supposed to be about declaring a variable or what, or how the vector bit fits in the whole code. All in all, I need help, I'm still pretty new to programming and general and these small nuances confuse me. Any help is greatly appreciated, Thank you. This is the code for the Platformer Character controller I followed from Sebastian Lague. using System.Collections using System.Collections.Generic using UnityEngine RequireComponent (typeof(EntityController2D)) public class PlayerController MonoBehaviour EntityController2D playerController region Y Velocity Fields public float jumpDisplacementDeltaTime 0.75f public float jumpHeight 6.0f float gravity float jumpVelocity endregion float moveSpeed 6.0f Vector2 velocity public void Start() playerController GetComponent lt EntityController2D gt () gravity (2 jumpHeight) Mathf.Pow(jumpDisplacementDeltaTime, 2) jumpVelocity Mathf.Abs(gravity) jumpDisplacementDeltaTime print ( "Gravity gravity ") Update is called once per frame public void Update() Vector2 input new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")) if (playerController.collisions.below playerController.collisions.above) velocity.y 0 if (Input.GetKeyDown(KeyCode.Space) amp amp playerController.collisions.below) velocity.y jumpVelocity velocity.x input.x moveSpeed velocity.y gravity Time.deltaTime playerController.Move(velocity Time.deltaTime) |
0 | How To Disable A Select Collider I have a character with 2 2D Colliders, one for the head, and one for the feet, How do I Disable only the Head Collider in C . |
0 | How I add gap between Instantiated objects? using System.Collections using System.Collections.Generic using System.IO using UnityEngine using UnityEngine.Networking using UnityEngine.UI public class SavedGamesSlots MonoBehaviour public GameObject saveSlotPrefab public float gap private Transform slots private string imagesToLoad Start is called before the first frame update void Start() imagesToLoad Directory.GetFiles(Application.dataPath quot screenshots quot , quot .png quot ) slots GameObject.FindGameObjectWithTag( quot Slots Content quot ).transform for (int i 0 i lt imagesToLoad.Length i ) var go Instantiate(saveSlotPrefab) go.transform.SetParent(slots) Texture2D thisTexture new Texture2D(100, 100) NOW INSIDE THE FOR LOOP string fileName imagesToLoad i byte bytes File.ReadAllBytes(fileName) thisTexture.LoadImage(bytes) thisTexture.name fileName GameObject ChildGameObject go.transform.GetChild(1).gameObject ChildGameObject.GetComponent lt RawImage gt ().texture thisTexture var raw go.GetComponent lt RectTransform gt () raw.anchoredPosition new Vector3(1 1 gap, 6, 0) Update is called once per frame void Update() The way I'm doing it now is not working it's moving all the objects to the same position and not adding equal gap's between them. In the loop I tried to do it this way in this line raw.anchoredPosition new Vector3(1 1 gap, 6, 0) |
0 | Objects rendering only on editor, but not on build (they get invisible) Everything works fine in the editor, but when I build the game, none of the objects in the scene are rendered, and only the skybox and UI text is visible. But although they aren't appearing, they are working as normally (i.e. these objects' triggers work normally when the determined event occurs, like for example, colliding to a specified object, or in other words, they are invisible). I searched for this issue but didn't found any answer. Could it be my cheap computer's fault (Intel Celeron without an external graphics card)? In editor game mode In buit game I ran both the editor and the built game in the same quality, and also tried to run it in Fastest quality, but no, it made no difference in the built game. Also, there is no object tagged with "Editor only", only one have a custom tag and all the others are "Untagged". And the camera's culling mask is set to "Everything". The result is the same either for web or Windows. Edit OK, I built for Android and the objects render normally. So, I'm not completely sure, but probably it's my PC that can't render the objects, because both building for web plugin and desktop have this disappointing result, but for Android it works perfectly (even the shadows, which wasn't being cast in the editor), so... |
0 | Unity 2D Input.gyro eulerAngles X value strange behaviour I am working on a project where I want to create an 'scrolling' effect using gyroscope on mobile devices. The basic idea is that I have an Image object in my Scene and I want to be able to show different part of it using gyroscope like for example you see the wall of a room and rotation your phone you see different parts of the room, but in 2D. For now I managed to move my Image using Input.gyro.attitude.eulerAngles.x from gyroscope like this protected void Update() var x transform.localPosition.x var gyroX Input.gyro.attitude.eulerAngles.x x gyroX Speed BackgroundImage.transform.localPosition new Vector3(x, transform.localPosition.y, transform.localPosition.z) The problem which I am seeing is that when Input.gyro.attitude.eulerAngles.x reaches 86.0 it starts decreasing and even if you are rotating your phone to right it changes it's direction. Checked the documentation, examples over internet, but didn't find anything about that. If you have any idea what can cause that issue and how can I fix it, or any other suggestions how can I achieve the thing which I want to create, pleae share your knowledge. Thanks in advance! Edit The only rotation axis which I am interested in is X, because the app will be in portrait mode and I want to be able to move the image only horizontal (by X). So the phone's rotation has to be similar to while taking an panoramic photo on your mobile as shown on the first picture |
0 | BIM Model clipping issues in Unity 2020 I have BIM model that I am using in 2018 version of Unity engine. When import the model into my project on 2019 OR 2020 version of the Unity engine, clippings on certain surfaces of the model occurs. Has anyone encountered this issue with Unity 2020? Any solutions that can be suggested for me to try? Examples attached. Appreciate any help in advance... |
0 | Sending RPC calls from server to client inside Unity In my game inside Unity, I have two scenes setup. One for the main server ( acts like authoritative server ) and the other scene for my client. The game starts once my client connects to the server. Now I am able to send RPC function calls from my scripts in my client scene to the server but I am not able to do it the other way around. Further edit to my code after comments This is my client side script attached to GameObject CursorDetection inside Scene2 using UnityEngine using System.Collections ON THE CLIENT SIDE public class CursorDetectionScript MonoBehaviour private bool hasGameStarted false void Update() if (Input.GetMouseButtonDown(0)) networkView.RPC("mouseDown", RPCMode.Server,true) RPC public void mouseDown(bool isMouseDown) On the server side script inside scene1 private void OnPlayerConnected(NetworkPlayer player) Debug.Log(" PLAYER CONNECTED " player) networkView.RPC("AddNetworkPlayer", RPCMode.AllBuffered, player) RPC public void AddNetworkPlayer(NetworkPlayer player) playersList.Add(player) Debug.Log(" FIRST PLAYER IS " playersList 0 ) if(startGame) networkView.RPC("SendMessageToClient1", RPCMode.AllBuffered, playersList 0 ) RPC public void mouseDown(bool isMouseDown, NetworkMessageInfo sender) isMouseDown true Debug.Log("CAN PLACE PANELS NOW" " VIEW IS " sender.sender.guid) back on the client side script inside scene2 I called the SendMessageToClient1 function call RPC public void SendMessageToClient1() Debug.Log(" INSIDE CLIENT 1 ") |
0 | 2D player controller moves to the left, but not to the right I wrote a C script to control a 2D player, but the script is not fully working. When I press the right arrow d key to move the player is not moving in the right direction, but I have done the same exact thing for left key which works fine.The script shows no errors too.Kindly help me to solve the issue.The code is using UnityEngine public class PlayerController MonoBehaviour SerializeField private Rigidbody2D rb2d SerializeField private float speed SerializeField private float jump private static float tempspeed private static float tempjump private bool isRight private bool isLeft private bool isSpace private void Start() isLeft false isRight false isSpace false speed 5f jump 7f tempjump jump tempspeed speed private void Update() ReadInput() private void FixedUpdate() Move() private void ReadInput() if (UnityEngine.Input.GetKey("d") UnityEngine.Input.GetKey("right")) isRight true else isRight false if (UnityEngine.Input.GetKey("a") UnityEngine.Input.GetKey("left")) isLeft true else isLeft false if (UnityEngine.Input.GetKey("w") UnityEngine.Input.GetKey("up")) isSpace true else isSpace false private void Move() Vector2 speedVectorRight new Vector2( tempspeed, rb2d.velocity.y) Vector2 speedVectorLeft new Vector2( tempspeed, rb2d.velocity.y) Vector2 jumpVector new Vector2( rb2d.velocity.x, tempjump) if ( isRight) rb2d.velocity speedVectorRight else speedVectorRight.x 0f rb2d.velocity speedVectorRight if ( isLeft) rb2d.velocity speedVectorLeft else speedVectorLeft.x 0f rb2d.velocity speedVectorLeft if ( isSpace) rb2d.velocity jumpVector When I tried to print debug statements in different parts of if statements, they work fine. The problem in my observation is in if ( isRight) rb2d.velocity speedVectorRight else speedVectorRight.x 0f rb2d.velocity speedVectorRight The rb2.velocity is not accepting speedVectorRight I guess.Thanks in advance! |
0 | How to rotate a local position offset based on a direction vector? I'm trying to fire three raycasts in the direction of movement, from offset starting points. I'm having trouble calculating the start positions of the rays based on the direction. As you can see in the animation, the three parallel lines in the middle overlap when moving upwards using the code below, but I want them to remain evenly spaced. I cannot use transform.right (up etc) etc because the transform is always facing the same direction by design. Instead I am using the currentDirection which is the normalized last movement velocity. I want the lines to always be evenly spaced based on the direction the object is moving without rotating the actual transform the problem is I don't know the math behind it and have spent last several hours trying to figure it out. Current code Debug.DrawRay(this.transform.position, currentDirection (avoidObjectsScanDistance 0.05f), Color.blue, 0.09f) Debug.DrawRay(this.transform.position new Vector3(0, 0.1f, 0), currentDirection (avoidObjectsScanDistance 0.05f), Color.magenta, 0.09f) Debug.DrawRay(this.transform.position new Vector3(0, 0.1f, 0), currentDirection (avoidObjectsScanDistance 0.05f), Color.blue, 0.09f) I've tried to get the position based on direction by using var drawRayTopPos currentDirection localpos position |
0 | In Unity, why do I get a "does not implement right interface" error when trying to sort my list of objects? I am trying to create a crafting panel that sorts the list of items you can make alphabetically, yet I cannot figure out why .Sort() is not working. What I have is a game object that holds a list of all the items you can make and the requirements, then in my crafting script I access the game object for the list and display the info. Everything works fine until I try to sort anything. craftDatabase is what I need to be sorted. Also, it needs to be sorted by ItemID. using UnityEngine using System.Collections using System.Collections.Generic public class CraftDatabase MonoBehaviour public List lt Blueprint gt craftDatabase new List lt Blueprint gt () System.Serializable public class Blueprint public string itemId public int itemAmount public float itemCraftTime 1f public CraftPanel.subsections subsection public CraftPanel.workstations workStation public List lt requiredItem gt requiredItems new List lt requiredItem gt () HideInInspector public string desc System.Serializable public struct requiredItem public string itemId public int itemAmount public Blueprint() When I try to throw in craftDatabase.craftDatabase.Sort() it gives me this error ArgumentException does not implement right interface How do I fix this error to use Sort()? |
0 | why is my (from example) shader appearing as black? I have the following (very simple) shader pragma kernel CSMain RWTexture2D lt float4 gt Result numthreads(8,8,1) void CSMain (uint3 id SV DispatchThreadID) Result id.xy float4(1,0,0,1) Here is the dispatcher code using UnityEngine using System.Collections public class SkyShaderDispatcher MonoBehaviour public ComputeShader shader public RenderTexture output void Start() RenderTexture output new RenderTexture(256,256,24) output.enableRandomWrite true output.Create() void Update() RunShader() void RunShader() int kernelHandle shader.FindKernel("CSMain") shader.SetTexture(kernelHandle, "Result", output) shader.Dispatch(kernelHandle, 256 8, 256 8, 1) which is the default red shader (it makes the texture red). However, when I put the texture in a material and give that to an object, then that results in the object being black. Anyone seeing what I'm doing wrong? As the shader is the default example right now it should work suggesting that maybe something is wrong with the texture? Edit Trying to fit the same code on a skybox also fails. I have changed the dispatcher code into using UnityEngine using System.Collections public class launchClouds MonoBehaviour public ComputeShader shader private RenderTexture output void Start() void Update() RunShader() void RunShader() int kernelHandle shader.FindKernel("CSMain") RenderTexture output new RenderTexture(256,256,24) output.enableRandomWrite true output.Create() Material mat gameObject.GetComponent lt Skybox gt ().material mat.SetTexture(" FrontTex",output) mat.SetTexture(" BackTex",output) mat.SetTexture(" LeftTex",output) mat.SetTexture(" RightTex",output) mat.SetTexture(" UpTex",output) mat.SetTexture(" DownTex",output) shader.SetTexture(kernelHandle, "Result", output) shader.Dispatch(kernelHandle, 256 8, 256 8, 1) but that turns the sky black rather then making the sky red. This is using unity 5 32 bits with DirectX11. |
0 | Extend distance for rendering grass and tree objects on terrain I am trying to make an adventure game with a big landscape (made the terrain with terrain tools) with 3D models of grass (that I placed using terrain tools) but it only shows the grass trees that are within a small area. Here is a pic of what I am talking about I would not want to totally remove this because otherwise the framerate will go too low. I just want to make the circle bigger. thanks ( |
0 | How to set the Y position of Camera to another object's y position, but only once, not continuously? Essentially, I want to set the camera's Y position to another GameObject's Y position, but I only want to do this one. If you do cam.transform.position new Vector3(0, thing.transform.position.y, 0), it will continuously update to that object's y. Even if I store the Y float in a variable and set the camera's y to that it still continuously updates. It is only supposed to happen once. |
0 | Setup script variables before attaching to an object I need to attach a script at runtime, but that script requires some public members to be set in order to be helpful. Is there a way for me to setup the public members of the script before attaching it to a GameObject at runtime? |
0 | Animations not accepted in animator In the official Unity Animator State Machine tutorial video animation clips are dragged out from the assets folder into the animator and dropped. I have a 3D model that i bought online to experiment with that comes with animations. I added a custom made animation as well. These all work well in my demo project. But when i add a animator to the assets and try to drag and drop animations onto it it doesnt work. I get a forbidden sign as a mouse pointer. I try to add animations through the inspector but that does not work either. The tutorials makes it seem so easy and does not talk anything about what animations can be used. What am i doing wrong? |
0 | Can I save a score as highscore, if it's a float? So I have this infinite runner type of game, subway surfers style. I chose a method where the player doesn't move, and instead the obstacles move towards him. My score is a float and it increases as time passes. However, I'm unable to figure out how can you save this as a highscore. I tried a few methods but most of them were for int so it didn't work out. Here is what I have for the score counting. It's currently missing the save score part completely. public class GameManagerC MonoBehaviour float score 0 public float scoreMulti 5 void Update() if (isPlayerAlive true) score Time.deltaTime scoreMulti scoreText.text score.ToString( quot Score 0 quot ) EDIT Many of you asked how I tried to implement the code I've found so here it is public float score public float highScore void Start() score PlayerPrefs.GetFloat( quot score quot ) highScore PlayerPrefs.GetFloat( quot highScore quot ) if (score gt highScore) highScore score StartGame() Update is called once per frame void Update() if (isPlayerAlive true) score Time.deltaTime scoreMulti scoreText.text score.ToString( quot Score 0 quot ) |
0 | Animated lighting in amusement parks What is the best way to handle animated lights on rides in a night time amusement park scene? Is there a better way that doing lots of emission lights? At the moment I have been using emission lights, but there could be a lot of them in a park (some are just static lights) and I would also like to animate some of them on some rides. Best example I could find was from GTA 5 Video https youtu.be zVj8D0lqgl4?t 146 |
0 | Why won't my ball bounce? (Unity, 3D) I'm trying to do a very simple ball bouncing setup in Unity. I have a sphere with a sphere collider and a plane below it was a rectangular mesh on it, isTrigger set to false for both, and they both have a physics material with bounciness of 1. I have the ball start a couple units above the plane, gravity pulls it down, but instead of bouncing it stops right at the collider for the plane, then (weirdly) slowly falls through the collider. Once it falls through the bottom it starts falling normally again. The collider is already really thick (I've been trying to fix this by changing collider types and making them way bigger than needed). I just have no clue what's going on and feel like I'm missing something obvious. |
0 | using Mathf.Clamp in Vector3 to restrict object drag I'm making a checkers game and I've got a movement controller working to move the pieces. I want to restrict the drag to be within the board. The center of the board is 0,0 so the far left side's x value is 4, top of the boards y is 4, etc... This is my drag script so far void OnMouseDrag() float distance to screen Camera.main.WorldToScreenPoint(gameObject.transform.position).z transform.position Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance to screen)) but when I try to clamp my new Vector3's x and y between 4 and 4 like this, transform.position Camera.main.ScreenToWorldPoint(new Vector3(Mathf.Clamp(Input.mousePosition.x, 4f,4f), Mathf.Clamp(Input.mousePosition.y, 4f,4f), distance to screen)) it shoots the pieces way off camera. This may be because don't truly understand Camera.main.ScreenToWorldPoint, is it returning different x,y coordinates than the global ones? |
0 | Why the rotation switching mode is not working right when using bools? using System.Collections using System.Collections.Generic using UnityEngine public class Objects MonoBehaviour public float maxScale 10.0f public float minScale 2.0f public float shrinkSpeed 1.0f public float rotatingSpeed 3f public bool automaticScale false public bool rotateOnMouseMove false public bool rotateOnMouseDrag true private float targetScale private Vector3 v3Scale void Start() v3Scale transform.localScale void Update() RaycastHit hit Ray ray if (Input.GetMouseButton(1)) ray Camera.main.ScreenPointToRay(Input.mousePosition) if (Physics.Raycast(ray, out hit) amp amp hit.transform transform) targetScale minScale v3Scale new Vector3(targetScale, targetScale, targetScale) if (automaticScale false) transform.localScale Vector3.Lerp(transform.localScale, v3Scale, Time.deltaTime shrinkSpeed) if (Input.GetMouseButton(0)) ray Camera.main.ScreenPointToRay(Input.mousePosition) if (Physics.Raycast(ray, out hit) amp amp hit.transform transform) targetScale maxScale v3Scale new Vector3(targetScale, targetScale, targetScale) if (automaticScale false) transform.localScale Vector3.Lerp(transform.localScale, v3Scale, Time.deltaTime shrinkSpeed) if (automaticScale true) transform.localScale Vector3.Lerp(transform.localScale, v3Scale, Time.deltaTime shrinkSpeed) if (rotateOnMouseMove true) transform.Rotate(Input.GetAxis("Mouse Y") rotatingSpeed, Input.GetAxis("Mouse X") rotatingSpeed, 0, Space.World) if (rotateOnMouseMove true) rotateOnMouseDrag false if (rotateOnMouseDrag true) rotateOnMouseMove false private void OnMouseDrag() if (rotateOnMouseDrag true) transform.Rotate(Input.GetAxis("Mouse Y") rotatingSpeed, Input.GetAxis("Mouse X") rotatingSpeed, 0, Space.World) The problem is at the bottom if (rotateOnMouseMove true) rotateOnMouseDrag false if (rotateOnMouseDrag true) rotateOnMouseMove false Once I'm starting the game by default the rotateOnMouseDrag is set to true. When I click on the check box of rotateOnMoseMove it's switching between them the rotateOnMouseDrag is false and rotateOnMouseMove is true. The problem is when then I click again on the check box of rotateOnMouseDrag but it's never switching between them again it keep staying true on the rotateOnMouseMove. I want it to act like a switch each time one of them is true the other should be false. |
0 | Bullet hits the object not in the center of the screen When player shoot, the bullet fly to the center of the screen. But if player stay too close to some object, then bullet hits it not in the center, because it flies from the gun on the right side of the screen. How can I fix this? public Rigidbody projectile public int speed 50 public Transform startBulletPosition void Update() if (Input.GetButtonDown("Fire1")) Rigidbody clone clone Instantiate(projectile, startBulletPosition.position, transform.rotation) as Rigidbody var centre new Vector3(0.5f, 0.5f, 0f) var ray Camera.main.ViewportPointToRay(centre) clone.velocity ray.direction speed Edit 1 |
0 | Unity3d Transform.position float range I thought floating point has a very large range, for example up to 3.4 10 38. However today I tried to set my player's Transform.position.x to 1000000 in the GUI and it gave me a warning "Due to floating point precision limitations, it is recommended to bring the world coordinates of the GameObject within a smaller range." Does that mean that my single scene has to be smaller than 1000000 1000000 1000000. Is this considered big enough? I will need multiple scenes if I want a larger world? When a new scene gets loaded, will my player's position be reseted? How do I manage the position data so that it doesn't go out of range? I'm using Unity3D Pro. |
0 | Unity Facebook WebGL build... Does this work or not?!?! Getting conflicting answers So here is the facebook documentation.. It seems to be saying you can output a Facebook WebGL build from Unity and upload it. It does not work for me, I get this message when I upload. "Games must reference one of our supported SDKs via our CDN." Theres also this thread, with people saying it is not supported. https forum.unity.com threads facebook instant games support html5.499198 Yet the latest version of Unity has a WebGL option when building to Facebook platform. What is going on? Does or doesn't this work? |
0 | Why does my character move diagonally? So i've been trying to make the player face towards the direction i pressed. That part works just fine but when I try to move the player it moves diagonally instead of left right. Any clues? if (Input.GetKey(KeyCode.RightArrow)) moves the player rb2d.velocity new Vector3(2.5f, 0, 0) transform.Translate(rb2d.velocity Time.deltaTime) flips the player right if (human.flipY true) human.transform.rotation Quaternion.Euler(0, 0, 270) else transform.rotation Quaternion.Euler(0, 0, 270) |
0 | Make transform.up face toward velocity while preventing transform.forward from rolling? I have been working on a personal project that is suppose to mimic Anthem. I am using a state machine for the character controller that I intend to integrate with the Unity's Animation state machine. I am calculating a new velocity that makes the player follow the mouse when flying, and I am making transform.up Velocity so that the player appears to be going head first towards its velocity. The issue is that when you start to rotate in a circular way on the xz plane, the player will start to roll and its transform.forward moves from facing towards the ground (which is what I want) to facing the sky. The core code is in public override Update() public class s MechFlyt MechStates float flySpeedPercentage public s MechFlyt(in MechController Master) base(Master) flySpeedPercentage 2.5f public override void Update() if ( Master.SprintButtonHeld) Quaternion Rot Quaternion.Euler( Master.DMouse.y , Master.DMouse.x , 0) Master.Velocity Rot Vector3.forward Master.Stats.Speed flySpeedPercentage Vector3 Rotation Master.Velocity Rotation.y Mathf.Clamp(Rotation.z, 0, 50) Master.transform.up Vector3.Normalize(Rotation) Master.transform.rotation Rot Master.transform.rotation Quaternion.RotateTowards( Master.transform.up, Master.Velocity, 5) Master. Controller.Move( Master.Velocity Time.deltaTime) if ( Master.JumpButtonHeld) Master.ChangeStates( quot hover quot ) Master.transform.up Vector3.up else Master.ChangeStates( quot fall quot ) Master.transform.up Vector3.up public override void EnterState() Master.CamController.ChangeStates( quot flying quot ) |
0 | Unity Manually sync location of players from server to client I am new to Unity networking. I've set up my scene with NetworkManager and the Player prefab having NetworkIdentity. I originally had my players set up to sync with a NetworkTransform. This worked, but the objects were very choppy whenever they were children of a moving object. In order to fix this issue, I've replaced NetworkTransform with a class extending NetworkBehavior, using UnityEngine.Networking, and containing the following code to sync localPosition void Update () CmdSyncPos (transform.localPosition, transform.localRotation) Command protected void CmdSyncPos (Vector3 localPos, Quaternion localRotation) transform.localPosition localPos transform.localRotation localRotation This works really well! The only problem is that this is one way, the server now has the updated position of all clients but the clients only have the updated versions of themselves. How can I do this in reverse Manually sync the location of non local players from server to client? |
0 | Unity 2d Not Destroying enemies impact on memory I know pretty much zero about game performance in Unity. I am trying to figure out if I can afford to put this feature in my game I would like to have the enemies killed to pile up in a sort of heap, so I was thinking about not using the same old destroying routine after they die. The game itself is really simple, it's 2D and for mobile. It has a fixed background and there's not much moving around aside from the player, the enemies and few npcs (which would get destroyed when offscreen), we're talking around ten 32X32 sprites onscreen at a time. Once dead the enemies would not be removed but they wouldn't need to be raycasting, colliding, ecc.. Just only be there for visual sake. So the question is would a mobile device easily handle not removed enemies in the order of a hundred or so (I could destroy those at the bottom of the heap) and not slow down or crash the game? Are there some example of this kind of feature (other games that don't destroy dead enemies)? Or is there a good practice too keep enemies in game without impacting memory resources? Thanks for the attention. |
0 | Animation inside GUI Good day. I would like to create a "rich" GUI for my game. How can i add a 3d model to a GUI Button (with continous rotation ) ? If I can't add a 3d model to a GUI button, what is the best way to visualize a 3d model rotating ? Maybe creating a video file or animated gif and adding it to my button ? Thanks |
0 | Visually updating the position of a game object controlled by an animator controller I have a game object that is controlled by an animator controller. In order to activate the next animator state, the user is supposed to grab this game object, and then move it from Point A to Point B. As a test, in said game object's Update() method, I added the following line this.transform.localPosition Vector3.up When running the game, I can see that the y coordinate of the game object's position increases every single frame, just as intended. However, visually, the game object's position is not changing at all it remains in the same place all the time. What should I do to ensure that game object's position is also visually updated? EDIT Here are the properties of the animator I am using EDIT If relevant, here is the skinned mesh renderer for said game object |
0 | Set default values by script? Insted of Inspector, I want to set default values by script because there is MeshRenderer, a RigiBody etc. I don't know how to write this in script. These are not numerical values. |
0 | How can I record gameplay footage as a video within Unity? I am building a traffic simulator in Unity. I need to record my game as a video, so that I can use the video for machine learning purposes. I used fraps for the same but didn't find it worked for me since it's not within Unity. How can I make a video recording of the gameplay? |
0 | How do I set a scene up for two players? I m finishing a game in Unity, but I have a new requirement make it multiplayer. I will do this by splitting the screen and running two instances. Is there a way to instance a scene twice at the same time, and render them two a different part of the screen? Alternativley, what is the best approach to achieve this? |
0 | first person character controller error I have opened new scene, deleted camera and imported first person character controller from Standard assets. I placed plane on scene and put first person character controller on plane. I got this error Assets Standard Assets Characters FirstPersonCharacter Scripts RigidbodyFirstPersonController.cs(3,27) error CS0234 The type or namespace name CrossPlatformInput' does not exist in the namespaceUnityStandardAssets'. Are you missing an assembly reference? How to fix it? |
0 | Setting up a low res viewport to stretch in Unity I am working on porting a low res game over to Unity. In my previous engine, I had the option to set a native resolution (say, 160 x 144), and it would automatically stretch when the player entered fullscreen (with options for whether you wanted to keep the same aspect ratio, or stretch). I am having trouble figuring out how to set up something similar in Unity. I see that you can play around with resolution settings from Edit Project Settings Player. I tried various combinations of Default Is Fullscreen, Default Is Native Resolution, and Default Screen Width and Default Screen Height, but I haven't been able to get it to work. When I play the scene in the editor, the viewport is still much larger than my desired resolution. And when I Maximize On Play, the FOV is even larger. I Googled around, but couldn't find an answer that helped. Any advice? |
0 | How do you have rigged clothing animate with a base model? How do you have rigged clothing animate with a base model? Or how can you coalesce multiple skinned mesh renderers or have them all be controlled by just one? Or, do you just have multiple animators for each SkinnedMeshRenderer (and there would be quite a number, for a character with a complex outfit that is modular)? Have not been able to get it to work from the only thing I can find online (surprised there aren't more tutorials on this) https forum.unity.com threads tutorial how to make clothes animate along with character.475253 I've applied the method by looping through the SkinnedMeshRenderers present in the clothing assigned when a character root is loaded in ApplyClothing(clothing,root). Clothing and character have the same bone structure, as the clothing is custom modeled to the character model and rig. I get a few unable to map L R Knee Ankle Foot errors, but I have removed the break. I've tried rotating several other joints in the root character but the clothing is still not deforming with the joints. void ApplyClothing(GameObject clothing,Transform root) GameObject g Instantiate(clothing) g.transform.parent root g.transform.localPosition Vector3.zero BoneSyncer(clothing, root) void BoneSyncer(GameObject clothing,Transform root) SkinnedMeshRenderer smrclothing clothing.GetComponentsInChildren lt SkinnedMeshRenderer gt () for(int i 0 i lt smrclothing.Length i ) SkinnedMeshRenderer rootsmrs root.GetComponentsInChildren lt SkinnedMeshRenderer gt () SkinnedMeshRenderer rootsmr null for(int j 0 j lt rootsmrs.Length j ) if (!rootsmrs i .name.ToLower().Contains( quot haircut quot )) rootsmr rootsmrs i if(rootsmr! null) BoneSyncer(smrclothing i , rootsmr) void BoneSyncer(SkinnedMeshRenderer clothingmeshrenderer, SkinnedMeshRenderer targetmeshrenderer) Dictionary lt string, Transform gt boneMap new Dictionary lt string, Transform gt () foreach (Transform bone in targetmeshrenderer.bones) boneMap bone.gameObject.name bone Transform newBones new Transform clothingmeshrenderer.bones.Length for (int i 0 i lt clothingmeshrenderer.bones.Length i) GameObject bone clothingmeshrenderer.bones i .gameObject if (!boneMap.TryGetValue(bone.name, out newBones i )) Debug.Log( quot Unable to map bone quot quot bone.name quot quot to target skeleton. quot ) break clothingmeshrenderer.bones newBones |
0 | Can't Get .enabled to Work for Children Sprites. What Gives? So I have an object with a few children. I want to be able to disable enable 2 of their SpriteRenderers via one of my scripts. I feel like I'm doing things right, but apparently I'm not. And yes, my game objects have the appropriate tags that are being searched for in my code. I'll paste the relevant bits of code below public bool isAiming false Animator playerAnim GameObject arm GameObject weapon SpriteRenderer armRenderer SpriteRenderer weaponRenderer void Start() playerAnim gameObject.GetComponent lt Animator gt () arm GameObject.FindGameObjectWithTag("Arm") weapon GameObject.FindGameObjectWithTag("EquippedWeapon") armRenderer arm.GetComponent lt SpriteRenderer gt () weaponRenderer weapon.GetComponent lt SpriteRenderer gt () void Update() CheckIfAiming() void CheckIfAiming() if (Input.GetButton("Fire2")) Holding right click isAiming true armRenderer.enabled true weaponRenderer.enabled true playerAnim.SetBool("isAiming", isAiming) else isAiming false armRenderer.enabled false weaponRenderer.enabled false playerAnim.SetBool("isAiming", isAiming) What gives? I want to just enable the sprite rendering when I hold down the right mouse click. SetActive(false true) is not an option as I still want code to affect them while they're not visible. Am I just trying to access the SpriteRenderers incorrectly? |
0 | Getting distance between point of an object and another object in Unity First, I'd like to apologize because this is a very basic and repetitive question, but I am completely new to game development. I understand that I can find a distance between two objects using float dist Vector3.Distance(other.position, transform.position) However, how can I find the distance between a point of one object to other object? For instance let's say my object is this sphere Now, how can I return an array that says that there are no objects to the left (null), in the front there is an object at 1, and to the right there is an object at 0.5? Thank you for your patience and understanding |
0 | Unity Editor wont open When attempting to open an old project or create and open a new project unity won't open. The hub will open and when you choose a project it will close and then nothing will happen. Also when a new project it will state the unity version for the new project as unknown. I have tried uninstalling, deleting all the files under the registry editor, and also removing the files from the appdata and reinstalling and it doesn't appear to fix it. Does anyone have any suggestions on how I can fix this? |
0 | Bounce with multiple collisions Here's the problem I'm writing an Arkanoid like game in Unity 5.3. I'm using 3D physics and simply ignoring z axis in computations. No gravity, 0 drag and velocity reset every bounce by script. My ball has sphere collider and rigidbody with continuous dynamic collision detection on it, and bricks have box colliders with continuous detection. They are set like tiles, one by one, without gaps. The problem occurs when a ball collides with two bricks at once, which causes a wrong bounce angle. Smaller sphere colliders makes this situation occur less often, but causes the ball to ignore collisions sometimes and phase through a single brick. I know the probable reason for this bug, I think a collision with two objects affects ball physics twice. The question is how to avoid it? |
0 | Calculating the distance from a line to a point in 2D I have a simple setup How do I calculate the orange distance? It's the distance between the block on the left to the white line in the center (X amp Z axes combined). I don't have the intersection point. My only knowledge of the white line is that it goes through the point (0, 0, 0), running between (10, 0, 10) and ( 10, 0, 10) My problem is that I need to calculate this distance without the depth (Y value). Only on two planes combined X amp Z |
0 | How to update Unity? I have clicked on check for updates but it says I have latest Unity. But latest is 5.6. How to update it to 5.6? |
0 | What will happen with PlayerPrefs data after updating the app? I'm using PlayerPrefs (Unity3D, on Android). If a user updates my application via the Google Play store, what happens to the data I've stored in PlayerPrefs? |
0 | How to best apply colliders on a rough 3D shape I have a 3D model for a level in unity. I want to add colliders to it. What is the best type of collider for this model? And,it is 3D |
0 | Unity how do I edit a second scene when my objects are still in the first? I have my game set up so that objects like the Canvas and the main character are set to DontDestroyOnLoad they're only initiated in the first scene. However, this means that when I load my second scene in the editor, those objects aren't there yet. I could copy and paste them over, but then the objects in the second scene will be duplicates of the ones in the first. This is a problem because I can't, for instance, create a public variable on the character controller and attach an object from the second scene to it. The character doesn't exist in scene 2 yet and the object doesn't exist in scene 1. |
0 | How to have 3d multiple planet gravity in unity c ? Im using unity and I want to make a game where you can walk around small planets and the further away you get, the weaker the gravity, so you can go to other planets. All the tutorials so far only work with one planet, how do I code this? Is there anything I can download that does it for me? |
0 | Disable and re enable image tracking ARKit Is there a way to disable and re enable tracking for images in ARKit? From the older versions, this was the solution. But the newer versions have removed the UnityARSessionNativeInterface script. void Start () m session UnityARSessionNativeInterface.GetARSessionNativeInterface() void AddImageAnchor(ARImageAnchor arImageAnchor) at the bottom of this function StartCoroutine(RemoveAnchorCoroutine(arImageAnchor)) IEnumerator RemoveAnchorCoroutine(ARImageAnchor anchor) yield return new WaitForSeconds(3.0f) doesn't have to be in a coroutine, but for my uses it is m session.RemoveUserAnchor(anchor.identifier) |
0 | Using a object as origin for a Raycast using mouse position as direction Is there any way to cast a ray from an object using the mouse position as the direction for the ray? I ve been looking for a while but I can t find something like that anywhere, so if anyone could help with this it would be great. I m using kind of a top view, you can see how here And what I want to do is set a empty game object on top of the character to act as the origin for the ray, then when I press a key the mouse is unlocked and an area appears, here s how that looks And I want to use the position where the mouse clicks to be the direction of the ray. |
0 | Playing a video in AR using Vuforia and Unity 5 I am trying to play a video in augmented reality using Vuforia and Unity5. I followed a few videos but I am still not able to play it. Can anybody help? I get the "error texture icon" instead of the play icon. |
0 | Will importing more items from unity packages increase the build size? I'm developing a GoogleVR (formerly Google Cardboard) application and need to import the GoogleVR SDK. While I only expect to use some of the items available in the Unity package, I'd like to import them all at once and save potential headaches later when I can't find something I might need. However I'm worried that including everything in the project may affect the build size, which would be troublesome on a mobile application. |
0 | Building an Octree for terrain generation I've previously implemented marching cubes tetrahedra to render an IsoSurface. It worked (YouTube), but the performance was dire as I never got around to implementing variable Level of Detail based on view distance (or even removing old, distant chunks). I decided to have another go and do it properly this time. I've started by creating an OctreeNode that works as follows when Build() is called. If the chunk is too small to build, return immediately. Work out if the surface passes through this chunk's volume. If so, then decide if we want to raise the LOD (because the camera is close) If so, then spawn 8 children and call the same process on them If not, build the mesh using the current node's dimensions Some PseudoCode OctNode Build() if(this.ChunkSize lt minChunkSize) return null densityRange densitySource .GetDensityRange(this.bounds) if(densityRange.min lt surface lt densityRange.max) if(loDProvider.DesiredLod(bounds) gt currentLoD) for(i 1 to 8) if(children i null) children i new OctNode(...) children i children i .Build() else BuildMesh() return this As well as returning density at a point, the density source can determine the possible density range for a given volume. The LoD provider takes a bounding box and returns the max desired LoD based on camera position frustum, user settings, etc... So... This all works fairly well. Using a simple sphere as the Density source, and showing all nodes And just the leaves However, there are a couple of issues I have to define the initial bounding volume (and the larger it is, the more processing I need to do) At the root of the tree, I have no idea how deep the leaves will be, so my LoD numbering starts at lowest quality (root) and increases as chunks get smaller. Because LoD is now relative to initial volume, it's not much use when I want to do things at specific sizes qualities. I've thought of a couple of options but both seem flawed Maintain a collection of Octrees and add remove depending on distance. Can't see how I'd mesh across nicely , plus I'd need a list of known empty nodes, especially if I want arbitrary 3D surfaces (to avoid re calculating empty volumes repeatedly) Add a parent Node to the current root, then add seven siblings for the original node. This would work and be on demand but it seems complex to shrink back down sensibly as the player moves through the landscape. It would also make LoD numbers even less meaningful. In clarification to Q below At present, if 2 physically adjacent nodes in the tree are at different LODs, I have some code to coerce the verts such that there's no seam when the meshes are generated. I'm able to do this by knowing the the density for multiple of surrounding nodes. In a scenario where I have 2 independent octrees side by side, I'd have no easy way to retrieve this information, resulting in seams. What's an optimal way to approach this? |
0 | How to use a .cube LUT file with Color Lookup? I have used quot Image 2 LUT quot to create a LUT for Unity from a certain movie. However, currently quot Image 2 LUT quot only outputs quot .cube quot files. For HDRP, this is great, but for some reason, URP doesn't accept .cube file. URP expects specially laid out .png LUT file. Is there any way to convert a .cube LUT file to a PNG that I can put into the slot of Color Lookup gt Lookup Texture with URP? Unity expect this format The tutorial that Google finds and recommends is this. However, I don't have Photoshop. Also, the tutorial deals with a square LUT that looks like this So even if I had Photoshop and I would follow the tutorial, I would still have a square LUT which is not laid out as Unity would expect it, so I did not use that tutorial. How do I create a LUT png from a .cube file that I can use with URP? Thank you. |
0 | 2 D character not falling to the ground I am very new to Game Development and I am making a game with a simple Ragdoll which has a body, a head, and 2 limbs(hands). The head and the limbs are hinged to the body and I have kept the Ragdoll above a cube to be used as the ground on which the Ragdoll falls. Till now, I haven't added any scripts for movement or anything, I just want my Ragdoll to fall on the cube below it properly. But when I click play, the Ragdoll just starts to float above its original position. When I move it through the editor away from the cube(ground), it does fall down. It's like the cube is opposing the downward acceleration of the Ragdoll. The Ragdoll won't land on the cube. All the bodies have Rigid body and collider scripts. The Ragdoll also doesn't disassemble, it manages to keep itself together. Can someone please tell me what I am doing wrong. I researched about this but I have found no solution. I am using the free version of Unity. |
0 | How can I create an extending chain like the hookshot in Zelda in Unity? In the Zelda games, there is an item called the hookshot. It is a small mechanical apparatus held in one hand that acts similar to, but not the same as the gun. When it is triggered, the hook at the tip of the item springs forward and an extending chain follows behind it. This chain is spawned when the hookshot is triggered and disappears when the hook is retracted. The chain is not visible beforehand, i.e, it is not spooled around any kind of cylinder and unspooled when shot.There are also other games where characters use grappling apparatus that can be made shorter or longer when a character is hanging from a specific point or pivot. Similarly, this grappling tether is created or hidden as needed to support whether the player wants to shorten or lengthen it. My question is, how could one create an extending chain whose links are only visible when triggered and when retracted disappear from view? This chain does not need to necessarily interact with physics. I've thought of a couple of ways someone could create an effect like this, but I would rather see if there is a better known solution or implementation of this or a similiar effect before I dive in. Potential solutions could include A particle effect between the base of the hook and the tip of the gun. This might be far better suited for displaying a non physical, energy tether, but I am not as familiar with the particle system in Unity and I am curious to see if a chain link could be faked with a particle. Creating a chain link by link or section by section procedurally based upon the direction the hook was firing in and the distance between the positions of the gun tip and hook base. This seems like a more direct solution, but could have higher processing cost as the links are created on the fly and in rapid succession. Creating a chain that is hidden when not fired and is made to slowly appear when fired as the hook leaves the hookshot apparatus. This seems like the most likely solution, but I have little to no idea as to how it could be implemented. I would not be surprised at all if there is a better solution that I didn't mention. I look forward to seeing what people suggest. Thank you. |
0 | Unity sprites and layouts I am trying to learn Unity for a simple board game. The question is, is it possible to use grid layout group (or any layout component) with sprites? The goal is to fit a board into my view regardless of the aspect ratio of the device. The following grid should contain 7 by 7 sprites and it should scale up and down (no more then lets say 100 px) and have an aspect ratio of 1. I've tried adding a canvas and a panel that has a grid layout group component but it seems like sprites are not affected when added to the panel. Also it seems like when I try to work with a panel or a canvas they have a fixed sizes in units. Having fix sizes feels a little bit off. Is there a way to use layout components so sprites can have relative distances between them. So far I am stuck and lost in tutorials and feeling like the answer should not be this complicated. Any push to the right direction is welcome. |
0 | Make half of the sprite transparent Guys if I have two sprites placed on the same spot. How can I show the half of each Sprite instead of the one on top? The sprites are basic circles All sprites have basic colors, no textures. |
0 | How to edit key value pairs (like a Dictionary) in Unity's inspector? I have a spell system I am creating, the principle is as follows Each spell is an autonomous prefab. It contains a script with some properties (base damage, duration...) that can be modified in the inspector. I have a Spell enum listing all possible spells in the code, which is used in the game logic When I want to cast a spell, I need to be able to get this spell's prefab to instantiate it and read its informations Each actor (be it players or enemies) needs to have a list of possible animations for the spells The problems with how I am trying to implement are For listing each actor's animations I could use a Dictionary lt Spell, Animation gt , but dictionaries aren't supported by the inspector which makes it hard to easily edit multiple actors type. I need some way to easily access a spell prefab from the corresponding enum. Here too I could use a dictionary but I can only reference to prefabs in the inspector, not in code, meaning I wouldn't be able to fill this dictionary I am looking for a way to easily associate my spells enums to the corresponding prefabs and animations |
0 | Per component Shader Blend in Unity Context I'm writing a 2D mobile game in Unity where the graphics are essentially black lines drawn on a background image plus some lighting. Running full RGB calculations for every step seems like a waste of processing power. What I'd like to do is render everything in grey, alpha and then multiply by the sRGB background image in a separate shader at the end. Actually, ideally, I'd like basically to specify custom components like grey, highlight, additive, alpha , each of which can be ignored in a given pass, and then do a custom operation with those when I apply the background image, like ceil(src (dst.r dst.g)) half4(dst.b). I can figure out how to do that between 2 textures within a shader, but not between texture and screen (a.k.a. src amp dst). Question Basically, is there a way of writing a per component replacement of the built in Blend functions? Because something like Blend SrcAlpha OneMinusSrcAlpha only works with the full float4 or half4 vectors. Or do I need to grab the screen like a texture and handle it within a pass block, and then do Blend Off or Blend One Zero? Or do something with RenderTextures perhaps? My intuition suggests that that would undo some of the efficiency I'd gained in previous steps, though...? |
0 | Unity assets turned binary from text I'm working with unity and git, and for some reason, from some point the assets started being Binary files, meaning that they're not visible as normal YAML files, and I cannot see textual git diff results on them. Has anyone experiences it and knows how to revert to the textual format from the binary format? |
0 | Help with modifying a geometry grass shader to allow removing areas? So I have this geometry grass shader from a roystan tutorial I followed but it applies the grass effect to the entire mesh at once. I need to find a way to only apply grass to set areas much like how the unity painting vegetation tools work. I had an idea of using a quot guiding quot texture that the shader would follow which would only apply grass onto set areas on the texture e.g areas that are green but I'm not sure how to implement it. I would appreciate any advice! |
0 | Unity Get list of gameobjects close to object clicked? I have a stack of balls of 4 colors some touching some not. When you click on one color ball I want to destroy that ball and any other balls of that color that are close. They may not be touching so collision wont work. How do I detect gameobjects close but not touching that are the same color? Say half a radius away from the edge of the ball clicked. Here are the two scripts I'm working with to create and touch the game objects. public class SpawnBalls MonoBehaviour public Rigidbody ball public float waittime 0.5f Use this for initialization void Start () spawn () Update is called once per frame void Update () Instantiate (ball) public void spawn() yield WaitForSeconds(waittime) for (var i 0 i lt 10 i ) Instantiate (ball) Selecting the balls public class Ball MonoBehaviour public Color colors private Color ballpicked Use this for initialization void Start () GetComponent lt Renderer gt ().material.color colors Random.Range (0, 4) Update is called once per frame void Update () void OnMouseDown() if (Input.GetKey("mouse 0")) ballpicked GetComponent lt Renderer gt ().material.color if (ballpicked "Any other balls within a half a ball width") Destroy (gameObject) |
0 | Unity build error "Could not find file...build.asm.js " I made a WebGL game and the first few times it built well, then I continued working on it a bit and when I build it it gives me an error (and does not generate the build files), error FileNotFoundException Could not find file "C Users Public Documents Unity Projects Infinite Side Scroller Temp StagingArea Data Native build.asm.js". Heres the full error message FileNotFoundException Could not find file "C Users Public Documents Unity Projects Infinite Side Scroller Temp StagingArea Data Native build.asm.js". System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean anonymous, FileOptions options) (at Users builduser buildslave mono build mcs class corlib System.IO FileStream.cs 305) System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share) (wrapper remoting invoke with check) System.IO.FileStream .ctor (string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare) System.IO.File.OpenRead (System.String path) (at Users builduser buildslave mono build mcs class corlib System.IO File.cs 363) System.IO.StreamReader..ctor (System.String path, System.Text.Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize) (at Users builduser buildslave mono build mcs class corlib System.IO StreamReader.cs 167) System.IO.StreamReader..ctor (System.String path, System.Text.Encoding encoding) (wrapper remoting invoke with check) System.IO.StreamReader .ctor (string,System.Text.Encoding) System.IO.File.ReadAllText (System.String path, System.Text.Encoding encoding) (at Users builduser buildslave mono build mcs class corlib System.IO File.cs 587) System.IO.File.ReadAllText (System.String path) (at Users builduser buildslave mono build mcs class corlib System.IO File.cs 582) UnityEditor.WebGL.CodeAnalysisUtils.ReplaceDuplicates (System.String builtCodePath, Int32 interations) (at Users builduser buildslave unity build PlatformDependent WebGL Extensions Unity.WebGL.extensions CodeAnalysisUtils.cs 145) UnityEditor.WebGL.WebGlBuildPostprocessor.PostProcess (BuildPostProcessArgs args) (at Users builduser buildslave unity build PlatformDependent WebGL Extensions Unity.WebGL.extensions BuildPostprocessor.cs 589) UnityEditor.PostprocessBuildPlayer.Postprocess (BuildTarget target, System.String installPath, System.String companyName, System.String productName, Int32 width, Int32 height, System.String downloadWebplayerUrl, System.String manualDownloadWebplayerUrl, BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.BuildReporting.BuildReport report) (at C buildslave unity build Editor Mono BuildPipeline PostprocessBuildPlayer.cs 186) UnityEditor.HostView OnGUI() What is the problem? And how can I fix it? Feel free to ask me for more information? Thanks in advance for the help! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.