#archived-code-general

1 messages · Page 233 of 1

lean sail
#

Repeated keys in a dictionary wouldnt make sense, because you wouldnt be able to differentiate between which are which. So you can just use a regular dictionary (the key is whatever you want) and the value is a list of the type you wanted to store. Instead of having a repeated key, you add to the array

#

Like dictionary<int, List<int>>

soft ruin
#

what my intended use case is an <int, string> list that stores the message and how fast its typed

soft ruin
soft ruin
#

nevermind

lean sail
dusk apex
#

Int to anything would always be preferred with list or arrays

lean sail
#

I would just store this in a class

latent latch
#

in a hashset too

soft ruin
#

is hashset 2d i forgot

latent latch
#

message as the ref with variables of how fast it's typed

lean sail
soft ruin
#

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)

lean sail
soft ruin
#

tyty

latent latch
#

what's the use case of the dictionary anyway?

#

as such, how are you accessing the dictionary

dusk apex
#

I'm assuming it's to map the speed of typing to particular string responses.

hard viper
#

i would only use a dictionary for random access of whole cutscenes, maybe

#

a dictionary is a terrible data structure to hold dialogue

latent latch
#

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?

hard viper
#

i would make one class for a single textbox. and give an inner data structure to change text speed throghout

latent latch
#

easy -> dictionary 1
medium -> dictionary 2

hard viper
#

i would probably write dialogue as a string with special formatting characters. Then textbox class parses that string onto a couple of distinct parts

latent latch
#

oooh it's a dialogue system (I must have read over that)

#

im thinking it's some word game

hard viper
#

eg “I like to go <fast>really <slow> fast.”
Textbox clsss parses this into:
0) “I like to go “, speed = medium

  1. “really”, speed = fast
  2. “ 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

dusk apex
#

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.

hard viper
#

at no point should a dictionary be involved in this procedure

latent latch
#

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

hard viper
#

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

latent latch
#

Yeah, that itself would be some sort of system, and it would be unique to each message.

#

doesn't sound too hard

hard viper
#

this sounds like something you learn to do in an intro CS class

#

really basic shit

latent latch
#

you'd have a default speed, then interrupt it with different speed (maybe some wobbling text animation) depending on word (coroutine, yield, continue)

hard viper
#

yeah. there are addons for this, i bet

robust mantle
#

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

dusk apex
#

Is the player position relative to it's head or some other bodily part?

robust mantle
#

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

dusk apex
#

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

robust mantle
#

oh wait its not because the script allows you to move it according to the mouse y input

dusk apex
#

The one is obsolete here btw: a + 1 * (a - b)

robust mantle
#

oh ya ik

#

i was gonna replace it with magic numbers at some point

dusk apex
robust mantle
#

im still sorta confused though, if the cameraHolder's position - cameraPosition, shouldn't it be going on the red line backwards?

dusk apex
#

I'm assuming the camera holder position isn't what/where you think it is.

#

Try logging it.

robust mantle
#

i have a scene pulled up when im in game mode, it's always on the player's head

dusk apex
#

Log the position of the camera holder

robust mantle
#

okay wat now?

dusk apex
#

What did it print?

robust mantle
#

(0.00, 0.99, 0.00)

#

it stays constant pretty much the whole time

dusk apex
#

And what's the position of transform.position?

robust mantle
#

Vector3(-1.49011612e-07,1.53496134,-0.16560626)

dusk apex
#

So they aren't at the same height

robust mantle
#

ya the more you move your mouse vertically, the more the position of the camera's y value changes

dusk apex
#

(1.5 - 0.99) normalized is the offset you'll gradually get on the y axis

robust mantle
#

wait mb the camera's position is 0,0,0 until it gets to the minimum zone and starts glitching out

dusk apex
#

Meaning you'll eventually go above the target

dusk apex
#

We only care about what was logged, not what you see in the inspector

robust mantle
#

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?

dusk apex
#

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.

robust mantle
#

I thiiink I understand now

solemn wren
#

Is there a way to check if a nav mesh agent is at the edge of a nav mesh surface?

cosmic rain
solemn wren
#

@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

robust mantle
cosmic rain
solemn wren
#

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

