New answers tagged

0

Some developers hate singletons, but the canonical answer is to make a single long-lived class instance into a singleton, so there is one instance which can be accessed from any other script. public class GameManager : MonoBehaviour { public static GameManager Instance { get; private set; } void Awake() { Instance = this; } } Then ...


2

Answer I figured it out: there's absolutely nothing wrong with changing the direction of your rigidbody's velocity. The problem was using transform.up to rotate the game object itself. I replaced that with rb.MoveRotation(rb.rotation + angle) and it's buttery smooth now. Takeaway In general, if there's anything I've learned from this project, it's that ...


1

I made a custom toolbar. I uploaded it in my github


0

in unity basically pooling means: instead of using Instatntiate() that makes new object in the scene that takes cpu performance to allocate, make all of needed object on the start of the scene and only enable and disable them and only make new object when all of you instantiated objects are active and are not ready to reuse. you can use a foreach or for ...


0

You could have a timer as class' member instead of a local variable in your coroutine. private float powerupTimer; private IEnumerator powerupCoroutine; private void OnTriggerEnter(Collider other) { if (other.CompareTag("Powerup")) { hasPowerup = true; Destroy(other.gameObject); powerupTimer += 5; if(powerupCoroutine ...


1

In the updatescore method you simply ask, whether isGameActive is true or not.


0

welcome the community. that is so simple. you need to define some flag for running of your game and instead of writing logic of start game in Start(){} function that is called on start of game object, you should call it for example on button press and make your update function that is called every frame only Work if a bool flag is True. i re-write your code ...


0

TLDR: Add the SerializeField attribute to the GameManager variable in the PlayerController, then reference the desired GameManager instance through the inspector. In the PlayerController class you have included a variable of the type GameManager, but you have not populated the variable with any instance of GameManager. Populating variables and referencing ...


1

In a case like this you would either want to make that a public GameManager gameManager or add a [SerializeField]above the variable and simply drag it to the slot to set it. If you would like to keep it private you could either use a Gameobject.Find(); or something like FindObjectOfType() to set that manager in Start() After assigning your manager when ...


0

Near Clip Plane It sounds like you've misunderstood what a camera's near clip plane is. The official unity scripting manual describes the clip planes as: Clipping Planes: Distances from the camera to start and stop rendering. Near Plane: The closest point relative to the camera that drawing will occur. These planes create the camera's view frustum. The ...


0

Here are the things I have had to do to solve this issue before: Make sure you have Visual Studio Code set as your editor in the unity preferences. Make sure you have the C# Visual Studio Code extension installed. Check the VSCode OmniSharp logs for any errors. Let me know if this helps.


1

Do your entities both use box colliders? When two axis-aligned box colliders collide, then there isn't really a single collision point but rather a collision line on which the colliders touch. Unity is supposed to return multiple collision points in such a situation. That's why Collision2d.contacts is an array and not a single value. But your code only ...


-1

