_id
int64
0
49
text
stringlengths
71
4.19k
0
Why is my game object generated by a custom Unity editor script missing its sprite? I have a number of sprites that I generate outside of Unity. I'd like to automate the process of importing these sprites into Unity as fully configured game objects. I'm trying to do this through a Unity editor script, but I'm having some difficulty. When I run my script, my game object is saved as a .prefab as expected. However, the Sprite I'm assigning to my game object's SpriteRenderer component is missing In my script, I'm assigning my SpriteRenderer's sprite property to a Sprite object that I dynamically create in the script. Here's the relevant excerpt from my editor script GameObject gameObject new GameObject(fileName) SpriteRenderer spriteRenderer gameObject.AddComponent lt SpriteRenderer gt () texture size will be replaced during the LoadImage() call Texture2D texture new Texture2D(1, 1) texture.LoadImage(File.ReadAllBytes(Path.Combine(generatedOutputPath, fileName ".png"))) spriteRenderer.sprite Sprite.Create( texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.0f, 0.0f) ) PrefabUtility.CreatePrefab("Assets Prefabs " fileName ".prefab", gameObject) DestroyImmediate(gameObject) I can verify through logging that the image path to my .png is correct and that the Texture2D and Sprite objects seem to be instantiated correctly. For example, I can do this logs "580" as expected Debug.Log(texture.width) What am I doing wrong? How can I save this game object as a .prefab without losing its sprite information?
0
How do I slice a 3D object at runtime in Unity? I'm specifically looking for some sort of algorithm or way that can "cut" a 3 dimensional mesh with some other game object. How would I implement this?
0
Strange I'm getting exception but the scripts in the exception message are not exist on my pc. What should I do? I'm using unity version 2019.2.5f1 personal I searched on my hard disks the entire pc and none of the scripts in the exception message are exist. And the exception is happens only sometimes. When I stop the game in the editor by pressing the play button the exception is show sometimes and sometimes not. I tried to close and open over agai the unity editor and the project. Still strange. MissingReferenceException The object of type 'ReflectionProbe' 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. UnityEditor.ReflectionProbeEditor.OnPreSceneGUICallback (UnityEditor.SceneView sceneView) (at C buildslave unity build Editor Mono Inspector ReflectionProbeEditor.cs 651) UnityEditor.SceneView.CallOnPreSceneGUI () (at C buildslave unity build Editor Mono SceneView SceneView.cs 3359) UnityEditor.SceneView.DoOnPreSceneGUICallbacks (UnityEngine.Rect cameraRect) (at C buildslave unity build Editor Mono SceneView SceneView.cs 1935) UnityEditor.SceneView.OnGUI () (at C buildslave unity build Editor Mono SceneView SceneView.cs 2320) System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object parameters, System.Globalization.CultureInfo culture) (at lt 599589bf4ce248909b8a14cbe4a2034e 0) Rethrow as TargetInvocationException Exception has been thrown by the target of an invocation. UnityEngine.UIElements.UIR.RenderChain.Render (UnityEngine.Rect topRect, UnityEngine.Matrix4x4 projection) (at C buildslave unity build Modules UIElements Renderer UIRChainBuilder.cs 238) UnityEngine.UIElements.UIRRepaintUpdater.DrawChain (UnityEngine.Rect topRect, UnityEngine.Matrix4x4 projection) (at C buildslave unity build Modules UIElements Renderer UIRRepaintUpdater.cs 66) UnityEngine.UIElements.UIRRepaintUpdater.Update () (at C buildslave unity build Modules UIElements Renderer UIRRepaintUpdater.cs 54) UnityEngine.UIElements.VisualTreeUpdater.UpdateVisualTree () (at C buildslave unity build Modules UIElements VisualTreeUpdater.cs 72) UnityEngine.UIElements.Panel.Repaint (UnityEngine.Event e) (at C buildslave unity build Modules UIElements Panel.cs 637) UnityEngine.UIElements.UIElementsUtility.DoDispatch (UnityEngine.UIElements.BaseVisualElementPanel panel) (at C buildslave unity build Modules UIElements UIElementsUtility.cs 240) UnityEngine.UIElements.UIElementsUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr) (at C buildslave unity build Modules UIElements UIElementsUtility.cs 78) UnityEngine.GUIUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr) (at C buildslave unity build Modules IMGUI GUIUtility.cs 179)
0
How to make UI text longer? I'm working on a menu that needs a wordy description, but I've noticed that it only shows 4 letters, then cuts off and this doesn't seem right. I right click, select UI text and again, it only displays 4 words, even though I can write a lot more there. Am I doing something wrong here? I'm not sure how to get past this and I want to ask if anyone knows how to get past this? It seems like such a strange limit to put on the UI canvas.
0
ReorderableList in Unity with Enums I'm trying to setup a simple ReorderableList in Unity 2017.3 for a list of enums. Adding items workes fine but selecting, dragging and deleting items from the list does not (see gif). Here is my code Serializable public enum RoofType HIP, GABLE, FLAT, NONE UnityEditorInternal.ReorderableList roofTypeList new UnityEditorInternal.ReorderableList(roofTypes, typeof(RoofType), true, true, true, true) roofTypeList.drawHeaderCallback (Rect rect) gt EditorGUI.LabelField(rect, "Roof types") roofTypeList.drawElementCallback (Rect rect, int index, bool isActive, bool isFocused) gt roofTypes index (RoofType)EditorGUI.EnumPopup(rect, roofTypes index ) roofTypeList.DoLayoutList() Any ideas why this does not work? My guess it is because I use enums and not classes but it is not documented anywhere.
0
Rushing water in Unity How would I go about creating a river with rushing water? I can do the texture around it but I'm stuck on the actual water part. This is in Unity3D.
0
Are constantly growing (in dimensional size) GameObjects a problem? It's possible the following is fundamental to Unity, and not a problem? I am using an example of a WheelJoint2D Car from the Ray Wenderlich tutorials. Note from the pic below, the top level game object called "Car". It has children of "Body" which contains the wheel joints and the wheels (attached to the wheel joints). The top level "Car" GameObject is placed in the scene (here at X 6.4). Now we run the game for a short time, and the car rolls forward as expected. From the inspector, we would see that X position of the Body and the wheels has changed, but note that the Car game object's X position has not changed So, in reality the game object "Car" has grown in the X dimension. Granted this growth seemingly has nothing to do with physics simulation (as all the rigidbodies and joints are moving along as expected). One interesting side affect is that this growth might make scaling the parent object problematic. But it seems that if this were an infinite runner, you would have an ever increasingly wide "Car" object. On the surface this seems undesirable, but is it really? And if so, how would you mitigate this (given that this game object hierarchy seems to be the prescribed way of using the wheel joints).
0
What does vertex disp and tessellate tessEdge mean? Shader Unity I came across the following declaration on unity tutorial pragma surface surf BlinnPhong addshadow fullforwardshadows vertex disp tessellate tessEdge nolightmap I think disp is the displacement shader but what does vertex disp mean? Likewise for tesselate tessEdge. from https docs.unity3d.com Manual SL SurfaceShaderTessellation.html Thanks. I am rather new to HLSL.
0
Recursive Unity Coroutine I have a co routine which is heavily reliant on calling itself to get the task done. I have tested it and the code works fine, the problem is that the co routine will return every time that it enters itself recursively. IEnumerator test(arg1, arg2) I want to pause here yield return null I don't want to pause on any of these yield return test(arg1, arg2) yield return test(arg1, arg2) yield return test(arg1, arg2) yield return test(arg1, arg2) In the example above I have a yield return at the top that is hit and pauses the co routine, thats fine. Then there are the calls to itself below which also pause the co routine. How do I avoid pausing the co routine on the recurcive calls?
0
Trouble with LineRenderer with orthographic camera in Unity When a weapon is fired, I want to draw a line for the bullet's trajectory. I am using a LineRenderer to draw the trajectory with the code below void FixedUpdate () timer Time.deltaTime if (Input.GetButton ("Fire1") amp amp timer gt timeBetweenBullets amp amp Time.timeScale ! 0) Shoot () if (timer gt timeBetweenBullets effectsDisplayTime) DisableEffects () void DisableEffects () gunLine.enabled false void Shoot () timer 0f Set first point gunLine.SetPosition (0, transform.position) shootRay.origin transform.position shootRay.direction transform.forward gunLine.SetPosition (1, shootRay.origin shootRay.direction range) I am using an orthographic camera in the scene. The line will show up but at certain rotations the line will partially render or be completely hidden. Oddly, the line will always render in the scene view the problem only exists in the game view. Has anyone had this issue?
0
Unity Part of the sprite is covered in shadow I have a sprite with Transparent Cutout Diffuse shader. Recieving shadows is turned on in SpriteRenderer. The light is a pointlight and I am using deffered rendering path. However when I am above or right of the object, it is covered in shadow. When I am below or left of the object everything seem to work as it should.If I place the light in the center of the sprite, only a part of the sprite is lit up, the other part is covered in shadow. Maybe it is something with normals? I need to get rid of the self shading effect. Shader Shader "Transparent Cutout Diffuse" Properties Color ("Main Color", Color) (1,1,1,1) MainTex ("Base (RGB) Trans (A)", 2D) "white" Cutoff ("Alpha cutoff", Range(0,1)) 0.5 SubShader Tags "Queue" "AlphaTest" "IgnoreProjector" "True" "RenderType" "TransparentCutout" LOD 200 CGPROGRAM pragma surface surf Lambert alphatest Cutoff sampler2D MainTex fixed4 Color struct Input float2 uv MainTex void surf (Input IN, inout SurfaceOutput o) fixed4 c tex2D( MainTex, IN.uv MainTex) Color o.Albedo c.rgb o.Alpha c.a ENDCG Fallback "Transparent Cutout VertexLit" I found out what unity uses for lambert lightning. Since I use deffered rendering so unity should use function with PrePass prefix. But the implementation of the actual lighning is implemented somewhere else and is it used for all materials, that looks like dead end. Custom Lightning inline fixed4 LightingSLambert (SurfaceOutput s, fixed3 lightDir, fixed atten) fixed diff max (0, dot (s.Normal, lightDir)) fixed4 c c.rgb s.Albedo LightColor0.rgb (diff atten 2) c.a s.Alpha return c inline fixed4 LightingSLambert PrePass (SurfaceOutput s, half4 light) fixed4 c c.rgb s.Albedo light.rgb c.a s.Alpha return c inline half4 LightingSLambert DirLightmap (SurfaceOutput s, fixed4 color, fixed4 scale, bool surfFuncWritesNormal) UNITY DIRBASIS half3 scalePerBasisVector half3 lm DirLightmapDiffuse (unity DirBasis, color, scale, s.Normal, surfFuncWritesNormal, scalePerBasisVector) return half4(lm, 0)
0
Player not detecting layermask I'm trying to implement a simple collision detection for my player but it is not detecting the layer mask as my Player comes into contact with it. I have a move point that moves slightly ahead of the player, and if it comes in contact with the StopMovement layermask then it should NOT move any further. Unfortunately, the layer is never detected and therefore the player just moves right through the object. Script using System using System.Collections using System.Collections.Generic using UnityEngine public class PlayerController MonoBehaviour public float moveSpeed 5f private float moveHorizontal private float moveVertical public Transform movePoint public LayerMask whatStopsMovement Start is called before the first frame update void Start() movePoint.parent null Update is called once per frame void Update() moveHorizontal Input.GetAxisRaw( quot Horizontal quot ) moveVertical Input.GetAxisRaw( quot Vertical quot ) private void FixedUpdate() transform.position Vector3.MoveTowards(transform.position, movePoint.position, moveSpeed Time.fixedDeltaTime) stops the movePoint from going too far if (Vector3.Distance(transform.position, movePoint.position) 0f) if (Mathf.Abs(moveHorizontal) 1f) makes it so we can check if 1f OR 1f without 1f 1f if (!Physics2D.OverlapCircle(movePoint.position new Vector3(moveHorizontal, 0f, 0f), 0.2f, whatStopsMovement)) Debug.Log( quot No collision quot ) movePoint.position new Vector3(moveHorizontal, 0f) else Debug.Log( quot Collision quot ) else if (Mathf.Abs(moveVertical) 1f) makes it so we can check if 1f OR 1f without 1f 1f if (!Physics2D.OverlapCircle(movePoint.position new Vector3(moveVertical, 0f, 0f), 0.4f, whatStopsMovement)) Debug.Log( quot No collision quot ) movePoint.position new Vector3(0f, moveVertical) else Debug.Log( quot Collision quot ) Any help at all is appreciated.
0
Unsticking game objects I have used void OnCollisionEnter(Collision collision) collision.gameObject.transform.parent gameObject.transform To stick two players together when they connect. Basically after they have collided the second game object is still stuck to the original object and i need that not to be the case. How do i make the game object not stuck when they come apart ?
0
Player losing alignment with tilemap after moving I'm using an isometric tilemap(2 1) and I can't figure out how to make grid based movement on it's surface. I managed to get a code working for the grid based movement, moving my character with 0.5 along the Y axis and 0.86 ( sqrt(3) 2 ) along the X axis since I imagine it should work as if they are diamonds with the side of 1 unit, but it doesn't align with the center of the next tile. Here is my movement code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Assertions.Must public class Movement MonoBehaviour Vector3 pos For movement float speed 5f Speed of movement public float x 0.86f public float y 0.5f void Start() pos transform.position Take the initial position void FixedUpdate() if (Input.GetKey(KeyCode.A) amp amp transform.position pos) Left pos Vector3.left pos new Vector3( 0.86f, 0.5f, 0) if (Input.GetKey(KeyCode.D) amp amp transform.position pos) Right pos Vector3.right pos new Vector3(0.86f, 0.5f, 0) miscare in diagonala if (Input.GetKey(KeyCode.W) amp amp transform.position pos) Up pos Vector3.up pos new Vector3(0.86f, 0.5f, 0) if (Input.GetKey(KeyCode.S) amp amp transform.position pos) Down pos Vector3.down pos new Vector3( 0.86f, 0.5f, 0) transform.position Vector3.MoveTowards(transform.position, pos, Time.fixedDeltaTime speed) Move there
0
Animation position leftover I am fairly new to unity and I have encountered this same problem previously. I have a gun with hands and I created an animation that simulates shot movements with properties transform.position and transform.rotation. Root motion is applied and motion curves are generated for the animation.The default state animation for that object has no properties assigned to it and as much as I understand from the animation controller window, the shot animation is completed before the transition to the default state is made. The problem is that on every 3 shots 0.001 is added to the X rotation Y and Z positions are losing some small values. I tried to prolong the animations exit time but the result is the same. I checked the key values and the motion curves, the first and last ones are the same. Why is this happening and how can I fix it ?
0
Additive Scene Loading Buttons not Becoming 'Active' I'm quite new to Unity but I'm making a game, and have created a simple Pause menu, when a key is pressed (escape), I just load a Pause scene, additively, and set that Pause scene to the active scene, however, only the buttons on the previous 'game' scene are interactive. The mouseEnter, exit etc aren't triggering on the pause menu buttons, despite the pause menu being overlayed on top of the 'game' scene the Pause scene being the active one and the 'game' scene buttons are still the interactive ones (i.e. register clicks, mouse overs etc). Obviously when I open the pause menu, I want the pause menu buttons to be the interactive ones (registering clicks, mouse over etc), not the previous 'game' scene buttons. The pause menu scene interacts perfectly when loaded additively with a scene that had no buttons. Many thanks.
0
Use a different target framework version in a unity c project, other than 4.6 I'm using a dll in my project which is built against a higher target framework (4.6.1 actually) I can't build or attach to Unity because of this. Visual Studio shows this error The primary reference "MQTTnet" could not be resolved because it was built against the ".NETFramework,Version v4.6.1" framework. This is a higher version than the currently targeted framework ".NETFramework,Version v4.6". The only option in player settings in Unity for API compatibility level is .NET 4.6 how can I change that to 4.6.1 in order to be able to build or attach to Unity?
0
Unity Create a custom editor for Vector2 I'm starting to dig into Unity's editor customization. What I'm looking for is a way to create custom line (or a point at least) which I could move around in SceneView and set a Vector2 value that way. I might create a child GameObject and then calculate the relative distance, but I'd like to know, if there is any way using the Editor instead of adding other useless GameObjects. Thanks in advance.
0
How to check if NPCs are on ground or not? I'm using Unity Engine. I see the common way to check if player is on ground is shooting a Raycast How to solve the ground check problem? How to check if grounded with rigidbody I have a simple scene with Unity's terrain for ground (Game Object 3D Object Terrain). Imagine you have a lot of NPCs (like GTA), is it possible to check a character on ground without Raycast? Do you have to run loop to ray cast check each NPC?
0
Maintaining facing direction at the end of a movement I want to make my 2D top down walking animation stop and revert to the idle animation while continuing to face in the same direction as the previous movement. For example, when I go up then stop, my character should continue to look up. If I go down, it should continue to look down. I use lastmoveX and lastmoveY floats for idle and for walking I use moveX and moveY floats. moveX and moveY change when I move with the joystick, but lastmoveX and lastmoveY do not change, and I don't know how to fix this. Here is my code using System.Collections using System.Collections.Generic using UnityEngine public class PlayerController MonoBehaviour private Rigidbody2D myRB private Animator myAnim public Joystick joystick public MoveByTouch controller SerializeField private float speed Use this for initialization void Start () myRB GetComponent lt Rigidbody2D gt () myAnim GetComponent lt Animator gt () Update is called once per frame void Update () myRB.velocity new Vector2(joystick.Horizontal, joystick.Vertical) speed Time.deltaTime myAnim.SetFloat( quot moveX quot , myRB.velocity.x) myAnim.SetFloat( quot moveY quot , myRB.velocity.y) if(joystick.Horizontal 1 joystick.Horizontal 1 joystick.Vertical 1 joystick.Vertical 1) myAnim.SetFloat( quot lastMoveX quot , joystick.Horizontal) myAnim.SetFloat( quot lastMoveY quot , joystick.Vertical)
0
Will my huge sprites for a 2d game create performance issues? I'm new to Unity, and have been confused about this issue for a while. Some people say that for 2D games you don't need to worry about performance (I'm making the game for PC, not mobile) while others report bad performance with larger sized sprites I have a long scene with some large background sprites, measuring about 14552x3308 (weird resolution I know, would that also cause issues?) All methods of scaling it down and resizing in Unity lead to jagged edges (these are basically hills so I need them to be significantly bigger than the player character) I always keep the image size in the inspector similar to the resolution of the actual file, and set the filter mode to Point, so the jagged edges are not due to that, but only because of me scaling up a smaller file size to fit the scene. If I use the original sprites of 14552x3308, it's perfectly smooth (image size set to 8192 in inspector) but each file takes about 120mb in the profiler. All combined, my assets are showing a usage of 1.25 GB for this scene. How bad is this? Should I be trying to keep it under 1GB? I don't really know what the best practices are in this situation, so I don't know what to aim for. I'd ideally like to keep the sprites at this large size so that I don't have to redraw anything.
0
Material colours in unity not displaying correctly? Even though I've picked blue the color is displayed as something pinkish. All colors are like this
0
Unity3D Making heavy calculation on separate thread So, I've created a program with Kinect as its input. As you know, Kinect will send the data 30 frame per second. I have a model that will mimic Kinect's input motion, so on Update() I read the motion from Kinect. The problem is, on Update(), I've done a heavy computational algorithm. It makes the system lag and freezing. I've tried to do the calculation every 60 frames instead of each frame, but the system still got lag. void Update() ... GET DATA FROM KINECT frame new SkeletonRecorded() frame.root.rotation skeletons kinect2SensorID, playerID .root.rotation ... frame.rightShoulder.position skeletons kinect2SensorID, playerID .rightShoulder.position frames.Add(frame) if (frames.Count gt 60) CALLING THE CALCULATION METHOD (Here is the heavy part begin) comparatorClass.GetSkeletonData(frames) frames.Clear() The above code is just small parts of the Update() method (I cut it short for convenience). So, how should I call the GetSkeletonData() method without making the interface lag?
0
I try to recreate a plasma gun from halo into my fps game this is my code public class WeaponTest MonoBehaviour public float weaponHeat public float weaponOverHeat 100f public bool weaponIsOverHeat Start is called before the first frame update void Start() weaponHeat at the start was 0 weaponHeat 0 Update is called once per frame void Update() if (Input.GetButton( quot Fire1 quot ) amp amp !weaponIsOverHeat) if (weaponHeat lt weaponOverHeat) Weapon Shoot() weaponHeat IsHeating() float IsHeating() weaponHeat Random.Range(5f, 10f) return weaponHeat void Weapon Shoot() RaycastHit hit if (Physics.Raycast(playerCam.transform.position, playerCam.transform.forward, out hit, range)) code for damaging the enemy the shoot method was function exactly like what is want but I need the cooldown method I already try a few them but it not work exactly like I want. the I idea was went the left mouse was click the weapon heat will increase and when the left mouse was not been click the weapon heat will decrease until it reach 0. I hope you can help me solve this problem
0
How do you "branch" a Unity project How do you branch a unity project? Suppose you have Game Project A, and say there is variant A' that requires a large convoluted plugin. But the idea is also that you want to keep developing this without the plugin getting in the way, for the other variants say A and A'' that don't require it.
0
Why is my sphere jumping? I got a sphere that moves with an angular velocity of 2000 in the X axis, I need that sphere moves on 130 platforms, all those platforms have 0.0182175 in the Y axis. The problem is that when I play, the sphere starts normally but as it advances starts make some jumps, first shorts but then more large, and it is as if the platforms did not have the same value in the Y axis. Can someone help me, please? I've put some images. Very thanks Hey people!! I've uploaded a video to show you clearly the problem. Here's the link Platforms, sphere and sphere script Sorry for my english by the way.
0
How to update UI after changing text in a view After applying a text change to a scrolling view, how do you get the new height of the text, resize other UI elements around the changed text length, etc? Many have posted this question. Some have noted that the rect size doesn't change or that they have to wait multiple frames to then react to the UI updates.
0
How do I tell if an object is currently colliding with another object? I can't figure out how to tell if a GameObject is currently colliding with another in Unity. I've looked online and can't find any tutorials or answers that work. Also, what's the difference between a Collision and a Collider w.r.t. Unity? My dilemma I have a third person controller set up and want it to wall jump. I already have an isGrounded function, I just need to test if I'm hitting anything other than the floor. Otherwise I want it to wall jump backwards. I've already tried if (this.OnCollisionEnter) ... if (Collider.OnCollisionEnter) ... But it did not work. I now tried function OnCollisionStay() Debug.Log("Collision") I checked my logs, console and still can't find anything.
0
How should I reload a ball? I am making an angry bird type 2d game using Unity and C . After I throw the ball from catapult, I have no idea on reloading the ball. Then I use SceneAsync to reload the ball but it is the worst thing I've ever made since I can't make the other sprite objects to continue their movents after the ball is thrown. So what code should I use to reload the balls after throwing?
0
How do C and UnityScript differ in Unity development? Other than the obvious language differences, how do UnityScript and C differ when developing games in Unity3D? Is there a noticable performance difference? Is the UnityScript code packaged as is? If yes, does this help the game's moddability? Is it possible to use libraries developed for one language while developing in the other one? Can the two languages be mixed in the same Unity project coding some parts in C and others in UnityScript?
0
Using enums for detecting object collisions As far as I know, I can detect what objects the player is colliding with is by the following code private void OnCollisionEnter2D(Collision2D collision) if(collision.collider.name.Equals("")) But I have heard that I can use enums instead to reduce computations. Could anyone explain to me using examples?
0
UI looks different between editor and in game I am very confused about Unity's UI system. This is how my inventory menu looks in the Editor And this is the view in game Settings Can someone please explain why this happens?
0
Can Cloud Functions be used for a multiplayer game server? I'm building a turn based online multiplayer game with Unity for both desktop and mobile. Traditionally, I would build a Java socket server, host it in Google Compute Engine or similar, and have players connect to it. Since this works with sockets I can easily notify players of relevant events, such as matchmaking, chat, enemy turn, etc. I've been curious about Serverless Functions for a while, such as Google Cloud or Amazon Lambda. However, at first glance it doesn't seem to me like that would work for my game because there ins't a constant connection (with sockets), I can't notify players of relevant events in realtime or can I? For mobile I realize I could probably use something akin to push notifications (so the serverless code may push messages to the relevant player's phone). But that doesn't seem as simple for desktop games. Well, what if the players poll for messages? Like every second, call a Cloud function and ask them if there's anything for them. I'd image that would work, but that seems rather overkill with as little as a couple thousand players, calling the same function every second for prolonged times (the game's matches are long) sounds like it would easily increase expenses. Is there something I am missing? A coding practice that would make serverless code feasible for a cross platform online multiplayer game? I want to make it work, but it would seem like a socket server is still my only option.
0
Choosing random array indexes in Unity C I want to change a string by randomly choosing an index in an array, using the random.range command in unity. Bare in mind that I'm using strings here, not floats or integers. Here is a code example(not the real thing. I'm just coming up with this by example, but it still has the same meaning. I may make a few typo errors as a result) public string ChangingString ("") public string ExampleArray new string 2 void Start () ExampleArray 0 ("String1") ExampleArray 1 ("String2") void OnGUI () if(GUI.Button(new Rect(10,10,100,24), "Randomize text")) ChangingString (code to choose random string using the ExampleArray) GUI.Label(new Rect(10,30,100,20), ChangingString) EXTRA NOTE I'M NEW TO USING ARRAYS.
0
Force Reload VS soution Explorer when adding new c Script via Unity3d? When I create C script (Create gt C Script) via Unity3d or delete it from Unity3d Visual Studio shows me the warning window. it's annoying. Is there any way to force "ReloadAll" in solution Explorer without the window?
0
How to make dynamic DOF from mouse position in Unity 5? I found a video a while ago for how to make a dynamic DOF in unity. It fires rays from the camera and positions an empty at the location that the ray first hit. How can I change this so that it doesn't fire rays from my camera but rather from my mouse position, and then positions the empty from there? Code public Transform origin Raycast origin public GameObject target public CameraMovement cameraMovement void Start () void Update () Ray ray new Ray(origin.transform.position, origin.transform.forward) RaycastHit hit new RaycastHit() if(Physics.Raycast(ray, out hit, Mathf.Infinity)) Debug.DrawRay(Input.mousePosition, origin.transform.forward, Color.cyan) target.transform.position hit.point else Debug.DrawRay(Input.mousePosition, origin.transform.forward, Color.red)
0
Multi Screen Rendering in Unity My experience with Unity in not that in depth. But I am wondering if it possible in unity to split what is being rendered across multiple screens. It's hard to explain, so here is an image So while the middle screen is fine to render, I want to spread the image all around the player. That is both to the side and, the bottom and top of the player. Is such a thing possible? Has anyone ever done something similar?
0
Efficient way to load chunks of a 2d level to prevent game from loading stutters I am building a 2D sidescroller game in Unity3D. It's tile based. To get better performance I divided the level into chunks. I activate these chunks when the player enters 2D Triggers and deactivate it again when he exits the 2d trigger. So I normally only have a max of 2 chunks loaded. This works good BUT I do have some loading stutters of a few frames when I load a new chunk. How can I prevent that from happening? Thank you!
0
How to serialize animation state? In Unity, I have an Animator on a character. Upon saving loading the game, I want to preserve the pose and animation state the character is in. However, I can see no way to read write all the data from the Animator Animation Controller in such a way that I can store it in and retrieve it from a binary file. Is there a non obvious way to achieve this?
0
Invoking a common method after a button press I want to implement a common method that handles several numeric values and performs and action based on those values. So I have buttons with specific methods to change this values without affecting the rest. However I want to link them all to a final method that runs right after the press of a button, so this way the game will change only when the player chooses to change it and changes according to the players decisions. How can I implement this in my script? Most of my methods are like this public void "ButtonIDGoesHere" (int "SpecificVariable") Add, Sub, Multiply, etc. What can I add so that it goes to a common method right after it executes its instructions?
0
How to get plane geometry associated with primitive 3d plane in unity3d I assume there should be a plane (struct) associated with a primitive 3d plane in unity3d, how to get that? Or if not associated, can we build plane struct object somehow using corner vertices of 3d plane. Can somebody help me how to get cornor vertices of 3d plane mesh. Update What I am trying to achieve is to use Plane.Raycast on a 3d Plane, but I am not certain whether there is any plane geometry component associated with it, or Is there any way to build a plane geometry which should be going through all the corners of the 3d plane, so that I'll be able to use Plane.Raycast from the normal direction of 3d plane towards itself.
0
Get world position of touch on objects In my Unity3d game, I want to get the world position that was touched, when I touch a specific object, regardless of all objects that are in front of it. How would I do that, I only know Camera.ScreenPointToRay(...), but for some reason that does not work properly? OK one cannot answer the question with the information I provided. In order to determin the point, where the Ray hit the object, I used RaycastHit.transform.position (which refers to the Transform object that was hit) as opposed to RaycastHit.point (which refers to the Vector3 in world space, where the RaycastHit happened).
0
SteamWorks.Net for unity and inviting a friend to a multiplayer game I'm trying to send an invitation to a steam friend and have it that when he accepts I create a PUN 2 room for both players and they can start their match. So far I've done this protected Steamworks.Callback lt GameRichPresenceJoinRequested t gt m GameRichPresenceJoinRequested private void OnEnable() m GameRichPresenceJoinRequested Callback lt GameRichPresenceJoinRequested t gt .Create(OnGameRichPresenceJoinRequested) public void InviteFriend() SteamFriends.InviteUserToGame(steamFriendData.friendSteamId, "") private void OnGameRichPresenceJoinRequested(GameRichPresenceJoinRequested t pCallback) Debug.Log(pCallback.m rgchConnect) Debug.Log(" lt color green gt Friend accepted the invite lt color gt ") The invite is being sent to the correct friend and when he accepts it launches the game but I get no callback from that and thus have no way to place them in a room. What am I doing wrong ?
0
How to stop camera from rotating in 2.5d platformer I'm stuck with a problem I can not make my camera stop rotating after character. What I already have tried using empty game object with rigid body and locked rotation and make it parent of camera, while player being the parent of object. Also, I've tried using few scripts from web, that did not help. Right now I'm bad with using JS in Unity (can handle JS on website, but I dont know how to integrate it for now) and practicing the basics, making easy 2.5d platformer with basic features, so I can not write code for now.
0
Unity2D force of an impact I don't know how to name what I am searching for... Force, Impact? It's easier to explain with an image for me. We have two GameObjects with colliders, A and B. They can move in any direction (top down game with 360 movement possibilities). First case (left) A go to the right at a speed of 2, B to the left at a speed of 1 and they collide. How to calculate that A take 1 damage (from the speed of B in its direction) and B take 2. Second case A go to the right at speed of 2 and B to the right at speed of 1. A take 0 damage and B take 1. I am using Collision2D which doesn't have "impulse" property. I have no idea how to calculate thing like this manually.
0
What is Unity Quaternion range? I've read somewhere that a Quaternion in Unity ranges between 1,1 values. I mean the individual XYZW values. Ex new Quaternion(.1f,.2f, .3f, .4f) Is this true? More clearly I know they take float values therefore the theoretical limit is floating point value limitations, I'm asking the real rotation results. For instance when I look up Quaternion values while rotating a GameObject it is usually in the 1,1 limits. But I'm not sure if that's my case or not.
0
How can I stop this fixed update from executing so I want this FixedUpdate() Method to stop executing when the Method OnMouseDown() is executed. A bool doesn't work a if() statement also doesn't work Please use my whole code Please help ) Thanks, private void FixedUpdate() int random Random.Range(1, 4) if (random 1) m SpriteRenderer GetComponent lt SpriteRenderer gt () m SpriteRenderer.color Color.green if (random 2) m SpriteRenderer GetComponent lt SpriteRenderer gt () m SpriteRenderer.color Color.blue if (random 3) m SpriteRenderer GetComponent lt SpriteRenderer gt () m SpriteRenderer.color Color.yellow private void OnMouseDown() shouldexecute false
0
Still i can't make the cross hair to be in the middle of the screen, What am i missing? In the editor i did GameObject UI Image On the Canvas i changed the Render Mode to Screen Space Camera. It created a Canvas and a child Image in the Hierarchy. Then i changed the Image source to UISprite changed the color to red also added to it a material in red. I can't changed the Canvas anchors not sure why. The Image rect transform anchors is set to the center. I don't have a Main Camera the only camera i have is on the FirstPersonController (The FirstPersonController is a child of a FPSController). But still the red dot circle is a bit to the left not in center. Screenshot of the Canvas And two screenshots of the Image And
0
Allocator error in Unity Suddenly, a wierd error started to come up in my console saying More than 2048 allocators are registered. Reduce the allocator count. This error leads to freezing of editor.
0
Subsurface Scattering Transmittance I have a question related to SSS and especially transmittance. I've looked at several papers about that topic, most of them from Jorge Jimenez, which are very interesting and, I admit, a bit hard for me. Here is one of the papers http www.iryoku.com translucency I have some difficulties to understand the way it works and the way it calculates the distance the light traveled through the object. I think that I understand the very big lines but I am also a bit confused as I am trying to integrate this into the Unity engine and I have some difficulties to match Unity engine available values such as the shadows maps, the shadows coords, etc... to make them fit the way they are used in the paper. So here it is, I am a bit lost in the "in between" and I hope that somebody might be able to help me. Thanks a lot. EDIT added the shader code from referenced paper float distance(float3 posW, float3 normalW, int i) Shrink the position to avoid artifacts on the silhouette posW posW 0.005 normalW Transform to light space float4 posL mul(float4(posW, 1.0), lights i .viewproj) Fetch depth from the shadow map (Depth from shadow maps is expected to be linear) float d1 shwmaps i .Sample(sampler, posL.xy posL.w) float d2 posL.z Calculate the difference return abs(d1 d2) This function can be precomputed for efficiency float3 T(float s) return float3(0.233, 0.455, 0.649) exp( s s 0.0064) float3(0.1, 0.336, 0.344) exp( s s 0.0484) float3(0.118, 0.198, 0.0) exp( s s 0.187) float3(0.113, 0.007, 0.007) exp( s s 0.567) float3(0.358, 0.004, 0.0) exp( s s 1.99) float3(0.078, 0.0, 0.0) exp( s s 7.41) The following is done for each light 'i'. Calculate the distance traveled by the light inside of the object ('strength' modulates the strength of the effect 'normalW' is the vertex normal) float s distance(posW, normalW, i) strength Estimate the irradiance on the back ('lightW' is the regular light vector) float irradiance max(0.3 dot( normalW, lightW), 0.0) Calculate transmitted light ('attenuation' and 'spot' are the usual spot light factors, as in regular reflected light) float3 transmittance T(s) lights i .color attenuation spot albedo.rgb irradiance Add the contribution of this light color transmittance reflectance
0
Changing AnimationOverrideController "sometimes" fails Unity 5.2.1 I have the following code, in a menu where you can chose the armor and weapon of a character private List lt string gt armors new List lt string gt "armor1", "armor2", "armor2" private List lt string gt weapons new List lt string gt "weapon1", "weapon2", "weapon3", "weapon4", "weapon5", "weapon6", "weapon7", "weapon8", "weapon9" private int armor index 0 private int weapon index 0 public GameObject avatar body public GameObject avatar weapon void Update() if (Input.GetKeyDown(KeyCode.RightArrow)) nextArmor() else if (Input.GetKeyDown(KeyCode.LeftArrow)) previousArmor() else if (Input.GetKeyDown(KeyCode.DownArrow)) nextWeapon() else if (Input.GetKeyDown(KeyCode.UpArrow)) previousWeapon() else if (Input.GetKeyDown(KeyCode.Return)) loadLevel() void nextArmor() if (armor index lt armors.Count 1) armor index 1 else armor index 0 setArmor() setWeapon() void previousArmor() if (armor index gt 0) armor index 1 else armor index armors.Count 1 setArmor() setWeapon() void nextWeapon() if (weapon index lt weapons.Count 1) weapon index 1 else weapon index 0 setWeapon() void previousWeapon() if (weapon index gt 0) weapon index 1 else weapon index weapons.Count 1 setWeapon() void setArmor() avatar body.GetComponent lt Animator gt ().runtimeAnimatorController Resources.Load("AnimationControllers player " armors armor index " body" ) as AnimatorOverrideController void setWeapon() avatar weapon.GetComponent lt Animator gt ().runtimeAnimatorController Resources.Load("AnimationControllers player " armors armor index " " weapons weapon index ) as AnimatorOverrideController The problem is when I start switching between the weapons, sometimes the sprite showing does not update. Inspecting the GameObject, it is weird, because the Animator Component has successfully updated, but the Sprite Renderer still shows a fixed sprite from the last Animator. Here are 2 examples Here we see that the animator is set for the weapon Gladius, and that the Sprite renderer is looping through all the frames of that animation Here we can see that even though we have moved to the Flanged mace animator, the Sprite Renderer is still stuck on a sprite of Gladius The problem is hard to recreate, because it happens just SOMETIMES. If I were to switch back to gladius and then once again back to flanged mace... Now it works... but I didn't change anything. What is going wrong??
0
How to add the sound effect of a ball rolling, based on his velocity? I have a ball which roll (like all ball does ) ) ... My ball can roll on different type of surfaces (2 or 3) and at different velocity. I don't know how to approach to reproduce in my game the sound effect. I can assume to do Get an Sfx of a rolling ball Run in loop if my ball is moving then ? Well.. i need some help. Thanks
0
How do I know when the app is launched, loses focus and gets focus again on mobile? I searched in Unity Documentation but there are no information. I'd like to know which methods is called and what it returns in the following scenarios on Android App initially starts App goes in the background App is brought forward after being in the background As for IOs I know that the scenarios should be the following App initially starts OnApplicationFocus(true) is called App goes in the background OnApplicationFocus(false) is called OnApplicationPause(true) is called App is brought forward after being in the background OnApplicationPause(false) is called OnApplicationFocus(true) is called
0
Where does Unity save Inspector properties for objects in a scene? If I add a collection of objects to my scene and configure Inspector properties on those objects (like name, layer, tag, transform parameters, attached Components and their parameters), where does the information about those Inspector properties get saved within my project? Is it all saved within the scene's .unity file or are there other files I should look at?
0
Data structure for objects in a galaxy of star systems I'm having some difficulty coming up with the appropriate data structure to use for a game. I'm aiming for a galaxy view with tens of thousands of visitable star systems. Structure Hierarchically, each star system can contain one or more of the following Planets and their moons Asteroid Belts Megastructures and their moons sub structures All of the above can have quot points of interest quot POI eg a station in low orbit, a surface resource node, a docking bay. Usage I don't particularly care about physical location within a system beyond knowing its order in the hierarchy (I'll be showing a list of locations, rather than trying to render them in 3D space). So I can treat all objects within a system as located at the star for the pursposes of calculation. I do, however, need a way to specify routes from any Planet AsteroidBelt Moon Megastructure POI to any other. I also need to be able to search for other locations meeting certain criteria both to offer as destinations in the UI and to handle rendering . Each type of location will have some unique properties (Asteroid belts have resource distributions, for example whereas planets ave atmospheres) but they also have lots of common properties (inventory, owner, comms network node id, etc). Ideas so far Obviously, with the numbers I'm considering I need to take a sparse lazy generated approach. Currently the galaxy is built entirely in the GPU and stars are only presented to the CPU when the user first clicks on them. That lends itself nicely to a hierarchical data structure with a load on first access approach. Click on a star and it's added to the list, so the name is saved. Scan visit it and I'll generate the system contents. Unfortunately, I also need to be able to search across all generated locations efficiently (given an ID, find the star system coordinates, find planets with an atmosphere like X, find any location with X in its inventory) in a potentially huge search space. That doesn't align with recursively walking up down trees. I considered using a heirarchy and manually maintaining a number of separate indices to speed up searching. It's doable but a pain and error prone. It also feels like one of those solutions where I'm going to keep finding one more type of query I need to support and before long I'm trying to implement a minimal database. Speaking of which I also need to persist this data at some point. Currently I'm serializing to a densely packed binary blob. So... I took a step back and wondered whether I should actually use a database. I can see the benefits of using something like SQLite which I could bundle with the game and would handle persistence, indices, and the rest. Db? After spending a couple of days implementing the basics, I can see this is going to be quite a long and involved process. None of the friendly tooling works well in Unity, so I can't take advantage of entity framework w code first, nor nice Linq To Sqlite predicate handling. Even worse, most of the libraries to work with EF are tightly coupled to windows. EF Core seems like an option but I haven't been able to get it working in Unity (I need to do some assembly version mapping but as Unity overwrites the project file regularly and doesn't seem to support this itself, I think it's a losing battle). So I've headed down the route of implementing a data layer that generates SQL as needed. I can do that, but it opens up a huge can of worms in terms of manually maintaining the DB schema. I'm going to have to start tracking a DB version and bundling migration scripts with any update patch. It's a whole new maintenance burden. Question So... What am I missing? What's the elegant way to store a sparse hierarchy of data whilst still supporting flexible search across disparate object types that just happen to have a lot of common properties?
0
Unity Ajax and json data sending once again i need your help! with help from here i managed to make a function that sends a formated json text to a subscription service.the format is this quot profiles quot quot email quot quot example example.com quot that works fine and great from my pc but once i upload the game it gets blocked by cors. Now i have cors enabled so i contacted klaviyo which handles the data and they told me their api does not accept data from the front end and i could use ajax to make it happer, an example of which is this var settings quot async quot true, quot crossDomain quot true, quot url quot quot https manage.kmail lists.com ajax subscriptions subscribe quot , quot method quot quot POST quot , quot headers quot quot content type quot quot application x www form urlencoded quot , quot cache control quot quot no cache quot , quot data quot quot g quot quot LIST ID quot , quot email quot quot email address.com quot , pass in additional fields (optional) quot fields quot quot source, first name, last name quot , quot source quot quot Account Creation quot , quot first name quot firstname, quot last name quot lastname .ajax(settings).done(function(response) console.log(response) ) now my code which is working from my pc is this public class testing MonoBehaviour public InputField field private string URL quot https a.klaviyo.com api v2 list YeXzKp members?api key pk ec448e1bdab7504c143466ca5eeabc5e95 amp profiles quot public void SaveData() string data JsonUtility.ToJson( new EmailApiData() profiles new EmailApiProfileData new EmailApiProfileData() email field.text ) StartCoroutine(SaveIntoJson(URL , data)) IEnumerator SaveIntoJson(string url, string data) var request new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST) request.SetRequestHeader( quot Content Type quot , quot application json quot ) request.SetRequestHeader( quot Access Control Allow Origin quot , quot quot ) request.SetRequestHeader( quot Access Control Allow Credentials quot , quot true quot ) var jsonBytes Encoding.UTF8.GetBytes(data) request.uploadHandler new UploadHandlerRaw(jsonBytes) request.downloadHandler new DownloadHandlerBuffer() yield return request.SendWebRequest() if (request.isNetworkError request.isHttpError) Debug.Log(request.error) Debug.Log(request.downloadHandler.text) else Debug.Log( quot Form upload complete! quot ) Debug.Log(data) Serializable public class EmailApiProfileData public string email Serializable public class EmailApiData public EmailApiProfileData profiles how can i put those two together?? i know im way out of my waters here but i want to learn it!Thank you once more!
0
Emissive material from white texture I have texture with black and white shapes. I would like that white parts are emissive and black parts are transparent glass. How to make such material ?
0
Play two different audio sources depended on code behind How can I play two different audio clips in Unity depended on the code behind? Into my object I've added two audio sources namely 'Player GunShot' and 'outOfAmmo'. Into the same object I've also added a C script whit this code public currentBullets 1 private AudioSource gunAudio private AudioSource outOfAmmo void Awake() gunAudio GetComponent lt AudioSource gt () outOfAmmo GetComponent lt AudioSource gt () void Update() if (currentBullets 0) outOfAmmo.Play() else gunAudio.Play() Can this code give any problems because in the Awake methode? I've not defined with audio source the variable must be. So which source go he take to play?
0
How do I cover a plane in a bumpy foam material effect? I need to fill a weapon bag with foam material. This is what it should look lik The material in the upper part of the bag looks like this I'm using HDRP. How could I do this? Thank you! Edit I have played around with Parallax Occlusion mapping, and I got this result. Edit2 I am not sure if I use the Pixel Displacement as it has been suggested to me. Also, I'm not sure if I use it the correct way I have created a Height map and put it into the Height map slot. This doesn't create any effect. I have to put the same map into the Base map slot in order to see the effect. If I put a black image into the Base map slot or if I choose Black as the Base color, no effect is visible. I don't understand why this is so. I think even if my Base map is black, the Shader has pixels that it can move. This is my height map Edit 3 It was suggested that I should use a normal map. This doesn't look at all what I expected. The normal map was created from the Height map using an online tool By Philipp's answer I found out that the normal map alone is not enough.
0
How to make a custom event system framerate friendly? I have a simple event system class GameEvent float executionTime Action action class EventMgr MonoBehaviour List lt GameEvent gt events new List lt GameEvent gt () void Update() float timeNow Time.time for(int i events.Count 1 i gt 0 i ) if(timeNow gt events i .executionTime) exents i .action() events.RemoveAt(i) public void ScheduleEvent(float delay, Action action) events.Add(new GameEvent() action action, executionTime Time.time delay ) Then, I schedule events like this eventMgr.ScheduleEvent(0.1f, () gt EVENT A should be fired first eventMgr.ScheduleEvent(0.15f, () gt EVENT B should be fired second Everything works fine when I play on 60 FPS. Update() is fired once every 0.016s. When I play the game on a device with 20 40FPS things got a little bit tricky. Events seem to run in an incorrect order (Event B fired before event A). The only possible cause is of course the framerate itself. If the game runs at 20FPS, Update() would be called less frequently and both of these events would be fired in the same frame and then, the order of their execution depends on the list itself. What to do here? Is there any trick to prevent this, is there any pattern for accurate, ordered event system in games which is FPS friendly?
0
Build displays black screen with static Something really odd happens when I'm trying to load a scene. It is supposed to look like this (it also has to show the next scene after loading) What is going on?
0
How to convert game object world position to hex grid cell coordinates? I have a hex grid and a game object, let's say it's the player. What I want to do is know on which cell the player is on based on his world position, this would be easy on a simple grid but on a hex grid it's giving me a headache.
0
Why does Unity ignore normals when calculating backfaces? Here's some code to generate a square mesh. Vector3 vertices new Vector3 new Vector3(x1, y1, z), new Vector3(x2, y1, z), new Vector3(x2, y2, z), new Vector3(x1, y2, z) int triangles new int vertexIndex, vertexIndex 1, vertexIndex 2, vertexIndex, vertexIndex 2, vertexIndex 3 Vector3 normals new Vector3 this.normal, this.normal, this.normal, this.normal The resulting mesh looks like this The normals have been set to (0, 0, 1), making the square face in the positive Z direction. I would like them to face in the negative Z direction, so the intuitive solution would be to set the normals to (0, 0, 1), but the result looks like this Despite the normals facing the opposite direction, the face's front is still in the positive Z direction. When viewed from the negative Z direction, the square is invisible due to backside culling. Why do my normals not affect the directionality of the faces?
0
Editor throwing NullReferenceException I have the following exception being thrown at compile time NullReferenceException Object reference not set to an instance of an object UnityEditor.Graphs.Edge.WakeUp () (at C buildslave unity build Editor Graphs UnityEditor.Graphs Edge.cs 114) UnityEditor.Graphs.Graph.DoWakeUpEdges (System.Collections.Generic.List 1 T inEdges, System.Collections.Generic.List 1 T ok, System.Collections.Generic.List 1 T error, System.Boolean inEdgesUsedToBeValid) (at C buildslave unity build Editor Graphs UnityEditor.Graphs Graph.cs 387) UnityEditor.Graphs.Graph.WakeUpEdges (System.Boolean clearSlotEdges) (at C buildslave unity build Editor Graphs UnityEditor.Graphs Graph.cs 286) UnityEditor.Graphs.Graph.WakeUp (System.Boolean force) (at C buildslave unity build Editor Graphs UnityEditor.Graphs Graph.cs 272) UnityEditor.Graphs.Graph.WakeUp () (at C buildslave unity build Editor Graphs UnityEditor.Graphs Graph.cs 250) UnityEditor.Graphs.Graph.OnEnable () (at C buildslave unity build Editor Graphs UnityEditor.Graphs Graph.cs 245) I know well enough what a NullReferenceException is and what causes one, but the stack trace above implies that it's being thrown by the editor or some other internal thing. Does anyone have any advice on how to debug this?
0
If a 3d surface is occluded by another 3d surface, does this have any effect on the performance and rendering speed? We have a 3D character who is wearing a gauntlet on his forearm and visibility of which can be turned on and off. Would it be better to create two versions of arm, one without extra triangles that are hidden beneath the gauntlet? Or we can just one model with gauntlet as separate object which can be turned on and off ? Does the hidden triangles have any effect on rendering or are they completely ignored by engine? We are using Unity 3D.
0
How to calculate IsGrounded more effective? if (SimpleInput.GetButtonDown(jumpButton) amp amp IsGrounded()) rb.AddForce(0f, 8f, 0f, ForceMode.Impulse) bool IsGrounded() return Physics.CheckCapsule(Char Collider.bounds.center, new Vector3(Char Collider.bounds.center.x, Char Collider.bounds.min.y, Char Collider.bounds.center.z), Char Collider.radius 0.27f, GroundLayers) I've multiplied Char Collider.radius with 0.27f 'cause in the tutorial that guy said You need to multiply this with 90 of your character's actual size That might be the problem because i don't actually know my character's size, i've made it in blender and scaled it down at the unity. So if you look at the inspector panel you'll see it's 0.1 0.1 0.1 but it's actually not. I tried to spawn a cube and match them together roughly, cube's size was 0.3 1.2 0.3, that's way the number is 0.27f 'cause i just simply calculated it with the 0.3. And finally my problem is I get return values from IsGrounded delayed, sometimes doesn't even get a value. Like example when i jump, sometimes it returns the value of IsGrounded False when i'm just about the hit the ground, and sometimes it doesn't returns the value of IsGrounded False. Because of this i can't make jump animation properly. This is my HandleAnimation() method (I call that from FixedUpdate()) void HandleAnimation() if (!IsGrounded()) anim.SetBool("Jumping", true) else anim.SetBool("Jumping", false) And this is my animator I am also adding those because sometimes when IsGrounded() returns false, animation doesn't works.
0
Animation Change Delay When Landing On Ground I am working on a 2d platformer like game in Unity. My problem is that when my player character jumps and lands back on the ground, there is a slight delay at times when transitioning to the player idle animation. This is not due to exit time. Instead, upon researching this topic, I found that my real problem lies in the Unity physics loop(FixedUpdate). FixedUpdate, as the name implies, is called a fixed amount of times, not every frame. My animator relies on a Jumping boolean to tell it whether or not to be in the jumping animation. In my code, the Jumping boolean is set to false when the player lands on the ground. This is handled by OnCollisionEnter2D, which runs on FixedUpdate. This is were I think my problem lies private void OnCollisionEnter2D(Collision2D collision) if (collision.gameObject.CompareTag("Ground")) isOnGround true animator.SetBool("Jumping", false) I need to know whether or not the player is colliding with the ground, So I setup a tag. I need to find a way to constantly check whether or not I am colliding with the ground, So that I do not see an animation transition delay. Any Ideas of how I could accomplish this?
0
Changing distance after some time on OnGUI Unity Though I am using IEnumerator to calculate the distance travelled value, the distance is updated very frequently, how can I change that? and why exactly increasing the time in WaitForSeconds function not changing the behaviour? void OnGUI () GUI.contentColor Color.black GUI.Label (new Rect (40, 40, 140, 40), "Speed " speed, "color") StartCoroutine (distancetravelled ()) GUI.Label (new Rect (40, 100, 100, 140), "Dist " Mathf.RoundToInt (distance 1000) " Kms", "color") IEnumerator distancetravelled () timeInHours (Time.smoothDeltaTime 60) 60 if(PlayerControl.collision ! true) distance speed timeInHours yield return new WaitForSeconds (60)
0
NullReferenceException in StartCoroutine method Maybe it's a repeated subject in the community but other answers didn't solved my question... I tried as the tutorial http answers.unity3d.com questions 11021 how can i send and receive data to and from a url.html and worked fine in start method but when I try public Class A ...CODE... new B().JSONRequest(jsonString) public Class B public void JSONRequest(string json) string url URL.LOCAL.url Hashtable postHeader new Hashtable() postHeader.Add("Content Type", "application json") UTF8Encoding encoding new System.Text.UTF8Encoding() WWW request new WWW(url, encoding.GetBytes(requisicaoJSON.ToCharArray()), HashtableToDictionary lt string, string gt (postHeader)) print("Request " request) StartCoroutine(WaitForRequest(request)) IEnumerator WaitForRequest(WWW www) yield return www check for errors if (www.error null) Debug.Log("WWW Ok! " www.data) else Debug.Log("WWW Error " www.error) It gives me in the StartRoutine line NullReferenceException UnityEngine.MonoBehaviour.StartCoroutine (IEnumerator routine) (at C buildslave unity build artifacts generated common runtime UnityEngineMonoBehaviourBindings.gen.cs 61 Console prints Request UnityEngine.WWW so it does not appear to be null.
0
Applying movement to a Rigid Body Isometric in Unity 3D I'm making an isometric dungeon crawler. I initially used transform to get isometric movement and things worked well, but I couldn't use collision which meant it was unsuitable. So I'm now trying to use Rigidbody and I'm having some weird issues. First of all, this is the code I currently have public class CharControllerRigid MonoBehaviour SerializeField private Rigidbody characterRigid private Vector3 inputVector void Start() characterRigid GetComponent lt Rigidbody gt () void Update() inputVector new Vector3(Input.GetAxis("Horizontal") 10f, characterRigid.velocity.y, Input.GetAxisRaw("Vertical")) transform.LookAt(transform.position new Vector3(inputVector.x, 0, inputVector.z)) private void FixedUpdate() characterRigid.velocity inputVector I have two issues First, how do I get the movement to work on an isometric plain? Second, how do I get the movement to work in all directions? Current when I move left and right the movement is good, but up and down are really slow in comparison.
0
Periodic updates of an object in Unity I'm trying to make a collider appear every 1 second. But I can't get the code right. I tried enabling the collider in the Update function and putting a yield to make it update every second or so. But it's not working (it gives me an error Update() cannot be a coroutine.) How would I fix this? Would I need a timer system to toggle the collider? var waitTime float 1 var trigger boolean false function Update () if(!trigger) collider.enabled false yield WaitForSeconds(waitTime) if(trigger) collider.enabled true yield WaitForSeconds(waitTime)
0
How to know the size of object in Unity in world units? Suppose I have some external package with objects. Suppose I place some of these object to the scene. Now how to know actual size of object in world units? I found no any rulers or something in Unity. The I thought I can place primitive cube and compare it, but then I realized that I don't know the size of cube too. Is is possible to "measure" arbitrary object in Unity somehow?
0
Network Message Registering message handler Problem I have a confusion about when and where to use NetworkServer.RegisterHandler() and NetworkManager.singleton.client.RegisterHandler()? And also I am getting Unknown message ID 1002 error. I have a message class public class NetworkMsgHandler NetworkBehaviour public const short movement msg 1002 public class BulletMovementMsg MessageBase public string objectName public Vector3 objectPosition public Quaternion objectRotation public float time I have ServerRelay which has ServerOnly authority has Script ServerRelay for registering Message Handler on Server. public class NetworkServerRelay NetworkMsgHandler private void Start() if(isServer) RegisterNetworkMessages() private void RegisterNetworkMessages() NetworkServer.RegisterHandler(movement msg, OnReceivePlayerMovementMessage) private void OnReceivePlayerMovementMessage(NetworkMessage message) BulletMovementMsg msg message.ReadMessage lt BulletMovementMsg gt () NetworkServer.SendToAll(movement msg, msg) Then I have Bullet GameObject it has script Projectile which is sending movement message this class is derived from NetworkMsgHandler. public class NetworkProjectile NetworkMsgHandler private void Start() if (localPlayerAuthority) canSendNetworkMovement false RegisterNetworkMsg() else isLerpingPosition false isLerpingRotation false realPosition transform.position realRotation transform.rotation private void RegisterNetworkMsg() NetworkManager.singleton.client.RegisterHandler(movement msg, OnReceiveMovementMsg) private void OnReceiveMovementMsg(NetworkMessage networkMessage) Debug.Log("Message received") BulletMovementMsg msg networkMessage.ReadMessage lt BulletMovementMsg gt () if(msg.objectName ! transform.name) ProjectileManager.Instance.SpawnedBullets msg.objectName .GetComponent lt NetworkProjectile gt ().ReceiveMovementMsg(msg.objectPosition, msg.objectRotation, msg.time) public void ReceiveMovementMsg(Vector3 position, Quaternion rotation, float timeToLerp) lerping between position private void Update() if(!canSendNetworkMovement) canSendNetworkMovement true StartCoroutine(StartNetworkSendCoolDown()) private IEnumerator StartNetworkSendCoolDown() timeBetweenMovementStart Time.time yield return new WaitForSeconds((1 networkSendRate)) SendNetworkMovement() public void SendNetworkMovement() timeBetweenMovementEnd Time.time SendMovementMsg(bulletID, transform.position,transform.rotation, (timeBetweenMovementEnd timeBetweenMovementStart)) canSendNetworkMovement false public void SendMovementMsg(string bulletID, Vector3 position, Quaternion rotation, float timeToLerp) BulletMovementMsg msg new BulletMovementMsg() objectRotation rotation, objectPosition position, objectName bulletID, time timeToLerp NetworkManager.singleton.client.Send(movement msg, msg) So whenever a bullet spawns it generates an error on client side saying Unknown message ID 1002 connId 1 UnityEngine.Networking.NetworkIdentity UNetStaticUpdate()
0
strategies for detecting regressions I know writing tests would be a good way to catch regressions. But what are some other strategies? TDD and game dev don't suit, but catching regressions is obviously something desirable. I would love to find some cheap and easier ways to catch regressions without having to invest a lot of effort or writing tests after the fact. Strategies suggested don't have to be perfect, if they can give rough ideas or things to playtest rapidly then that would also be beneficial. Please advise.
0
Effects of collisons broken glass, damaged cars, how are they created? My question is related in particular to achieving the effects of collision in game engine, how is this done? I have searched a bit, read from the internet and went through a few tutorials, and saw that one way to create one of the effects, explosion, or something breaking is to create the model in pieces, and apply force (in a game engine such as Unity 3D) to make the pieces fly off. It seems to be a solution, but it doesn't address the problem of items that are vaporized in a big explosion, with so many pieces. How is this done? Basic methods and tricks etc would be helpful. Secondly, the problem of things bending and getting damaged on impact, such as a car's front end destroyed when it hits a wall? How is this done? One thing that comes into my mind is to create each component of a car in a different state as an animation in 3Ds Max or Maya, and then in the engine, according to the collision, switch the model state in the time bar. Is this how it is done? Finally, what about materials, such as net of a basketball net, or a soccer goal net for example? Effects of ball hitting it can be calculated and applied in a script, but how to make the net bend and stretch with it? Is it done through models or materials? Also what about a flag fluttering in the wind? My questions are specific to game engines, particularly Unity3D. Some good links on the subject would also be helpful.
0
Making a zoom out in space map in Unity I'm new to unity, I was wondering how would one go into implementing a dynamic 2d space map. Let me give you an example what i mean. You see our solar system on the map, if you zoom out at a treshold value this solar system would just be represented by a name and our sun and around it you see adjacent solar systems. How would I do this in unity?
0
OnTriggerEnter With First Person Controller I'm working on an FPS for my first time. I'm creating a simple terrain and instatiating 15 cubes on my terrain. (This works fine). Each cube is named "cube" and has a static trigger collider. Here's what my scene looks like When my first person controller collides with my cube (instantiated object) then I want the cube to deactivate and add 1 to my score, but nothing happens. Code I added this code in FirstPersonController.cs void OnTriggerEnter(Collider other) if (other.gameObject.name "cube") other.gameObject.SetActive(false) when the player touches my spawned object then I want to deactivate my cube, but nothing happens Debug.Log("collidedwith " other.gameObject.name) score 1 scoreText.text score.ToString()
0
Write Data From List To CSV File I am trying to write to a CSV file the values that I put in lists from a key press in the keyboard. It does work somehow but in my csv file I get the values 2 times. Also, when I put values to only one of the lists, I don't get any data to CSV file. How can I save the values from the lists to my csv file but to be independent from each other? This is my code using UnityEngine using System.Collections using System.Collections.Generic using System.Text using System.IO using System public class record MonoBehaviour public List lt string gt inventory new List lt string gt () public List lt string gt OnlyX new List lt string gt () void Update() if (Input.GetKeyDown(KeyCode.F)) inventory.Add("F") if (Input.GetKeyDown(KeyCode.J)) inventory.Add("J") if (Input.GetKeyDown(KeyCode.X)) OnlyX.Add("X") string filePath getPath() StreamWriter writer new StreamWriter(filePath) writer.WriteLine("Inventory,OnlyX") for (int i 0 i lt inventory.Count i) for (int j 0 j lt OnlyX.Count j) writer.WriteLine(inventory i "," OnlyX j ) writer.Flush() writer.Close() private string getPath() if UNITY EDITOR return Application.dataPath " Data " "Saved Inventory.csv" elif UNITY ANDROID return Application.persistentDataPath "Saved Inventory.csv" elif UNITY IPHONE return Application.persistentDataPath " " "Saved Inventory.csv" else return Application.dataPath " " "Saved Inventory.csv" endif
0
When the motion button is pressed, the shape of the character changes and always goes to the left direction good day. When the motion button is pressed, the shape of the character changes and always goes to the left direction. Why is this happening and what is the solution? Pressing two buttons moves to the left and the shape changes. using System.Collections using System.Collections.Generic using UnityEngine public class PlayerKontrol MonoBehaviour public float karakterHizi 8f, maxSurat 4f private Rigidbody2D myRigidbody private Animator myAnimator private bool solaGit, sagaGit void Awake () myRigidbody GetComponent lt Rigidbody2D gt () myAnimator GetComponent lt Animator gt () void FixedUpdate () if (solaGit) SolaGit () if (sagaGit) SagaGit () public void AyarlaSolaGit (bool solaGit) this.solaGit solaGit this.sagaGit !solaGit public void HareketiDurdur () solaGit sagaGit false myAnimator.SetBool ("run", false) void SolaGit () float Xdurdur 0f float surat Mathf.Abs (myRigidbody.velocity.x) if (surat lt maxSurat) Xdurdur karakterHizi Vector3 yon transform.localScale yon.x 0.3f transform.localScale yon myAnimator.SetBool ("run", true) myRigidbody.AddForce (new Vector2 (Xdurdur, 0)) void SagaGit () float Xdurdur 0f float surat Mathf.Abs (myRigidbody.velocity.x) if (surat lt maxSurat) Xdurdur karakterHizi Vector3 yon transform.localScale yon.x 0.3f transform.localScale yon myAnimator.SetBool ("run", true) myRigidbody.AddForce (new Vector2 (Xdurdur, 0))
0
What are some strategies for handling a zoomed out grid of sprites? I'm writing a grid based 2D game in Unity3D that would ideally use grid sizes of around 200x200 or so, with multiple zoom levels, including all the way out. When I tried render a 200x200 grid at the most zoomed out level where everything is visible, Unity crapped out saying that there were too many vertices to attempt to draw. This makes sense, as it's trying to render 40,000 sprites. I was wondering, how do games like Dwarf Fortress and OpenTTD manage so many sprites at once on the screen when the map is zoomed out all the way? Are there any general strategies for handling the rendering of a large number of sprites such as this?
0
Unity URP Batching GPU instanced objects with same material mesh not working I have 100 units (exact same prefab) on screen. The material is a URP Lit using a texture with GPU instancing enabled. Why is it not batching? Am I missing something? I also noticed it requires 3 4 batches per model, why is this? See screenshots for stats and info.
0
Video play in unity3d skybox I want to play 360 video in skybox. Is there any direct way avaiable to do this task. One long, boring, inefficient procedure which seems that Convert 360 to frames Convert frames into cubmap Use that cubeMap in skybox and Programatically change it's textures(Frame) quickly so that video effects shown This is the long task which seems to me possible but is there any other way available?
0
Unity Exporting Game creates Texture Glitches In the editor the textures are fine, however upon exporting I'm constantly faced with glitches like these I mainly use the Built in Standard Specular Shader and the texture that gets glitched is always the Detail Texture. When re exporting the game multiple times the texture gets glitched exactly the same way in the same spots. Meshes are always below 65536 polygons. In game size is usually around 2x2 kilometres. The smallest Terrainmesh is 500x300metres and the origins are usually close to the terrain, always at 0,0,0. Scale and Rotation are always reset. This has happened in pretty much every scene so far. Screenshot of UV coordinates
0
Character permanently disappears when camera zooms in I am using ThirdPersonController and FreeLookCameraRig, both from the standard assets package. The camera generally follows the player fine but there is an issue when I move the camera very close to the player. When I do this, the character disappears, though it still behaves as though it is in the scene. For example, the xyz coords still show it as being in the scene and when it jumps, the camera still follows it. Here's a visual explanation. Notice how the character disappears after about 5 10 seconds and doesn't come back. (Note the gif is too large to display here, so please see it on imgur. http i.imgur.com PbMDlXD.gifv). The ThirdPersonController has Transform, Animator, CapsuleCollider, Third Person User Controller, and Third Person Character The FreeLookCameraRig has Transform, Free Look Cam, and Protect Camera From Wall. I have tried messing with many of these settings, but nothing has worked. By the way, some of the course was created in Sketchup.
0
How can I play an audio source while a key is being held down? if (Input.GetKey(KeyCode.A)) audioSource.Play() Except this only functions once as the key is held down. Same goes with GetKeyDown. Is there any way I can get this to loop as long as they key is being held down? (Is in Update)
0
How can I set a property for the upper limit for another property's range I have two properties, I would like to set one property as the upper limit of another property, hence making the upper rely on a property. As below public int fullLength Range(0, fullLength) public int segmentLength Is there a way to do this, possibly with a custom editor? If yes, how can it be done?
0
Debug.Assert Behavior in Unity Is this normal behaviour that Unity continues to run after a condition in a Debug.Assert statement was NOT met when I launch the game within the Editor? I can see the assertion in the console output, but still would expect it to stop the game. Development build and Script Debugging are turned on in my player settings.
0
Accelerometer bike game rotation help Hi I've been making a game for the last few months and not sure what to do. It's a 2d bike game and I want the rotation done with accelerometer, at the moment To test on computer I've set the rotation up as if left is hit transform.rotate to the left but because gravity my bike will not stay doing a wheelie. Is there another way to do this can I just set up that the rotation of the bike is equal to the screen rotation? Or do I need the bike to stay in the air first and then when rotated right it goes right ect? Really not sure and have been stuck on this for a month noob to unity too thanks
0
Is a final yield return 0 required in corutines? I have the following code run in a coroutine. I would like to know if the last yield return 0 is necessary and why. Thank you! private IEnumerator pChangeFoV() float duration 0.7f float zValue 5f for (float t 0f t lt duration t Time.deltaTime) float fNew Mathf.Lerp( camera.fieldOfView, zValue, t duration) camera.fieldOfView fNew yield return 0 camera.fieldOfView zValue make sure we're really where we want to be now do everything that should be done after we're done with this coroutine pEnableSomeScripts() yield return 0 is this final yield return 0 required???
0
Unity AI issue with recalculating NavMesh at runtime I am using Unity NavMesh to control my units. I am running into an Issue when updating Navmesh at runtime, It seems agents re calculate their path whenever it is modified, which makes sense, but it causes this line (check if unit is on last corner) to return an IndexOutOfBounds error agent.steeringTarget agent.path.corners agent.path.corners.Length 1 I guess something is happening while re calculating path that might mess with this for 1 frame. I solved this by putting a try catch around it, but is there some better way I can manage this so I don't get the error at all?
0
How to Get VR Controller's Velocity in Unity with SteamVR? Back when I used Unity 2017 and controller bindings weren't a thing, I simply attached a rigidbody to my Vive controller and read out the velocity of the rigidbody to know how fast the player was swinging the controller. Now, I've updated to Unity 2021.2.0a14, I went through all the effort of modifying my code to work with bindings, and it doesn't seem like I can get velocity anymore. The rigidbody always reports zero velocity. I can see the World Center of Mass vector changing so I know it registers motion, but it's just not reporting the velocity anymore. Is there a new setting in Unity I need to turn on to measure things that it doesn't personally control? Or do the new bindings options have a way to get velocity as an input? Am I forced to calculate it myself now? Thanks! Edit Base assumption was wrong, I did not get velocity from the rigidbody attached to the hand controller like I thought I did. I got it directly from SteamVR Controller. So Unity is probably acting like it ever did.
0
SteamWorks.Net for unity and inviting a friend to a multiplayer game I'm trying to send an invitation to a steam friend and have it that when he accepts I create a PUN 2 room for both players and they can start their match. So far I've done this protected Steamworks.Callback lt GameRichPresenceJoinRequested t gt m GameRichPresenceJoinRequested private void OnEnable() m GameRichPresenceJoinRequested Callback lt GameRichPresenceJoinRequested t gt .Create(OnGameRichPresenceJoinRequested) public void InviteFriend() SteamFriends.InviteUserToGame(steamFriendData.friendSteamId, "") private void OnGameRichPresenceJoinRequested(GameRichPresenceJoinRequested t pCallback) Debug.Log(pCallback.m rgchConnect) Debug.Log(" lt color green gt Friend accepted the invite lt color gt ") The invite is being sent to the correct friend and when he accepts it launches the game but I get no callback from that and thus have no way to place them in a room. What am I doing wrong ?
0
Why do I get this error with FB.LogInWithPublishPermissions? I don't know what's wrong. I know that FB.Login is already deprecated. I don't know what syntax to use. public class FBholder MonoBehaviour void Awake() FB.Init (SetInit, OnHideUnity) private void SetInit() Debug.Log ("FB Init Done") if (FB.IsLoggedIn) Debug.Log ("FB Logged in") else FBlogin () private void OnHideUnity(bool isGameShown) if (!isGameShown) Time.timeScale 0 else Time.timeScale 1 void FBlogin() FB.LogInWithPublishPermissions ("user about me, user birthday", AuthCallback) void AuthCallback(ILoginResult result) if (FB.IsLoggedIn) Debug.Log ("FB Logged in worked") else Debug.Log ("FB Logged in failed") and I'm getting this error Assets FBholder.cs(40,6) error CS1502 The best overloaded method match for Facebook.Unity.FB.LogInWithPublishPermissions(System.Collections.Generic.IEnumerable, Facebook.Unity.FacebookDelegate)' has some invalid arguments and this Assets FBholder.cs(40,35) error CS1503 Argument 1' cannot convertstring' expression to type System.Collections.Generic.IEnumerable'
0
Adding Animation to Object Unexpected Behavior I've been following the Unity 2D roguelike tutorial and I'm a bit confused about something. When he drags a series of sprites to his player object, a dialog box appears that prompts him to name and choose a location for his animation. I have seen this behavior in a couple video tutorials now. When I do this, it simply creates the animation and animation controller in the sprite folder and nothing more. This becomes a bit tedious after a while and I'm not sure these animations are being associated with the object correctly. What am I doing wrong?
0
How do I add a "pointer" to my UI menu? I'm sure there has to be a simple answer to this, but frankly I cannot find anything about it anywhere on the internet, so I'm asking here. How do I add a pointer like this hand to the side of the currently selected UI button in my game? I tried using Unity's built in UI system to do this, using the "sprite swap" feature that changes sprites based on whether or not the button is currently selected. I made an image for my "Play" button, and then an image for when the play button was selected that included a pointer as part of the image, but the image would either resize when the button was selected, or the image was moved to the right to accommodate Unity's centering mechanic on the UI. Perhaps this wasn't so wrong, and I'm just not using the UI system correctly. Does a feature like this have to be hard coded into the UI design?
0
Unity animation tool doesn't save changes I'm trying to create an animation inside Unity using the animator tool, however the record tool isn't recording my changes and I'm struggling to get this to create animations. I have created an example here https i.gyazo.com 91f88b3531b4fb3ffd4100d40f06bdcf.mp4 I have tried recreating the animation file, but no matter what I do it refuses to record the element? Any information would be appreciated, as it appears unity may be bugged. When applying an update between tweened keypoints the fields for X Y Z are red and do not apply changes
0
How can I debug a black screen when testing on a device? I have made an Android game with Unity. But, when I opened my game, I see a black screen and a closed game. It works on a tablet but does not work on mobile phones. I tested it on 2 mobile phones. On the first phone I installed it on, I see nothing but a black screen and closed game. On the second one, it installed once and worked, but when I uninstalled it and tried to install it again, I get the black screen and closed game. What can I do to help me find out what is going on?
0
Unity3D Change Background Image on a GUI Skin So I'm testing with GUI Skins and trying to make something cool, and I want to change the background image of the application background. This is what I mean In the screenshot above, the background is just blue, i'd like to change that to an image so it looks a lot better. Anyone know how to do this?
0
How to design prefabs in Entity Component Systems In Unity (and I presume other game engines) you can create "prefabs" which are blueprints for game objects. They contain a list of components, and default values for those components. Prefabs can be instantiated many times, which is an efficient way of creating many objects of the same kind. One feature in particular of prefabs is that you can modify an attribute on a single instance of a prefab, without modifying the prefab itself. Similarly, you can modify the prefab, which will propagate the change to all instances. I've been working on an implementation of the Entity Component System (for a high level description of ECS see this question How to implement n body in an Entity Component System), and I got stuck on how to implement prefabs efficiently in ECS. I think it's a powerful capability of EC design, and implementing this on native ECS would be awesome. I can come up with a few approaches Create archetypes, which are predefined lists of components (Unity approach). This does not let me set initial values for the components, nor override them (there is nothing to override). Easy to implement, but doesn't really do what I want it to do. Create a "prototype" entity from which other entities are cloned, including component values. With this design I can override individual attributes, but when I update the prototype, the clones don't get updated. Create entities with a reference to a "base" entity. When getting a component from an entity, first look in its component list, then try the base entity. This way when I update a base component, base instances change as well. To override a base component I can simply add it to the instance entity. Of these three approaches the third approach comes closest, but I don't see a straightforward way to extend it so I can override a single attribute. How can I make this work?
0
Unity2D jumping inconsistancy I'm tinkering with a unity2D sidescroller, and am trying to make a player controller to jump. However, when I tell my character to jump, it sometimes jumps twice the distance, and I don't know why. Below is my controller script using System.Collections using System.Collections.Generic using UnityEngine public class PlayerMovement MonoBehaviour public float playerSpeed 10 public float jumpForce 20 private bool ableToJump false public GameObject groundCheck place an empty object slightly below the character where it will collide with any ground Update is called once per frame void Update() if (Input.GetKey("space") amp amp ableToJump) ableToJump !ableToJump GetComponent lt Rigidbody2D gt ().AddForce(new Vector3(0,1,0) jumpForce) if (Input.GetKey("a")) transform.Translate( playerSpeed Time.deltaTime, 0, 0) if (Input.GetKey("d")) transform.Translate(playerSpeed Time.deltaTime, 0, 0) The player is grounded if a linecast to the groundcheck position hits anything on the ground layer. ableToJump Physics2D.Linecast(transform.position, groundCheck.transform.position, 1 lt lt LayerMask.NameToLayer("Wall")) Here is the glitch as it appears when I am previewing the game (watch how the third jump seems to be twice as high). There is no consistency to when it occurs, but it has occurred any time between two in a row and 10 12 between times it happens. I have tried long versus short presses of the jump key (space bar), moving versus standing still, and jumping on different locations. I have also tried disabling animations and waiting between presses versus pressing and holding space, versus pressing space rapidly. The only consistent thing is that sometimes I jump about three blocks (200 x 200px each) high, and sometimes I jump about six blocks high. Any tips are appreciated. Thanks!