#💻┃code-beginner
1 messages · Page 813 of 1
me or nuke?
you, the last message Faywilds sent
faywilds link is the route 💯
yeah didnt work
there is no onUnitCircle
but there is a sphere
and the sphere didnt work as intended
ohh i did not realise thats a new thing
There is you'd just need to update your unity editor version to 6.3 or newer
question: how do I backup my code if i try to mess with my code and want to go back if I break stuff? For mow i copy the script and if something happens i rename the copy to the original and delete the broken. I know theres something like git but i dont know how to use that or if it even works with unity
onUnitCircle is new, so if you're on an old Unity it won't exist.
Just use insideUnitCircle and normalize the result 🤷♂️
ah yeah, apparently that is rather new. in that case if you don't want a point on a sphere then just normalize the point returned by insideUnitCircle and it would be pretty much the same
i use 2022 unity
you can just sample x,z on onunitsphere right?
That'll give you a vector of length 1, and then you can multiply it by however big you want the circle to be.
If you need it to be 3D yeah
you use a version control like git
would onUnitSphere work but i ignore the z?
is there an human friendly alternative? im not good at using the terminal
git is not the terminal
Github isnt with the terminal, only one i've used but im sure the other versions also arent
that would not be the same
git cli uses the terminal, you can use git via other clients like integrated in your ide or with github desktop
git is just the underlying system.
oh right different random range
(are you referring to github desktop? that's not the same thing as github)
it would still need to be normalized even after dropping the Z so you may as well just use insideUnitCircle and normalize the result
yo guys, want a smooth camera in a pixel art game (as in having damping) but I do not want pixel snapping. I know Godot can do this somehow, but I don't know about Unity. I have tried just about every plugin/addon asset that there is, and they all still have pixel snapping. I know you can do imperfect pixel art or whatever, but aren't there downsides to it? If not, how do I use imperfect pixel art for a smooth camera? any help is appreciated bc i'm REALLY lost on this tbh
Is it not?
it is not
the website, repos, and account all lead to the same place though whats different?
github is a company/service for hosting and managing remote repositories
github desktop is a gui git client made by github
like this ?
well you've got the code there why not test it
cause i did and doesnt work lol
Inb4 it doesn't work. What is your actual goal with this random direction?
Because if it's to move the object from its current position to a random direction from its current position, this isn't that.
i want an obejct to only move like this
But you haven't explained what you're actually trying to do.
does vector.normalize() actually modify itself or does that return a value (im asking cuz idk)
You want the object to move around a circle?
and i want it to be random movement
instant change of position
no teleport as in change
You want it to pick a random position, a distance away from itself, move to that position and upon arriving, pickg another random position?
yes
but the radius isnt based around the object
around a fixed object
Sure.
-
Pick a random direction via insideUnitCircle and normalize it.
-
Multiply that value by the size of the circle you want (it'll be 1 by default when normalized)
-
Calculate the point to move to by adding that value to the position of the fixed object
-
Move your character to that point
-
When it arrives, repeat the process
normalize mutates, normalized returns a modified copy
dang i guess i was too slow 😔
@rough granite does that make sense? kinda along the same lines as google (search engine) and google chrome (browser) being different things
yeah yeah i got what you meant
cool, gonna keep that explanation handy for future questions
hi guys, so, I'm making a game for a project for school, and I'm going nuts over this, it is malfunctioning like crazy, can someone help me pls? The game starts on the main menu, and I press play, if I return to the main menu again and then press play again the character is nowhere to be seen, and when I change scenes the player does not change too, it was working and just stopped working. The console shows no errors and I started the project from scratch, just following youtube tutorials and altering it to what I wanted, I would really appreciate it if anyone who has time adopted it and helped me out. This are the videos of the problems mentioned
show relevant code
Do you have DontDestroyOnLoad on the player?
My guess its the player falls out of the screen and you forgot to set a starting position on load scene
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
public class GameStateManager : MonoBehaviour
{
public static GameStateManager instance { get; private set; }
[HideInInspector] public string spawnFromName;
[HideInInspector] public Vector2 playerPosition;
[HideInInspector] public int sceneIndex;
private void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
public void SavePlayerState(Vector2 position, int scene, string spawnName)
{
playerPosition = position;
sceneIndex = scene;
spawnFromName = spawnName;
PlayerPrefs.SetFloat("PlayerPosX", position.x);
PlayerPrefs.SetFloat("PlayerPosY", position.y);
PlayerPrefs.SetInt("SceneIndex", scene);
PlayerPrefs.SetString("SpawnName", spawnName);
PlayerPrefs.Save();
}
public Vector2 LoadPlayerPosition()
{
if (PlayerPrefs.HasKey("PlayerPosX") && PlayerPrefs.HasKey("PlayerPosY"))
{
float x = PlayerPrefs.GetFloat("PlayerPosX");
float y = PlayerPrefs.GetFloat("PlayerPosY");
return new Vector2(x, y);
}
return playerPosition;
}
public string LoadSpawnName()
{
return PlayerPrefs.HasKey("SpawnName") ? PlayerPrefs.GetString("SpawnName") : spawnFromName;
}
public int LoadSceneIndex()
{
return PlayerPrefs.HasKey("SceneIndex") ? PlayerPrefs.GetInt("SceneIndex") : sceneIndex;
}
}```
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
public class SavePoint : MonoBehaviour
{
public string savePointName = "LastSavePoint";
public Animator animator;
private bool playerInRange = false;
private GameObject player;
private void Update()
{
if (playerInRange && Keyboard.current.eKey.wasPressedThisFrame)
{
ActivateSavePoint();
}
}
private void ActivateSavePoint()
{
if (player == null) return;
var pd = player.GetComponent<Damagable>();
if (pd != null)
pd.Health = pd.MaxHealth;
var inimigos = GameObject.FindObjectsByType<Damagable>(FindObjectsSortMode.None);
foreach (var d in inimigos)
{
if (d.CompareTag("Enemy"))
d.Health = d.MaxHealth;
}
GameStateManager.instance.SavePlayerState(player.transform.position, SceneManager.GetActiveScene().buildIndex, savePointName);
if (animator != null)
animator.SetTrigger(AnimationStrings.interacted);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
playerInRange = true;
player = collision.gameObject;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
playerInRange = false;
player = null;
}
}
public static void SaveGame(Vector2 position, int sceneIndex, string savePointName)
{
PlayerPrefs.SetFloat("PlayerPosX", position.x);
PlayerPrefs.SetFloat("PlayerPosY", position.y);
PlayerPrefs.SetInt("SceneIndex", sceneIndex);
PlayerPrefs.SetString("SpawnName", savePointName);
PlayerPrefs.Save();
}
}
public class PlayerBootstrap : MonoBehaviour
{
[SerializeField] private GameObject playerPrefab;
public static bool playerSpawned = false;
public GameObject SpawnPlayer()
{
Vector2 spawnPos = GameStateManager.instance.LoadPlayerPosition();
string spawnName = GameStateManager.instance.LoadSpawnName();
GameObject existingPlayer = GameObject.FindGameObjectWithTag("Player");
if (existingPlayer != null)
Destroy(existingPlayer);
GameObject player = Instantiate(playerPrefab, spawnPos, Quaternion.identity);
DontDestroyOnLoad(player);
playerSpawned = true;
return player;
}
}
There's only one save point in the whole game?
using UnityEngine.SceneManagement;
public class MainMenu : MonoBehaviour
{
[SerializeField] private int firstGameSceneIndex = 1;
[SerializeField] private string firstSceneSpawnPointName;
public void PlayGame()
{
int sceneIndex;
string spawnName;
if (PlayerPrefs.HasKey("SceneIndex") && PlayerPrefs.HasKey("PlayerPosX"))
{
sceneIndex = PlayerPrefs.GetInt("SceneIndex");
spawnName = PlayerPrefs.GetString("SpawnName");
}
else
{
sceneIndex = firstGameSceneIndex;
spawnName = firstSceneSpawnPointName;
}
if (GameStateManager.instance != null)
{
GameStateManager.instance.spawnFromName = spawnName;
}
if (ScreenFader.instance != null)
{
ScreenFader.instance.FadeToScene(sceneIndex, spawnName);
}
else
{
SceneManager.LoadScene(sceneIndex);
}
}
public void QuitGame()
{
Application.Quit();
}
}```
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
using UnityEngine.SceneManagement;
public class ColorMove : MonoBehaviour
{
public int sceneBuildIndex;
public string spawnFromName;
private void OnTriggerEnter2D(Collider2D other)
{
if (!other.CompareTag("Player"))
return;
if (ScreenFader.instance != null)
{
ScreenFader.instance.FadeToScene(sceneBuildIndex, spawnFromName);
}
else
{
if (GameStateManager.instance != null)
{
GameStateManager.instance.spawnFromName = spawnFromName;
}
SceneManager.LoadScene(sceneBuildIndex);
}
}
}```
srry i didn't see it
how do I use it
you only have one save point in the whole game?
no, it is one per scene
why do you have two different scripts saving the player position?
open the site, paste the script, give us the link
idk, I lost track of it a while ago
well that sounds like a problem - you're not sure how your code architecture is supposed to work

You are supposed to be keeping track of it though
I know, I was
Still not seeing anything that says "when starting this scene, place the player in a platform" if you
I actually think you're probably just not using SavePoint.SaveGame at all and it can and should be deleted
i think it's here v
public GameObject SpawnPlayer()
{
Vector2 spawnPos = GameStateManager.instance.LoadPlayerPosition();
string spawnName = GameStateManager.instance.LoadSpawnName();
GameObject existingPlayer = GameObject.FindGameObjectWithTag("Player");
if (existingPlayer != null)
Destroy(existingPlayer);
GameObject player = Instantiate(playerPrefab, spawnPos, Quaternion.identity);
DontDestroyOnLoad(player);
playerSpawned = true;
return player;
}
``` though im not sure if the method is even being called
I think it should be in colormove
I think I need it for when I close the game and reenter no?
atleast it should do that
just call the other save function instead of having to worry about the up keep of two identical functions
so I should delete savepoint.savegame?
Guys, why does the gun and the background like glitch backwards and forwards and go from blurry to not blurry?
lets not post the same thing in multiple spots
i didn't know which place to post it in
@whole gulch Add some Debug.Logs() on OnSceneLoaded and SpawnPlayerRoutine (GameLoader.cs) it has many Debug.LogWarning s but none are being used?
Very suspicious, i googled it and some people report OnSceneLoaded doesnt trigger for them so maybe thats the problem.
then post it in 1 place and move if needed, don't crosspost please.
i gotchu chieftonus prime
CameraManager - https://paste.ofcode.org/UKHavNAmwAcvhZP57MDLmV
GameStateManager - https://paste.ofcode.org/SSbCSuk4EA7izVkjY2etTZ
PlayerBootstrap - https://paste.ofcode.org/4mf4CzZN8Fchj72cKUVkiv
GameLoader - https://paste.ofcode.org/BTZrZmpgQf6dGapz5zptHd
ColorMove - https://paste.ofcode.org/KjcYTSVdNSvxF6Tq9CjcKB
PlayerController - https://paste.ofcode.org/DGjVLmR9L8iNhiLhrWev3C
SavePoint - https://paste.ofcode.org/6pF59HMgLLWAJyneuUUYvm
PauseMenu - https://paste.ofcode.org/PdPrX5rjfC7twTQKNc2nCf
Attack - https://paste.ofcode.org/7gTgMzLLVqjHRZqCnWBsuH
Damagable - https://paste.ofcode.org/39fS6xZaCybLG7rc5DPLUjJ
ScreenFader - https://paste.ofcode.org/a9tcXYQQV3XMxFbkb5eW7z
TouchingDirectrions - https://paste.ofcode.org/36HDNT5hAAbDyAc84cnCWGD
there are most of the scripts, the ones that I think may have anything to do with the problems
ik there are too much, srry in advance
did the first 2 sites go under they both gave me a 502 error
I used the third one
what do u mean, srry
just add some to see which code is being used, for example if this is the one being used:
spawnPos = GameStateManager.instance.LoadPlayerPosition();
because there is no name, then the error is probably on LoadPlayerPosition
like this?
sure but also add some to the save and load methods to see the data that is being saved and loaded when they are being saved / loaded
i mean like like you add a
Debug.Log($"Saved player position: {position}"); in the save method and a Debug.Log($"Loaded player position: ({x}, {y])"); before the return new Vector2(x, y ; in the LoadPlayerPosition method
if (!string.IsNullOrEmpty(spawnName))
{
GameObject spawnPoint = GameObject.Find(spawnName);
if (spawnPoint != null)
{
Debug.Log("Loaded position from spawnPoint");
spawnPos = spawnPoint.transform.position;
}
else
{
Debug.LogWarning($"Spawn point '{spawnName}' não encontrado!");
}
}
else if (GameStateManager.instance != null)
{
Debug.Log("Loaded position from LoadPlayerPosition");
spawnPos = GameStateManager.instance.LoadPlayerPosition();
}```
something like this
whats não encontrado! :?
u think ~_~
yes
ahh
exactly
some of the commentaries are in portuguese
I really should start to be more consistent
well, I add it but nothing showed on the console
I tried to save the game, enter and reenter
oh so none of the code is being called
and change scene too
oh
oh no
I have 1 month to finish this and it is like, not half done yet💀
I'm cooked
did you add debugs to the OnSceneLoaded to see if at least that one is being called?
I added this
Also make sure you didnt turn off debug logs in the console
idk if it is right
and make sure youa actually placed the script, sometimes we forget and this one doesnt seem to be a static Instance so it has to be in every scene
yeah, does this appear on console?
when I press play and enter the game this appears
I placed the script in two other scenes to test it out and when I tried to switch scenes this show up on the console
ok, so the non-existing character when switching scene comes from a poor configurated vcam, I'm trying to solve that now
if u guys or anyone has an idea of what I can do to solve it or wants to help dm me pls
What is the issue
This has been going on for a while I don't know what the actual question is
here it is
and here are the (i think) relevant scripts
So, is the player actually in the scene? If so, what is their position and what is it supposed to be?
when I change scene I have seen that the player is on the scene and in the position that the game starts, it should be on the position stated by the color move, for exemple, it should spawn in the object SpawnFromHollow
and the vcam isn't working in any scene other the the first one
is there a SavePoint-Hollow transform in the Blue-Pre scene? you should add more logs or learn to use breakpoints
So, the player is just always in the scene, not spawned in as a prefab? What's supposed to be moving it when the scene starts?
i don't think so, i think there is a SavePoint-Pre-Blue
what are breakpoints?
isn't it colormove's job?
or gameloader?
or playerbootstrap, I think it is this one
You kind of fired thirty scripts out of the window of a moving vehicle so if you have code doing something you should probably share the relevant stuff because I'm not going to read every single script you posted
What specific function is supposed to be moving the player at the start of the scene
spawnplayerroutine inside gameloader
it should be this one
i'm sorry for the confusion
So, the player is a prefab, and they're a DDOL object. This means anything in the scene that referred to the player in the scene is going to get recreated without that reference when the scene reloads.
If you want the player to be persistent, you're going to need to ensure nothing in the scene is getting that reference set in the inspector anywhere
And what object has this script on it? You're subscribing in OnEnable, is this object itself a DDOL or is it in the scene? If it's in the scene you're reloading, the OnEnable is going to run and add another subscription to sceneLoaded
Also, this warning shows that there's no spawn point named SavePoint-Hollow, so spawnPos is not set to anything
that's cuz it shouldn't go to savepoint-hollow
it should go to spawnfromhollow on the blue scene
idk why it tries to go there
If you're getting that warning message, that's what it's looking for.
You're logging spawnName
If it's logging SavePoint-Hollow that's the value you have for spawnName
how should i set the velocity of my players rigidbody in a 2d movement script?
I think it should get the value for spawnName from the color move when it changes scene
Is it? Use logs to check.
Instead of thinking about what it should do, check what it is doing
Follow the breadcrumbs. See where spawnName comes from, and see if that value is what you expect. If it's not, see where that is getting the value, and so on until you find where it's becoming something you don't want
idrk how to use logs
You log a value, and then you read it
I am using some non mono classes with delegates; is there any easy way to unsubscribe when those objects are deallocated by gc?
or do i just have to be really really careful and do it manually
hmm though actually now I think about it this is a nonsense question because it wouldn't be being collected by gc if it is still subscribed
nvm!!!
guys is there a way to get the normal from an overlapsphere
Nope. You need a cast.
Is there some easier way of making a moveset without having a spaghetti of if (Input.
Hey can anyone else tell me why c# isn't showing when I am trying to script something or is MonoBehaviour do the same thing?
Monobehaviour is a vanilla script with a bit of stuff in it that uses C#, so yes, use monobehaviour. From what you said I think it is pretty much the same thing you're looking for.
ok sounds good thank you
Just remove the MonoBehaviour inheritance and the default methods, then you're good to go . . .
Are there any resources on where to learn how movement scripts are written with kinematic rigidbodies?
I'm trying to make this function in my game where when the drill (the square looking thing going towards the capsule) hits the mole (the player) it reloads the scene, but for some reason nothing is working when the mole goes towards it and is in the box collider.
Google + middle school physics textbooks.
First try to use Debug. Log in OnTriggerEnter to output a message and confirm that the collision event method has been called. Additionally, if both of your objects have IsTrigger enabled and both have non kinematic rigid bodies with simulation enabled, then OnTriggerEnter should be callable. The OnTriggerEnter method is a method that can be successfully called as long as there are triggers in two game objects
In this scene, both the Player and the Cube have a non kinematic rigid body with simulation enabled. The Player has gravity disabled and is waiting for the Cube to collide. They both have a collider, and as long as the collider of a certain game object is used as a trigger, the OnTriggerEnter method in the script on the Cube will be called
only 1 object needs a rigidobdy aswell
yeah, just cuz his scene he used 2 rigidbody, so i use 2 to show him how it works
i mean, that would explain the laws of physics. but that probably wont help solve collisions, solve slopes and what not 🤔
You don't need to solve collisions. There's unity api for that, like casts, overlaps and rb sweep tests. These can be found in the api docs. Other than that, just Google. There should be plenty of tutorials and open source projects that can serve as a reference.
Well you would still need to solve collisions because casting rays, spheres, boxes and what not wouldn't make it so I don't be inside objects, it would just cast a ray. And then it's also about where to cast a ray from. Center? Top? Bottom? All? Maybe even more in-between? All these questions feel like it's a complicated topic. I'm interested enough to dive into that rabbithole which is why I'm asking if there's any resources which I could read into. I also considered using Godot's CharacterBody2D as a reference implementation to see how they deal with their collide_and_slide algorithm.
What you're asking is basically how physics engines work. To put it simply, you have 2 options:
- detect collision ahead of time with rays/casts and adjust the object velocity such that it doesn't overlap with the hit object.
- detect and overlap after the collision happened, then calculate a depenetration velocity/displacement and apply it to your object.
If you want to learn down to Avery deep level might want to look for resources on physics engines independent of any specific game engine.
Mhh that makes sense. Sooo, are there any resources I can look into?
Not sure if I can find some books, so maybe that. But from the kind of your responses I'm judging there's no well-known or popular thing.
I don't know if there are any "good" resources. There are probably plenty of resources in general if you Google. This is not really something every unity developer has a sticky note on their fridge for.
I see, thanks 😊
Maybe I should also just focus on actual gameplay mechanics and how to deal with them with rigidbodies though
I know that I definitely want to recreate some behaviour with a kinematic some day but maybe I don't have to deal with it right now just to keep motivation on game dev in general 😊
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
so you specifically ask about physics for a character?
If you want to simplify it to that, yeah.
that's a very different topic from general physics
also pita
google rigidbody character controller or something
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class RollRight : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
private bool isPressed = false;
public GameObject Player;
public float rollSpeed = 25f;
private float rollInput = 0f;
private float rollAcceleration = 2.5f;
void Update()
{
if (isPressed)
{
// Smoothly accelerate toward forwardSpeed
rollInput = Mathf.Lerp(rollInput, rollSpeed, rollAcceleration * Time.deltaTime);
}
else
{
// Smoothly decelerate back to 0
rollInput = Mathf.Lerp(rollInput, 0f, rollAcceleration * Time.deltaTime);
}
// Move the player forward
Player.transform.Rotate(Vector3.back * rollInput * rollSpeed * Time.deltaTime, Space.Self);
}
public void OnPointerDown(PointerEventData eventData)
{
isPressed = true;
}
public void OnPointerUp(PointerEventData eventData)
{
isPressed = false;
}
}
it really is annoying to make a character to properly interact with physics
yloing with CharacterController component is good enough for many if not most cases tho
which is not obeying physics but kidna interact with it
I try to roll an object, but my coding seems off, the object roll too fast. Do i must delete the rollSpeed on the rotation part?
CharacterController is only in 3D.
Ignore the // note
character physics in 2d is also a way smaller niche
That's why I'm currently rolling with Rigidbody2D with no gravity and frozen roztation.
at that point it's only really physics in regards to referencing unity's "physics" system. most of what you do is gonna be closer to smoke and mirrors than stuff comparable to real physics
Well, character controls are usually still gravity-restricted, collision-restricted and so on, even in 2D. And for that in Unity the only option is a rigidbody unless you want to do manual physics checks.
oh sure, im pointing this out so you might have a better idea of what to specifically look for
Yeah, for sure.
this might help https://gmtk.itch.io/platformer-toolkit
interactive game to showcase what goes into a standard 2d controller + source code accessible for nity grity
That looks cool, will look into it, thanks 
googling/asking about 2d character controllers will get you further than how your initial question was phrased
best of luck
I wonder if anyone ever found a code (if it's mathematically reasonable even) to have a Quaternion.SmoothDamp with a limiter and at the same time using spherical motion (like if I get it right if you go with Eulers the path would be not ideal)
trying to figure that out lead me to.... robotics forums? I am too silly
also am I getting it right that in modern animation software interpolation is not spherical so the path inbetween keyframes is not ideal?
Well, I mean, understanding how to code movement with a kinematic rigidbody (including collisions and what not) would be a good start because from there you can probably incorporate stuff like slopes and so on too.
Or at least is a start that can transition into it.
are you sure you want a kinematic rigidbody
I mean idk how to properly do that
I would try to use a frictionless no bounciness no gravity non-kinematic rigidbody
Yeah, thats what I am using right now. I was just curious to see how stuff works if you do it manually, as I don't know it either 😄
Speaking of which, is it a good idea to do the frictionless thing as the default material or assign it separately for each? Feels a lot more predictable if everything has no friction from the get-go.
slopes... you just check the angle of normal below you and slide (FSM of movement went from full control to something like sliding in a manner you like) if it's too bad
I mean that's what I would do
also to move along slopes without slowing down I project movement force onto normal
might be terrible for complex rough terrain
are you sure it's what you want
I suspect you need some objects with zero fricion
and everything else having it
friction combine mode minimum works alright
so some things are slippery and controlled by the world while some ain't
Yeah but what should the default be
I think my character stuck to walls too much when jumping against it which I solved by making the player AND the wall have no friction
So I feel like the default being no friction would be better so I adjust it if I need some things to be stickier
what's the difference between average and mean 🤔
i have no idea 
Hello !
Im trying to get the healthbar. UI_healthBar, but for some reason, unity wont let me reference it, instead recommending that is use Ai_healthBar that simply exist nowhere in my program.
Do you know why such a issue happen ? Thanks !
Do you actually have a ui health bar class?
Or struct.
check if script name matches class name just in case
OOOHHH THATS WHYY !!!
always thought it only used the script's name 😅, still learning i guess. Thank you !
Script name is just the file name. It doesn't really matter in code.
Alright, thanks !
how do i send code blocks
or can i send screenshots
private void Start()
{
StartPosition = transform.position;
}
private void Reset()
{
if(ResetAction.IsPressed())
{
Debug.Log("Reset !");
transform.position = StartPosition;
}
}
wrap them in
```cs
// CODE
```
Your reset function is never called anywhere, I think you want to name it update (which is automatically called every frame)
also you want WasPressedThisFrame instead of IsPressed or it will fire every frame as long as you hold down your ResetAction key
{
// Ground Check
grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, whatIsGround);
MyInput();
SpeedControl();
CheckForWall();
StateHandler();
// Handle Drag
if (grounded && !isDashing) rb.linearDamping = groundDrag;
else rb.linearDamping = 0;
// Dash Cooldown
if (dashCooldownTimer > 0) dashCooldownTimer -= Time.deltaTime;
//RESET Player position to starting positiion
Reset();
}
i didnt send entire script cause its too long
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
So what could still be wrong:
- ResetAction is not assigned
- ResetAction has no key assigned
see it is
oh sorry didnt see the screenshot
whats the difference between the two
no problem
will it work if i assign it in editor but not code
Hey, guys! I have an issue with a trigger box. For one reason, when my player enters the trigger box, it doesn't execute the code that I have written. I have tried to use debug.log to check if its actually executing the logic, but no. Here is my code:
{
if (other.CompareTag("Player"))
{
lanternLightFlickeringTriggerCollider.enabled = false;
StartCoroutine(FlickerDelay());
}
}
private IEnumerator FlickerDelay()
{
float elapsedTime = 0f;
while (elapsedTime < flickerDuration)
{
lanternLight.intensity = Random.Range(minFlickerIntensity, maxFlickerIntensity);
elapsedTime += 0.05f;
yield return new WaitForSeconds(0.05f);
}
lanternLight.intensity = 0f;
}```
I can't know without seeing the full code, but I assume your ResetAction is just a serialized property?
So to confirm, it is not even going into the OnTriggerEnter method?
yes its a private variable serialized. i have assigned it both in code and in editor
and both are same keys
r for reset
Can you show the full code and a screenshot of the inspector?
yes
Sorry, when I did debug.log I saw the message player is on trigger box so it actually executes but it doesn't apply my random values of lantern light intensity
Its by default with a value of 2 that I have
even though I have declared the variables for min and max, as well as flicker duration
private float minFlickerIntensity = 0f;
private float maxFlickerIntensity = 2f;```
test
did you maybe accidentially override the value in the inspector with 0 duration?
No because flicker duration is private
let me send you a video clip
use one of the links above in the message I sent or https://share.sidia.net
Paste your code and share it with others.
of what is actually happening in depth
If you know how to debug I would do that or put a bunch of Debug.Log that outputs current values of things to check if they actually run and change
using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;
[RequireComponent(typeof(Rigidbody))]
do your other input actions work?
because you are not supposed to compose an input asset like that usually 😄
you are better of actually creating an InputActionAsset and assigning that to the player
so it still dont work
you are also missing the inputactiontype button
wdym in old input system we had no other choice but to give axis name in string
for the reset action
yeah but this is the new input system that was created to fix those issues 😄
Hey! I spread out like almost everywhere debug. log and what I have noticed is that, the lantern intensity is actually changing for 2 seconds as expected but I dont see it change in the inspector and visually at all XD
even when adding the InputActionType in code?
are you sure you assigned the light in inspector / getting the right light?
you know maybe because I am using animations at one place for my lantern light?? Maybe animation actually affects how it works, when player enters the trigger box. Oh, I think thats the reason bro.
Because I have an idle animation for my light
if you are animating the intensity value it would override it, yes
which keeps my light at 2 by default
even if you are not changing it, but having a keyframe set it to 2 would block external changes
though that should be easy to fix, you can manually delete the keyframes of intensity from the animation
So probably I am going to create this flickering effect via code like I did and yes I am going to delete the keyframes and the animation for the flickering effect.
Hey guys !
I got the error NullReferenceException: Object reference not set to an instance of an object
When i double click on the error, it brings me nowhere. I checked : Both my players and my enemy has all their option correct.
Do you know what it could mean ?
⚠️ the error is displayed even when i dont start up the game
As for the code, here is it :
a powerful website for storing and sharing text and code snippets. completely free and open source.
Unless you wrote some editor script, usually messages about Edge.WakeUp are false positives. Try restarting the Unity Editor?
😅 thank !
Hey, guys! Can somebody explain please, what yield return null does actually? I was just wondering, in which cases do I have to use yield return null?
I have heard it waits for the next frame to proceed but cant understand the use case of it.
When and why to use it?
it basically returns nothing and keeps continuing the code. For example when you are waiting for a request or initialisation or what not, you could yield your async method and continue as soon as the check is done or aborted.
I can't undertand it bro, I mean I know what yield return new WaitForSeconds does but still cant
It means "wait one frame then continue" when used in a coroutine
Yes but why to wait that one frame?
For example if you want to do something every frame in a coroutine
You could put it in a loop
something is happening internally in the memory or what exactly?
Not sure what that question means
while(myManager.isNotThereYet)
yield return null;
basically means, wait for something before using it for example. This way you can "pause" methods until everything is set up. Just one example
Surely you've used Update a lot? Update does something once every frame. If you want to do that same thing in a coroutine, you can do it with a loop and yield return null
your async method runs until its done. If you want to pause it, you gotta put it in a loop of doing nothing basically
The Unity engine sees that you yielded null and says "ok I will continue executing this coroutine next frame".
So, I can think of it "Wait for something before using it"?
It's literally just waiting one frame it's not that deep. There are infinite reasons you might want to do that.
that was just the example in context. The line, you were asking about, is just, wait one frame of execution then keep going in code, what ever that is.
so instead of seconds its frame right thats the difference from yield return new waitforseonds?
Yes
One frame...
you are making more out of it than there is to that topic. Do not overcomplicate it in your head
I just wanted to really understand where we use it?
Whenever you want to wait a frame in a coroutine.
It can be but probably not
and why
That's likely more time based
Although you may still use it there and set the brightness of a light based on an animation curve
So yes it could be used there
The most common thing would be smoothly animating the position of an object over time. To do that you need to set the object position once per frame
Same way you'd use Update usually.. but in a coroutine
seek for different homing missle approaches lead me to some github and stuff and...
am I not getting something or this code shouldn't work?
void FixedUpdate(){
float navigationTime = (target.position - transform.position).magnitude / speed;
Vector3 los = (target.position + targetRb.velocity * navigationTime) - transform.position;
float angle = Vector3.Angle(rb.velocity, los);
Vector3 adjustment = pValue * angle * los.normalized;
rb.velocity = rb.velocity.normalized * speed;
var target_rotation = Quaternion.LookRotation(adjustment);
transform.rotation = Quaternion.RotateTowards(transform.rotation, target_rotation, turnRate * Time.deltaTime);
rb.velocity = transform.forward * speed;
}
like, LookRotation only care about a Vector direction, am I getting it right?
pValue presumably meant to adjust leading
I mean the code does work... kinda.... not sure that leading works
Hello !
I want the player to shoot, and i want to pass the projectileSpeed value to the projectile (with various other values). The player has different shoot so i cant really ignore that. But i have this error, do you please know how i can fix it please ? Thanks !
I'd suggest to go over C# basics. newSpawnedObject is not an object of your PlayerProjectile type.
Trying to read the writer's mind, I suppose the plan was to use
Vector3 adjustment = Quaternion.AngleAxis(pValue * angle, Vector3.Cross(los, rb.velocity)) * los.normalized
PlayerProjectile could be GameObject, but GameObject is not PlayerProjectile
you should type the prefab field and the result of Instantiate as the desired component type instead
you can instantiate something as a MonoBehaviour instead of GameObject?
Yes
I was getting this component for nothing all this time
Yes
a lot of the time you generally don't need to/shouldn't use GameObject as a serialized reference or for passing around
since you generally care more about components than gameobjects
Hi need help with a couple of things...
Im pretty sure I can make the. Ui with udon, but cards in a 3d plain field with shuffling is kinda difficult and can't find any videos or assets to help with it x.x
So far I have been using udon unity ._.) because it's for vrchat
!vrchat
Join the growing VRChat community as you explore, play, and create the future of social VR! https://discord.com/invite/vrchat
And quest version
Banned
Idk why
Still it's unity. So it should work anywas
Udon is just an, hehe, addon
Then it's going to be difficult for you to get your question answered there
You're probably not going to find much help with their SDK here.
Probably not but the question asked is super vague anyway
God knows what happens in the vr chat server
the people who are able and willing to help with vrchat would be in the vrchat server 
But it's unity no?
I mean I can also start asking guides for Unity games here in that regard
what question you got anyway
"cards in a 3d plain field with shuffling is kinda difficult" like... how does that relate to Unity
"Udon is a programming language1 for VRChat worlds. Scripts can interact with scene objects, players, synced networked variables, and more. Udon makes your world come to life!" ugh welp yeah you are out of luck
asking about it here is about as useful as asking guides for a random Unity game
People here don't know what is and is not possible in VRChat. You can ask your question but if you get an answer you can't use we can't really do anything about that.
This is why you should ask it in the Udon section of the VRChat server. They're familiar with the restrictions of the language and can actually answer you
Oh well that makes sense
Yeah well both udon banned me after asking such question and vrchat idk why they banned me x.x
Like literally the only thing I typed in the udon discord was some help with stuff and fell asleep, then bam banned like wth
That's something you'd need to ask them
rules saying you only can do that at proper channels?
Can't break the rules if you don't know them
no, you can do that
besides as I checked they shove "read rules" as one of non skippable things on joining
Hey guys. I'm trying to make a 2D game like Super Mario but its not working out great. Right now I have the Movement set up, an Inventory but not the actions to get collected items into it, and thats where I'm stuck, I followed a video to help me make scripts so I could grab items but Its not working. The item just rolls away. And if I make it kinetic (so it doesnt move) I can literally stand on it like an object and it never gets picked up by me. Also tried activating Boxcollider2D --> IsTrigger ON but then it fell through the ground.
This is the video: https://www.youtube.com/watch?v=e7-EJd5dQgQ
Please Pm me if you could help. Id be reallllly greatful. This is for a school project.
"your honor i'm not guilty of theft, i don't know the law"
we don't do DMs here, sorry.
it sounds like you might want to temporarily control the other object when you pick it up
Hello ! My game is crashing because one canva (prefab) doesnt have the camera. But i cant drag and drop the camera to the prefab. (because it's not on the list)
I tried putting one prefab and the scene, setting putting the camera and then Apply changes (overrides) but the "camera" field is still empty. Same if i try to create a new prefab with the camera put...
How can i avoid this problem please ?
its alrighttt
What do you mean "temporarly control" it? It just needs to get picked up .
you can't reference scene objects in a prefab, since the prefab isn't in the scene.
are you instantiating this prefab at runtine, or do you already have an instance in the scene?
well, you have to actually pick it up?
it rolling away just sounds like you're walking into it
It just needs to get in my inventory at the end.
Yea, when i walk into it.
so remove it from the world when you pick it up?
im confused what the issue is here
is the issue that the object is solid?
or that it's simulated by physics?
Basically when I toch the object It needs to get "picked up" and dissapear, and later go in my inventory that I set up but I'm not that far yet. Anyways, when I touch the object it just slides/rolls away and doesnt get picked up or destroyed.
Don't think so... I've never coded before, this is my first time. Im a complete newbie following a youtube tutorial.
The object also has BoxCollider2D and ridgidbody2D if thats what you mean.
and do you want the object to be completely static, or what exactly?
I already have an instance in the scene ! And okay !
assign the camera to the instance in the scene then
Yeah, static (just be on the ground) and when you step to it (touch) it gets picked up and dissapears from the world. And later placed in your inventory but thats another tutorial video.
Dont give it a rigidbody then
Only one object in the collision process needs one and if the player has one the object wouldn't
Or if the player doesnt have one for whatever reason give it one but make it a kinematic/static (say kinematic cause i dont remember if static has collision detection)
Just tried it, now It just doesnt move at all and I still cant pick it up.
You just said you didnt want it to move, bruh
Yeah, but It still needs to be picked up and when its picked up destroyed
Is the handling of position when being picked up done through code? Or from collision?
I'm so sorry but I totally dont understand what you mean... I made 2 codes, 1 called Item and another InventoryManager.
This is the 'Item" code:
And the InventoryManager:
I put the "Item" code into the item I wanted to "collect"
Neither of these have anything about moving when picked up ~_~
This is literally what the video: https://www.youtube.com/watch?v=e7-EJd5dQgQ Told me to do...
Right im not watching a video but that isnt my problem you talked about how not having a rigidbody makes it so when you go to pick it up it doesnt get physically picked up but neither of the two codes you have; have anything about controllering it's position when picked up
Oh alright, thanks for trying to help tho!
I mean you are the one not giving enough information
One minute you are telling me you dont want something to move then the next you are
Oh I'm sorry for that. The problem is that I'm completely new in the coding thing and dont know how anything works.
The thing is that it doesnt matter if it moved or not. I just need it to be collectible.
Like the coins in Mario Bros
Then the second thing i gave the first time should work
Add the rigidbody back but make it kinematic
Oh alrightttt!! thanks!!
Did a code without just following a tutorial
Feels good 
Hi
I'm trying to crack the Granny Legacy Il2cpp
Unofficials
Decompilation is not allowed here
1 ,2and 3 are old
Well the Granny 2 is better than all
I think the first one and second are the best
and third
sorry
I really want to contact the developers of the game
uhh this seems kinda off-topic...
probably thats what I am going to do cuz I would like to collaborate with them
Also this is not a social server, if you want to talk about the games take it to DMs
This is a new remake made by OmGi.
It is horror game channel of Granny.
how can i make my object face another object
when i try to use the LookAt method x and y are the only modified rotaions and it causes it to disappear
is this in 2d or something?
it disappers because it use the forward axis which is z in 2d
LookAt makes the forward vector point that direction, but you need the forward vector to be perpendicular to the camera in 2d
how to do that
just don't use LookAt
change the up/right vector of the transform instead
provide it a direction vector
(depending on which vector is the "forwards" of the object)
how is that done im so lost lol
transform.up = newDirection
and the newDirection is a vector of the targeted object right?
to
transform.up = new Vector2(center.position.x,center.position.y);
this line of code is not working
what is the error?
transform.up = (transform.position - center.position);
This worked for me
what was the problem is...
i was chaning position after rotating
that's the opposite direction
didnt pay attention lol
i put center first right?
using base square so didnt notice
yes, the direction is the target position relative to (ie, minus) the current position
quick question
for a towerdefense
do yall recommend Rigidbody movement or vector movement
performance wise
if you want proper collision detection and physics such as gravity etc, you´d have to use a rb
What do you mean by vector movement?
transform.position method
Ah, teleporting using the Transform component. If you're planning to roll a ball or fly a rocket, RB would simulate those pretty well. If you're only needing gravity and some complex or strict movement system, you could opt for a kinematic rb and implement the moving yourself with the kinematic method.
Do you want physics or teleportation
i just want straight line movement
Well, do you want physics or teleportation in a straight line?
It's not really a performance question, it just depends on what you need
If you need units to push each other then you probably want to use a dynamic rigidbody
But for a tower defense I'm not sure if that's needed
yeah i dont want them to push each other
ill stick with MoveTowards for now
i have a question
lets say there are lots of objects and i want to print the name of the closest one within a certain range
i thought of making a list and putting all the objects within that range and compare who is the closest to print the name of it
is this the proper approuch or is there a simpler method
I'd say the simplest is just to compare the magnitudes of the distance vector for these objects
and how can i keep track of them?
Wdym "keep track of them"?
the magnitude of all the objects within that range
I get the Error Message: MissingMethodException: Method 'PlayerController.OnMove' not found. when Trying to use Unity's New Inputs System
this is how I set up my code:
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
public float movementSpeed = 10.5f;
public Rigidbody2D rb;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
}
public void OnMove(InputAction.CallbackContext PLEASE)
{
Debug.Log(PLEASE.ToString());
}
}
WHen you're using Broadcast Messages mode on the PlayerInput component, there should be no parameter or only an InputValue parameter,
the CallbackContext parameter is wrong
Vector2 distanceVector = target.position - transform.position;
but that only tracks one doesnt it
ill have tons within that range
Yes, I know. That was just for getting the vector itself. If you need both the vector itself and the distance then you can call Vector2.magnitude()
What you can probably do is have some circle or sphere around the player and any of a specific object that is within said circle you track the distance
Oki but when I test it out while It was working it only gave me back inputvalue
when it should be -1 or 1
How do i return the object with this??
You can reference a specific tag and assign the appropriate tag for the objects
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Physics2D.OverlapCircle.html
It returns a collider.
im reading them rn
I mean the collider2d
how can i use that to return the object
i just refer it o it as var name.gameobject?
The circle itself is a collider. Then just use collidername.CompareTag("Tag name")
enemy isnt getting assigned reason why?
For example
Collider2D circ = Physics2D.OverlapCircle(transform.position, radius);
if (circ != null && circ.CompareTag("Object") { /*do something*/ }
Then assign the tag "Object" to the objects you wanna track
is the object you are trying to find on either layer 2 or 3?
but i specified it to be layer 6
Tags are better than layer imo anyway
no, you passed 6 as the layer mask, which is 0b110 in binary, or a mask for layers 2 and 3
which is a lyaer i made
it's literally not faster nor cleaner to use tags instead of a layermask
Faster to code (my example), ergo its cleaner
Rather than passing layermasks for the overlapcircle
it's literally more clutter, and it is easier to just expose a LayerMask variable to the inspector and pass that to the overlap circle call than it is to use a separate tag check
What if it finds two objects, returns the first one, and that one does not have the tag? And the second one actually has, but you never get to check it
this is such a weird way of declaration
no, you just don't understand what bitmasks are
https://unity.huh.how/bitmasks
A bitmask is a representation of many states as a single value.
well i made a var for layermask and assigned it manually in editor and works
Check each collider and compare tags
overlapcircle is returning a single one though
It's the same with layermasks
it's literally not. a layermask does the filtering as part of the physics query, and not separately after the fact
Typically you use a LayerMask from a serialized field or get it witih LayerMask.GetMask().
LayerMask casts (converts) to int
so its just a binary counter?? and the number i give is the co-existing number of the binary formation?
Yes, I know. But if you're filtering for a specific type of object why would you filter for a specific layermask in the first place
No denying that it can be useful but idk if that's necessary here
because you want to only find specific objects so those objects should be on a specific layer
so if i give it 9
ill get the first and the fourth layer? am i correct
You can check colliders and just assign the appropriate tag for the object, though?
so you create extra work for not only yourself but the runtime. and you somehow think that is cleaner and faster?
It's faster to write and unless you have a shit ton of stuff the performance gain is negligible
is it possible to remove a value from a list? cause in most lists and programming languages they dont allow deletion of a value
if it is a list and not an array then yes
It's not. Tags are hashed strings which are compared for equality. Layers are bitmasks done with boolean operators and thus require only a single CPU cycle to compare instead of multiple function calls
They do
Instead of using numbers, make a LayerMask variable containing the layers you want
it's literally not faster to write, that's the whole fucking point. you are writing an extra check, as opposed to passing a single extra argument. that's the definition of not faster
i did
but to understand it is what i said correct?
read the page i linked about how bitmasks work to understand them
It will get you layer 0 and layer 3
OverlapCircleAll?
OHH yeah i forgot we start 0 not 1 my bad
so what i said is partially correct
so now you're using a different method and still writing an extra check
Why use tags when you can use a layer mask
my whole point here was that comparing tags is in no way faster or cleaner than just filtering the query using a layermask first
Fair enough
I thought the setup you were suggesting was
Assign tags for objects --> then assign the layermask for the object --> filter layermask --> comapre tags
My bad
nobody said "use binary assignment" whatever the hell that is supposed to mean. we explicitly said to expose a LayerMask variable to the inspector and use that
Oki then when Should CallbackContext be used?
When subscribing to an event in code instead of using the PlayerInput component
When using Unity Events mode on PlayerInput or when manually subscribing to the events in code.
quick question
when i remove a value from the list and will the ones above it go down by 1??
the indices of all the other elements after it will be reduced by one yes. They shift over
thank you
that is why List.Remove is an O(n) operation and the larger the list, the slower the operation will be when removing things nearer index 0. though for the most part you won't really have to worry about that so much
Just out of curiousity is there a way to reduce the time complexity
of List.Remove? no. Lists are just arrays where things move around sometimes (notably when you insertat or remove)
I meant more generally if you have a set and you wanna remove an element from said set
anything after the InsertAt or Remove(At) call needs to be shifted up/down appropriately which is where that time complexity comes from
If it's ordered you can do a binary search but... it'd have to be ordered
If you find a way to, there's probably a PhD in it for you
If you don't care about the order of the elements you can use the RemoveAtSwapBack approach - where you take the last element of the list and put it in the removed slot, and therefore you basically are always removing from the end of the list which is O(1)
But often with a list you care about the ordering
Ooh pretty cool lol
but if you care about ordering and don't want any gaps, you can't help it
another approach is basically nulling the element out instead of removing it - but then the index of the list elements gets weird and you have gaps you need to skip over when iterating
so.. .everything is a tradeoff
O(n) isn't really a big deal anyway to be fair unless you have TONS of objects, in which case other optimizations should be at play regardless
this is why there are many different types of collections and using the right one for what you are doing is important.
if you only ever care about what was most recently put in, you should use a Stack, if you only care about the last object put in then a Queue, if you want something you can index into and resize as needed a List, and a fixed size with indexing an Array, etc
no, it's a list of booleans
is there away to change the values of a vectorn into a whole number??
Are there other methods where it's still O(n) but in practice it's faster?
so i can compare which is bigger
why do you need whole numbers for that? you do know the comparison operators work for floats, right?
to compare which vector is "bigger" you usually want to compare their magnitudes
that's the "length" of the vector
remove from tree has a complexity of O(log n)
remove from hashset has a complexity of O(1)
otherwise it's not clear to me what you mean by "which one is bigger"
i just meant like one number not multiple values lol
yes take the magnitude
(that's not what whole numbers are btw, whole numbers are integers.)
so this is a correct statement
and if you just want to know which one is better - you should compare sqrMagnitude
then yeah, use the magnitude or sqrMagnitude if you want a slightly smaller performance impact
realised to late yeah
I don't know if this is correct because IDK what you're trying nto test with this statement
closest object in a list
then no, it's not correct
Then use the distance method instead
You should be doing Vector3.Distance(A, B) and comparing the distances
what you're doing right now is not right, no
subtract the vectors and get the magnitude of that. or just Vector3.Distance which does all that for you
a - c > b - c is the same as a > b. you're just comparing the magnitudes there, so just whichever is farthest from the origin
subtracting position vectors essentially changes the origin point
Yeah, exactly. One point with your code is that it only subtracts the magnitudes which doesn't take direction into account which is important for this case (Talking to @supple flume here, just backing you up)
what abou tthis
yes but you can optimize your code to do fewer calculations than this
but it's correct
how so
i feel like a few sqrts is worth the readability here tbh, unless this is a hot codepath
pretty sure it's in a loop in update so pretty hot
its in void Update yes
ah. just got here, mb.
something like:
float closestDistance = float.PositiveInfinity;
Transform closestEnemy = null;
foreach (Transform enemy in enemies) {
float distance = Vector3.Distance(enemy.transform.position, transform.position);
if (distance < closestDistance) {
closestEnemy = enemy;
closestDistance = distance;
}
}```
in a loop
more readability hell yeah
yes also that
ah, i see
having very long lines with lots of functions etc is hard to read and often less performant because you tend to not be using intermediate variables
i was missing a lot of context lmao
I might add that you likely don't want to update the target every frame anyway. It's unnatural, chaotic and can be jittery if boucning between targets
For example doing it a few times in a second usually works
should this work if i replace my forloop?
fwiw though this can probably be moved to FixedUpdate since it's not like physics is updating between FixedUpdate calls anyway, and this seems to be a TD game so the towers probably aren't moving their positions either, so the OverlapCircle call would be returning the same information for however many frames between FixedUpdates anyway
cause i just realised this doent work cause it will only loop once
yes approximately but I haven't seen your full code so I can't tell for sure if this syntax is all correct
why would it only loop once? is size just a constant 1
this enemies.Add(...overlapcircle..) thing you're doing looks really fishy to me
and yeah where does size come from here?
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class Raduis : MonoBehaviour
{
public Vector2 vector;
public Transform center;
public LayerMask mask;
public float size;
public Collider2D closest;
public List<Collider2D> enemies = new List<Collider2D>();
public float rot;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//if (Input.GetKeyDown(KeyCode.Space))
//{
//vector = Random.insideUnitCircle.normalized * 2f;
//Debug.Log(vector);
////transform.position = vector;
//}
if (!enemies[0])
{
closest = Physics2D.OverlapCircle(transform.position,2,mask,0,6);
enemies.Add(closest);
}
if (enemies[0])
{
enemies.Add(Physics2D.OverlapCircle(transform.position,2,mask,0,6));
for(int i =0; i < size; i++)
{
if(Vector2.Distance(closest.transform.position,transform.position) > Vector2.Distance(enemies[i].transform.position, transform.position))
{
closest = enemies[i];
}
}
}
}
}
this is the code
Don't use lists here. OverlapCircle returns colliders. filter the layermask(s)
should be passing the list to OverlapCircle so it can fill it in with all of the nearby results
there's no need to manually add things to this list
use the override that dumps the results in the list
im not manually doing it
they should still be using a list, actually. or a pre-allocated array
it adds anything that comes in range
they were referring to the .Add call
why is size a float
idk man sometimes i autopilot
you are - you're getting an allocated array from the OverlapCircle call and then adding it manually to your list
you should use the version of OverlapCircle that dumps the results directly in your list
I haven't coded in Unity for a while but doesn't OverlapCircleAll handle that
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics2D.OverlapCircle.html see the third overload
if (!enemies[0])
{
closest = Physics2D.OverlapCircle(transform.position,2,mask,0,6);
enemies.Add(closest);
}
This is either never going to run at all or produce an out of bounds exception. There's no point to including this
OverlapCircleAll returns a new array each time and is therefore worse than what is being suggested to them
I see
i need to know the place of the first closest object
and !enemies wont have an assigned value at first so the first time it does it will assign it to closest as well
interesting
using the overload of OverlapCircle that populates an existing collection with the results means that there are fewer allocations, and with this happening in Update it will put far less pressure on the garbage collector
If enemies contains nothing, then enemies[0] will be an out of bounds exception.
If enemies contains anything, if (!enemies[0]) will be false and not run
The body of this if statement literally will not run
oh
Yes, I got it. Thanks for letting me know tho
i tried following
why is this not true
or do i put the assigning of the var in here?
how do i check if the list is empty or no?
you need to use a ContactFilter2D rather than those two middle parameters
Check the count
oh yeah thank you
also this overload of OverlapCircle will return the number of objects it found so use that rather than the count of the list
if you just blindly loop through the list populated by OverlapCircle you're going to run into invalid results because it doesn't clear the list, it just overwrites up to the index it needs to
so how can i compare which is closer
you loop through the list up to the index returned by the method call
or rather the count returned by the OverlapCircle method call
how do i do that
so you know how to use a for loop, right? and you know how to store the return value from a method?
yes
for both
so put that knowledge together
ok before that help with this
if i dont put [] i get an error what should i put in
putting in [] also gives an error, so clearly not that
stop using enemies.Add there, and i already told you why that happens. and also you get an error when you do put [] there because that's even more wrong
It returns an int.
You pass it the list.
bruh i thought i deleted it
i mustve CTRL z it
enemies is not a list of ints, so enemies.Add(<thing that returns an int>) is not valid
yeah works now
make sure to actually store the returned int from the OverlapCircle call like we just discussed
will try to do that
i mean tbf you don't even really need to use the return with the list overload, you could just foreach over the list
doesn't the list not get cleared and just overwritten?
...i don't see how those 2 are different
If the list is too small it will be resized. If the list is too big, it will not overwrite the unused values
so when fewer results are found they wouldn't want to be checking the invalid ones at the end of the list
So, you do need to use the int result, otherwise you'll have garbage data at the end of the list
ah, i see what you mean. you could just clear the list beforehand though, no?
that's what i usually see, i feel like
Yes, but that'd defeat the purpose of optimizing the clear out
i think i lost the plot. aight
Clear isn't free, it causes garbage collection. By not doing the clear, it prevents needing GC
i don't think that's true
does it cause GC though? I know it's an O(n) operation and would be slower than just using the returned int, but it wouldn't get resized when cleared
in editor
well, any GC other than releasing references to destroyed objects, i mean
any particular reason you're using depth for that? and are the objects you are trying to find within that range?
Try logging the count after this call. If it's still empty, then there's nothing in the overlap range
they are not using depth there
the 2 is radius
cause i tried it wo it and didnt work so i thought it was the probvlem and enabled it
in the contact filter they are
ah, mb. i read that as a layermask in the code
You're right, they wouldn't get GC'd unless the list was the last thing that referenced them, which can't be the case because it's a component
making it filter more wouldn't solve the problem of it not detecting anything
they move till they sit ontop of the object so yeah
that doesn't mean they are within that range of depth you are checking. depth isn't distance from the object, it is distance along the z axis
i disabled depth
i did depth just to make sure its missing wasnt the problem
i disabled it again
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class Raduis : MonoBehaviour
{
public Transform center;
public float size;
public Collider2D closest;
public ContactFilter2D filter;
public List<Collider2D> enemies = new List<Collider2D>();
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//if (Input.GetKeyDown(KeyCode.Space))
//{
//vector = Random.insideUnitCircle.normalized * 2f;
//Debug.Log(vector);
////transform.position = vector;
//}
Physics2D.OverlapCircle(transform.position,1,filter,enemies);
}
}
the code
the enemy object
you have IsTrigger there, but Use Triggers is unselected in the ContactFilter2D
How about you show the current values of the contact filter instead of us playing 20 questions
so it's working now?
yes thank you
so i did some tweaking
{
enemies.Clear();
Physics2D.OverlapCircle(transform.position, 5f, filter, enemies);
if (enemies.Count == 0)
{
closest = null;
return;
}
closest = enemies[0];
float closestDistance = Vector2.Distance(transform.position, closest.transform.position);
for (int i = 1; i < enemies.Count; i++)
{
float distance = Vector2.Distance(transform.position, enemies[i].transform.position);
if (distance < closestDistance)
{
closestDistance = distance;
closest = enemies[i];
}
}
if (closest != null)
{
Vector2 dir = closest.transform.position - transform.position;
if (dir.sqrMagnitude > 0.001f)
transform.up = dir;
}
}```
you mentioned erlier that i should put the update stuff in fixedUpdate should i do it now?
and will it impact performance if i dont
there likely won't be much performance impact compared to doing this in FixedUpdate, but there will be some benefit, even if it is fairly minor. if you end up with a lot of objects doing this though the benefit to making that change will increase.
Like i said before, physics objects only update on FixedUpdate frames so all those frames in between you are just getting the exact same results as the last FixedUpdate frame
so i dont really need to change anything?
not really, but there will be some benefit if you do. literally the only change would be prepending "Fixed" to the word "Update"
lol true
one more question the version of overlapcircle auto removes anything that leaves the range right
well no, that was my whole point before about using the returned int from the method. but clearing the list like you're doing does that anyway
i dont know if this has already been answered but why is vscode being deprecated and what does this mean?
it got rolled into the Visual Studio Editor package
-Code
ah, where do i find that?
in the package manager
im only finding these 3
yep
OH
the third one
yeah my bad
thanks for explaining
what code is needed for stats increase per level up?
that's a really vague question that can't be answered out of context
like for example when an enemy object levels up how to increase the stats like HP DMG and stuff. do i do it manually or there is some sort of code that automatically multiplies it?
DIfferent games do it in different ways
some games use linear growth. Some use polynomial growth. Some use exponential growth. Some even use logarithmic growth
Obviously you would need to write the code to apply whatever growth function you want.
And yes some games use manually created piecewise functions or tables, where every value is manually defined.
thanks for the explaining i will look them up
like... "+" alone?
same ways as i++?
i++ is the same as i = i + 1
i was referring to the i++ in the ''for'' code
and that is exactly the same as i = i + 1;
its the same i++
in that case, i++ is the same as i = i + 1
uh. i still got things to learn huh
we never stop learning
wait till you learn about ++foo and bar++
i recently learned that i can type 2+ names in a single primitive type and it will work just fine instead of 1 name for every primitive type
you mean like "int b, a" ?
you could do that but i honestly dont see any point in keeping it on the same field
you typically want them to be seperate for other reasons
i find that less readable
it is imo
this weird feeling i get stresses out about learning code that brings me to think ''am i finlay done? did i learn everything?'' then in reality i only learned like 5% and there is waaaay more to learn
yup
nobody is ever done learning
you stop learning when your dead
i was about to say something equally macabre
bit of a complicated question but:
im working on a car chase game with some friends and im in charge of making the cop ai for the game. ive tried using the navmesh/nave mesh agent to make them fallow the player and that works.. kinda... it doesnt allow me to apply our custom car physics the the cars. does anyone have an rescources or anything i can use the find an alternitave ?
There is always more to learn but once the basics are under your imaginary belt you will do fine
the beginner skill check is honestly learning how to learn
Or when you eventually give up, sell all your worldly possessions and go wrestle bears in the woods
i'm sure a life of bear wrestling either involves a lot of learning or very little 😛
should i jsut repost my question there?
I never said you had to win
just FYI, you can use the NavMesh to get the desired path, then use your own movement code to move it. you don't need to use a NavMeshAgent
good to know
this reminds me of someone saying ''bro teach me your fighting techniques i just wanna learn training'' lol
This is how I've done this very same thing before, but with A* pathfinding asset
Is the free version of it still available?
i distinctly remember it being on the asset store along side the pro one
i think you have to get it from the dev's website but should still be available
I dunno, I've got the paid version.. which I have no idea when I got, possibly in a humble bundle pack? possibly forever ago
Is there any one thing about it in particular you feel like makes it worth it over using the default ai navigation tools?
oh looks like he stopped updating the free version, hasn't been updated since 2021. the paid version also just got a new major release recently (feb 2024 is not recently lol)
The devs of Recompile swapped from Unity's Navmesh because it was too slow/ performance intensive (I forget which) when updating the path a lot. They swapped to A*. I know them in RL and trust their judgement
out of context but what is you guy's favorite code? mine is IF because it can be use almost everywhere
I know some people in the lethal company modding community do weird stuff to pull up some of the c++ side of unity's navmesh stuff for worthwhile performance benefits too
shame it's not easily touchable
I think baking the navmesh at runtime is rather expensive and time consuming too? Whereas with A* it isn't
yeah but i imagine that just comes with the territory of reading and processing mesh data right
I haven't touched either in ages.. and i tend not to look into the workings of plugins beyond how to use 'em
super fair
spent a fair bit of time playing with navmesh stuff for lethal mods experimenting with sampling data in general and potential ways of optimising bakes
would someone be able to help with this?
im trying to make controller work on a pause menu but its not working. I was following a tutorial and this error happened
use the correct type name
Show your code for InputManager
i mean i was following a tutorial and copied what they did, idk what the correct tyoe name would be
then you didn't follow it 100%
Show us your InputManager script
and show us what the Tutorial has for the InputManager script
did you miss a public class InputManager?
I have a sneaking suspicion that we are looking at what the tutorial has for the InputManager script 😉
or at least, with a single word difference
Show the tutorial
I think I pulled a stupid
When you're doing a tutorial, and it's not working for you but is for them, then you either:
- missed something
- did something wrong
and that I was supposed to name the thing after the code itself
I didnt realize it mb
you should start by learning the basics of the language, so that you'll realize that what you are referring to as "the code itself" is the class, which is a type.
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 200
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2026-02-25
200 


ok
helloo
where do I start getting back into coding for unity, I haven't worked on it in months
!learn or the pins in this channel
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
it's always this
why are you writing this to other channels too...
Cuz this is "code-beginner" channel
yeah well
that is not code
pls use #🤝┃introductions
as we said in #💻┃unity-talk
got it
discord has them flagged as a likely spammer btw
how do i make this material only render to the back or face
trying to make a card template sooo
This is the beginner coding channel, you should probably move your message to #💻┃unity-talk
oh
what happens when you have a class and an inheritor that both derive from an interface, and you try to retrieve an instance of that interface with Get/TryGetComponent, and call the interface's methods? does it return the "topmost" instance of the interface or do something else?
Can you show an example?
You would get whatever component you've substituted type T with relative to TryGetComponent.
public interface ISpawnListener
{
public void OnSpawn();
}
public class EnemyController : MonoBehaviour, ISpawnListener
{
// ... other stuff
public void OnSpawn()
{
// some initialization
}
}
public class Enemy : EnemyController, ISpawnListener
{
// ... more stuff
public void OnSpawn()
{
// more initialization
}
}
public class Spawner : MonoBehavior
{
public GameObject Spawn(string obj, Vector3 where)
{
// stuff
spawnedObject.TryGetComponent(out ISpawnListener listener);
listener.OnSpawn();
}
}
something like this
ISpawnListener isn't a component?
? you can do that though
why are they separately implementing the interface instead of just making the methods virtual then overriding in the inheriting class? it already inherits them
I feel like it'd just be easier to have an interface specifically for classes that want to listen for events like being unloaded or spawned
what i mean is that Enemy here already inherits the EnemyController's implementation of the interface so just make those methods virtual and override them in Enemy instead of just reimplementing the interface
public class EnemyController : MonoBehaviour, ISpawnListener
{
// ... other stuff
public virtual void OnSpawn()
{
// some initialization
}
}
public class Enemy : EnemyController
{
// ... more stuff
public override void OnSpawn()
{
// more initialization
}
}
just this
ISpawnListener isn't a component, so you'd simply use EnemyController or Enemy
by manually implementing the interface again you're just hiding the base class's methods. doing this allows you to even optionally call the base class's methods, and won't cause issues if you store the instance in a variable of the base class's type
you absolutely can use an interface for GetComponent or TryGetComponent, and their question is about how that is handled when the classes implement them separately
that works
Hmm, I had always thought it'd only work for component types.
if its not implemented by a component type it wont return anything
but any component that does implement it is the type the function is looking for so
i should put time counters in Update Not fixed Update right
it depends, what exactly are you doing
attack delay
then unless a difference of 0.02 seconds is too much, it doesn't really matter
so i can put it in fixed update and keep everything there
wait can i just use invoke??
wait no doesnt seem right cause i dont want it to instantly attack
I don't personally recommend Invoke, but yes that is an option
keep in mind that any timer you use for it doesn't necessarily have to be directly tied to the actual attack. you can even do your timer in Update and just check a variable in FixedUpdate
yeah ik
the timer will enable a boolean
so seems a bit realistic like the bullet was already reloaded
why isnt this working
and yes delay value is 5 and i do call the function
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i made timer a public var to see it in editor
using System.Collections.Generic;
using UnityEngine;
public class Raduis : MonoBehaviour
{
public ContactFilter2D filter;
public List<Collider2D> enemies = new List<Collider2D>();
public Collider2D closest;
public float timer=0;
public float delay=5;
public bool canshoot;
void FixedUpdate()
{
enemies.Clear();
Physics2D.OverlapCircle(transform.position, 5f, filter, enemies);
if (enemies.Count == 0)
{
closest = null;
return;
}
closest = enemies[0];
float closestDistance = Vector2.Distance(transform.position, closest.transform.position);
for (int i = 1; i < enemies.Count; i++)
{
float distance = Vector2.Distance(transform.position, enemies[i].transform.position);
if (distance < closestDistance)
{
closestDistance = distance;
closest = enemies[i];
}
}
if (closest != null)
{
Vector2 dir = closest.transform.position - transform.position;
if (dir.sqrMagnitude > 0.001f)
transform.up = dir;
}
Shooting();
}
void Shooting()
{
if (timer < delay)
{
timer += Time.deltaTime;
}
}
}
how do you know you are calling it
keep in mind that your code doesn't reach that point if no enemies are within range
Oh shi i totally forgot
i wanted to make that process into a function earlier but a friend visited and i forgot to do it now
using System.Collections.Generic;
using UnityEngine;
public class Raduis : MonoBehaviour
{
public ContactFilter2D filter;
public List<Collider2D> enemies = new List<Collider2D>();
public Collider2D closest;
public float timer=0;
public float delay=5;
public bool canshoot;
void FixedUpdate()
{
facingEnemies();
Shooting();
}
void facingEnemies()
{
enemies.Clear();
Physics2D.OverlapCircle(transform.position, 5f, filter, enemies);
if (enemies.Count == 0)
{
closest = null;
return;
}
closest = enemies[0];
float closestDistance = Vector2.Distance(transform.position, closest.transform.position);
for (int i = 1; i < enemies.Count; i++)
{
float distance = Vector2.Distance(transform.position, enemies[i].transform.position);
if (distance < closestDistance)
{
closestDistance = distance;
closest = enemies[i];
}
}
if (closest != null)
{
Vector2 dir = closest.transform.position - transform.position;
if (dir.sqrMagnitude > 0.001f)
transform.up = dir;
}
}
void Shooting()
{
if (timer < delay)
{
timer += Time.deltaTime;
}
}
}
yeah now it works
one question when instantiate an object can i decide where it faces?
I like to keep most of the gameplay update logic in FixedUpdate, and use Update mostly for visual stuff or input polling if needed
is there a reason for that?
It just makes the game logic non-framerate dependent
And for example I know that I never need to tick my AI classes faster than fixedupdate (50 fps)
I'm really dumbing it down here, but I guess that's the main attraction of it
If the game renders at 25 FPS or 150FPS, fixedupdate will still run at 50 FPS which I want for the gameplay logic
I guess I'm also futureproofing for networking, from my understanding servers usually tick at a certain rate
can i collision detect by 2 triggers?
o interesting
triggers don't collide, but if you want a physics message, there is OnTriggerEnter which is the trigger counterpart to OnCollisionEnter. obviously use the 2d version if using 2d, and make sure you've got the correct setup for the message
Ik so
void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "enemy")
{
ES = collision.GetComponent<EnemyScript>();
ES.health -=1;
}
}```
is this correct
both of the objects are trigger
wait i need to do collision.gameobjcet
ideally you'd use the CompareTag method rather than string equality for checking the tag, but otherwise yes. also is there a reason that ES is a field rather than just a local variable?
you do not because collision is a Collider2D which has those methods/properties on them because it is a Component, unlike the Collision2D type which doesn't because it isn't a component
will it access enemy script just by getting component from Enemy Script??
yes, you can call GetComponent on any component and it will get the component from that component's game object. just like calling it on the component's gameObject property would
wdym field?
a field is a variable declared at the object level (directly in the class in this case)
ohhhh i thought there is no performance issue by making it up there
why does the object try to move but keep being stuck?
transform.position += transform.right * speed * Time.deltaTime;```
instantiation method
Instantiate(Bullet, shootpoint.position, transform.rotation);
this is not enough information to know why.
but also you should ideally be moving these objects with a rigidbody rather than with its transform, especially if you want physics messages like OnTriggerEnter2D to work
oh will imploment that rn
using System.Collections.Generic;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
public class Raduis : MonoBehaviour
{
public ContactFilter2D filter;
public List<Collider2D> enemies = new List<Collider2D>();
public GameObject Bullet;
public Collider2D closest;
public Transform shootpoint;
public float health = 2;
public float timer=0;
public float delay=5;
public bool canshoot;
void FixedUpdate()
{
facingEnemies();
Shooting();
if(health <= 0)
{
Debug.Log("YOU LOST");
}
}
void facingEnemies()
{
enemies.Clear();
Physics2D.OverlapCircle(transform.position, 5f, filter, enemies);
if (enemies.Count == 0)
{
closest = null;
return;
}
closest = enemies[0];
float closestDistance = Vector2.Distance(transform.position, closest.transform.position);
for (int i = 1; i < enemies.Count; i++)
{
float distance = Vector2.Distance(transform.position, enemies[i].transform.position);
if (distance < closestDistance)
{
closestDistance = distance;
closest = enemies[i];
}
}
if (closest != null)
{
Vector2 dir = closest.transform.position - transform.position;
if (dir.sqrMagnitude > 0.001f)
transform.up = dir;
}
if (canshoot)
{
Instantiate(Bullet, shootpoint.position, transform.rotation);
canshoot = false;
timer = 0f;
}
}
void Shooting()
{
if (timer < delay)
{
timer += Time.deltaTime;
} else canshoot = true;
}
}```
this is the script where it gets cloned
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
public float speed;
private EnemyScript ES;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.position = transform.up * speed * Time.deltaTime;
}
void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "enemy")
{
ES = collision.gameObject.GetComponent<EnemyScript>();
ES.health -=1;
}
}
}
``` this is the script where it moves
forSome reason it spawns in 0,0,0 even tho i assigned shootpoint
I manually changed the GUID of my only scene in Unity... and now unity doesn't recognize it... is it recoverable???
this is a code channel
what is shootpoint assigned to, and are you sure its position isn't 0,0,0?
its a child of the object this script is assigned to
an yes im ceretain its 0,0,0
and the thing is
it keeps going to 0,0,0
how have you confirmed either of those things
cause the values try to move up but they keep getting reverted to 0
inspector
stop making assumptions based on what you see in the inspector
i figured out the problem..
transform.position = transform.up * speed * Time.deltaTime;
I SWEAR i saw the + like 5 times
you need to verify everything in your code either with logs or breakpoints. the inspector can only render once per frame, things can change more frequently than that
about this
i just added kenimatic rigidbody to bullet and its getting the trigger collision*
can i just keep it?
wdym "and its rendering"?
you also need to be moving using the rigidbody rather than the transform
any reason for that
Im not arguing i just need to know
because physics messages may not work if you aren't moving the rigidbody. what you're doing now is effectively just teleporting it every frame
oh will change movement to rigidbody when i done with all the basic ideas i need
one question
how different is GameManager
i don't understand what you mean by that question. GameManager is not something built in, so the question without context is meaningless
why when i name a script GameManager it gets a special icon
is it special in anyform
just an old quirk of unity, doesn't really mean anything
the icon is the only thing
pretty sure it's been patched out at this point too
oh lol
i use unity 2022 lol
wait, it was removed in 2022, what specific version are you using?
yeah i just found it i dont have it anymore
{
StartCoroutine(UnlockRankBootstrap());
}
private IEnumerator UnlockRankBootstrap()
{
yield return StartCoroutine(AlignKeyWithLock());
}
private IEnumerator AlignKeyWithLock()
{
yield return new WaitForSeconds(1.0f);
UnlockRank(NextRankToUnlock, false);
NextRankToUnlock--;
}```
I might be missing something, but UnlockNextRank is called from another file. You need to be in a Coroutine to yield return, so this is the only way to get the program to 'halt' and wait for execution. Is there no easier way than StartCoroutine -> yield return another coroutine? It just feels like a lot of scaffolding to get things started
I guess you can nest the second IEnumerator inside the first with System.Collections but it still feels excessive
I'm not seeing why you can't just start AlignKeyWithLock directly?
What's the point of UnlockRankBootstrap if it does nothing but yield another coroutine?
public void UnlockNextRank() {
StartCoroutine(AlignKeyWithLock());
}``` would be perfectly valid and do exactly the same thing