cosmic rain
solemn wren
#

how do I do that, is that a built in function or will I have to make that myself?

polar marten
polar marten
cosmic rain
polar marten
#

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

tiny orbit
#

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?

solemn wren
#

@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,

cosmic rain
polar marten
tiny orbit
#

ok

polar marten
visual fjord
#

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?

cosmic rain
visual fjord
#

ok but how do I compare if a vehicle has more number of laps?

spring creek
visual fjord
#

You have an exaple script?

fervent furnace
#

do you know what are array and loop?

visual fjord
#

Yeah

#

Why?

fervent furnace
#

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

cosmic rain
#

You can have a list of cars and use the sorting function to sort it by their progress.

visual fjord
#

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

fervent furnace
#

store the vehicles somewhere in the manager then after every one updates its position, sort it

visual fjord
#

How call the function sort?

visual fjord
#

Ok

cosmic rain
indigo plume
#

can someone help me for some reason i tried building my marble game on webgl and i got this error

hasty wave
#

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

grim acorn
#

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

somber nacelle
lean sail
fervent furnace
#

i use vsc since i need it to code c/cpp/java, not just c#.......

hasty wave
#

I see... interesting. Thanks :)

lean sail
#

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

dull glade
#

I can't seen to get my UI elements to be draw on top of everything

sour wasp
#

first child object (from the top) is drawn first, second is next, etc

lean sail
lyric moon
#

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

tired elk
#

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 ?

brittle sparrow
#

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

main shuttle
brittle sparrow
#

looks lke this

#

oh

#

paint

#

im using gimp, but that also has text

#

but yeah..

knotty sun
#

why are you writing out a byte[] as an ascii string?

brittle sparrow
#

to save it into a file

#

not sure how else to save it

knotty sun
#

just use the WriteAllBytes and ReadAllBytes methods

brittle sparrow
#

oh

#

oh god im saved

#

thank you

#

i havent tested it yet but it seems so promising

#

it has to work

knotty sun
#

next time try doing some research and read the damn docs

brittle sparrow
#

thank you very much!

soft shard
lyric moon
#

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

knotty sun
elfin quest
#

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

visual fjord
#

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?

edgy sierra
#

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.

cosmic rain
#

Also, it seems like unity web request doesn't have a problem with https. Although, you might need to implement a custom certificate handler.

edgy sierra
#

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

visual fjord
#

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?

edgy sierra
#

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

visual fjord
cosmic rain
edgy sierra
#

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

knotty sun
# visual fjord

your sort is pointless, you cannot return a value from a void method also !code

tawny elkBOT
cosmic rain
#

Well, you can write your own wrapper to get a return value.🤷‍♂️

edgy sierra
#

of course i can I can also use the legacy WWW request handler, I'm asking what are the best practices for it

cosmic rain
#

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.

edgy sierra
#

not exactly an answer...

cosmic rain
#

There are no best practices when it comes to choosing implementation

visual fjord
#

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?

cosmic rain
visual fjord
#

no not yet

cosmic rain
visual fjord
#

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. .

cosmic rain
#

You can even make it a percentage of the whole loop: current checkpoint index / total checkpoints.

visual fjord
#

because if several cars are at the same checkpoint number I need to compare the distance of each checkpoint each

cosmic rain
knotty sun
#

just keep a running total of the total distance traveled per car

cosmic rain
#

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

visual fjord
#

I take the first option

cosmic rain
#

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.

knotty sun
cosmic rain
#

Also performance cost(probably negligible but still)

cosmic rain
visual fjord
#

ok I'm going to see what I can do based on the orderby functions and I'll tell you anything about that

urban lintel
#

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?

knotty sun
urban lintel
#

and im assuming the best (only?) way to do that is through the inspector?

somber nacelle
#

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

hard viper
#

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

clear umbra
#

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:

  1. Should I be using c# events or UnityEvents? Are there pros and cons to each one?
  2. 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?

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?

leaden ice
# clear umbra Hey guys, old unity dev getting back into things. I'm creating an event system ...

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.

leaden ice
#

Player.OnHit is a lot more expressive than EventManager.OnHit.

