# Tag Info

## New answers tagged c#

0

It looks like you meant to write something like this: void Update() { // When the ways list is empty, we've reached the last waypoint. if (pathTarget.ways.Count > 0) { // Move one step toward the next remaining point in the list. target = pathTarget.ways[0]; transform.position = Vector2.MoveTowards( ...

1

Here's a slightly more explicit test: public class IfTest : MonoBehaviour { public GameObject toAssign; void TestIfs() { if (toAssign) { Debug.Log("if (gameObject) passes."); } else { Debug.Log("if (gameObject) fails."); } if (toAssign != null) { Debug.Log("...

0

I don't actually use Unity, but I do some 2D game programming and I use C#, so I'll chip in an idea hopefully it might help. From what I know a technique to create a smoothing-effect for movement is to linear-interpolate ("LERP") the movement of the target object against the profile of some function. It sounds a little complex but at a high level ...

0

Fixed! The ball was rolling rather than gliding, and because it wasn't smooth enough, gave me the feeling it was bumpy.

1

I think you are looking for coroutines. A coroutine is a method which can interrupt itself using the yield return statement in order to be later resumed on another frame. This is useful when you have sequences of actions you want to perform within pauses between them instead of all at once. This example will log "1", "2", and "3"...

1

I don't see any issues with your ball movement. The shadow is bumpy. Shadow maps are textures with pixels, but smoothing is applied so that low resolution shadows don't appear pixelated. However, the shadows in the shadow map can still only move one pixel at a time. When the resolution is low, the pixels are large and the shadow motion will appear jumpy. ...

1

There are likely some bugs because it is a new feature C# - the language - is well supported. Also, a lot of effort have gone into supporting ahead of time compiling, which allows greater platform support than it would have otherwise. However: Some .NET libraries may cause trouble (mainly related to threading and reflection). It is not well integrated into ...

4

The TextMesh component (or its superior alternative TextMeshPro) is perfectly fine if a naked text is all your want to show. That's what it's for. But a world-space canvas has benefits when you have more than one UI-element to attach to an object. Like, for example, a panel with a border and a background which contains the name, a health bar and a couple ...

0

This seems to be working as I wanted. Though I wonder if I did it right and if there is a way to get to exactly speed 3. using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Rotations : MonoBehaviour { public Text textName; public float rotationSpeed; public bool rotateText = false; ...

0

This is empirical formula for easing in and out. $1-sin(\frac{\pi}{2}(1-t))$ $sin(\frac{\pi t}{2})$ $t\in[0,1]$ Example code: float time, easeDuration; private void Update() { const float HALF_PI = Mathf.PI / 2; time += Time.deltaTime; var t = Mathf.Clamp01(time / easeDuration); if(rotateText) t = 1 - Mathf.Sin((1-t) * ...

1

This is not a good use of a matrix. Just write it as a plain old float multiplication / addition (or power, if you're using gamma, which cannot be represented as a matrix operation). public static float AdjustChannel(float colour, float brightness, float contrast, float gamma) { return Mathf.Pow(colour, gamma) * contrast + brightness; } ...

1

Well, you get the exact error what went wrong. Your index counts to high and you try to access an element in the array that does not exist, your script crashes (and stops moving). Now why it does not work with your OnTriggerEnter is, it counts the index to 5. And in your update you try first to move to index 5 in your List (which does not exist since it has ...

0

Figured out the solution. Based off of Elliot's answer from this post How do I convert from the global coordinate space to a local space? var deltaX = Car.m_worldPositionX - PlayerCar.m_worldPositionX; var deltaZ = Car.m_worldPositionZ - PlayerCar.m_worldPositionZ; double deltaYaw = Car.m_yaw - PlayerCar.m_yaw; var radius = Math.Sqrt(deltaX * deltaX + ...

0

My guess would be that m_worldForwardDirX/Y/Z is a unit vector pointing forward from the white car in world coordinates, and m_worldRightDirX/Y/Z is a unit vector pointing right. If you take the position of the blue car and subtract the position of the white car, you have a difference vector in world coordinates. If you project this vector on m_worldRightDir ...

2

OpenTK is discouraging the use of immediate mode. But it is still supported. To use it, you need to set NativeWindowSettings.Profile to ContextProfile.Compatability. That is, you want an entry point that looks something like this: using OpenTK.Windowing.Common; using OpenTK.Windowing.Desktop; namespace tktest2 { internal static class Program { ...

0

Currently your t is evaluated the same for all your objects. If they should arrive at different times at your destination, they need their own t or at least know the delay. Without changing too much of your logic, you could assign a negative startTime to future objects and apply it only once it turns positive. private List<float> startTime = new List&...

1

This variable is the maximum distance the object is allowed to move on this method-call. You usually call MoveTowards in Update in order to move an object one step closer to its destination. But the frequency of Update calls depends on the current framerate. So on lower framerates you need to move the object further per update than on higher framerates. ...

1

Make the regular hardware mouse cursor disappear with Cursor.visible = false; in the Start method of some script. Create a new game object called "Mouse Cursor". I recommend using an image on a screen-space canvas for this purpose, but in a 2d game you could use a sprite in world-space as well. Give it a pointy-looking sprite asset which goes well ...

0

I found this link https://developer.android.com/guide/playcore/in-app-review/unity but I´m really curious if there are other ways, and how to send them to play store and get them back safely. Nice to mention there is a time limit on how many times you can call this in app review. Sending directly to play store this doesn´t apply.

0

If someone wants to use the function GenerateSmoothNoise() in Unity for example here is a small adaptation (with the function Interpolate()) : public static float[,] GenerateSmoothNoise(float[,] baseNoise, int octave, float frequency) { int width = baseNoise.GetLength(0); int height = width; float[,] smoothNoise = new float[width, height]; ...

1

After further research, I figured it out. If you wanted to increase the size of a specific tile by two times, all you need to do is unlock the tile flags and set the new scale matrix like so: Matrix4x4 newMatrix = Matrix4x4.Scale(new Vector3(2, 2, 2)); Tilemap.SetTileFlags(position, TileFlags.None); Tilemap.SetTransformMatrix(position, newMatrix); There is ...

0

Thank you DMGregory for your reply. I [FIXED] it, the problem was really something else, so here it is, if that can be useful to anyone : I tried with a backup of the project, and Unity 2018, no issues I exchanged the scripts, gameobjects attributes etc. not working in Unity 2021 IN THE END, I tried unticking the checkbox Constraints > Freeze Position &...

0

A solution I often use is creating "pseudo-buttons" using bools and Unity's OnValidate() method void ExampleMethod() { Debug.Log("Hello World!"); } public bool pseudoButton = false; void OnValidate() { if (pseudoButton) { ExampleMethod(); pseudoButton = false; ...

2

You can accomplish this using the Curiously Recurring Template Pattern: public class Weapon<T> : MonoBehaviour, IInteractable where T: Weapon<T> { public void Interact(Player player) { player.gameObject.AddComponent<T>(); } } public class RangedWeapon : Weapon<RangedWeapon> { // Put anything the derived weapon ...

0

I used the following method and it worked: Change in External Tools: Edit -> Preferences :choose " Visual Studio Code" Open file : Assembly-CSharp-Editor in your project folder and Download the Framework Version that is the same as the version in this file EX: v4.7.1 Open VScode tool - Settings - >code lens and tick. original solution ...

0

Okay. Depending on what you're doing with this, a coroutine might be more appropriate. It allows you to "fire and forget", with the added bonus that local variables are kept alive as long as the coroutine is, so you don't need long-lived state cluttering your classes up. I think you're overcomplicating things, unless there's more logic not shown ...

2

SOLUTION: Thanks to DMGregory showing how to use Vector3.Dot(), I was able to fix the solution and easily change the zOffset depending on which side of the wall the player is on. Also thank you to Pikalek for fixing my post formatting. hit = Interactor.hit; anchor = hit.transform; float playerSide = Mathf.Sign(Vector3.Dot(transform.forward, anchor.forward));...

1

Use NativeQueue for your results, then obtain a NativeQueue<T>.ParallelWriter for it using results.AsParallelWriter(). It exposes a method Enqueue(T) to add elements to the queue. You can then later read from that queue by copying it to an array using results.ToArray() or by processing the queue using a while(results.TryDequeue(out result)) { loop. The ...

1

Yes, it indeed appears as if the majority of the execution time goes into building the NativeArray with all the tile coordinates, while the job operating on said array only takes a tiny fraction of the computational time. But that array does not even contain very useful data. It's really just a consecutive list of all the coordinates within a large rectangle....

1

Your vector projection expression is incorrect for the general case. It's basically coincidence that it works when all axes but one are zero and the remaining is ±1. What you want is this: // Project displacement from collider to hit point onto local x-axis. Vector3 xOffset = Vector3.Dot(hit.point - hitCollider.position, hitCollider.right) * ...

0

I normally use Animation Event Handlers public Animator animator; public AnimationClip AttackedAnimationClip; private void Awake() { AttackedAnimationClip.AddEvent(new AnimationEvent() { time = AttackedAnimationClip.length, functionName = "OnCompletedAttackedAnimation" }); } public void OnAttacked() { // this is ...

1

The current state-of-the-art for multithreading in Unity is the jobs system using the burst compiler. It not only gives you far more performance than regular C# code for most situations (at the cost of being restricted to a subset of the language), it also gives you multithreading managed by the engine itself. So you can just schedule parallel jobs and let ...

-1

You could use a ComputeShader to offload the ai logic to your GPU, which is better in running parallel tasks, like AI pathing and the sorts. Or just teach your AI chess with unity ml-agents, so that fuzzy logic and neural network make the AI more human and choose the best move that "feels right", and you could just edit the thinking time and have ...

3

It's possible natively since 2019.3 release via [SerializeReference] attribute. Unity's SerializeReference documentation.

2

Something like this? Here we use a serializable struct to bundle together some text information with each sprite in the collection, and a TextMeshProUGUI component to display that text when the sprite is selected. [System.Serializable] public struct DescribedSprite { public Sprite sprite; public string description; } public List<DescribedSprite&...

0

Using DefaultInputActions can be one way to help transition your code. For example, the following could replace your class: using System.Collections; using UnityEngine; using UnityEngine.InputSystem; public class ExampleClass : MonoBehaviour { public GameObject projectile; private float nextFire = 0.5F; private GameObject newProjectile; ...

0

Posting since this might help someone else. Thanks to @Philipp's helpful answer, this is what I ended up with. This organization feels much cleaner! StairMaster feels a little weird since it does not use Start or Update, and StaminaBar had a bit of a race condition where Player was calling Reset() on it before Start() was called, so localScale was being ...

1

The Problem In Unity's Docs : [Serialize] Referenced values cannot be shared between UnityEngine.Object instances. For example, two MonoBehaviours cannot share an object that is serialized by reference. Use ScriptableObjects instead to share data. As Instantiate creates a new Unity Object, its data cannot be shared by reference by just decorating the ...

1

Getting your code to work is the easier part. You would need to change your getter and setter to match what the tutorial is teaching you. A setter needs the parameter to well, set things. Your getter returns a totally different class than you would expect, it should be of type PlayerScrolls. public void SetValue (PlayerScrolls item, int index) { ...

0

My wild guess is that you deleted a script which was on a GameObject or a prefab, and that's why Unity is throwing an error that the script is missing. This could help: an editor script to find such missing references https://web.archive.org/web/20200724123545/http://wiki.unity3d.com/index.php/FindMissingScripts

0

Why not use #define directives?(https://docs.unity3d.com/Manual/PlatformDependentCompilation.html) So when on Windows UNITY_STANDALONE_WIN Or on windows editor UNITY_EDITOR_WIN Then always replace with CR LF

0

If you create an empty object in the editor, by right-clicking in the hierarchy and clicking Create Empty (as shown in the picture above), and put the script in there it should work, as Unity requires that a script be put in a GameObject .

5

At the end of your Update method, you have this block: if (isGrounded == false) { Speed = AirSpeed; } else { Speed = 20; } That means that after this block, Speed will be either AirSpeed or 20. The stuff you are doing further above based on the value of isCrouching is irrelevant, because it gets overwritten before ...

2

Single responsibility principle Every script should do exactly one thing. So when you describe the functionality of a script and you use the word "and" in that description, then that's a sign that it should probably be split up. For example, this script could be documented as "This script spawns the stairs and moves the player and updates the ...

1

I found my mistake: The script was NOT in the "Editor" folder at first. Then, at some point, I moved it into the "Editor" folder. I didn't notice which effect this had. Now when I take a look at a game object which uses this script, I can see that it actually doesn't work anymore: After I moved the script from the Editor folder to a &...

Top 50 recent answers are included