#archived-code-general
1 messages · Page 233 of 1
what my intended use case is an <int, string> list that stores the message and how fast its typed
wait
This sounds backwards to begin with
Int to anything would always be preferred with list or arrays
I would just store this in a class
in a hashset too
is hashset 2d i forgot
message as the ref with variables of how fast it's typed
What's the game mechanic you are trying to make?
so i have a dialog system where as the text is typed out it can changed the speed its typed out at mid message
and so what i plan to do is split the sections out into its different typing speeds
but if i use something like a dictionary it risks the edge case of repeating messages or typing speeds not working (depending on how you setup the dictionary)
Sorry something came up so I cant elaborate much more, but I'd use a class still given this description
tyty
what's the use case of the dictionary anyway?
as such, how are you accessing the dictionary
I'm assuming it's to map the speed of typing to particular string responses.
i would only use a dictionary for random access of whole cutscenes, maybe
a dictionary is a terrible data structure to hold dialogue
im trying to understand though, is this dictionary being populated as the game goes on, or are they cacheing messages by a difficult of speed?
i would make one class for a single textbox. and give an inner data structure to change text speed throghout
easy -> dictionary 1
medium -> dictionary 2
i would probably write dialogue as a string with special formatting characters. Then textbox class parses that string onto a couple of distinct parts
oooh it's a dialogue system (I must have read over that)
im thinking it's some word game
eg “I like to go <fast>really <slow> fast.”
Textbox clsss parses this into:
0) “I like to go “, speed = medium
- “really”, speed = fast
- “ fast”, speed = slow
using a struct to hold individual bits of dialogue.
you might look into some software called “yarn maker” or something, designed for making dialogue
I would assume
speed < 5 wpm: "hurry up!"
speed > 30 wpm: "you're doing great"
Which doesn't mean key to value but rather should be done with some logical operation and possibly store the responses in some array or list to grant exposure to the inspector.
at no point should a dictionary be involved in this procedure
Yeah, that's actually a little tricky. I think just fully customizing each message with a animation curve/routines is the idea
doing it per word for the whole game doesn't make too much sense
you need a work flow where you can crank out text, tho.
the spec needs to be 1) write simplish text document, 2) program parses it to know how to display it
Yeah, that itself would be some sort of system, and it would be unique to each message.
doesn't sound too hard
you'd have a default speed, then interrupt it with different speed (maybe some wobbling text animation) depending on word (coroutine, yield, continue)
yeah. there are addons for this, i bet
a powerful website for storing and sharing text and code snippets. completely free and open source.
hoya i've got this third person camera controller script but scrolling in does weird things and I'm not sure why
when I get too close to the minimum distance set it like almost rotates it up or something
basically the script is letting it rotate based on position of the mouse and if it gets too close I want to set it to the minimum distance from the player but when i try to do that it just does that
when i scroll in it just rotates upwards or something
this is how its set up and the cameraholder is the cameraholder in the script
and this is how it is physically
if the script is cancer sorry
Is the player position relative to it's head or some other bodily part?
just the head
when it rotates up it just does that
waiiit
maybe its supposed
hold on
for some reason when it gets too close it changes the camera's rotation but i dont change the rotation in the script
oh wait i do, when it looks at the cameraHolder.transform i guess
but anyways its moving the camera upwards which is messing everything up, that's the issue ig
the red line is the vector I want it to move, which is cameraHolder - cameraPosition
The only extra irregular offset is the cameraHolder position
Print that and ensure that it's on the same height level as the player else you'll be elevating up gradually
oh wait its not because the script allows you to move it according to the mouse y input
The one is obsolete here btw: a + 1 * (a - b)
Other than that, this is likely the cause.
im still sorta confused though, if the cameraHolder's position - cameraPosition, shouldn't it be going on the red line backwards?
I'm assuming the camera holder position isn't what/where you think it is.
Try logging it.
i have a scene pulled up when im in game mode, it's always on the player's head
Log the position of the camera holder
okay wat now?
What did it print?
And what's the position of transform.position?
Vector3(-1.49011612e-07,1.53496134,-0.16560626)
So they aren't at the same height
ya the more you move your mouse vertically, the more the position of the camera's y value changes
(1.5 - 0.99) normalized is the offset you'll gradually get on the y axis
wait mb the camera's position is 0,0,0 until it gets to the minimum zone and starts glitching out
Meaning you'll eventually go above the target
Is that what it printed?
We only care about what was logged, not what you see in the inspector
oooh okay
I thought they were directly the same
im still having trouble understanding, by subtracting the cameraHolder's position from the camera's position, it makes an offset and that grows every time?
Their y-values need to be the same else you'll get gradual changes as it repeats.
Consider backing up the y value and restoring it after the change unless you're wanting to smooth step the x and z components separately.
I thiiink I understand now
Is there a way to check if a nav mesh agent is at the edge of a nav mesh surface?
Not really. You could sample several points around the character and if some of them return a different position, you can guess that it's near an edge, but I'd double think before doing that.
@cosmic rain well then whats a good way to have a sort of timer for when the agent is at the edge of the surface, based on when it doesn't move, since it's target is outside of the surface it won't be moving
it took all my braincells but I understand the issue now
Wdym by a timer? Can you explain a bit better what you're trying to achieve?
sort of like patience, like if the agent is trying to go to a target that's not on the surface, then it will forever try to get there, being stuck at the edge, unmoving, after said hypothetical timer is up, it will then recalculate a point to go to
You can check the path status. It can tell you if the target destination is unreachable.
how do I do that, is that a built in function or will I have to make that myself?
what are you trying to do? what is the issue you're observing?
like if the agent is trying to go to a target that's not on the surface, then it will forever try to get there
what do you mean? if you try to navigate to a point that's not on the surface, it will go to the nearest point on the surface, and it will arrive in a technical sense
It is part of the navmesh agent API. You'll need to look at the docs as I don't remember the exact name.
it will then recalculate a point to go to
recalculate a point to go where exactly?
you can do a navmesh raycast hit to see if a point isn't on the surface. if it's not, don't set it as a destination.
navmesh agent will happily try to reach any destination
I need a regular expression that will split a string at the first "space followed by a letter" but I cant for the life of me come up with one... can anyone help?
@polar marten When my navmesh agent tries to go to a point that's not on the surface, it will constantly try to go to it, staying unmoving on the edge, I want it to after a while of not moving, to recalculate to a random point to go to, based around the agents position, kinda like wondering around aimlessly,
@solemn wren
You can still get that info from the path status. It should be "partial" if the path doesn't get to the destination:
https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent-pathStatus.html
https://chat.openai.com/share/5f381625-1a72-45d8-8f8b-352ac7dea7a1
you should try gpt4 in chatgpt
ok
https://dotnetfiddle.net/35UDkp
it's close enough for you. you can sort things out from here
Test your C# code online with .NET Fiddle code editor.
Hi
How can I make a positioning system for a racing game with a pass on the number of laps each vehicle has completed in Unity?
Have waypoints spread across the road and when cars pass by them add to a counter(passed/total). When they pass the starting point, add to the loops counter and reset the waypoints counter. Then just compare loops*total waypoints + waypoints of each car to find their position.
ok but how do I compare if a vehicle has more number of laps?
Loop over the cars and compare the counters with > or <
You have an exaple script?
do you know what are array and loop?
I should ask you if you want to make a scoreboard or rank list indeed, just find out the vehicles have maximum numbers of waypoints passed seems a bit weird
You can have a list of cars and use the sorting function to sort it by their progress.
Ok but the script should to be in the game object for example "RacerManager"?
Because my cars track have the checkpoint and the cars have the variable the current lap and checkpoint number
store the vehicles somewhere in the manager then after every one updates its position, sort it
How call the function sort?
Ok
Lookup "C# list sort"
can someone help me for some reason i tried building my marble game on webgl and i got this error
uhm, what's the difference between VS and VSC as an Editor?
I kinda wanna switch to VSC for light-weight. but can't decide if I should
Hi everyone my name is Ghassan Im currently working in a game project with 3 people and were having a problem with make a checkpoint in which when the player hits it they respond from that point do you guys have a recommendation to how to approach that
i believe the visual studio code extension is not fully supported yet. Visual studio allows you to use the debugger.
Light-weight means nothing here, you simply need to open your IDE once per coding session.
i use vsc since i need it to code c/cpp/java, not just c#.......
I see... interesting. Thanks :)
thats a valid reason. but in terms of integration with unity only, VS is better. I remember i had like 4 IDE's installed during school which is very annoying
I can't seen to get my UI elements to be draw on top of everything
iirc ui elements draw in the order they're placed in the hierarchy
first child object (from the top) is drawn first, second is next, etc
not a code question, maybe you just want simple camera stacking with one focused primarily on UI if you are talking about world space UI and want it rendered on top of other objects.
does Directory.CreateDirectory make a folder on the pc
if so
where tf is it
oh. its a built game. of course i cant see Assets
Hi ! Trying to instantiate a PopupField in VisualElement for dynamic type. Problem is, since I don't know the type in advance, I can't do PopupField<typeof(variable)>. What is a good workaround to that ?
i'm attempting to encrypt a string, throw it into a file, then read the file again and decrypt! Unfortunately, right when I decrypt, my code goes kaboom
After doing some testing, I found out that I know nothing about what format the byte[] of the encrypted string is. Like, you can turn a string into a byte[] through System.Text.Encoding.ASCII.GetBytes(yourstring), or you could also use UTF8 instead of ASCII, or even Unicode. At least, that's what I thought was at play here. I also printed out my whole encrypted byte[], and it turns out that it had values larger than 128. Yikes
I can throw in some source code on the encryption/decryption process, it's really just something i found from microsoft.net's aes encryption thing, but the main thing for me is to find out what format a certain byte[] may be, if that's what I'm supposed to be doing. I'll triple check my code again but please let me know if i'm screwing up something simple! Thank you very much for your help
Kaboom doesn't say much, do you have any actual error code? Also in paint you can add text so you don't have to draw it, that's way more readable then this.
why are you writing out a byte[] as an ascii string?
just use the WriteAllBytes and ReadAllBytes methods
oh
oh god im saved
thank you
i havent tested it yet but it seems so promising
it has to work
next time try doing some research and read the damn docs
thank you very much!
What is it that your trying to do? Why might you want to create directories at runtime to "Assets"?
theres another script that does it that i cannot change, but its saving .wav files there that i wanna load and play from an audiosource
that's not going to work at runtime only in the Editor.
If you want runtime save/load for PC use Application.persistentDataPath or Application.streamingAssetsPath
Hi everyone! I’d like to get some thougts about an issue I’m having. It’s an ai-navigation issue, but that channel is dead so I hope uou can forgive me for bumping it here, mods if u have to delete this messgage
!bump #🤖┃ai-navigation message
Don't working the system of positions of cars
How can I make a positioning system for a racing game with a pass on the number of laps each vehicle has completed in Unity?
Whats the current best practices to handle web requests? UnityWebRequest forces you to use coroutines. UniRX allows you to bypass this because there is an AsObservable overload for UnityWebRequest. In addition, as far as I've understood HTTPS support is tricky. I've read that .NET's HttpClient has limitation that is solved by using a Factory wrapper but that is only available in .NET Core.
How does UnityWebRequest force you to use coroutines and what do you want to use instead?
Also, it seems like unity web request doesn't have a problem with https. Although, you might need to implement a custom certificate handler.
UnityWebRequest.Get/Post returns an async operation, the only way to handle this without creating overhead data is with a yield return which means you can't use return values
How can I make a positioning system for a racing game with a pass on the number of laps each vehicle has completed in Unity?
UniRX offers an overload for that called AsObservable/AsAsyncOperationObservable which allows you to use it simliarly to how you would use it with await/async
It just creates a wrapper for it. It does introduce an overhead. Besides, I don't think performance should be a concern in this context.
overhead in the meaning that you don't have an on complete that has a reference to the result
or on fail for that matter
your sort is pointless, you cannot return a value from a void method also !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
Well, you can write your own wrapper to get a return value.🤷♂️
of course i can I can also use the legacy WWW request handler, I'm asking what are the best practices for it
A third party package introduces a lot of other clatter to your projects so I wouldn't use it just for one small feature like that.
Whatever works for you
not exactly an answer...
There are no best practices when it comes to choosing implementation
Ok, how do I get the position of a car based on the number of laps traveled and the current checkpoint for a racing game?
Didn't we go through it already?🤔
no not yet
see example code here https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.orderby?view=net-8.0
Sort a list of cars by the progress. The index of each car would be equal to its position.
Ok, to start, how can I calculate the distance that a car has with respect to the checkpoint number it is in? For example, if this is at checkpoint 8, calculate the distance of that checkpoint and if I passed it, I calculated the distance of checkpoint 9 and so on. .
Why would you need to know the distance? Just compare how many checkpoints a car has passed.
You can even make it a percentage of the whole loop: current checkpoint index / total checkpoints.
because if several cars are at the same checkpoint number I need to compare the distance of each checkpoint each
One thing you can do is place more checkpoints, so that there's very little chance that 2 cars are on the same one, and if they are, it shouldn't be too noticable.
Now, if you need it for the finishing line, you would use a different approach, where you'd just add cars to a list as they arrive.
just keep a running total of the total distance traveled per car
That's another option👆
Though it might not work in cases where you compare a car that goes straight with one that goes in zigzag
I take the first option
While calculating a distance between the checkpoints is an option, you should consider wether you need that much precision and wether the work put into the implementation is worth it.
no, because you would only take 1 vector into account
Also performance cost(probably negligible but still)
Hmm. That might work.
ok I'm going to see what I can do based on the orderby functions and I'll tell you anything about that
is there any considerations to be made when fetching references for a script? For example I currently have an hp bar i want to implement, and some ways to do it would be to pass in the player through the inspector or to do something like finding the player by tag in the constructor of the hp bar, but is there any considerable difference between the two approaches?
yes, having a reference already established is much more performant
and im assuming the best (only?) way to do that is through the inspector?
assigning via the inspector is the fastest way because the object starts with the reference. finding via tag is slower (but far from the slowest option) since it doesn't just already have the reference
GetComponent is pretty solid, because you only need to sift through one object’s components
and you avoid fuckups from forgetting to or assigning the wrong reference
Some people use GetComponent in OnValidate()
i might change to that in future tbh, especially if GetComponent becomes too expensive during initialization
Hey guys, old unity dev getting back into things. I'm creating an event system for my game and I have a few clarifying questions to ask:
- Should I be using c# events or UnityEvents? Are there pros and cons to each one?
- I'm currently thinking about having a
EventManager.csand having my events be static and to have triggers for the events also be static. Is this a good idea or are there downsides to this?
Something along the lines of:
//EventManager.cs
public class EventManager : MonoBehavior {
public static event EventHandler OnHit;
public static void TriggerHit() {
OnHit(this, EventArgs.Empty);
}
}
//Player.cs
public class Player: MonoBehavior {
public void Start() {
EventManager.OnHit += HandleHit;
}
public void HandleHit(object sender, EventArgs args) {
//handle the hit somehow (just an example)
}
}
//Thing.cs
public class Thing : MonoBehavior {
public void FixedUpdate() {
EventManager.TriggerHit()
}
}
Thoughts?
Should I be using c# events or UnityEvents? Are there pros and cons to each one?
UnityEvents if you want to assign listeners in the inspector. Otherwise C#.
I'm currently thinking about having a EventManager.cs and having my events be static and to have triggers for the events also be static. Is this a good idea or are there downsides to this?
Static events are convenient but also somewhat risky. You are in full control of the lifecycle of static objects. They won't be cleaned up automatically between scenes etc. It's easy to end up with orphaned subscriptions etc.
Also in this case there's little benefit to the EventManager class. If you have a static event that has something to do with the player, why not just put the event on the Player class?
Player.OnHit is a lot more expressive than EventManager.OnHit.
Third piece of advice - don't use the EventHandler pattern in Unity. Create your own delegate types. EventHandler/EventArgs creates unnecessary garbage and the object and EventArgs classes are way too generic
my understanding is EventHandler/EventArgs is built on top of delegates?
would it be similar syntax / usage to do so?
yes, they are unecessary bloat on top of delegates
you can define your own simple delegate type without using EventArgs
public delegate void ExampleDelegateType(int param);``` for example this defines a delegate type that takes an int parameter with `void` return type
alternatively Action<int> is identical to this
explicitly defining delegates has the bonus that the parameters will be named, and you can look at their definition to know what each parameter represents.
the parameters are named and the delegate type itself is named!
This is super useful sometimes
public void AddDamageHandler(DamageHandler handler) { ... }```
this is very easy to understand!
you put a DamageHandler in here
Ok so if I'm understanding this correctly, the delegate would be equivelant to the TriggerHit function I described, and I would still use the event keyword to keep track of listeners?
Listeners can be added to delegates without the event keyword, the event keyword just means that only the class that the event is defined in can invoke it
To help you understand let's dissect this line:
public static event EventHandler OnHit;```
I'm sure you know `public` and `static`
`event` means "this delegate can only be invoked from inside the EventManager class".
`EventHandler` is the delegate type (you can use any delegate type here, including a custom type)
`OnHit` is the name of the delegate.
Overall this line is declaring a public static delegate called `OnHit` of type `EventHandler` that can only be invoked from inside the `EventManager` class
oh I think i get it now
I usually have a few key singletons with super important public events, like OnLevelLoad, OnEnterPlay, OnRespawn…
Then different classes have their own actions if needed to subscribe
public class DelegateExample : MonoBehavior {
public static event HitDelegate OnHit;
public delegate void HitDelegate(GameObject player);
}
or alternatively:
public class DelegateExample : MonoBehavior {
public static event Action<GameObject> OnHit;
}
of all my delegates, 95% of them are Actions
Exactly!
alright, thanks for clearing this up for me!
Action vs custom delegate type is a matter of personal preference
makes a lot of sense now
event is like an access modifier.
event exposes only += and -= externally, but fully exposes the delegate within the class that holds it
so the class that holds it can set delegate = null, to blank out everything
https://www.jacksondunstan.com/articles/3335
Some interesting read for native events vs unity events
JacksonDunstan.com covers game programming
thanks, will take a look!
I have a class, and I want a table of stuff, is this okay enough?
FinishPosition[] fp = {
new FinishPosition(1, 2),
new FinishPosition(3, 4)
};
the [] thing, should I use something else, or is it a bad idea basically to store it like this
oh wait, this channel is for Unity related only questions?
so question like mine should rather go to beginner/advanced?
I think this would be called a public class
i need it to look like this
after collision with an object
if (collision.gameObject.TryGetComponent(out FlagVaribles redFlag))
{
flagVar = redFlag;
}```
Why would it not be ok?
idk, there is no range given
the range is 2 because that is how many items you declare.
well, I'm asking because I'm a general developer
I know stuff about programming, but I'm doing this across different languages and I don't know how each language acts when doing something
while the output is the same, stuff may be different inside
This is called an array in C#. Not a table.
Tables are LUA things
yeah I know multiple languages but not theory specific stuff though
So when you say "I want a table" you need to be more specific because C# doesn't have anything called a table. It depends how you want to use this thing.
this isn't really "theory" stuff this is very concrete data type stuff.
yeah, it also acts different, thats why im asking
It depends how you want to use this thing
just wanna get random class out of it and access its data
You want to get a random item from it. This array holds multiple FinishPosition objects. You want a random FinishPosition
not a random class.
Classes are blueprints for objects.
there is only one class here called FinishPosition. You have multiple objects of that class.
To actually answer your original question:
If you want to just pick a random one, yes an array is a good choice.
oh yeah, I mean theory again
I mean theory as in "you know what I mean but theoretically this isn't right"
my bad
i cant get it to work
im not sure why i can do this
but not put it in code
to change it to red flag
when it hits the flag
I do not understand your problem.
Is TryGetComponent not working?
you should use some log statements to check
you have them backwards
flagvar = redFlag needs to go first
otherwise you are calling flagVar.flagPickedUp on null
hence your error
does it make sense?
also calling it redFlag is a bit confusing and inaccurate. I don't think you can say that is the Red flag here. It's just some flag.
it's whatever flag you collided with
See how it works with the blue flag as well? You should just call it flag for example
okay! Thank you so much I have been stuck on this for a while haha
okay i changed it
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
I have 2 gameobjects moving at each other using the same base class and pretty much not changing anything and that base class tells them to stop when they detect each other, but only one of them stops and i can't figure out the difference between them.
base class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Minion : MonoBehaviour
{
protected Rigidbody2D rb;
public float moveSpeed = 3f;
public float range = 2f;
public string enemyTag;
protected virtual void Start()
{
rb = GetComponent<Rigidbody2D>();
rb.velocity = new Vector2(moveSpeed, 0);
}
private void Update()
{
DetectEntety();
}
void DetectEntety()
{
Collider2D collider = Physics2D.OverlapCircle(transform.position, range);
if (collider.CompareTag(enemyTag))
{
rb.velocity = Vector2.zero;
}
}
}
i thought it might be that the tags dont match up bc I checked and the thing does detect collision but it doesnt stop obv but they should match
Did you actually type a string value into enemyTag for both objects? One of them could be blank or mistyped.
i did and i removed the = "Enemy" after the issue first happened as an attempted fix
Can you show that you've assigned values to enemyTag?
this is the class thats not stopping
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MinionBasic : Minion
{
protected override void Start()
{
enemyTag = "Enemy";
base.Start();
}
}
And show the object's inspector that you're hitting?
hitting?
The thing you want this Minion to stop when it hits
You sure there's no trailing space in that tag?
how would i check that? i tried adding another tag where i was sure were no spaces and it didnt so that means the existing one is the same
i usually use a plugin that autogenerates a static class so I can refer to Tags by a const variable
eg Tags.PLAYER. It blocks so much confusion from spelling errors
Well, a plugin isn't going to solve the issue. No need to go chasing that down.
Are you sure there's a collision even happening? Can you debug.log your overlap?
Debug.Log is your friend. Print out what the tags are and whether they are equivalent
Because you're also use OverlapCircle which checks if there's a collider in that area. But if there are multiple, you have no way of knowing if it's the one you want.
So you either need to include a layermask, or use the OverlapCircleAll alternative and iterate through the list of colliders you've found and check if any have the Enemy tag.
works! tysm
void DetectEntety()
{
Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, range);
foreach (Collider2D collider in colliders)
{
if (collider.CompareTag(enemyTag))
{
rb.velocity = Vector2.zero;
}
}
}
i added a foreach loop
But you still didn't add any Debug.Log
oh sorry, yeah i guess that was the issue
yes
but logging would help you find it in the future
ok ty
you can also add breakpoints in a debugger
BTW if you're doing this - why not just use OnTriggerEnter2D for example?
i've started doing that more often
this seems like a less efficient version of OnTriggerEnter2D
it doesn't require a compile!
i wanted to but i didnt know how to use that with multiple colliders
and chatgpt said to use Physics.Overlap
each collision will cause a separate message to be sent.
https://openupm.com/packages/net.tnrd.layertagsgenerator/
This won’t necessarily fix your problem, but it is a useful tool to have.
neat! thanks
huh, "TNRD" is a familiar name...
ChatGPT doesn’t actually know anything.
i just use it as a google alternative
same
i would avoid ChatGPT for anything coding related, unless you know what you are doing so well that you can immediately spot every mistake
why
then you can be like that one guy who constantly raves about chatGPT while everyone else boos him
because it will write code that looks plausible, but is wrong
it generates plausible text
it does not generate "correct" text
i just ask it googleable questions not write code
chatGPT is not a knowledge engine. it doesn’t know things. it is based on a language model
it’s specialty is syntax. it produces things that have the right formatting to look like normal plausible syntax/language
if you ask it a question, it will give you a response that is not necessarily correct, but will have what it predicts to be the expected shape of it
ill consider that
whats not working? You are doing nothing with the output of the OrderBy
OrderBy does not order the list in-place, it gives you a new one to iterate on
yes, it's a method from LINQ
My idea is to organize them from largest to smallest
all of those methods produce a new sequence. they don't mutate the original.
List<T>.Sort() sorts in-place
You'll still have to pass a lambda expression to specify what to sort by
How?
Documentation tells you how
I'd make a custom comparer, that would be prettier. Change the code so the list is a List<CheckpointChecker> instead, then have CheckpointChecker implement the IComparable<CheckpointChecker> interface.
Then you'll be able to just do cars.Sort(); and it'll pick up that your class implements IComparable
I might be misunderstanding the numeric formatting, but I figured that ToString("G3") should limit something to three digits, and use scientific notation as necessary if it's more than that. Here's a few numbers all using that format, you can see it's properly scientific-ing the four-digit number, but the decimal numbers are still shown with full digits, even though they should be formatted, right? If this isn't what the general formatter does, does anyone know how I could get a format that'd auto-scientific-notation any number if it's got more than 3 digits in either direction?
Okay yeah I definitely posted something too advanced lol
This will never change the contents of cars
you need to read what we're writing.
You aren't storing the results anywhere
How
The first one works, not the second
yes, because, as we all wrote, OrderByDescending just produces a new sequence
it doesn't change cars
cars.Sort alone is enough.
see
separately, that list should be public get private set.
eg public List<CheckpointChecker> positions {get; private set;}
let's not throw more information in right now..
sorry, i can’t help myself
Yeah you can consider a Gx format string to format in scientific notation only if there's more than x zeroes to the left/right of the decimal point. It doesn't rely on the length in characters of the number.
For numbers between 0 and 1, that are not small enough to turn into scientific notation, it'll round them to x decimals after the last zero
OrderByDescending returns an IEnumerable<CheckpointChecker>, not a List<CheckpointChecker>. You can use ToList to produce a list out of the sequence if you need to.
I don't see any reason to do that, since you've already sorted cars.
is he using System.Linq? I think that method requires it.
How can see the array in the Inspector?
do you have NaughtyAttributes?
hold up, you can’t do that
I suggested a way to get a list.
If you don't get a list, you can't see it in the inspector.
positions should be a list
cars.DoSomething().ToList();
this produces a List<CheckpointChecker>
also, if you don't want cars to get rearranged, don't do cars.Sort().
do you want cars to remain unchanged and for positions to change?
is he still here?
i worry he’s just plugging things in and only coming back after it doesn’t work, without listenning
So is there some way to conditionally apply scientific notation for numbers that have a lot of leading 0s?
I don't think so, you might need to roll your own - but the E format specifier will do half of the job
thanks
gridCells = new GridCell[10];
gridCells[0].x = 1;
This is returning a null reference exception and my brain is not braining any more
gridCells[0] returned null, you cannot access .x on null!
That tells me GridCell is a class. This does not have a default value, so your array will be filled with nulls when you create it
ic
You need to do gridCells[0] = new GridCell() before trying to access anything on it
the thing that confuses me is that this exact code was working completely fine
I don't think so
then I decided to take a break so I closed unity and when I went back it stopped working
Either the code was not executing, or it was modified
I'll look into it
Adding that bit worked which is surprising cause I'm 100% sure I didn't fiddle with that bit , I won't say no tho thank you so much
How can i know the index the each car in the List Cars?
Do you have a specific car variable, and need to find its index, or just get all indices of all cars?
makes no sense
Yeah can you rephrase that? I didn't understand
This list
Ah I think I see
oh this is some sort of leaderboard?
They want to use the list index to fill out the CheckpointChecker:Position variable
or AI manager
yes
Then use a for loop to go through the list
How?
you don't need to do anythingwith multiple colliders - your code only cares about any collider having the tag. Just check the tag in OnTriggerEnter and do what you need to do (set the velocity to 0 it seems)
don’t take this the wrong way, but I think you need to learn the basics before you start trying to make your own program in unity
How to use a for loop?
for (int i = 0; i < someMaxValue; i++)
if you are unfamiliar with for loops, you need to do some metaphorical pushups before tackling a game
but the gameobject that the script is on has multiple colliders i meant and also the gameobject that is being detected
one for detecting and one for being detected
Doesn't really make a difference
especially in this case
OnTriggerEnter gives a specific collider. You can get all sorts of information from that collider, including the gameObject it is on
but then the detection area of the gameobject that is being detected will be detected
and also whcih collider would the function use
OnTriggerEnter just detects any valid trigger entries
exactly
yeah i didnt get the layer thing thats why i used the other way
do you have a screenshot of your game?
i just don’t understand the issue. If you have a reference to the collider that triggered, you can do everything
and if you can’t distinguish between two colliders on the same gameobject, then you have a different problem
i have the different problem
one option is to make a second gameobject, make it a child of the first, and send one colllider to it
you can make the child gameobject have different tags/layer
or separate scripts that only get triggered with that one collider
Well, I literally wrote it out. I guess replace "someMaxValue" with Cars.Count (it's a list right?)
that looks pretty nice. i think you are in a good place
so complicated, guess ill ask chatgibidi to explain it
Thanks
i’m sure ChatGPT will explain it perfectly
the code that you've written is almost there. you should try using gpt4 for further programming questions, and definitely look at the source code of other unity games
good luck with that
As mentioned already, use a for loop to go through your list. Since it's sorted, the car in the first position will be the first one in the list
just don’t ask ChatGPT to make you a 60 card deck. You won’t end with 60, and some of the cards in the deck will be made up
just don’t ask ChatGPT to make you a 60 card deck
but i’m sure ChatGPT can handle simpler tasks like programming, just fine
bad advice
Awful advice lol
Asking a beginner to use gpt
well what do you suggest? a magic 8 ball?
you're better off
XD
Actually learning the language is an option
ChatGPT is always a bad at programming, but it is good at writing clean code (:
genuine troll
These statements contradict themselves
So, in my opinion, you can use it only if you know what you're doing
at which point you wouldn’t be using chatGPT
but if you know what you're doing then you recognize is bad..defeats the whole point of using it in the first place
And I'm not going to get into a gpt argument again
#📖┃code-of-conduct : Do not ask or answer questions with unverified AI-generated tools
Simple enough, if you want to suggest beginners to use gpt to make their code, you go elsewhere
Now back to code shall we
Im bad explaining myself. It's good at... Just writing code, at organising code, but not at making it. I don't know how to explain, but I use it to give me an initial idea of what I should code, because I recognize what it did well and bad
it doesn't organize anything, it doesnt have critical thinking to do that..
chatGPT is really good at quick simple questions, just so you dont have to find a good link on google
but yes lets move on from this topic
ok
as long as we don't tell someone use GPT which is just reckless advice
they did say GPT 4 no ChatGPT 3.5
Yeah, I mean... Like I use it to get an initial idea, being aware of how bad it is, but at least the code looks clean, not spaghetti code or complex code
Forget it, I know it's a really bad idea
Yeah, lets get back to programming :p
gpt is fine when you know it's wrong but if you're not experienced enough then you're setting yourself up for failure
if you think "its clean" you have a lot to still learn
I mean, I know its code is usually trash, but I use it if I need a simple character controller or something as simple as that.
Do you get what I'm trying to say?
no because if you're aware its bad why say its clean, they contradict
Your controller will probably multiply mouse input by deltaTime haha
always happens hahaha
plus you know its bad why not just learn to do it properly and actually gain knowledge
I mean, I use it to make really repetitive tasks. When Im making a really short prototype and I need a simple first person character controller, for example
But if Im in a relatively serious project I never use ChatGPT
ehh if you reuse code then you should learn how to make libraries / custom packages
so if you lose internet, you won't know how to do shit 😆
anyway lets move on from this as its not related to unity .
Lets leave it as "one person's trash is another person's treasure" 🤷♂️
Yes I did I can send you the script for both MediaPipe and implementing it for unity
well... are you sure? lol
the sample is there
Just checked it and I created mine a completely different way
Do you want me to explain what the actual problem is?
Cause it's a little bit more than what I left off
sure
are you saying you are using the media pipe package i linked, or did you try to integrate mediapipe yourself?
I already have the hand tracking in MediaPipe using Python and OpenCV(Open ur webcam) and it's able to track both hands fine. I'm trying to transfer all of that into a Unity simulation. The first hand worked fine but adding both of them is causing some issues
And Yes I tried to intergrate it myself
Sorry if i'm causing confusion
so... why not use the existing, high quality plugin that someone has authored?
it closely follows the javascript API, which is the authoritative one
i have a feeling that with how much lift mediapipe does, the whole thing would be less than 200 lines of meaningful python code. so it's not really worth doing yourself
-
It's a project for school and I got a deadline(Nothing serious as long as put effort I'll pass )
-
you're so right lol
lol i am sorry
I'll make a separate project with the plugin so I don't have to start from square one
i think this will all work out
yeah
i mean you learned the important parts which is the mediapipe api and turning 2d anchors into approximated 3d
hi guys ive ran into an error that has messed up my game, i was wondering if anyone could help me?
so as soon as i run the game it automatically pauses and shows this
well you have Error Pause on
so as soon you get error it pause
double click it and see where it takes you
how do u remove it?
which file is this
its this
yeah but where did you install it from exactly?
asset store or
https://gdl.space/iderocileg.cs
I'm trying to make an index of various classes inheriting from Particle that i can call to retrieve a new instance of that class, how do i store a reference to the class? above was my shot at it which dosent work but should get across what i was trying to do
apologies if i didnt understand your question (english aint my first language)
asset store
what version of unity are you using ?
I wanted to see where the url is coming from , the query
if its a url might need to just update it from http ot https
how do i do that?
dude you genuinly a legend , thank you so much , omgggggg thank youuuuuuu
can i why did the error randomly start popping up when it was working fine this whole time?
depends what you mean by the "whole time" ? afaik unity changed this requirement a while ago
its the asset dev that hasn't kept up with those changes i suppose
ah okay
its a safety feature
https://gdl.space/tuxizihofu.cs i think i figured out my issue
generally https are encrypted /secured connection
so doing anything over http(in this case asset tries to download update) can lead to compromises aka "insecure"
seems like you try to use stuff on enemy collider while it got destroyed at some point
Yep it's enemy
idk if this makes a diference but ive put loot that spawns when the enenmy dies
hmm what does TakeDamage method do inside
Between the time you get it with the OverlapCircle, and the time you try to get its .transform.position, you yielded a few seconds, and in the meantime the object got destroyed
You should check that it's not null before using it
1 sec lemme try it
The issue is not on TakeDamage, but one line above
The if statement with TryGetComponent will also throw the exception
yield return new ...;
if (enemy != null)
{
// do stuff with 'enemy'
}
should i add this word for word?
I removed stuff that was too long to type, but the if statement is what's essential here
This ensures that the code inside of it only runs if the enemy isn't destroyed
oh yeah good point
i think im too slow cause nothing has changed
Show your updated code
yeah dodnt judje ive got no clue whats happening
i believe i was not supposed to copy it word for word 
Well I told you not not copy-paste it blindly
// do stuff with 'enemy'
I mean, did you even read what you copied? Like this comment should be explicit enough on where to put the code that usesenemy
we have a strict “we will help, but not do it for you” policy
my bad i just dont really understand what he means
also should prob go in #💻┃code-beginner at this point xD
alright
is there a way to use the event keyword for a public event Action, but also give derived classes full access to the variable?
make a protected method that invokes the event, derived classes can call the method then and nothing else can
you're smart, bawsi
this is an unnecessary complication with the event keyword, but smart workaround.
err, I have a followup issue that confuses me
mover.joint is of type MoverJoint.
MoverJoint has protected void ImportSubscriptionsFrom
This code is in JointApproach : MoverJoint. Why must my qualifier be of the type of my derrived class?
can a derrived class not call protected methods from a different instance of a less derrived type?
Never seen that error before lol
CS1540
A derived class cannot access protected members of its base class through an instance of the base class.
whyyyyy
that is so asenine
whatever, I resolved it by making it static. which is a really dumb workaround
ty guys
Hey guys! I'm currently making a custom editor for my game
In a Button I have I'm trying to instansiate a new prefab and then move it to a specific position that is defined. However.. It instansiates the prefabs fine, but newPoint is null, so I'm never able to access the newly created gameObject and therefore can't move it
Any pointers?
GameObject newPoint = PrefabUtility.InstantiatePrefab(serializedObject.targetObject.GetPrefabDefinition()) as GameObject;
if (newPoint == null)
{
Debug.Log("well shit");
}
Is it possible to make Rigidbody2D.Cast() from custom position?
Without manually moving the object.
Nope, read the implementation of the docs. There's no option to supply a position.
Hey all. I am trying to create a new project, but I am getting the fallowing error.
Assembly 'Library/ScriptAssemblies/Unity.Collections.CodeGen.dll' will not be loaded due to errors:
Unable to resolve reference 'Unity.Collections'. Is the assembly missing or incompatible with the current platform?
Reference validation can be disabled in the Plugin Inspector.
I have Collections installed. I am not sure what is causing this
Also not sure how to/where is Reference validation can be disabled in the Plugin Inspector.
Could it be like the order in which the packages are being loaded?
Maybe the missing Unity.properties is causing it?
No just this time
it seems like a package confilict of some kind, but not sure where
Guess I am gonna make the project all over again -.-
Unistalled Netcode for GameO - Relay - Unity Transport... I forget why, there was a reason.. Oh yeah I was getting another error. It worked at any rate
I realize that my weird code before was adding a function to my OnDestroy method, which was accidentally public. So I had OnDestroy += method;
Is there a way to use this to just add methods to a call of OnDestroy?
hi guys, how can change the key of onmouse functions for instance onmouse functions using mouse0 but i wanna use the mouse1
probably use a getter
oh, actually you can change it directly on the event system on the scene
oh, okey
thank you but it won't crash will it? because I'm using an onmouse function and I know these are old system
or Is this old, too?
I don't know much about the input system
What OnMouse method are we talking about
onMouseDrag, onMouseUp etc.
Oh, hmm I'm actually not too sure of the input on those. Let me look at my built-in project
yes, go on
I just tried and this module working on just UI elements
Yeah, you're trying to grab input from just monos in general using the mouse, and not implementing the IHandler interfaces
I think I remember using this to remap keys in built in:
https://docs.unity3d.com/ScriptReference/KeyCode.html
Mouse event stuff like drag I remember having trouble with too, but I think I was polled input and checked for different input
okey, thank you for help I will try
Yeah, it seems that OnMouse from mono isn't customizable or rebindable from what I'm seeing. Usually I'd just use the Input class and raycast to see selected mono instead.
I like the way unity does the dragging so if I can get the right click that would be good but I also started thinking about raycast
if (Input.GetKeyDown(KeyCode.Mouse2)) //I think Mouse2 is right click, or it's middle
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //If we're using the mouse position too!
if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity))
{
Debug.Log(hit.collider.name);
return true;
}
}```
something like that usually
Yes, thank you for this instance
im making a 2d topdown minecraft like and I need some help with shading, I want it to look like terraria's shading. I have no clue what to do pls help
I drew this rectangular cuboid for my cursor with LineRenderer (for the simple reason that I need this to be dynamic in the future and have the lines stretch out). Those red-ish lines are lines which are drawn twice. Is there a way for the Line Renderer to "skip" these without having to create three additional line renderers which sole job it is to create the other three lines?
https://docs.unity3d.com/Manual/class-LineRenderer.html
The line is always continuous; if you need to draw two or more completely separate lines, you should use multiple GameObjects, each with its own Line Renderer.
can't I cheat this with manipulating the line size
🤷♂️ havent tried it specifically, maybe you could. There could even be some shader way of doing it but realistically your best solution is have more line renderers. No point in really finding a workaround that might bug out
man I didn't wanna refactor to have a dedicated LineRenderer script just to handle this stuff
I just threw it into my cursor script as a visual representation of the potential selection and was hoping for a dirty workaround
Your alternative was going to require more code anyways, making more linerenders is easier. You already have all the points, now you just split them up between the line renderers
what would create more stress on the CPU/GPU tho
considering that there are more objects 🤔
pre-mature optimization, use the profiler if you really care to find out. you'll need a ton of objects to even notice this in the first place
guess I'm using multiple LineRenderers then
Oh wait, it does have different colors
What if I use the alpha channel and set the color to full transparency when I'm drawing the affected lines?
that way they're still technically getting drawn, but they're transparent so they shouldn't show up
why are you using line renders for shapes
because it's a dynamic shape selector tool.
where are you going to set the color of a subset of your linerenderer? the color is for the entire line renderer
you can use unity's low level GL tools which is basically opengl immediate mode
this looks nice. you are overthinking this. create additional line renderers
there is no optimization issue here
Overthinking is my personal strong suit 💪
never looked into those. Could I create flexible wireframe cuboid shapes that I can stretch using coordinates with these?
(I've been using Unity for like a month, but I have been coding prior to that)
what
trust me
🤔 I still need to make a grid anyway, so it'd definitely be worth looking into that either way.
you shouldn't touch this namespace
if you need a line grid in 3d, you know, say so. what is your goal?
what are you actually trying to do?
basically a level editor.
For the sake of simplicity (as this is a prototype) I'm restricting myself to 90° angles for this
I'm not seeing where it says it's deprecated beyond some extra settings you need to adjust for SRP
The line grid is a different thing that I've yet to implement, the current thing I'm doing is supposed to be the drawing tool
and you can like manipulate its size and the "cursor" cuboid thing is gonna stretch in size according to your liking
use this asset - https://doubtfulpixel.github.io/AssetStore/WirePrimitives/index.html
that is lookin fancy
This is my GL implementation via editor scripting
specifically just show the grids but I make large shapes as previews too since
I guess simply due to me having implemented a bit of logic to what I already got, I'll just do some additional LineRenderers for the cursor
as much as that annoys me...
you can use EventSystem on 3D objects. use input system. then you can customize as you need.
Why are you sharing a chatgpt link
Honestly, if it works then go for it. I'd expect more drawcalls per shape than normal though, but it's probably not of an issue if your game is small enough.
I guess we'll see later if that's gonna make a difference or not
I get you really like gpt, but it is explicitly against the rules to use it for answers here. Please stop
Does anyone have any experience
Coding a wander AI?
Using A*?
Because I want to make my little butter creatures wander around the garden, however the online resources seem to not use A*, and ignore obstacles.
Navmesh is the default implementation of pathfinding in unity.
• Use unverified AI-generated responses in questions or answers.
i am verifying the answer is totally correct. it saves me the extremely tedious experience of writing step by step beginner content
It should avoid obstacles if set up correctly.
However I have another issue
The traversing seems quite random, and seems to have no purpose
How do I create a priority to a specific location?
Or a specific thing?
Just don't answer then
Save it for people who don't find helping people to be tedius
Like sometimes I would love the little things to walk to the player randomly
Would I just randomly add a waypoint?
That's all up to your code logic.🤷♂️
So it doesn't have a specific function for setting priority?
I'd have to force it there?
Look into creating a statemachine of logic for your AI
I shall
I've seen it coming up
No, there's no such function. PathFinding would just find a shortest(mostly) path to the destination. Any other logic is unique to your game.
Thank you, I'll work around it then
I appreciate the help, I was struggling to find a proper starting point
I'll check out navmesh
How i can mouseover the list object at list of script in the inspector?
decided on adjusting the material instead so it wouldn't shine through, now it looks pretty good!
@cosmic rain
Sorry I think I forgot to say that I was using 2D
That was why I was using A* not Navmesh
How would I let my little 2d butter guys
Walk around this map
Randomly
Not stepping on garden beds
The squares with the birch outline
I can use A star, but how do I make A star randomly move it
I can't find proper wander tutorials online for this
hello, everyone. I recently got a new computer and cannot get the microsoft visual studio code that comes with unity to show me error squigglies or any errors at all. Looking for any help I can get :(
thats not visual studio code
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
One of the most surprisingly efficient ways is to just pick a random point and check whether or not it's valid, that gives you a target for A* - keep picking until you find one that is
an alternative would be to just iterate smaller steps - just pick a direction and move one tile in that direction if it's valid, then repeat
Hm, thank you, how would I figure out whether or not it is valid. And how do I set a position instead of object for target? Because I'm using a tilemap.
Do I just spawn an object in a random position?
And set that as the target?
Oh yeah
How do I check for a tilemap
whoops you're right, mb. I had to completely reinstall the editor package through unity and it worked so 🤷♂️
Thank you!!
https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap.GetTile.html is probably sufficient
Thanks man!
However
They're all seperate tilemaps
So do I just check if it's colliding with that?
The beds tilemap?
Would the be sufficient?
Excuse me Lashen and Deynai do you guys know what is unity rider failed
No, sorry man
wow thank you, this thing can work on 2d object?
@mental rover
I was trying to employ the technique you described to me, however I have an issue, and it comes from the documentation for A*
They always use:
ai = GetComponent<IAstarAI>();>
However how would I set this up in my scene? I do not seem to be able to find a script called IAstarAI
When I try to add a component
I have attempted to do it this way
Ignoring the tile situation for now, I have used the same reference as they have in the docs, however how do I add that component into my object
If it's a component: https://docs.unity3d.com/ScriptReference/GameObject.AddComponent.html
No that's not the problem, in A* we have a pathfinding component and such, however the docs are asking for IAstarAI and they never say how they attach this component. I'm pretty sure a pathfinding component requires me to check a few boxes manually in the editor, so adding a component this way is not optimal.
the name suggests it's an interface, I'd read the docs more carefully on how to use whatever plugin or repo you're looking at
I couldn't understand your original question
how do I add that component into my object
sorry, I meant through the editor
sure I will do that further, it's not apparent to me though.
thank you
Unless your class inherits monobehaviour it'll not be visible through the inspector without a custom editor.
yes, physics raycaster 2d
then you don't need to use your own raycasts
it's like a lite version of web page event listening
hey all. One more question, I'm dynamically updating a navMeshSurface, and my projectiles are now editing this surface to not be walkable. What's the best way to fix this? Obviously you can't use navigational static anymore
Managed to kind-of work around this by changing the navMeshSurface component to only check for the physics colliders, but it still seems to have changed the collisions for my enemies for some reason.
Exclude the object from the considered objects to bake.🤔
I think it depends on the settings of the surface, but usually it would only consider stuff parented to it. If you put the projectiles outside it's children hierarchy, it shouldn't consider them during baking.
Oh, I guess it's defined by the Collect Objects setting.
Set it to Children to only consider it's child objects.
Could also use layers to exclude whole layers of objects.
thank you so much
Basically, read the manual:
https://docs.unity3d.com/2020.1/Documentation/Manual/class-NavMeshSurface.html
yeah I got it to work by excluding a bullet layer. Thanks for helping me troubleshoot 😄
if im using a service like unity relay, will using authentication like this allow me to test with the host andclient on the same machine without any errors? imn trying to make sure that they don't have the same playerid
InitializationOptions options = new InitializationOptions();
options.SetProfile("Player" + UnityEngine.Random.Range(0, 1000));
await UnityServices.InitializeAsync(options);
await AuthenticationService.Instance.SignInAnonymouslyAsync();```
Cinemachine 3.0 is murdering me but I've successfully managed to make a custom input controller where you can control the sensitivity :')
Anyone have a good strategy for how to handle satisfying souls-like dodge rolls?
I currently have a simple constant velocity transform.position style code, but obviously it seems not so satisfying and a bit janky. Anything in specific I should look into for this?
can somebody help me with this movement that im trying to implement?
Need to ask a question with some details before anyone can decide if they can.
I have this script and i am using the unity input system and i know its getting input correctly but in my script its not assigning the vertical/horizontal input in my script
Well, share you code as you were asked in #💻┃code-beginner and stay in one channel (there)
sorry
async Awaitable JumpCooldown()
{
onJumpCooldown = true;
await Awaitable.WaitForSecondsAsync(.9F, destroyCancellationToken);
onJumpCooldown = false;
}
```Hey, is that really an error or just an information that async method has been cancelled? What should I do with it? 
Just spent about 20 minutes trying to debug something but turned out to be due to the script execution order... sigh
Be grateful that it wasn't 20 hours😛
Yeah, at least you did find solution
{
StartCoroutine(HealthRegenerationCoroutine());
}
private IEnumerator HealthRegenerationCoroutine()
{
while (true) // Infinite loop, you can add a condition to stop regeneration
{
if (playerHealth.currentHealth <= playerHealth.startingHealth)
{
playerHealth.currentHealth++; // Increase health by 0.5
yield return new WaitForSeconds(1); // Wait for 1 second
}
}
}```
i have these two funcs, and EnableHealthRegeneration() is called when i press a button, but my game completely freezes when this func is called and the only way for me to fix this is to close unity through the task manager bc i can't even see my cursor (alt+tab and pressing the x doesnt work either for whatever reason). Does anyone know why this code is so bad? (my cpu and memory usage are fine so i dont think thats an issue)
how about when playerHealth.currentHealth > playerHealth.startingHealth
that crashed unity even faster 😭
wtf is going on??
what will heppen when playerHealth.currentHealth > playerHealth.startingHealth?
they were asking you a question, not telling you to change your code
nothing bc it can never be achieved
i should rephrase my question, a bit weird....
so what will your code does
i have no idea what you mean by that
lets say your coroutine starts, the current health is 5 and starting health is 4 . What happens line by line in your code?
oops, fixed
while(true){
if(somebool){
wait one second
}
}
```what will happen when somebool is false
ummm, i dont know?
will it waits for one second?
nothing would happen, i assume? bc the condition isnt met?
no it would skip over bc the if statement isnt called
ok and what does while do?
makes it so that it checks the if statement
so will your code stop executing if it doesnt wait for one second?
it'll crash your unity because it would never exit out of the while(true) clause
or spin endlessly
you need an alternative method of implementation where there is no while loop that is inifnite
so all im missing is "return;"?
it is a loop. meaning that it will continue to check the "if statement" (its just checking true) over and over
why is that an issue? what makes it so that the other code doesnt run?
because its a while loop
If I told you to count to a billion, then go clean the kitchen. The kitchen is never gonna get cleaned
ig i never knew how while loops worked, thanks for the analogy
more like if you told him to count upwards towards infinity, starting at 0, and only stop when you reach -1
so how do i fix this?
i dont know if your regeneration buff is based on current health or time-out (minecraft potion), so "return" may or may not fix it, depends on your choices
You dont want to just return, because you have to yield in a coroutine or you might freeze up your editor still. If the method starts and the current health is already above the starting health, itll freeze. I would just throw a yield break in that while true if its greater
to clarify also, it is not a crash. your editor is simply freezing
you could alwyas implement it so:
bool canRegen;
void RegenHealth()
{
if (!canRegen) return;
currentHealth += [whatevervalueyouwant]
StartCoroutine(regenCooldown);
}
IEnumerator RegenCooldown()
{
camRegem = false;
yield return new WaitForSeconds([value]);
canRegen = true;
}
keep regen health inside of update or smth
if you're using update already, no need to use a coroutine for that..
FixedUpdate()
{
if (currentHealth < maxHealth && canRegen)
RegenHealth
}
true
but its a faster implementation
🤔 faster in what regard, we are talking about a difference of 2 lines of code. Starting a coroutine every 1 second is gonna be more costly than not doing it
I mean faster to get implemented
not physically faster
I'm probably mistaken lmao
idk what you mean by that. its the same lines of code pretty much
why does it freeze EVERYTHING tho? wouldnt it just pause all game physics calcs and not everything that has to do with the unity editor?
float timer = 0f;
float regenCooldown = 1f;
void Update()
{
timer += Time.deltaTime;
if(timer > regenCooldown)
{
timer -= regenCooldown;
// Add healing logic
}
}
as simple as that
that's just how unity handles it
You are telling your editor to count towards infinity before doing ANYTHING else.
unity will be like "oh no infinite loop, that's not meant to happen, lets crash the editor so that its not having to be force shut via task manager or smth"
it is not running everything async
even though coroutines are single threaded, there is some performance gains for sleeping
the entire editor tho? do programs not have logic split amongst cores so that you have multiple workers instead of one?
over polling each frame (so it becomes a cache/GC to runtime performance problem)
unity does its own async stuff for some things. Your code is all gonna be single threaded unless you do some async sheniangans yourself (you dont want to)
yeah ^
Still, it is an infinite loop. What should unity really do about it, they cant just assume your code is stuck and free you out. What if you were doing expensive terrain generation and it took 30 minutes? how would they know
Most programs have a main thread loop and execute some other logic on background threads.
alr thx for all of the help guys @lean sail @untold siren @fervent furnace
unity has inifnite loops treated as a crash just incase the infinite loop is accidental (which is 99.9% of the time)
there is multi thread support but you dont get to touch it
most of it is done under the hood
You can't have the whole program spread between cores evenly. That's not gonna work.
I'm not sure about that statement.🤔
You can't really detect an infinite loop from outside of it.
if its something like a permantently while(true) with no valid exit clause though then wouldn't unity kinda be like "huh"
what, no
No. Not really.
halting problem
windows might give you the "your program isnt responding" thing after awhile, dont know but thats not a unity thing
beautifully said
no cap this is what one of my lecturers told me 💀
Some platforms would wait for an event from the app on regular basis and shut it down if it didn't respond for long enough. For example PS4/5, but I'm not sure there's a mechanism like that in windows.
Hey, sorry but I am experiencing a strange issue unrelated to "coding" per-say but I do need assistance with this. I am running Unity in Linux and opening a file that was once running on a windows machine but now I am getting this error. Anybody have any idea how I can repair this?
Aborted (core dumped)
what distro ?
watchdog timer, but i believe window os doesnt provide such functionality, it is mainly used in embedded system (you can just open task manager and close the freezed application)
erm, 21.2
that and sudo apt install libssl-dev
I remember having the same issue on my laptop a while back
Yeah, I ran this command and it downloaded and all but didn't resolve the issue. I'll check out that link though, thank you for the help!
yeah most the time its due to version mismatches
pain in the ass sometimes with linux lmao
That's sort of what I figured
It can be, but the pay off is worth it for me 🙂
oh I completely agree :D I love linux don't get me wrong, part of the fun is fixing this type of stuff but sometimes its annoying when you just wanna work on something 
Haha, I totally agree homie
My man, you fixed it
Thanks a million, going to take note of this
just you wait until you try to install smth like autodesk maya on a distro that isn't fedura or centos lmao
Oh heck no 🤣
Blender for 3D, Aesprite for 2D, Unity ofc, the only "windows" program I actually run in Linux is Visual Studio but that's because it's so good
I like blender but since I learnt maya first I have no idea where to start with blender
Jetbrains is a nice ide to try btw
Jetbrains, I'll have to check that out
Can I save 2d array to json? I get right now
yes but not using unity's jsonutility
What do I use Instead?
pretty sure newtonsoft can do it
Has anyone here played around with MLAgents?
Yep, they are pretty cool
ok right:
so I have a state machine setup for my camera perspectives, each has its own individual state script alongside its own cinemachine camera
everytime I go to change camera perspective, I need to set the previous cams priority to 0 / something that isn't the highest priority in the scene
would the best way to store a reference to each cam belonging to a state be via a dictionary? or would there be a more efficient way of going about this
how many cameras in each state?
each perspective will be its own state
like 1st person is its own state, 3rd is its own state etc
but there's a camera controller script basically
you're not answering my question
ok, how many states
there should be four or five by the end of implementation
then a List which you loop over will be more efficient than a Dictionary
so I could just do List<CinemachineCamera> stateCams and then each time I define a state I'd just do stateCams.Add( //state name cam )
(I'm uising CM 3.0 btw which is why its not CinemachineVirtualCamera)
no, I would have all the cams in one list, you dont want to have to move cams from one list or dictionary entry to another, very costly
FirstPersonState = new FirstPersonState("FirstPerson", _cameraStateMachine, this, firstPersonCam);
cinemachineCameras.Add(firstPersonCam);
ThirdPersonState = new ThirdPersonState("ThirdPerson", _cameraStateMachine, this, thirdPersonCam);
cinemachineCameras.Add(thirdPersonCam);
so basically like this?
yep
awesome, and then if I were to do the whole priority setting thing I check if List contains the certain camera I want, then exclude it from making sure that the priority is then set to 0
its the same way I've setup my player states too, it's not actively being checked or anything, its more just as a label
I can understand the reasons to use enums but I'm making no proper checks for them
Enums much more efficient than strings
I'll shift it to that at some point, will add a // todo:
who needs type safety

if (!_cameraController.cinemachineCameras.Contains(newCamera)) return;
var camIndex = _cameraController.cinemachineCameras.IndexOf(newCamera);
var activeCam = _cameraController.cinemachineCameras[camIndex];
foreach (var cinemachineCamera in _cameraController.cinemachineCameras.Where(cinemachineCamera => cinemachineCamera != activeCam))
cinemachineCamera.Priority.Value = 0;
activeCam.Priority.Value = 10;
assuming this is a valid way of setting the priorities?
horrible but valid
XD I would have assumed that, what's the better method of going about this?
just a straight for loop with an if check
you could even just set the priority to 0 of the previous active cam, no need to go through every camera
indeed, cache activeCam
true that works
or, better yet cache active cam index
I'm learning lmao
need to move it off of one of my static classes to do so but this seems to be for the best
Yeah, just going to stick to caching the active cam instead of the index as this seems a bit :/
that's the old school in me, why use 64 bits when 32 will do the job
if it was within the same script file etc then I'd have done it via the index reference, but also by doing it via variable reference it makes it a bit more readable for me :) thank you for the help though!
I've created an hp bar with hearts for my game, and the way I'm deciding how the hearts should render is I iterate through my max hp (think like 8 hearts), and if the (current iterator - hp) is more than 2 it's a full heart, between 0 and 2 it's a half heart, and if it's negative then the rest of the hearts are empty. I come from a web background so my perception of UI is a bit different, but is it fine for this loop to be run on pretty much every update? The players' hp is expected to change quite rarely, yet this loop (which only has like 10 iterations but still) would almost unnecessarily run every single frame. Is this a normal pattern for gamedev, or would it be better to memoize the hp and only recalculate if the player hp has changed? Or is the memoizing just gonna do more harm than good. I know this is probably a very tiny micro-optimization, but just slightly worried of dying from a thousand paper cuts later on because of doing things in an anti pattern way
(also I know I can remove the if conditional there if I just do 3 separate loops by precomputing the number of full and empty hearts)
Unity also has to do the work to call that Update each frame, which is surprisingly non trivial. I would consider events as an alternative. Early outs to skip redundant work is common.
But yea, it's unlikely to matter here.
Yeah I was thinking if I had a similar case but for example with inventory, which I suppose would be bigger and could require some fancier computation. I'll look into events
Would this still be a monobehaviour with an update in it? It's what I've been gravitating to by default but not sure if I should be carelessly throwing it around
Depends on whether you still have code that you want to run each frame. It's fine to throw around whenever you want to run code per frame.