leaden ice
clear umbra
#

would it be similar syntax / usage to do so?

leaden ice
#

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

crude mortar
#

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.

leaden ice
#

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

clear umbra
#

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?

crude mortar
#

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

leaden ice
# clear umbra Ok so if I'm understanding this correctly, the delegate would be equivelant to t...

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
clear umbra
#

oh I think i get it now

hard viper
#

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

clear umbra
#
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;
}
hard viper
#

of all my delegates, 95% of them are Actions

clear umbra
#

alright, thanks for clearing this up for me!

leaden ice
#

Action vs custom delegate type is a matter of personal preference

clear umbra
#

makes a lot of sense now

hard viper
#

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

quasi cobalt
#

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?

south gorge
#

I think this would be called a public class

#

i need it to look like this

#

after collision with an object

somber tapir
# south gorge
if (collision.gameObject.TryGetComponent(out FlagVaribles redFlag))
{
    flagVar = redFlag;
}```
quasi cobalt
#

idk, there is no range given

somber tapir
quasi cobalt
#

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

leaden ice
#

Tables are LUA things

quasi cobalt
#

yeah I know multiple languages but not theory specific stuff though

leaden ice
#

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.

quasi cobalt
#

yeah, it also acts different, thats why im asking

leaden ice
#

It depends how you want to use this thing

quasi cobalt
#

just wanna get random class out of it and access its data

leaden ice
#

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.

quasi cobalt
#

I mean theory as in "you know what I mean but theoretically this isn't right"

#

my bad

south gorge
#

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

heady iris
#

Is TryGetComponent not working?

#

you should use some log statements to check

south gorge
leaden ice
#

flagvar = redFlag needs to go first

#

otherwise you are calling flagVar.flagPickedUp on null

#

hence your error

south gorge
#

omg

#

i think it worked

#

thank you

#

so much

leaden ice
#

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

south gorge
#

I need to study this a bit

leaden ice
#

See how it works with the blue flag as well? You should just call it flag for example

south gorge
#

okay! Thank you so much I have been stuck on this for a while haha

#

okay i changed it

tawny elkBOT
finite prawn
#

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

vagrant blade
#

Did you actually type a string value into enemyTag for both objects? One of them could be blank or mistyped.

finite prawn
#

i did and i removed the = "Enemy" after the issue first happened as an attempted fix

vagrant blade
#

Can you show that you've assigned values to enemyTag?

finite prawn
#

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();
    }
}
vagrant blade
#

And show the object's inspector that you're hitting?

finite prawn
#

hitting?

vagrant blade
#

The thing you want this Minion to stop when it hits

finite prawn
vagrant blade
#

You sure there's no trailing space in that tag?

finite prawn
#

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

hard viper
#

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

finite prawn
#

where would i get this plugin

#

or how would i do this

vagrant blade
#

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?

leaden ice
vagrant blade
#

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.

finite prawn
leaden ice
#

oh sorry, yeah i guess that was the issue

finite prawn
#

yes

leaden ice
#

but logging would help you find it in the future

finite prawn
#

ok ty

heady iris
#

you can also add breakpoints in a debugger

leaden ice
heady iris
#

i've started doing that more often

leaden ice
#

this seems like a less efficient version of OnTriggerEnter2D

heady iris
#

it doesn't require a compile!

finite prawn
#

and chatgpt said to use Physics.Overlap

heady iris
#

each collision will cause a separate message to be sent.

hard viper
heady iris
#

huh, "TNRD" is a familiar name...

hard viper
heady iris
#

ah! same person that wrote SerializableInterface

#

that's why.

finite prawn
heady iris
#

i just use a grenade as a toilet plunger alternative

#

💥

finite prawn
#

same

hard viper
#

i would avoid ChatGPT for anything coding related, unless you know what you are doing so well that you can immediately spot every mistake

finite prawn
#

why

hard viper
#

then you can be like that one guy who constantly raves about chatGPT while everyone else boos him

heady iris
#

it generates plausible text

#

it does not generate "correct" text

finite prawn
#

i just ask it googleable questions not write code

hard viper
#

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

finite prawn
#

ill consider that

visual fjord
#

Don't working

knotty sun
# visual fjord

whats not working? You are doing nothing with the output of the OrderBy

simple egret
#

OrderBy does not order the list in-place, it gives you a new one to iterate on

heady iris
#

yes, it's a method from LINQ

visual fjord
#

My idea is to organize them from largest to smallest

heady iris
#

all of those methods produce a new sequence. they don't mutate the original.

simple egret
#

List<T>.Sort() sorts in-place

#

You'll still have to pass a lambda expression to specify what to sort by

visual fjord
simple egret
#

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

visual fjord
#

See

naive swallow
#

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?

simple egret
heady iris
#

you need to read what we're writing.

visual fjord
#

wait

#

I think those functions of "Order" not working

naive swallow
visual fjord
#

How

simple egret
#

The first one works, not the second

heady iris
#

yes, because, as we all wrote, OrderByDescending just produces a new sequence

#

it doesn't change cars

#

cars.Sort alone is enough.

visual fjord
hard viper
#

separately, that list should be public get private set.

#

eg public List<CheckpointChecker> positions {get; private set;}

heady iris
#

let's not throw more information in right now..

hard viper
#

sorry, i can’t help myself

simple egret
heady iris
# visual fjord see

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.

hard viper
#

is he using System.Linq? I think that method requires it.

visual fjord
#

How can see the array in the Inspector?

hard viper
visual fjord
#

I don't idea

hard viper
#

hold up, you can’t do that

heady iris
#

I suggested a way to get a list.

#

If you don't get a list, you can't see it in the inspector.

hard viper
#

positions should be a list

heady iris
#
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?

hard viper
#

is he still here?

#

i worry he’s just plugging things in and only coming back after it doesn’t work, without listenning

heady iris
#

yes

#

getting a strong "shotgun debugging" vibe here

naive swallow
simple egret
#

I don't think so, you might need to roll your own - but the E format specifier will do half of the job

visual fjord
#

thanks

steel finch
#

gridCells = new GridCell[10];
gridCells[0].x = 1;

This is returning a null reference exception and my brain is not braining any more

simple egret
#

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

steel finch
#

ic

simple egret
#

You need to do gridCells[0] = new GridCell() before trying to access anything on it

steel finch
#

the thing that confuses me is that this exact code was working completely fine

simple egret
#

I don't think so

steel finch
#

then I decided to take a break so I closed unity and when I went back it stopped working

simple egret
#

Either the code was not executing, or it was modified

steel finch
#

I'll look into it

steel finch
visual fjord
#

How can i know the index the each car in the List Cars?

simple egret
visual fjord
#

Well

#

I need know index the cars the list

rigid island
#

makes no sense

visual fjord
simple egret
#

Yeah can you rephrase that? I didn't understand

visual fjord
#

This list

rigid island
#

yes but what do you want to do

#

forget the index part for sec

simple egret
#

Ah I think I see

rigid island
#

oh this is some sort of leaderboard?

simple egret
#

They want to use the list index to fill out the CheckpointChecker:Position variable

rigid island
#

or AI manager

simple egret
#

Then use a for loop to go through the list

visual fjord
#

How?

leaden ice
hard viper
# visual fjord How?

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

spring creek
hard viper
#

if you are unfamiliar with for loops, you need to do some metaphorical pushups before tackling a game

finite prawn
#

one for detecting and one for being detected

leaden ice
#

especially in this case

hard viper
#

OnTriggerEnter gives a specific collider. You can get all sorts of information from that collider, including the gameObject it is on

finite prawn
#

but then the detection area of the gameobject that is being detected will be detected

#

and also whcih collider would the function use

hard viper
#

OnTriggerEnter just detects any valid trigger entries

finite prawn
#

exactly

hard viper
#

which can be manipulated with things like layer

#

and layer overrides

finite prawn
#

yeah i didnt get the layer thing thats why i used the other way

polar marten
hard viper
#

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

finite prawn
#

i have the different problem

hard viper
#

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

hard viper
#

or separate scripts that only get triggered with that one collider

visual fjord
spring creek
# visual fjord Yes

Well, I literally wrote it out. I guess replace "someMaxValue" with Cars.Count (it's a list right?)

polar marten
finite prawn
hard viper
#

i’m sure ChatGPT will explain it perfectly

polar marten
# visual fjord

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

hard viper
#

good luck with that

visual fjord
#

Well now i need know the position de each car the list de card

#

This list

simple egret
#

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

hard viper
#

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

simple egret
#

just don’t ask ChatGPT to make you a 60 card deck

hard viper
#

but i’m sure ChatGPT can handle simpler tasks like programming, just fine

simple egret
#

Awful advice lol
Asking a beginner to use gpt

hard viper
#

well what do you suggest? a magic 8 ball?

rigid island
#

you're better off

visual fjord
simple egret
#

Actually learning the language is an option

grizzled ferry
simple egret
#

These statements contradict themselves

grizzled ferry
#

So, in my opinion, you can use it only if you know what you're doing

hard viper
#

at which point you wouldn’t be using chatGPT

rigid island
simple egret
#

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

grizzled ferry
# simple egret These statements contradict themselves

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

rigid island
finite prawn
#

chatGPT is really good at quick simple questions, just so you dont have to find a good link on google

rigid island
#

but yes lets move on from this topic

finite prawn
#

ok

rigid island
#

as long as we don't tell someone use GPT which is just reckless advice

finite prawn
#

they did say GPT 4 no ChatGPT 3.5

simple egret
#

lol

#

Shows the knowledge of the tool

grizzled ferry
latent latch
#

gpt is fine when you know it's wrong but if you're not experienced enough then you're setting yourself up for failure

rigid island
grizzled ferry
#

Do you get what I'm trying to say?

rigid island
simple egret
#

Your controller will probably multiply mouse input by deltaTime haha

grizzled ferry
rigid island
#

plus you know its bad why not just learn to do it properly and actually gain knowledge

grizzled ferry
#

But if Im in a relatively serious project I never use ChatGPT

rigid island
#

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" 🤷‍♂️

vestal surge
#

Yes I did I can send you the script for both MediaPipe and implementing it for unity

polar marten
#

the sample is there

vestal surge
#

Do you want me to explain what the actual problem is?

#

Cause it's a little bit more than what I left off

polar marten
vestal surge
# polar marten sure

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

vestal surge
#

Sorry if i'm causing confusion

polar marten
#

it closely follows the javascript API, which is the authoritative one

polar marten
vestal surge
vestal surge
#

I'll make a separate project with the plugin so I don't have to start from square one

polar marten
#

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

vestal surge
#

Yessir

#

I'm pretty sure having hand tracking in general is sure to get a solid A

broken zodiac
#

hi guys ive ran into an error that has messed up my game, i was wondering if anyone could help me?

broken zodiac
#

so as soon as i run the game it automatically pauses and shows this

rigid island
#

so as soon you get error it pause

#

double click it and see where it takes you

broken zodiac
#

it takes me here

#

this is the A* pathfinding project i imported

broken zodiac
rigid island
broken zodiac
#

its this

rigid island
#

asset store or

rugged storm
#

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

broken zodiac
broken zodiac
rigid island
rigid island
#

if its a url might need to just update it from http ot https

broken zodiac
rigid island
#

fix Url

#

or you can try this I suppose. Project Settings -> Player

broken zodiac
rigid island
#

and change it to https

broken zodiac
broken zodiac
rigid island
#

its the asset dev that hasn't kept up with those changes i suppose

rigid island
#

its a safety feature

rigid island
# broken zodiac ah okay

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"

broken zodiac
#

ah okay thanks

#

takes me here

rigid island
# broken zodiac

seems like you try to use stuff on enemy collider while it got destroyed at some point

simple egret
#

Yep it's enemy

broken zodiac
rigid island
simple egret
#

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

broken zodiac
simple egret
#

You should check that it's not null before using it

broken zodiac
#

1 sec lemme try it

simple egret
#

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'
}
broken zodiac
broken zodiac
simple egret
#

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

rigid island
broken zodiac
#

i think im too slow cause nothing has changednotlikethis

simple egret
#

Show your updated code

broken zodiac
#

yeah dodnt judje ive got no clue whats happening

#

i believe i was not supposed to copy it word for word awkwardsweat

rigid island
#

no

#

ur if statement is empty rn doing nothing

simple egret
#

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 uses enemy

hard viper
#

we have a strict “we will help, but not do it for you” policy

broken zodiac
rigid island
broken zodiac
#

alright

hard viper
#

is there a way to use the event keyword for a public event Action, but also give derived classes full access to the variable?

lean sail
hard viper
#

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?

simple egret
#

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.

hard viper
#

whyyyyy

#

that is so asenine

#

whatever, I resolved it by making it static. which is a really dumb workaround

#

ty guys

split sparrow
#

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");
}
hollow hound
#

Is it possible to make Rigidbody2D.Cast() from custom position?
Without manually moving the object.

vagrant blade
#

Nope, read the implementation of the docs. There's no option to supply a position.

fluid lily
#

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?

heady iris
#

something sounds mega broken here

#

does this happen every time you create a project?

fluid lily
#

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

hard viper
#

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?

limber halo
#

hi guys, how can change the key of onmouse functions for instance onmouse functions using mouse0 but i wanna use the mouse1

latent latch
#

probably use a getter

#

oh, actually you can change it directly on the event system on the scene

limber halo
#

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

limber halo
#

I don't know much about the input system

latent latch
#

What OnMouse method are we talking about

limber halo
#

onMouseDrag, onMouseUp etc.

latent latch
#

Oh, hmm I'm actually not too sure of the input on those. Let me look at my built-in project

limber halo
#

yes, go on

limber halo
latent latch
#

Yeah, you're trying to grab input from just monos in general using the mouse, and not implementing the IHandler interfaces

#

Mouse event stuff like drag I remember having trouble with too, but I think I was polled input and checked for different input

limber halo
#

okey, thank you for help I will try

latent latch
limber halo
#

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

latent latch
#

something like that usually

limber halo
#

Yes, thank you for this instance

rose willow
#

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

sly wave
#

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?

lean sail
sly wave
#

can't I cheat this with manipulating the line size

lean sail
sly wave
#

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

lean sail
#

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

sly wave
#

what would create more stress on the CPU/GPU tho

#

considering that there are more objects 🤔

lean sail
sly wave
#

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

latent latch
#

why are you using line renders for shapes

sly wave
lean sail
latent latch
#

you can use unity's low level GL tools which is basically opengl immediate mode

polar marten
#

there is no optimization issue here

sly wave
sly wave
polar marten
#

listen to yourself

#

this is one cube, for one cursor effect in game

sly wave
#

(I've been using Unity for like a month, but I have been coding prior to that)

latent latch
polar marten
#

make multiple line renderers

#

you cannot use the GL commands for line drawing

latent latch
#

what

polar marten
#

trust me

latent latch
#

I make shapes and matrices out of it

#

grids specifically

sly wave
#

🤔 I still need to make a grid anyway, so it'd definitely be worth looking into that either way.

polar marten
#

no... GL is deprecated

#

you cannot use it at all

polar marten
#

if you need a line grid in 3d, you know, say so. what is your goal?

#

what are you actually trying to do?

sly wave
#

basically a level editor.

#

For the sake of simplicity (as this is a prototype) I'm restricting myself to 90° angles for this

latent latch
#

I'm not seeing where it says it's deprecated beyond some extra settings you need to adjust for SRP

sly wave
#

and you can like manipulate its size and the "cursor" cuboid thing is gonna stretch in size according to your liking

polar marten
latent latch
sly wave
#

that is lookin fancy

latent latch
#

This is my GL implementation via editor scripting

#

specifically just show the grids but I make large shapes as previews too since

sly wave
#

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...

polar marten
polar marten
night harness
#

Why are you sharing a chatgpt link

latent latch
sly wave
spring creek
swift falcon
#

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.

cosmic rain
polar marten
cosmic rain
swift falcon
#

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?

spring creek
swift falcon
#

Like sometimes I would love the little things to walk to the player randomly

#

Would I just randomly add a waypoint?

cosmic rain
swift falcon
#

I'd have to force it there?

latent latch
#

Look into creating a statemachine of logic for your AI

swift falcon
#

I've seen it coming up

cosmic rain
swift falcon
#

I appreciate the help, I was struggling to find a proper starting point

#

I'll check out navmesh

visual fjord
#

How i can mouseover the list object at list of script in the inspector?

sly wave
swift falcon
#

@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

upper wigeon
#

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 :(

rigid island
#

!vs

tawny elkBOT
#
Visual Studio guide

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)

mental rover
#

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

swift falcon
#

Do I just spawn an object in a random position?

#

And set that as the target?

swift falcon
#

How do I check for a tilemap

upper wigeon
#

Thank you!!

grim acorn
#

Does anyone understand how to fix rider unity problem

#

It says rider editor failed

swift falcon
#

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?

grim acorn
#

Excuse me Lashen and Deynai do you guys know what is unity rider failed

swift falcon
#

No, sorry man

limber halo
swift falcon
#

@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

dusk apex
swift falcon
mental rover
#

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

dusk apex
swift falcon
swift falcon
#

thank you

dusk apex
#

Unless your class inherits monobehaviour it'll not be visible through the inspector without a custom editor.

polar marten
#

then you don't need to use your own raycasts

#

it's like a lite version of web page event listening

upper wigeon
#

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.

cosmic rain
#

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.

limber halo
cosmic rain
upper wigeon
native folio
#

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();```
untold siren
#