hmm i have been working on a project for 4 years now, 4 years ago i put it aside, because there were too many bugs in Monogame. I continued the work 2 month ago, only to struggle with the exact same issue i did back then (4 years ago), it still doesnt work, and its still full of bugs and memory leaks. :( - Many of the bugs has been found years ago (2016), ...


2

First of all I recommend not checking the doorLockState and globalDoorLock state in the update method. That method gets called on every frame (which impacts performance) and is better reserved for functions that actually needs to be checked constantly. (Like player movement) Now back on topic you want to be able to change the lock state of every door ...


2

As the documentation says, The Unity scripting API does not expose direct WebSocket access itself. But you can access the native web browser API by calling JavaScript from Unity C# scripts. Create a JavaScript file which defines the functions you need and implements them by calling native browser functionality. Give it the file extension .jslib Put it into ...


1

I'm unable to reproduce the problem described in this question when using types that are derived from MonoBehaviour or ScriptableObject as shown above. Using the following code: public abstract class SomeBaseClass : ScriptableObject { public int baseClassInt = 5; } [CreateAssetMenu(fileName ="Derived.asset", menuName ="Testing/Some Derived Class")] ...


0

I share some code which will help you out: public float force = 5; public ForceMode forceMode = ForceMode.Impulse; private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.CompareTag("Enemy")) { Debug.Log("Collision"); health -= 20; //Check for death if (health <= 0) { ...


2

Its look like that you have not installed the "Hybrid Renderer" Package. When you want to convert Game objects to Entities then you have to also install "Hybrid Renderer" from package manager. Open up package manager from Windows -> Package manager. Enable "Show Preview Packages" from Advance tab. Then search "hy" then Install "Hybrid Renderer". Same ...


1

Thanks @Draco18s suggest , I think I Slove this problem , this problem is a about alpha value missing. So just choose the larget alpha. like this: half orginA = color.a; color = (val * (1.0 - color.a)) + (color * color.a); color.a = max(orginA,val.a);// choosing larger one


1

An IndexOutOfRange exception is an exception that is thrown when an attempt is made to access an element of an array or collection with an index that is outside its bounds (index < 0 or >= length of the array) You need to make sure your currentTexture does not go outside those bounds. Here is a solution to make the currentTexture loop (of value was ...


2

When you change scenes, the camera gets destroyed Because the camera gets destroyed (and the new scene has a new one) your cam variable no longer points to the main camera. You can detect this and do the appropriate thing, void Update () { if(cam == null) cam = Camera.main float dist = cam.transform.position.x * parallaxEffect; transform....


0

It depends on how your game works. Both of your leads are correct if you just need to know what tile is under the player. Between the two, again depending on your type of game and gameplay, I'd use the one using a Raycast. TL;DR: if you organize your grid objects in a linear way (from first to last) you could easily find the cell your player is on with a ...


1

Forces are directional, so if you want to decelerate an object by using rigidbody.AddForce, you need to do that with a force vector which goes in the opposite direction of the current velocity. The easiest way to obtain such a vector is by multiplying rigidbody.velocity with a negative value. For example, if you want to add a deceleration force which reduces ...


2

you can use NaughtyAttributes NaughtyAttributes is an extension for the Unity Inspector. It expands the range of attributes that Unity provides so that you can create powerful inspectors without the need of custom editors or property drawers. It also provides attributes that can be applied to non-serialized fields or functions. It is ...


0

Like it says. "You need to set variable cam in inspector". To do this: In Hierarchy panel right and click choose "Create Empty" to add a new Game Object and rename it as ParralaxController (you can give any name you want). In Inspector panel press Add Component and type Parralax then choose the Parralax script below. When this ParralaxController is ...


0

try smoothing it out a bit with something like Vector3.SmoothDamp() public Transform target; float damping = .05f; float followDistance = 2; private Vector3 currentVelocity; private void Update() { if (target != null && Vector3.Distance(transform.position, target.position) > followDistance) { Vector3 newPos = Vector3.SmoothDamp(...


1

If you use things that are Framerate Dependent (Update or things with deltatime) then it can cause this. If you do not want the routine to be framerate dependent then you can use WaitForFixedUpdate() or put the movement in FixedUpdate() These have a fixed timestep loop


0

Try updating you camera transformation in the MonoBehaviour.LateUpdate function.


1

A Hashset is a collection that can't be sorted and cannot contain duplicate values, making it ideal for checking for duplicates especially due to how values are stored in memory. It checks for equality first by calling GetHashCode(). Which is a method that all objects in C# implement, if you don't override it yourself it'll use the default implementation. ...


0

https://docs.unity3d.com/Manual/class-MonoManager.html in unity we dont Have such a thing. instead you have to change script running priority. for example you have many scripts that have Awake methods. just go to: Edit > Project Settings> then select the Script Execution Order just find you resolver script and drag it on top of others scripts. this way ...


0

Abstract chunks! You probably have a class handling these chunks, have it be the source of truth for your world, mine is called WorldHandler, I tell it to read from position x,y and it transparently gets the chunk I need and uses it. class ChunkHandler { // this is our "WorldHandler" private int[,] _chunks = new Chunk[ 16, 16 ]; // Use a ...


1

Are you aware of the PointEffector2D component? I believe that is exactly what this is for. See this tutorial (step 7). (Link directly to video)


0

You can't use the Unity gravity system for point gravity sources. As mentioned by the answer by Ed Marty, you can use the PointEffector2D component to create a point gravity source, but only if all your rigidbodies have the same mass. But you can also very easily build your own gravity system. Here is an example script for a "Gravity Source" component. ...


4

gm.GetComponent<Inventory>().AddItem(Instantiate(items[randInt])); On this line you instantiate a new GameObject on your scene, which happens before loading the new scene. You put a reference of that new object in the list of the Inventory (which is set as persistent during loadings). When you ask for a scene loading, all the content of your current ...


1

As DMGregory pointed out, you can make transform.Translate ignore the rotation of the object by passing Space.World as the second parameter: transform.Translate(Vector2.left * speed * Time.deltaTime, Space.World); However, you generally should not manipulate the transform of an object directly when that object also has a non-static and non-kinematic ...


0

When you have a question about how the Unity API works, please take thirty seconds to consult the documentation: public void Translate(Vector3 translation); public void Translate(Vector3 translation, Space relativeTo = Space.Self); Description Moves the transform in the direction and distance of translation. If relativeTo is left out or ...


0

I'm not sure what does a chunk actually contain in your implementation. I assume that these chunks are memory intensive, if you want to lazily load them. It seems to me that if you decoupled your logic from game engine content, you could easily load to memory and check a lot of grid spaces at the same time. This will require you to keep some kind of sparse ...


0

Collider boundaries extents do not scale with the Transform. The GameObject / MeshRenderer's role is to give a visual shape to your object while the Collider's role is to give it a physical shape in the Physics world. If one aspect (either visual or physical) changes it doesn't have an impact on the other one. I agree that the fact the Collider automatically ...


0

A common method to find out what kind of game object you are actually colliding with is to use collision.gameObject.GetComponent to find out if it has a certain component attached to it and then act accordingly. For example, if all enemies and obstacles in your game have a script Hazard and all the collectible goodies have a script Collectible, you can ...


1

I expect that the part you want to optimize is collision.collider.name.Equals("") because you used the Unity Profiler and found out that this particular line of code takes up an unacceptable amount of execution time (I would find that unlikely, though). You also might just want to find out if the other object is friend, enemy or neutral and consider the name ...


1

Moving on a single axis is just incrementing the value of the relevant axis in the position vector by the relevant distance. So just do (pseudo code here, because I'm not near my Unity machine) if (shouldMoveOnX(followerPos, myPos) { followerPos.x += step; } else { followerPos.y += step; } The only question is how to determine 'shouldMoveOnX' - and in ...


0

I checked each character value for the lines containing "--" and they did indeed have a third character with a char value of 13. Looking it up this translates to "\r". So, instead of removing "--" from the list I am now removing "--\r" from the list and this works now :)


0

First, we need to make an architecture decision: Where does the logic "key opens door" belong to? Is it a behavior of Door that it can be opened by Key? Is it a behavior of Key that it is able to open Door? Or is it something which belongs into neither class and should instead be encapsulated in an entirely separate InteractionManager which knows how each ...


0

Polymorphism seems to be what you're looking for. In the case you're describing, you could design your code to have a PuzzleManager object in your scene (that would inherit from MonoBehaviour), that would contain a list of Puzzle objects. The Puzzle could simply be an interface or a base class (if you're not comfortable with interfaces) with a unique ...


1

After trying several things it seems that it is a problem with version 3.7.1 of Monogame. I switched to Version 3.6 and the padding is gone. I will update this answer/question if I find the reason why 3.6 behaves differently then 3.7.1


2

I'm not very familiar with C# so most of the code will be pseudo code. You probably have to adapt it to work for you. You wrote in a comment that you were okay with using triangles instead of squares, so the example below is generating triangles and edge shapes. I also don't know anything about the coordinate system that you're using in your code, what ...


1

I am not sure if you have read the documentation or not on the matter but I would review here SceneManager The build index is the numbers to the right on your pic of the build settings so you have a choice of 0-12 to load by index. if loading by name you can load it SceneManager.LoadScene(scenename); or by index SceneManager.LoadScene(sceneANumber); ...


0

The other answer will work for your current need, but it will not work when you'll actually start using the timescale for purposes other than pausing the game, such as creating slow motion effects or when you'll want to debug and accelerate the process to attain certain events faster. The first thing to do is decide the rate at which your enemies spawn: you ...


1

just put this line of code on first line of function that instantiates enemies: if (Time.timeScale == 0) return; time scale basically work for objects Movement if you have used delta-Time in their movement function as delta time is multiplied with movement amount.


2

i think what you are looking for is async loading. async loading, just loads you scene in background and shows(runs) you scene anytime you want. https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadSceneAsync.html Smooth loading screen between scenes


Top 50 recent answers are included