Cinemachine 3.0 is murdering me but I've successfully managed to make a custom input controller where you can control the sensitivity :')

rich leaf
#

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?

random pelican
#

can somebody help me with this movement that im trying to implement?

vagrant blade
#

Need to ask a question with some details before anyone can decide if they can.

random pelican
vagrant blade
random pelican
#

sorry

fickle lichen
#
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? ![aniblobsweat](https://cdn.discordapp.com/emojis/586029851870363660.webp?size=128 "aniblobsweat")
untold siren
#

Just spent about 20 minutes trying to debug something but turned out to be due to the script execution order... sigh

cosmic rain
#

Be grateful that it wasn't 20 hours😛

fickle lichen
ocean hollow
#
    {
        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)
fervent furnace
#

how about when playerHealth.currentHealth > playerHealth.startingHealth

ocean hollow
#

wtf is going on??

fervent furnace
#

what will heppen when playerHealth.currentHealth > playerHealth.startingHealth?

lean sail
ocean hollow
fervent furnace
#

i should rephrase my question, a bit weird....
so what will your code does

ocean hollow
#

i have no idea what you mean by that

lean sail
#

oops, fixed

fervent furnace
#
while(true){
  if(somebool){
    wait one second
  }
}
```what will happen when somebool is false
fervent furnace
#

will it waits for one second?

ocean hollow
ocean hollow
lean sail
ocean hollow
fervent furnace
#

so will your code stop executing if it doesnt wait for one second?

untold siren
#

it'll crash your unity because it would never exit out of the while(true) clause

fervent furnace
#

or spin endlessly

untold siren
#

you need an alternative method of implementation where there is no while loop that is inifnite

ocean hollow
#

so all im missing is "return;"?

fervent furnace
#

no

#

ah, maybe

lean sail
ocean hollow
untold siren
#

because its a while loop

fervent furnace
#
while(true){}
```your code becomes this
#

if the condition is false

night harness
ocean hollow
lean sail
#

more like if you told him to count upwards towards infinity, starting at 0, and only stop when you reach -1

ocean hollow
#

so how do i fix this?

fervent furnace
#

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

lean sail
#

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

untold siren
#

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

lean sail
#

if you're using update already, no need to use a coroutine for that..

untold siren
#
FixedUpdate()
{
  if (currentHealth < maxHealth && canRegen)
    RegenHealth
}
untold siren
#

but its a faster implementation

lean sail
#

🤔 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

untold siren
#

I mean faster to get implemented

#

not physically faster

#

shrug I'm probably mistaken lmao

lean sail
#

idk what you mean by that. its the same lines of code pretty much

untold siren
#

ignore me dw

#

I'm being a tit

ocean hollow
lean sail
#
float timer = 0f;
float regenCooldown = 1f;
void Update()
{
  timer += Time.deltaTime;
  if(timer > regenCooldown)
  {
    timer -= regenCooldown;
    // Add healing logic
  }
}

as simple as that

untold siren
lean sail
untold siren
#

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"

lean sail
#

it is not running everything async

latent latch
#

even though coroutines are single threaded, there is some performance gains for sleeping

ocean hollow
latent latch
#

over polling each frame (so it becomes a cache/GC to runtime performance problem)

lean sail
untold siren
#

yeah ^

lean sail
#

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

cosmic rain
ocean hollow
#

alr thx for all of the help guys @lean sail @untold siren @fervent furnace

untold siren
#

unity has inifnite loops treated as a crash just incase the infinite loop is accidental (which is 99.9% of the time)

latent latch
#

there is multi thread support but you dont get to touch it

#

most of it is done under the hood

cosmic rain
#

You can't have the whole program spread between cores evenly. That's not gonna work.

cosmic rain
#

You can't really detect an infinite loop from outside of it.

untold siren
fervent furnace
#

halting problem

lean sail
#

windows might give you the "your program isnt responding" thing after awhile, dont know but thats not a unity thing

#

beautifully said

untold siren
#

no cap this is what one of my lecturers told me 💀

cosmic rain
#

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.

covert coral
#

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)
untold siren
#

what distro ?

covert coral
#

Linux Mint

#

22.03 Cinnamon

fervent furnace
#

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)

untold siren
covert coral
#

erm, 21.2

untold siren
#

that and sudo apt install libssl-dev

#

I remember having the same issue on my laptop a while back

covert coral
untold siren
#

yeah most the time its due to version mismatches

#

pain in the ass sometimes with linux lmao

covert coral
#

That's sort of what I figured

covert coral
untold siren
#

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 kekw

covert coral
#

Haha, I totally agree homie

#

My man, you fixed it

#

Thanks a million, going to take note of this

untold siren
#

just you wait until you try to install smth like autodesk maya on a distro that isn't fedura or centos lmao

covert coral
#

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

untold siren
#

I like blender but since I learnt maya first I have no idea where to start with blender kekw Jetbrains is a nice ide to try btw

covert coral
#

Jetbrains, I'll have to check that out

azure dome
#

Can I save 2d array to json? I get right now

somber nacelle
#

yes but not using unity's jsonutility

azure dome
#

What do I use Instead?

somber nacelle
#

pretty sure newtonsoft can do it

hasty silo
#

Has anyone here played around with MLAgents?

knotty sun
untold siren
#

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

knotty sun
#

how many cameras in each state?

untold siren
#

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

knotty sun
#

you're not answering my question

untold siren
#

one per state

#

sry

knotty sun
#

ok, how many states

untold siren
#

there should be four or five by the end of implementation

knotty sun
#

then a List which you loop over will be more efficient than a Dictionary

untold siren
#

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)

knotty sun
#

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

untold siren
#
            FirstPersonState = new FirstPersonState("FirstPerson", _cameraStateMachine, this, firstPersonCam);
            cinemachineCameras.Add(firstPersonCam);
            ThirdPersonState = new ThirdPersonState("ThirdPerson", _cameraStateMachine, this, thirdPersonCam);
            cinemachineCameras.Add(thirdPersonCam);
#

so basically like this?

knotty sun
#

yep

untold siren
#

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

knotty sun
#

sounds about right

#

@untold siren btw why are you using strings rather than Enums?

untold siren
#

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

knotty sun
#

Enums much more efficient than strings

untold siren
#

I'll shift it to that at some point, will add a // todo:

latent latch
#

who needs type safety

untold siren
#
            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?

knotty sun
#

horrible but valid

untold siren
#

XD I would have assumed that, what's the better method of going about this?

knotty sun
#

just a straight for loop with an if check

lean sail
#

you could even just set the priority to 0 of the previous active cam, no need to go through every camera

knotty sun
#

indeed, cache activeCam

untold siren
#

true that works

knotty sun
#

or, better yet cache active cam index

untold siren
#

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 :/

knotty sun
untold siren
#

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!

urban lintel
#

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)

oblique spoke
urban lintel
#

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

oblique spoke
#

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.