#archived-code-general

1 messages · Page 328 of 1

rigid sleet
#

btw if you dont care about having these kind of structure

#

you can just invoke SceneManager.LoadScene("Name")

wooden pawn
#

yeah but then id have to make a different script for each loading zone tile

rigid sleet
#

not really

wooden pawn
#

or i could just make the variable public yeah

#

i guess that works

#

and write in the variable for each tile

rigid sleet
#

public class SceneLoadingTrigger : MonoBehavior
{ 
  public string targetScene;
  
  public void OnTriggerEnter2D(...)
  {
    SceneManager.LoadScene(targetScene);
  }
}

wooden pawn
#

thats essentially the same thing as making this thing

rigid sleet
#

but yeah, write the variable for each

wooden pawn
#

except instead of using a string directly im putting the string in a SO

#

i guess ill do that instead lol

#

ill save this for when im better at programming

rigid sleet
#

putting the string into a SO doesnt really do anything for you at this point

#

that kind of data structure is really useful for more complex systems based on it tho

#

for example, a door system

#

where you open a door and teleport to another scene at an specific point

#

having a SO with your scene definitions, then have another SO with your door definitions, and in there define all of your transitions with door IDs into target door IDs

#

for that kind of systems, then yeah you must hold the data somewhere

#

and even then, you can still do this by just storing the info in the scene itself

#

it just doesnt scale well, while the SO approach is just cleaner and scales really well

wooden pawn
#

thank you

#

next up is figuring out how to make it so the camera wont follow the player if i get too close to a wall

rigid sleet
#

for most of your camera needs, use cinemachine

wooden pawn
#

i tried using cinemachine on a bunch of stuff in 3D earlier but god it was rough

#

i couldnt figure out how to make it so the camera just updated instantly instead of having it move on a slight delay when i moved the mouse

rigid sleet
#

aim settings

#

also, follow settings

wooden pawn
#

and god i had a couple of lights in one spot and it made the camera move 10x faster for some reason

#

something with framerate

rigid sleet
#

you have everything there, look up some tutorials if you have doubts, but I assure you Cinemachine is your best bet to have a decent camera system

wooden pawn
#

is cinemachine good in 2D?

rigid sleet
#

yeah

wooden pawn
#

for now i think im just gonna make tiles with "Wall" tags and put them up and then write some sort of raycast that checks if the player is within 8 tiles of one

#

cause thats the length

#

oh and 5 up and down

gleaming ore
#

hey guys i got a question

#

im a bit new to unity and im not sure if this is the right place to ask

#

im trying to load another scene

#

what does this mean?

wooden pawn
gleaming ore
#

it isn't doing anything

spring creek
#

Scene 1 would mean you need TWO scenes added in the build menu

#

Scenes are 0 indexed, just like lists and arrays

gleaming ore
#

all i see is this

spring creek
#

Scene 1 simply means the second scene in the build menu, not a specific scene

gleaming ore
#

i clicked the second scene

spring creek
#

Yeah, so you cannot load another scene by index

gleaming ore
#

went into it

#

clicked add open scenes

#

still doesn't add :/

spring creek
#

Do you have any errors?

#

Compiler errors I mean, not the one above

gleaming ore
#

oop i got it to work

#

i didn't double click it

#

i somehow single clicked it

#

thanks for the help :)

#

ooh i have another query

#

so everytime I restart unity

#

it always opens script in vs code

#

instead of visual studio

#

and whenever i select visual studio

#

it opens it in visual studio until i restart

#

then it's back to vs code

spring creek
# gleaming ore instead of visual studio

Then you have vc code selected in external tools.

Hey, can you finish what you are saying before hitting enter btw. What you're doing is called "message spam"

#

!ide follow the vs guide here

tawny elkBOT
gleaming ore
#

what else do I change? The only thing that I can change (regarding script editor) is the menu up on the top right. It always goes back to vs code

spring creek
#

Regenerate project files maybe? Be sure you are hitting ctrl+s too I guess?
It shouldn't be going back. So I am unsure

gleaming ore
#

hm lemme try

#

oh woah it worked, thanks!

simple ruin
#

does anyone know the solution to this voxel rendering issue

cosmic rain
simple ruin
#

Should I start one now?

#

i can retype the issue with more clarity if you'd like

cosmic rain
simple ruin
runic linden
#
enum state { a, traveling, b }

IEnumerator GoToDestinationRoutine()
{
    for(float f = 0f; f <= 1f; f += Time.deltaTime)
    {
        transform.position = GetPointOnBezierCurve(start, p1, p2, destination, f);
        yield return new WaitForEndOfFrame();
    }
}

I have this boilerplate routine that lerps from a to b. When it's at b it should allow the player to go back to a, simple stuff. Now ofc my coroutine could feature a block that checks for the current state and then sets start and destination accordingly. This check would have to be done at the end to, to update the new current state. Are there better ways to this without 3 if-statements? Would you pass everything as four arguments, or a struct? I know it's a bit over engineering but I want to write better code and not just throw if-statements at everything. 😄

Thanks!

plucky inlet
knotty sun
runic linden
#

Thanks 🙂

dusky niche
#

https://paste.ofcode.org/gigqPHFHzr9cRQfRgi3ghc
can anyone help me with what's wrong here?
I made a grapple hook which pulls the player towards the hook direction. When I press a key, the function gets called, the hook gets hooked on raycast.point.
Everything seems to work except when the function is called it stops pulling before the Vector3.Distance(transform.position, HookShotPos) is less than reachedHookPosDis.

knotty sun
#

you probably want to change

Vector3.Distance(transform.position, HookShotPos) > reachedHookPosDis

to

Vector3.Distance(transform.position, HookShotPos) - reachedHookPosDis > -0.01f

or another suitable offset

dusky niche
knotty sun
#

you are checking for > so <= will not fire the if

dusky niche
#

yeah ik but
It does pull me a little
so that means the distance was high when function was called.
something just stops it without getting close to the hook

knotty sun
#

then you need to debug your values to find out why

dusky niche
placid summit
#

Anyone use an asset or other C# .net library to manage session-based or general http communication in place of Unity's?

#

WebRequests are pretty limited without a lot on top

placid summit
# plucky inlet What is your issue?

Well I have to login to a session server, check my session does not end, check all returns for any failures and repeat if required. All these things are auto managed by other APIs with optional changes.

plucky inlet
placid summit
knotty sun
placid summit
lofty crest
knotty sun
lofty crest
knotty sun
#

should do. But not if you build for Android

placid summit
lofty crest
#

because i am seeing the debug.log from the save in the datapersistencemanager

placid summit
#

so just need to target .net framework?

knotty sun
#

indeed

lofty crest
#

i just added a debug.log for it

#

exiting playmode calls it

knotty sun
knotty sun
#

there are the Application.quitting and wantstoQuit events

lofty crest
#

the thing is, I know that SaveGame() is being called, because that debug.log is coming up

knotty sun
#

I can only go on the code you have shared which does not include your FileDataHandler class

knotty sun
lofty crest
lofty crest
knotty sun
lofty crest
knotty sun
#

ok, so moneyTotal == 0

lofty crest
#

yeah so whern i enter playmode it is 0

#

kill an enemy and collect money then quit

knotty sun
#

but your log says 10

lofty crest
#

so the loading side of things is perfect atm

knotty sun
#

Sorry, I'm confused. You posted a log with the value of 10. So the json should contain 10. True or not?

lofty crest
#

true, i then modified the json to say 0 and saved that,

knotty sun
#

wtf would you do that in the middle of a help session?

lofty crest
#

because i wasnt thinking

knotty sun
#

sorry, but I give up, you drip feed information and then change the data

plucky inlet
#

So, you load your asset. you change the coins to 10 and then save your asset and the json (after reopening) is still 0?

lofty crest
plucky inlet
#

Or was it just you changing it and there is no error anyymore? 😄

lofty crest
#

the whole reading the JSON part works perfectly though

plucky inlet
#

can you point me to the scripts again, where you update the values and actually save them?

lofty crest
#

this part of it is working exactly as intended.

lofty crest
lofty crest
lofty crest
plucky inlet
#

Do you ever update this.numGemsCollected = data.moneyTotal; ? Besides loading it from file?

plucky inlet
lofty crest
#

here when the gem is collected it updates the numGemsCollected

#

and the save happens on quit

#

on application quit

plucky inlet
#

And this debug is showing the correct or wrong moneyTotal?
Debug.Log("Saved money total =" + gameData.moneyTotal);

plucky inlet
#

Why are you passing your gamedata through three different scripts?

#

you could just make it public static for now and access it directly from all scripts

lofty crest
#

im not sure, the idea was to have any script that needs data saving to go through the interface and then have the manager gather and store references to the scripts that use the interface and then have the file data handler to save it to the file

plucky inlet
#

But right now your script takes all dataPersistenceObj and saves the same local gameData. I understand, what you are trying to achieve here. but its just not working right now. If you want your interface using classes to store their data, they need their own private variable, not a global one passing to them. And when saving, they should return their own gamedata to the savemethod. This right now is a great start for spaghetti code 😉 Maybe get some paper and write down what you actually wanna do and come up with your objects, inhertiances before trying to code them right away

lofty crest
steady moat
#

Yes, pretty much.

wooden pawn
steady moat
mental rover
# lofty crest the wrong one

if it's wrong here it's got nothing to do with your saving or json, your code isn't incrementing the gems correctly in the class itself at runtime. It sounds like you could have multiple versions of CollectiblesManager - debug your dataPersistenceObjects list and event calls

gusty aurora
#

Is there a working way to save changes made to a prefab through script ?

#

ie after
var vfx = this.GetComponent<VisualEffect>();
vfx.SetVector4("Color", color);

#

I want to save this change

dusk apex
#

You want to modify the prefab during gameplay?

gusty aurora
#

No, it's all editor scripting outside of play mode

trim schooner
#

Can't include that in a build tho, it'll fail

gusty aurora
#

Thanks 🙂

#

Could you point me to the method that actually works in there ?

knotty sun
dusk apex
gusty aurora
dusk apex
gusty aurora
#

Very very simple

#

Have a prefab, modify that prefab thourgh script

#

If I restart the editor, the changes are gone

#

I would like to save these changes, nothing more, nothing less

lofty crest
gusty aurora
#

even PrefabUtility.SavePrefabAsset(this.gameObject) does not save !!!

dusk apex
gusty aurora
#

A prefab asset with one script and one VFX

#

Editing the VFX works perfectly

#

The issue is that when I restart the editor, the change on the VFX is lost

#

After running the editor script

#

And after restarting the editor

dusk apex
gusty aurora
#

100% editor scripting bug, yes

mental rover
gusty aurora
#

That's the idea, if I manage to save the change, the blue bar will disappear

trim schooner
#

is there a reason you're not using the provided method to save the changes?

gusty aurora
#

Which one ?

#

PrefabUtility.SavePrefabAsset(this.gameObject) ?

trim schooner
#

the UI one.

gusty aurora
#

Even when I call it, the changes are lost when reloading the editor

lofty crest
trim schooner
#

Saving a scene will keep the changes on the instance

mental rover
lofty crest
#

but i dont know why it would affect only the money total

mental rover
#

I mentioned two things to debug and it looks like you've only checked one of them

lofty crest
#

ah the event calls, i forgot let me do that

swift falcon
#

Using Unity 6000 and getting error of:
error CS0518: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported
In line of:
public float test { get; init; }
Is it still necessary to do this solution?

#

Oh how great!

thick terrace
raven basalt
#

Melee meleeComponent = toolsList[i].toolGameObject.GetComponent<Melee>();

In this specific instance, toolsList[i].toolGameObject refers to the following gameObject, playerBat, which has a melee component:

However, Melee meleeComponent has a value of null. Why is this?

dusk apex
#

I'm assuming you're getting some sort of error (nre)?

heady iris
#

and how do you know that toolsList[i].toolGameObject actually refers to that object?

raven basalt
#

I vertified it through this:

        if (meleeComponent != null)
        {
            //throw new Exception { "The meleeComponent is null" };
            throw new Exception($"The meleeComponent is null at index {i}");
        }
heady iris
#

that's the opposite...

#

you checked if it doesn't equal null

raven basalt
#

oh wait my bad

alpine harness
#

Hey is there a better space to ask questions specifically about Splines?

alpine harness
rigid island
#

indeed

alpine harness
#

Wonderful. Thank you!

rigid island
#

🫡

dawn nebula
heady iris
#

nice layout

dawn nebula
#

Very productive day of getting people to fix multiple Spline packages 🙃

heady iris
#

while we're on that topic, I noticed that updating knots every frame causes extreme performance degradation in the editor

#

there's some weird editor-only caching it does that takes forever

#

i need to go make a project to demonstrate that

dawn nebula
#

who decided to call them knots

dawn nebula
#

The problem now is 2022.3.31f1 isn't out yet, and that PR to Dreamteck Splines hasn't been merged yet.

#

Sadge

#

I hate technology

somber nacelle
#

the patches have been coming out weekly, and i don't actually know the exact day that .30 came out since it isn't on the download archive for some reason, but if it came out a week after .29 like it should have, and if 31 comes out a week after that, it should be releasing today

knotty sun
somber nacelle
knotty sun
#

may be faster for 6 Preview as it's still pretty new

#

God, they have been busy introducing new bugs, bless 'em

#

I guess they finally got their CI/CD workflow functioning, now if they would only test stuff

somber nacelle
#

looks like weekly patches started in april, so it is possible that it is a temporary thing and we still have another week until the next patch, but .30 was released exactly a week ago today so maybe they'll stick with the weekly patches for at least a bit longer and we'll get the next patch today

dawn nebula
#

Wait is Unity 6 out or in Pre-release?

knotty sun
#

Preview, so pre LTS

somber nacelle
#

unity 6 is "preview" which is identical to a tech stream release, so it's out of beta, it's just not LTS yet

dawn nebula
#

I'm glad they ditched the yearly notation and went back to version numbers.

#

Unity 6 sounds quite a bit better than Unity 2023.3 LTS

knotty sun
#

they also ditched the LTS notation which I am less happy about

marsh wadi
#

I am using Application.wantsToQuit and returning false to delay quitting my application. This works fine, but when I later call Application.Quit(), for some reason, the application does not quit!
I debugged the build, and OnApplicationQuit is called on various scripts, but the application keeps running afterwards.. What could cause this?

leaden ice
#

it does nothing in the editor

marsh wadi
#

read the message! I am debugging the build!

leaden ice
marsh wadi
#

yes, I returned false and call Application.Quit() manually later

#

it works fine if I call it in the same frame, but not if I call it later; at least, that's one way to look at it. There's something that causes the app not to exit.

marsh wadi
#

I am unregistering from it, so it's not there the second time around

leaden ice
#

you need to have one that returns true

marsh wadi
#

It's not super complex; but I can try keeping the callback and return true explicitly

#

just to make it extra clear: after _QuitGame() is invoked, it does call OnApplicationQuit() on all the scripts that have it

#

it just keeps the app alive afterwards (and calls update on scripts etcetc)

open lake
#

Hey

#

Need some help with Action<>

#

So I have two scripts

hexed pecan
tawny elkBOT
open lake
#

my bad

#

So the first DataVariables has an action and I invoke it in line 130

#

even the debug.log on line 129 is being executed but 130 invoke isn't

#

and if I dont use the ? symbol it says the action is null

#

now in my second script, I'm subscribing to the Action<bool> action in a function thats called by the Start() on Monobehaviour

knotty sun
open lake
#

even the Line 21 debug log on my second script right after adding my function as a listener seems to be called without errors

open lake
#

the UpdateValue() function which eventually invokes the Action is called on a different thread but even then shouldn't only the invoking be affected? not the subscribing part?

open lake
simple egret
#

Events with no subscribers will be null. You're not calling override void ApplySettings() in void Start(). If there is also a void Start() but in the base class, it won't be called by Unity

knotty sun
#

then this

settings.palletLiftingBool.boolValueChanged += OnChangePalleteLifterValue;

is not being executed against the instance you think it is

open lake
#

oh

#

wait a second

#

I initially instantiate my GameObject with the second script and right after Instantiate(), I call apply settings() and then I deactivate it. and when I want to use this gameobject, I make duplicates of it, activate it and then use it

knotty sun
#

This is some serious spaghetti code. Are you sure it's all necessary?

open lake
open lake
knotty sun
#

like these

public Action<bool> boolValueChanged;
    public Action<float> floatValueChanged;
    public Action<TimeSpan> timeValueChanged;
    public Action<string> stringValueChanged;

could be replaced with

public Action<object> valueChanged;
open lake
#

and then cast it in the subscribed function?

knotty sun
#

yep

open lake
#

with the type enum

#

alright

knotty sun
#

Your datavariable class does not need to know what type of variable it is

open lake
#

is that safe?

knotty sun
#

sure, that is why we test

open lake
#

like would we lose the info somewhere along the way or smthng?

#

alright I'll get back to ya

open lake
#

the enum alone is enough?

knotty sun
#

exactly

knotty sun
waxen blade
#

I have a class containing a property:

public class Foo
{
public Coroutine PopUp { get; set; }
}

If I make a reference to it, it works fine:

foo.PopUp = StartCoroutine(PopUp());

But if I use this same methodology when the property is within another object, I get a null exception error:

public class Foo
{
public StoppableCoroutines StoppableCoroutines { get; set; }
}
public class StoppableCoroutines
{
    public Coroutine PopDown { get; set; }
    public Coroutine PopUp { get; set; }
    public Coroutine WaitDuration { get; set; }
    public List<Coroutine> CoroutineList { get; set; } = new List<Coroutine>();
}
foo.numPadSlot.StoppableCoroutines.PopUp = StartCoroutine(PopUp());
**NULL EXCEPTION**

Why does it work fine if the Coroutine property is directly in Foo, but not if the Coroutine property is within StoppableCourintes, which is in Foo?

simple egret
open lake
somber nacelle
waxen blade
knotty sun
knotty sun
somber nacelle
#

if you never actually create an instance of StoppableCoroutines though, that is 100% the issue

waxen blade
#

The Coroutine is null when I reach foo.PopUp = StartCoroutine(PopUp());, but it still assigns it successfully. I don't understand why I don't need to assign the Coroutine at the start but I do need to assign StoppableCoroutines.

somber nacelle
#

because you are not trying to access a property on the coroutine in that first bit. you are literally assigning something other than null to it.
you cannot access a property on a null object without getting a NullReferenceException

knotty sun
#

Spot the difference

public StoppableCoroutines StoppableCoroutines { get; set; }
public List<Coroutine> CoroutineList { get; set; } = new List<Coroutine>();
waxen blade
#

Alright, I got it.

#

Thanks guys, I appreciate all the information. I like having the solution but also understanding why it's behaving a certain way.

knotty sun
waxen blade
#

Hmmm.. is that where people start putting an underscore in front of the name to prevent it from being identical? I'm not sure what would be best here because it helps me when it's the same name and there aren't going to be multiples of the same class being used elsewhere.

knotty sun
#

stoppableCoroutines ?

waxen blade
#

That conflicts with another best practice, keeping properties pascal case.

knotty sun
chilly surge
#

Yes PascalCase for properties is the convention most C# code uses. Your issue is just that you shouldn't have a property with the same name as the class itself.

#

The _camelCase convention is a different thing, that's for private fields.

rigid sleet
#

Yeah this, _ is for private fields you don’t wanna expose directly and use with get/set methods

rigid island
#

_ ugly af

knotty sun
#

tbh MS C# coding conventions dont make a lot of sense. But, hey, if people don't want to think for themselves and use them, fine

chilly surge
#

What do you not like about the convention? The only part that I don't have an opinion on is the s_ for thread static, otherwise I agree with the convention.

knotty sun
#

I dont like any of it. I'm guessing you do know that the convention was developed before the advent of IDE's and so almost all of what they describe is, today, moot

sleek bough
#

Don't like how "_" prefix looks as well, but it is very practical at getting quick autocomplete for local fields. Makes them instantly accessible just by typing _.

chilly surge
#

That's definitely not the case, IDE helps but IDE is not always available when you are reading code, eg when you are doing a code review on GitHub.

rigid island
knotty sun
#

Am I the only person that actually remembers how they named their variables?

rigid island
#

but after a while _ everywhere looks off-putting

#

Ido remember them, I just work with some coders who enjoy the shite out of _ and it only has 1 benefit.
People usually do it just for "not conflict with method parameters" (which is nonsense, just use the this. keyword)

chilly surge
#

The thing about the convention is not about "why should it be localVariable, _privateField, and PublicProperty but not _localVariable/PrivateField/publicProperty?" which one uses what casing is not important, what's important is that private fields and public properties need to be different because they have very different impacts when you mutate them.
When you mutate a local variable, you only need to care about the effect it has within the scope of the variable; when you mutate a private field, you only need to care about the effect it has within the class; but when you mutate a public property, that's a public API surface and you must consider how it might impact every single piece of code in this entire code base (or if you are a library author, every single consumer of your library which you definitely don't have access to).

#

Without naming conventions differentiating them, when you are reading code you have no choice but to commit to memory "yep this variable is local, this is private, this is public, etc."

knotty sun
#

which is what you should, as a competent programmer, be doing anyway

chilly surge
#

IIRC you are also very against var, if the position you hold is that "IDE helps you to know everything there is to know about a variable and you should always commit to memory everything about a variable when reading code" then you shouldn't be against var.

knotty sun
#

I am very much against var. it's just pure laziness and I abhor laziness

rigid island
#

wtf thats weird..

#

what if you have a very long name for an object and you have to use foreach

knotty sun
#

I dont care, copy/paste exists

rigid island
#

by that logic copy and paste is laziness

knotty sun
#

var in no way makes code more readable and code needs to be read

chilly surge
#

So if you change the thing you are iterating, you now have to change 10 other places downstream, and your commit will look like +10/-10 even though you've only made one change.

#

And that +10/-10 is going to cause so much problems when you have merge conflicts with your team members.

#

But you know what, you are right convention is mostly just a style preference, so there's no absolute right and wrong. I personally think in a team environment these conventions absolutely help a ton.

rigid island
#

convention just help to get better consistency from people when collab

knotty sun
#

Yes, conventions are an absolute requirement in a team environment. But I can tell you having worked on 100's of projects over the years the only projects which used the same conventions were the ones where I was team lead and I imposed the convention on the team

#

what that convention IS is, basically, irrelevant

chilly surge
#

Whether a convention was enforced or not has nothing to do about how effective a convention is at solving problems.

#

I don't think this conversation is going anywhere so I guess I'll exit now.

knotty sun
#

conventions neither cause nor solve problems

chilly surge
#

I don't know how you can reach that conclusion when var objectively and measurably reduces the amount of merge conflicts.

knotty sun
rigid sleet
chilly surge
#

Ah yeah I really need to stop myself from engaging further after saying I'm exiting. I should've know this conversation goes nowhere when the premise is "people who follow Microsoft's C# conventions don't think for themselves."

rigid sleet
#

Specially when you are using scoped namespaces

rigid island
#

pretty sure they are trolling us when they say that stuff lol

rancid widget
#

Hello! I am trying to make a crater appear when punching. This is just blocks that appear above the groundlayer in the form of a crater and doesn't need to be fancy.

What I thought of is creating a raycast when punching that instantiates on that point some cubes (in a circle), but not sure if that's how it will work. Any advice?

rigid island
#

Random.insideUnitSphere then use that point to raycast it on the surface

#

oh wait not random you have the point already?

rancid widget
rigid island
#

oh so however you do the "punch" like ray or whatever, use that point on collider?

rancid widget
rigid island
#

well you can use maybe an Animation event to fire a Ray or other Cast shape to set a hit area

#

thats how I usually do it

rancid widget
#

also quick question. I want to create a new script for the cratereffect and not with the animations, but is it possible to have the logic of the animationcontroller in that cratereffect script? I can assume it will start glitching very hard if i am gonna implement the input.mousedown blabla in the cratereffect script aswell

rigid island
rancid widget
rigid sleet
#

Otherwise use a vfx/particle system

rigid island
#

Animation event is a way to fire off some code when reaching a specific animation keyframe

rancid widget
rancid widget
rancid widget
rigid island
rigid sleet
#

But yeah if you wanna know exactly whereyour punch landed, ray cast would be a good way to go

#

It really depends on what you are doing honestly

rancid widget
#

For now I wanted to play around with seeing what I could do, but hitting a punch indeed was the next step for a dummy for example

#

Thank you both for your help, I will look into raycast and VFX

fallow quartz
#

Someone knows why when i edit a custom physics shape on a tile sometimes it updates

#

and sometimes it doesnt? Im getting crazy

heavy egret
sleek bough
#

@heavy egret You already have a warning for cross-posting. And this is a code channel.

inner yarrow
#

Does it make a difference on performance whether you run one loop that runs two actions per iteration, or two loops that run one action per iteration?

#

So like this:

for(int i = 0; i < 10; i++)
{
  whitePiece[i].Update();
  blackPiece[i].Update();
}```
vs this:
```cs
for(int i = 0; i < 10; i++)
{
  whitePiece[i].Update();
}
for(int i = 0; i < 10; i++)
{
  blackPiece[i].Update();
}```
merry ridge
#

does anyone know a way to use world UI and Unity's even system with a locked cursor? All the solutions I found are either outdated or may cause other problems

spring creek
inner yarrow
merry ridge
inner yarrow
shell scarab
#

Do those double value sliders in the inspector have an attribute or is it only through custom editors / property drawers?

vivid halo
#

I remembered reading something about checking the distances of two objects being more performant if you don't squareroot their position values / something similar. Is this true?

spring creek
#

not doing something is always more performant than doing something

#

but computers are fast 🤷‍♂️

lean sail
vivid halo
#

Why isn't this the default operation?

#

It seems like it's just better

fervent furnace
#

depend, sometimes you may need the distance

lean sail
#

What do you mean? It's quite literally built in with sqrMagnitude

vivid halo
#

Ahh, okay, I see

#

Yeah I noticed two functions and thought one was just a more performant version of the other

spring creek
vivid halo
#

Is Rigidybody.velocity = (some Vector 3) functionally the same as Rigidybody.AddForce(some Vector 3, ForceMode.VelocityChange)?

spring creek
#

Oh dang. That is absolutely right, my apologies travis. Ignore me

vivid halo
#

I'm trying to change my player's movement system from Rigidbody.Move to use Rigidbody.AddForce() to make it feel more natural + To respect collisions better with just a tad bit of momentum, but I'm struggling to make it feel reasonably responsive while retaining a little bit of momentum. I think ForceMode.Acceleration might be a good choice

spring creek
vivid halo
#

I'm on the new input system and I use a composite 2D vector with the Digital Normalize mode

#

I'm not sure if this is the best choice

#

Currently, it's okay but whenever I jump while running, the continued applied force subtracts from my linear y-axis velocity and makes my jumps feel muted. Adding _rb.velocity.y on line 36 where the _rb.AddForce vector is defined doesn't work; that just whiplashes and makes the jump float upwards abnormally fast
edit: edits

frosty widget
#

Hello, I was wondering if anyone here has encountered the same problem that I am currently faced with. My problem is that my character's horizontal velocity is supposed to be capped at a certain speed, but it is being capped at higher speeds for some unknown reason. It is quite strange because it works when my character is on the ground but not the air. I have a video here to demonstrate.

#

You'll notice that the RigidBody shows that the character's horizontal velocity on the ground is the same as when it is in the air, despite that clearly not being the case

#

Here's a snippet of my code for how I capped the speed

plucky inlet
# frosty widget

Where do you cap it horizontally? And where is your SetVelocityX code? please refer to !code how to post code correctly

#

!code

tawny elkBOT
full canopy
#

hey yall, how do i rotate a parent so that its child has the same rotation as another transform's rotation?

transform.rotation = activatingObject.transform.rotation * (transform.rotation * Quaternion.Inverse(attachTransform.rotation));```
the solution that works for position calcualtions unfortunately doesn't seem to carry over to rotational math. Not quite sure how to do this as quaternions are a little complex for me
this code is run every frame as i don't currently parent the object here.
also, since my throw function throws this transform when it's let go, it must be vibrating slightly from the transform.position so if anyone could explain why it's doing that it would be greatly appreciated as well
plucky inlet
#

Ah I guess it can work with inverse too as you did. So you need to add the child rotation, which is attachtransform? But I think you need to inverse the transform.rotation and multiply by the child to get the correct localposition?

full canopy
plucky inlet
hexed pecan
#

Something along those lines. Seems like your current code is close, but I dont know which transform is which

#

luisfinke's answer is probably correct

sterile reef
#

any reason why T isnt found?

knotty sun
#

you are missing

using System.Collections.Generic;
sterile reef
#

no its there

knotty sun
#

AddElseRemove<T>

sterile reef
#

ah

#

thanks!

dusky niche
gray thunder
#
bool = !bool;
gritty lily
#

When implementing a state machine for a player, which approach is best? I'm considering using either an enum or an abstract/interface class for the base state. Additionally, I want to know if there are any ways to make the states manage input in a smart way.

thick terrace
#

either way assuming you have some event or virtual method called when transitioning in/out of a state, it's usually fine just to register/unregister listeners on input actions there

full oyster
#

Is it possible to tell a mono game to rejit some code? Modding a game and there’s a constant boolean property that is without a doubt being inlined

#

Just need to change what it returns

thick terrace
#

like a const, or just a property that doesn't change after initialization?

full oyster
#

Property that doesn’t change after initialization

#

‘Public static bool useOvercloud => false;’

#

Technically const

#

Basically const actually

late lion
#

JIT doesn't go that far to check if a property is a constant expression.

#

It will always call the property getter.

full oyster
#

Interesting, didn’t know that. I’ll play around with the getter then when I get home. Thanks

thick terrace
#

how are you modding it? just thinking if you're using something like harmony you might get better answers asking around that community, this isn't really focused on modding usually

full oyster
#

Okay, thats what I was expecting initially

full oyster
# thick terrace how are you modding it? just thinking if you're using something like harmony you...

With harmony, but this is one of the few things I was able to find that says it’s impossible on an inlined property https://github.com/pardeike/Harmony/issues/70

GitHub

So... here I am again =) And as always - If I'm dumb and this is a simple question, but I just doing everything wrong - just point me to the rigth direction, thanks (^^)/ So - the game has the ...

#

Which is why I was wondering if I could tell unity or mono to drop some jitted code and rejit it

thick terrace
#

ohh right yeah, as i think MentallyStable is saying it's not just JIT that's the problem, it's already inlined before compilation in the IL

late lion
#

It's not inlined yet in the IL. It's the JIT compiler doing it.

full oyster
#

It’s not inlined in the IL, its expanded to a property when I view the code

#

Yeah what stable said

thick terrace
#

hmm yeah i didn't read the whole thread on github lol

frosty widget
thick terrace
#

i guess you can look at the mono API docs and see if there's anything suitable there

#

which seem to be timing out right now lol

late lion
#

You can use a transpiler patch and replace calls to the getter with your own method. You just have to know which methods to patch, but you would have to know that with rejit method too, unless you intend to rejit the whole application.

frosty widget
#

Hi, I'm reposting this because I think I sent my previous message at too late of a time. My problem is that I am trying to limit the horizontal velocity of my character, but my character keeps exceeding this limit. This is only the case when my character is in the air, not when on the ground. I have a video to demonstrate

#

You can see that the RigidBody component shows that the character has the same speed when running as when they are jumping, which is clearly not the case

#

I beleive that the problem lies in my PlayerInAirState script, but I don't have any idea why it's not working

safe dirge
#

Are you sure it's actually traveling faster, and doesn't just look faster because the model is smaller/thinner?

leaden ice
#

one workaround for this is, insteasd of using AddForce, do a "poor man's AddForce" like this:
Replace:

player.RB.AddForce(Vector2.right * playerData.horizontalForce * xInput, ForceMode2D.Force);```
With:
```cs
player.RB.velocity += Vector2.right * playerData.horizontalForce * xInput * Time.fixedDeltaTime / player.RB.mass;```

The difference is that your velocity change will be immediately visible and your clamp code can then work properly.
heady iris
#

AddForce is ultimately just scaling your input based on the force mode

#

Force and Impulse divide by mass. Force and Acceleration multiply by fixedDeltaTime.

#

(and VelocityChange doesn't do anything!)

placid summit
#

Does anyone work with backend devs who return http results in the https://jsonapi.org/ way of wrapping it in an object with "message" and "status"? { "data": { "actualdata": "some data"}, "message": "Success", "status": 200 }

magic harness
#

Hey guys, help me out here please.
I feel like im doing something wrong with my references.

ive got this property that im serializing and adding values to some variables (attack, defense, etc) in the inspector.

On the construtor i take this variables and pass their values into a dictionary.

    [field: SerializeField] public UnitStats unitStats { get; private set; } = new UnitStats();


public class UnitStats
    public Dictionary<UnitAttributes, Attribute> stats { get; private set; } = new Dictionary<UnitAttributes, Attribute>();


    public UnitStats()
    {
        stats.Add(UnitAttributes.ATTACK, new Attribute(attack));
        stats.Add(UnitAttributes.ATK_SPEED, new Attribute(attackSpeed));
        stats.Add(UnitAttributes.ATK_RANGE, new Attribute(attackRange));
        stats.Add(UnitAttributes.CRIT_CHANCE, new Attribute(critChance));
        stats.Add(UnitAttributes.ACCURACY, new Attribute(accuracy));
        stats.Add(UnitAttributes.HP, new Attribute(maxHealth));
        stats.Add(UnitAttributes.MANA, new Attribute(maxMana));
        stats.Add(UnitAttributes.ARMOR, new Attribute(defense));
        stats.Add(UnitAttributes.MAGIC_DEF, new Attribute(magicDefense));
        stats.Add(UnitAttributes.EVASION, new Attribute(evasion));
        stats.Add(UnitAttributes.MOVE_SPEED, new Attribute(movementSpeed));
    }

In my inspector and by debugging, everything is fine. But when i try to get a reference to some dictionary value for some reason everything is set to 0

placid summit
#

well fill the screen why don't you!

chilly surge
#

Are you consuming such an API or are you making one?

placid summit
chilly surge
#

Welp unfortunate then, just have to deal with the hands you are dealt.

placid summit
#

yeah but I have some power to change!

frosty widget
#

I capped it at 40, and it stops at like 38.461

leaden ice
frosty widget
leaden ice
#

It will slow the body down

#

If it's not set to 0

#

You have it set to 0 I see

frosty widget
#

I have angular drag set to 0, but not linear drag

#

to be honest, I don't really know the difference between the two

frosty widget
leaden ice
leaden ice
#

it reduces the velocity every physics update

#

since the physics update happens after FixedUpdate, your velocity that is capped to 40 will be further reduced in the physics update

frosty widget
#

ok that makes a lot of sense, thank you

#

I set linear drag to 0 when I reach max velocity and it caps at just the right speed now, my problem now is that the jumps are very high

#

although I think i can just cap the vertical velocity as well

#

either way thank you all very much for your help

full oyster
zinc merlin
#

Are there any big games done in Unity that had their source code published? Super bonus points if the unity project file is available as well.

I have lots of experience with small projects but I'm very curious to see how a big project is organized, how is the code structured etc. etc.

chrome berry
zinc merlin
gray mural
chrome berry
#

Next time an AAA studio gets hacked and their project source gets dumped online, you can always take a peek. They're usually projects that are far from completion, or abandoned ones, that get stolen and exposed that way, but sifting through those monolithic folder structures might give you insights

#

But those aren't Unity

zinc merlin
gray mural
zinc merlin
zinc merlin
chrome berry
#

Also seeing how others code can be eye-opening. I find people's code all the time that makes me feel stupid. Even if it is just for an add-on

#

I make myself feel better by reminding myself that me from years ago would feel stupid trying to read my current code

zinc merlin
#

indeed, but I just have no access to other people's code in gamedev. And stuff on youtube is very often very bad in quality, or oversimplified

chrome berry
#

Any particular kind of system or genre?

zinc merlin
#

not really, pretty much any big project would be enlightening. I'm making a puzzle adventure game right now but those are usually on the simpler side (also why I chose it)

chrome berry
#

Good call, too many have big bold games they want to make, but are still learning at the same time, so frustration and impatience get in the way of enjoying the learning process

placid summit
#

Some games you used to buy from steam could easily be decompiled as no il2cpp used but now it may be harder

knotty sun
zinc merlin
#

oh I know, I have plenty of experience in the IT industry and C#, just much less in Unity/gamedev

placid summit
#

Best bet is look through GitHub unity code and unity's own examples. But some top games have terrible code

knotty sun
chrome berry
#

Also a puzzle adventure game probably won't have complex systems underneath it, so you shouldn't be too concerned about 'the right way' to do things for a game like that. Unlike an RPG, where a poor foundation to how systems communicate and interact will bite you in the ass in no time

#

The only right way will be in not making something that's horribly unperformant, or that goes against how Unity works

knotty sun
#

Indeed, data design is all, whether that be in an app or game context

spring creek
#

The best and quickest way to learn game dev, imo, is by volume. Produce as many small games as you can. Do them poorly but quickly. Try to improve a little the next one, but not to the point of hindering your progress. Continue iteratively until you know the WRONG way to do it well, and why it IS the wrong way. At that point you will know what to avoid, making it easy to know what solutions to look for to do it the right way.
Looking at other peoples code really doesn't help. Might even lead you to thinking the wrong way to do something is the best

zinc merlin
#

Best would be to see good, clean codebase of course but even if the code is terrible, I would still be curious to see it.

zinc merlin
#

and I have no way of getting access to them

#

there are no tutorials on them, not on the sufficient level anyway

chrome berry
gray mural
#

Is there any way to use WaitForSeconds in the Editor?

zinc merlin
# spring creek Like what specifically?

I worry about unknown unknowns, things that I don't know that I need. But also stuff like optimization, memory management, asset loading, many things that I'm aware or not even aware exist. It's not that I have a specific question (I know I can always ask someone for help), it's that I lack an access to many things that come with experience. Looking at a big project would help me reverse engineer things.

zinc merlin
chrome berry
spring creek
knotty sun
spring creek
#

Also consider doing console apps
It is a whole other facet that will help you understand some things about programming that you may not get from pure game dev

chrome berry
zinc merlin
#

Yeah I might be worrying too much about it for the game I'm making, that might be true

gray mural
zinc merlin
#

coz so far I didnt have any technical issues with it

knotty sun
chrome berry
zinc merlin
knotty sun
#

but that is not how you gather experience. Experience is in the doing not in the looking

zinc merlin
#

in any discipline you need to see examples of what people smarter than you are doing

knotty sun
#

but, as I said, you need to know why, not just how

zinc merlin
#

that would be best, yes. But I'm going to be happy with what I can get.

chrome berry
#

I was using coroutines for my RPG event/logic, but it wasn't until I had the whole system working that I found yield start Coroutine... delays the execution by a frame. And I had lots of nested calls with coroutines waiting for more coroutines, cascading down the line to handle all event listeners for any given action, and the frames were adding up. No frame rate loss, just unacceptable delays in between actions being carried out that would be annoying to the player.
At that point I knew that switching to async/UniTask was the proper solution, and a couple days of refactoring was done and its all good now. There wasn't much info out there on that behaviour of coroutines, because few people use them in a nested/chain approach. So I had to learn that myself.

livid loom
#

@zinc merlin You can look at examples and learn from them implementing them is an important step yes, Don't worry about SteveSmith he is always like that. Chill bro why you always on the offensive chill he is trying to learn clearly.

livid loom
#

Just one object that holds stuff for you easily referenced can help

chrome berry
#

They're alright in simple forms, a basic tool to bust out from time to time, but clearly async/UniTask is the right approach if you need something more involved

livid loom
#

Agree

chrome berry
#

async/UniTask does need a bit more care because of how it can continue to run after the editor's play session is over, or after objects are destroyed during play

chilly surge
#

I'd like to have some temporary configs only in the editor, which do not persist across sessions and ideally completely in memory, and use those configs in editor play mode to alter behavior as a quick way to test things. What's the best way to store and pass these configs?

chilly surge
#

Hmm, seems like it's in the editor assembly so the runtime code can't get access to it to grab its state.

leaden ice
#

Well you said it was "only in the editor" I thought

chilly surge
#

Yeah the runtime code in play mode still needs access to it to change the behavior, I can wrap it in #if UNITY_EDITOR to remove from production. I'll play around with it.

fleet tide
narrow summit
#

nice

chrome berry
#

doggo murder simulator 😮

gray mural
# fleet tide hey ! Idk if you wanted to know but i progress in my project ^^ thanks you for y...

Hey, that's cool. I appreciate you willing to share your progress with me.
I can already see the progress, and notice that you've implemented the logic we've been talking about (hopefully, they're done with ScriptableObjects).
You still have a long way to go, like adding more options, implementing cash, adding more sprites for UI and making the dog not suffer by reducing its health after it's already dead. Wish you good luck with that!
Feel free to share your progress and ask any further questions.

#

Also make sure those spells are assigned to the specific keys like 1, 2 etc.

fleet tide
gray mural
fleet tide
gray mural
#

Also the Child Alignment should be set to Upper

livid loom
#

Yeah it's a lot of work I spent months building my system nota coder per say but coded quite a bit in my life since young web pages and such. Go to a composite scho0l in Canada you can take all sorts of courses.

#

I have a Damage manager that oversees all damage in the game it runs fast as well, got it from Brackeys lol

#

built on it but yeah basic system

livid loom
#

Its a empty Gameobject that handles all incoming collisions then apply status effect which each projectile or raycast incoming it apply that game object which two script handle each type of project hitscan or projectile.

#

this scripts are public static for the damage manager script so every thing can access at start you setup up your static class variables.

spring creek
tawny elkBOT
gray mural
livid loom
#

I give up on that how why is it wanting to paste it as text file

#

im trying to post it via discord built in system

gray mural
# livid loom

Why not simply have these methods in the Enemy script?

gray mural
livid loom
#

because multiple enemies and why have 100 of objects running it when one can run it

latent latch
#

if it's just a method call it's just a call

#

the buff idea is fine (I've done it too)

gray mural
livid loom
#

Yeah why not it works singletons are sick

gray mural
#

It is usually not the best idea. You can simply make the Enemy have the methods, which are applied directly to it

livid loom
#

i use them for everything always get fast reponsive everything

somber nacelle
gray mural
#

Of course, if you have some kind of method, which should be called for Enemy, Player, GameManager etc., it should be implemented somewhere else

livid loom
#

when it comes to GUI stuff an handling large volumes of data easily with unity auto serialization that drives me crazy more then it helps

#

yeah no I want it null please and thank you is often in my head

latent latch
#

I would use unitask probably for a buff system if you do want the independency, otherwise a single update method for checking would probably better than the hundreds of coroutines you may be putting out each source of buff

#

or rather, you can also just self-check in each gameobject's update loop too

#

lot of choices for those systems

naive swallow
livid loom
#

Yeah, exactly I essentially have one coding loop and it works for everything essentially, lol I got one trick up my sleeve and I use on every object in unity allows for easy save states of anything as well to be serialized in my own system.

naive swallow
gray mural
# livid loom because multiple enemies and why have 100 of objects running it when one can run...

Calling the methods from the static class, which all have the 1st parameter of type Enemy, which is not even marked as this, is usually worse than putting the same method into the Enemy script, which not only reduces the number of parameters used by 1, but also covers the need to have an additional static script for every MonoBehavior in your game.
In the case, when the method should be used by the different types of the same entity, consider simply deriving them from each other and still implementing the method once in the parent class.

livid loom
#

The enemy is not static the list of them is

#

and the the functions associated searching looking how far away they are and such

gray mural
livid loom
#

hey not like I'm not willing to learn i learned Xml and SQl from people at Firaxis working with them on a super mod.

gray mural
#

The Enemy class is not static? It's derived from MonoBehavior though

livid loom
#

no it is public the data for the enemies is though you need to track every enemy in the game and player that needs to static that list.

gray mural
livid loom
#

Yeah exactly what I just said

gray mural
#

Also, why would you make that list static?

#

And that script should simply call the Enemy's method needed

livid loom
#

It's runs faster having a master list of stuff and you need a master list to make thing easier and faster! then each object builds a list of what they need keeps memory usage down if you only storing like 10 lists of 100 items maybe more I don't use a dictionary but still why not singleton it and use that as a list. Like every youtuber i have ever seen codes for unity the same way except for Scriptable object fanboys well they only exist in unity it is not transferable skill. Being able to build your own system is you can go to any engine then scriptable objects will also make more sense in how they work.

heady iris
#

this sounds like an entity-component-system design

gray mural
latent latch
#

I mean the concept of SOs is that you're not having to explicitly define paths (or instance IDs) every second

heady iris
#

except that it hasn't really gotten all the way there

#

actually, no, this isn't ECS; this is just manually reinventing the concept of instance methods

naive swallow
gray mural
#

Also, what does "master list" mean?

gritty lily
#

I have tried to implement a reuseable state system I want to hear some opinions on it if I made some mistakes or a better approach to it.

fleet tide
#

I tried grid layout group but it's was really bad

dark wedge
#

how can i make my movement smoother? rn it feels really laggy and stuttery with input lag, this is my controller script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float moveSpeed;
    private bool isMoving;
    public Vector2 input;

    private void Update()
    {
        if (!isMoving)
        {
            input.x = Input.GetAxisRaw("Horizontal");
            input.y = Input.GetAxisRaw("Vertical");

            if (input != Vector2.zero)
            {
                var targetPos = transform.position;
                targetPos.x += input.x;
                targetPos.y += input.y;

                StartCoroutine(Move(targetPos));
            }
        }
    }

    IEnumerator Move(Vector3 targetPos)
    {
        isMoving = true;
        while ((targetPos - transform.position).sqrMagnitude > Mathf.Epsilon)
        {
            transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
            yield return null;
        }
        transform.position = targetPos;

        isMoving = false;
    }
}

somber nacelle
dark wedge
#

wait i realised what the issue is

#

the character is moving 2 tiles when i click the movement key

#

or whatever the speed is

#

but i want to character to ONLY move when the key is pressed

#

is there any way to do that?

leaden ice
#

that sounds like a totally different issue

dark wedge
#

and also how do i make the camera update better cuz you did bring that up

leaden ice
#

But also it looks like based on this it should only move one:

                targetPos.x += input.x;
                targetPos.y += input.y;

                StartCoroutine(Move(targetPos));```
#

presuming input always is limited to 1

dark wedge
#

yes input is limited to 1

leaden ice
# dark wedge

that's just how fast it will move to the target position

dark wedge
#

im quite new to unity

leaden ice
#

I know

dark wedge
#

i was just wondering how i could make my movement feel better

#

rn its really weird

leaden ice
#
transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);```
This will never move you anywhere other than `targetPos`
dark wedge
#

what change would i have to make to my code in order for the character to only move when the key is held

leaden ice
dark wedge
leaden ice
#

e.g .like pokemon

#

that doesn't correspond to "only moving when held"

dark wedge
leaden ice
dark wedge
#

i think its because of the tutorial im following

leaden ice
#

you either:

  • wrote code to do it
  • are using cinemachine or another component like PositionConstraint
  • or simply childed the camera to the player
#

I don't know which one

#

you have to tell us

dark wedge
#

this is the only script ive wrote

#

the camera is static it doesnt follow the player

leaden ice
#

ok then let's back all the way up

#

And again can you tell us what the problem is?

#

rn its really weird
This isn't particularly helpful

#

showing a video or giving a better explanation would be helpful

dark wedge
#

hmm its really weird

leaden ice
#

As well as explaining how you want the code to work

dark wedge
#

the issues seems to be fixed when the speed is 10

leaden ice
dark wedge
#

no more input lag and the movement overall feels much better when the move speed is 10

leaden ice
#

The code you're using seems to be emulating for example the movement in pokemon

#

where the player moves around on a grid

#

and can't exist in spaces between grid spaces

#

if you explain how you want your movement to work, then it would be possible to help you

dark wedge
#

is there any way to make the player be able to exist between grid spaces without drastically modifying the code?

leaden ice
#

No

#

you would rewrite it from scratch

#

because this is meant for grid movement

#

follow a different tutorial

#

also this is only like 20 lines of code, there's nothing about rewriting that which is "drastic"

#

basic movement script:

public float speed = 1;

void Update() {
  Vector2 input = new(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
  transform.position += input * Time.deltaTime * speed;
}```
dark wedge
#

ok ty for the help

#

i found a different tutorial that makes a platformer game which i will follow

leaden ice
#

that's so different lol

#

maybe you should decide on what kind of game you want to make before picking a tutorial

dark wedge
#

also do you think i should use rider or visual studio

leaden ice
#

Rider if possible

dark wedge
#

okay i have rider already

#

from github student

#

i want to make like an rpg game

leaden ice
#

Rider is the best

leaden ice
dark wedge
#

okay ill surf on youtube for a good tutorial

#

hopefully ill find one

lean sail
# dark wedge okay ill surf on youtube for a good tutorial

You'll never find a tutorial that fits exactly what you want. Actually you'll probably find something that "works" for the time being, then later when you want to expand on it you'll realize it's not feasible. Most tutorials give the shittiest code. First you should consider how you want it to play out

latent latch
#

rather, larger

#

more indices ;)

#

if you make enough you'll have some good precisional movement without having to deal with floats! haha

frosty widget
#

Is there a way to have drag only apply horizontally and not vertically?

ebon nexus
#

Why does Rider (or VS) not show up in external tools? I want to generate project files using the JetBrains Rider Editor package, but it doesn't seem to work if I just add the executable of the IDE, as it just doesn't show the option to regenerate project files.
Unity 2022.3.17f1

void wedge
#

Is perlin noise still the best option for base procedural generation

leaden ice
#

That depends entirely on your needs

#

there are many noise functions

void wedge
#

Then I’ll add in some of my own prefabs with some other functions

leaden ice
#

Ok, go ahead.

heady iris
#

I saw a neat video on this subject recently

#

The first half would be relevant

#

I don't think that Mathf can give you the gradients -- but you can definitely get them from the Mathematics package

#

huh, maybe you can only get gradients from 3D simplex noise?

#

I guess you could just ignore the Z component.

#

ah, I guess you'd use noise.srdnoise

#

You give it a 2D position, and it returns a float3

#

The X component is the actual value, and Y and Z are the partial derivatives in the X and Y directions

#

The video talks about how to use them -- basically, the derivatives give you the steepness

#

You can use that to control the generation. Slopes are smoother than flat areas.

#

(so yeah, watch the video. it explains the idea very well :p )

#

and it has a cute dog

slender nacelle
#

hi, i'm trying to get the inspector to show different UI based on different values but i cant get it working, i want the fields to disappear /appear based on action type

[CustomPropertyDrawer(typeof(ActionInfo))]
public class ActionInfoDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        Debug.Log("Drawing ActionInfo");

        SerializedProperty actionTypeProperty = property.FindPropertyRelative("actionType");

        // Draw the actionType dropdown
        EditorGUI.PropertyField(position, actionTypeProperty);
        position.y += EditorGUIUtility.singleLineHeight;

        // Customize the GUI based on the action type
        switch (actionTypeProperty.enumValueIndex)
        {
            case (int)ActionInfo.ActionType.UnitTarget:
                // Show options for UnitTarget
                EditorGUI.PropertyField(position, property.FindPropertyRelative("actionDescription"), GUIContent.none);
                position.y += EditorGUIUtility.singleLineHeight;
                EditorGUI.PropertyField(position, property.FindPropertyRelative("baseRange"), GUIContent.none);
                break;
            case (int)ActionInfo.ActionType.GridTarget:
                // Show options for GridTarget
                EditorGUI.PropertyField(position, property.FindPropertyRelative("actionDescription"), GUIContent.none);
                position.y += EditorGUIUtility.singleLineHeight;
                EditorGUI.PropertyField(position, property.FindPropertyRelative("aoeRange"), GUIContent.none);
                break;
            // Add more cases as needed
        }
    }

    public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
        // Return the height needed for the number of properties you are displaying
        return EditorGUIUtility.singleLineHeight * 3;
    }
}

[CreateAssetMenu]
public class ActionInfo : ScriptableObject
{
    public string actionDescription = "Action Description";
    public int baseRange = 0;
    public int baseDmgAmount = 0;
    public enum ActionType
    {
        UnitTarget,
        GridTarget
    }
    public ActionType actionType;
    public int aoeRange =  0;
}
night harness
#

Trying to wrap my head around some delegate/func related stuff but I'm struggling to fully comprehend what internet is telling me

I have a class like

public class CoolCustomClass : MonoBehaviour

public void DoTheThing()

and in another class I have a list of CoolCustomClass and I would like to register them to a event in bulk (maybe using a linq extension?)

eg. i know how to do this

public class EventManager

event Action myCoolEvent;
List<CoolCustomClass> coolClasses;

public void AssignEvents()
    foreach (CustomCoolClass coolClass in coolClasses)
        myCoolEvent += coolClass.DoTheThing;

but i wanna do it in a way where i can pass in the list of functions generically via AssignEvents params instead of being explicit

#

I feel like this involves Func but i couldn't figure it out

leaden ice
#

If you want your event to accept parameters you need to use a different delegate type other than Action

#

either define your own delegate type, or use the generic forms of Action

night harness
#

eg. i wanna do something cursed like

AssignEvents(coolClasses.Select(o => o.DoTheThing))

or similar

leaden ice
#

I don't really get what that would be doing

#

Oh wait you mean

#

You want to only subscribe some subset of the functions to the event?

night harness
#

I wanna assign the group of functions in the eventmanager generically so i can be explicit when i use it in other places

#

right now no params or return values

leaden ice
#

If I understand you correctly...

public void AssignEvents(Func<CustomCoolClass, bool> predicate) {
  foreach (CustomCoolClass c in coolClasses.Where(predicate)) {
    myCoolEvent += c.DoTheThing;
  }
}```
fervent furnace
#

if you have the reference to some instances, you can just directly call their methods....
use IEnumerable as argument type
btw all the instances of that class will ofc have DoTheTing method.

leaden ice
#

(obviously a made up property)

#

Or:

AssignEvents((ccc) => ccc.HitPoints > 5);```
weak venture
#

I know I can offset position at same time to get this net effect but is there any way to set up a tiled sprite to grow from an edge rather than from its center?

leaden ice
weak venture
#

cool that works. I wasnt expecting that to be on the sprite itself. If I wanted this behavior to be instance specific rather than common to the entire sprite is there a way to set that up or should I just duplicate the sprite and change duplicated sprite's pivot?

night harness
#

Sorry didn't mean like a conditional type thing, made an extended example

public class EventManager
{
    public static EventManager instance;
    public System.Action myEvent;
    
    public void AssignEvents()
    {

    }

    public void InvokeEvent()
    {
        myEvent?.Invoke();
    }
}

public class LevelManager
{
    public List<GoodClass> goodClasses;
    public List<EvilClass> evilClasses;

    public void Awake()
    {
        EventManager.instance.AssignEvents(goodClasses.Select(o => o.DoGoodThing()));
        EventManager.instance.AssignEvents(evilClasses.Select(o => o.DoEvilThing()));
        EventManager.instance.InvokeEvent();
    }
}

public class GoodClass
{
    public void DoGoodThing() { }
}

public class EvilClass
{
    public void DoEvilThing() { }
}
leaden ice
fervent furnace
#

all the instances of EvilClass will have DoEvilThing method...

leaden ice
#

this won't work with two different classes though unless they share a base class or something

#

if you want GoodClass that always does GoodThing and EvilClass that always does EvilThing maybe you just want an interface like cs interface IThingDoer { void DoThing(); }

#

And have them both implement this^

night harness
leaden ice
#
public void AssignEvents<T>(List<T> theThings, Func<T, Action> getFunc) {
  foreach (T thing in theThings) {
    Action a = getFunc(thing);
    myCoolEvent += a;
  }
}```
#

E.g.^

#

Used like:

EventManager.instance.AssignEvents(goodClasses, (GoodClass gc) => gc.DoGoodThing);```
#

Or maybe just the simpler version:

public void AssignEvents(IEnumerable<Action> actions) {
  foreach (Action a in actions) myCoolEvent += a;
}```
Used like:
```cs
EventManager.instance.AssignEvents(goodClasses.Select(gc => gc.DoGoodThing));```
night harness
#

ahhh ok

#

thank you very much I appreciate it a lot

#

I'm always hesitant to ask for explicit examples but in this case a working example is helping things click in my head 🙏

#

getting hit with this error, Am I missing something obvious here?

#
    public void AssignEvents(IEnumerable<Action> collection)
    {

    }
leaden ice
#

try this

night harness
#

ahh ok ok

#

❤️

void wedge
#

What method do we think is best for realistic terrain procedural generation? I tried perlin noise but are there other ways just as good? Im happy to share my thoughts on what I think I need to do to create a realistic terrain and then bounce ideas around to come up with a better way

lean sail
cosmic rain
#

Perlin noise is the base of everything though. There are things that complement it or build on it, but don't replace it.

void wedge
#

I like this image as an example. A lot of the land is flat but when the terrain height increases so fast a rock prefab is placed against it

gray mural
lean sail
void wedge
lean sail
void wedge
#

normally after these prefabs have been placed you would press a button and the textures around the prefab would smooth so its a clean transition

lean sail
#

ah i can see that being viable too. Something like make a simple terrain, place prefabs, remake parts of it to fit

void wedge
#

Im completely new to procedural generation so I really have no clue how to do this but I think this would be how I attempt to do it

austere solar
#

Who else hates it when they change the initial value of a public variable, run code, code still not work, stress for 30 minutes and than realise they didn't reset the value in Unity?

rain minnow
#

who uses the default value from code anyway? once it's visible in the editor that values always takes over . . .

gray mural
#

This code returns the following output:

Space start
Something start
Space end

<- 3 seconds
Something end

Why does calling the method Something give me the following warning if that's how it's supposed to work? The Something method's Delay shouldn't stop the Update method from executing.

Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the await operator to the result of the call.
#

When applying the await operator, this gives the following result, which stops the Update method from executing before the Something method is finished

Space start
Something start

<- 3 seconds
Something end
Space end
#

So my question is how to avoid the warning without pragma

main shuttle
gray mural
gray mural
quartz folio
#

Discarding it is not the right solution

gray mural
quartz folio
#

I never said to await it

gray mural
quartz folio
#

And I didn't suggest you do that

gray mural
#

Right, you have mentioned that discarding it is not the right solution. Could you, please, tell me why?

quartz folio
#

Any exception thrown in a Task creating async function will be eaten if the Task is not awaited

gray mural
#

Even if the exceptions aren't eaten

quartz folio
#

Yes, so do what I and my resource suggested for fire and forget async methods in Unity

gray mural
quartz folio
#

I'm honestly not sure what's most appropriate for methods in the Editor. Awaitable is good for runtime

winged stag
#

Does anyone use A* Pathfinding Project?
How to get the collider to work on 2 Ais?

leaden solstice
#

And Unity already has NavMesh that covers pathfinding and little bit of collision/obstacles options. Is there a reason you are using astar specifically?

winged stag
#

I would love to show you it if you got time (sharing screen), since my game is a top-down view

#

Nav mesh calculation for the pathfiding is kinda weird, and it jiggles alot

leaden solstice
#

For NavMesh you’d need to adjust how it is generated and how your agent is set up. But if astar matches your need then it works.

#

I’m on mobile rn so don’t really have time for screen sharing, astar is pretty fast (depending on grid size, tho) so you could update your high-priority agent first and bake grid accounting that agent

#

Or you can just use physics approach

winged stag
#

Maybe a Rigidbody?

leaden solstice
winged stag
#

Yeah a rigidbody actually fixed it

#

My bad I was stupid enough not to use it

#

Woops

leaden solstice
winged stag
#

Hmmmmm, now another issue im having is if i have 100 units, they would actually climb on eachother xD

#

Aaaaahhhh

#

Lmao

#

I just made the Collider taller, so that fixed it ^^

leaden solstice
#

That’s more characters than I thought

winged stag
fleet tide
eager fulcrum
#

Hey, I have problem with cameras in URP, I have a tilemap on layer "Ground"

#

I have a main camera which renders everything

#

and another camera which should only render that Ground layer

#

and for some reason the output texture is black?

cosmic rain
#

Is the last screenshot rendered by the ground camera?

eager fulcrum
#

preview shows the same thing that the main camera

cosmic rain
#

Hmm. Does anything change if you enter play mode and pause the game?

eager fulcrum
#

nope

cosmic rain
gray mural
fleet tide
gray mural
#
Option name             |    cost | credits |
Cold 1 : Damage         |      10 |     -10 |
Mana 1 : Consume mana   |      10 |     +10 |
#

Note that every Option's item should be an empty GameObject with the TMP_Text inside of it

#
Vertical Layout Group
  - Option
    - Option name
      - TMP_Text
    - Cost
      - TMP_Text
    - Credit
      - TMP_Text
  - Option
  ...
fleet tide
#

Like this ? but it's not next to each other

fleet tide
torpid depot
#

hi people can you help me please? I am ın a exam rıght now but my audıoSource got some problem ı cant hear the sound

#

ı dont know why Anyone have any ıdea for ıt?

#

ı watch some basıc tutorıal about thıs component but ı dont know what ıs wrong about ıt

vivid halo
#

Min distance is 500, max distance is 1000. Is this what you intended?

torpid depot
#

because that dıdnt work wıthout ıt and ı just trıed to change

vivid halo
#

Is it outputting to the main camera's sound?

torpid depot
#

ı put audıoLıstener ın player

#

sorry ın camera

vivid halo
#

No errors? Can you verify it's trying to play the sound?

torpid depot
#

lıstener ın camera audıosource ın player

#

ı dont know what ıs that output varıable means

torpid depot
#

ın code that %100 should to work thıs code

#

because ı put jumpSound ın jump fonk

#

Character jumps but there ıs no voıce

vivid halo
#

Enable these two boxes

#

If you hear sound, then the issue is that you are not triggering the sound.

torpid depot
#

ı dıd

vivid halo
#

If you hear no sound, then the issue is that the audio player is not right

#

You did what?

torpid depot
#

ı just dıd add a audıo source and lıstener

#

that ıs all

vivid halo
#

Okay

torpid depot
#

and download some audıoclıp from ınternet

gray mural
# fleet tide Or maybe i need to add an VLG to each gameobject ?

You... have done it wrong enough.

  • Each GameObject inside of the Option may be assigned with the Horizontal Layout Group, but it's not necessary
  • These "sections"' heights should fit the whole Option and the widths and positions should be set the desired way
  • Note that the size of the sections of each Option should be the same if you want them to be "in a column"
vivid halo
#

So I need you to click these two boxes:

#

And then press play

#

And then put something in here:

#

Without an audio clip, nothing will ever play.

vivid halo
# vivid halo

This is just for troubleshooting. If you check these boxes and hear no noise, it's because there is no noise.

gray mural
torpid depot
#

my game have time.timescale in start fonk fırst

#

and a buton change ıt to 1

#

ı mean when game starts there ıs time.timescale = 0

vivid halo
#

The timescale doesn't matter

#

You have no audio clip to play.

torpid depot
#

start fonk and thıs audıosource can work ın zero timescale?

gray mural
#

Yes, AudioSource doesn't depend on Time.timeScale

torpid depot
torpid depot
gray mural
#

Do you mean "phonk"?

torpid depot
fleet tide
vivid halo
torpid depot
#

yea

gray mural
gray mural
torpid depot
#

ı cant add audıo ın thıs project...

fleet tide
dim frigate
#

How can I open this file in Unity? I transfer it to Unity and want to spawn it on the map, but it doesn’t allow it, what should I do?

knotty sun
dim frigate
knotty sun
vivid halo
#

Eloquently said, Ast. Can someone give this guy mod privileges?

gray mural
gray mural
# fleet tide Oh no i understand sorry !

Yeah, right, make sure you make them slightly wider. Also, it's quite troublesome to align them with the Horizontal Layout Group, so I would rather remove it from the Option object

#

But it's up to you

fleet tide
#

Yeah my "option" is empty , what you mean by "slightly wider" ?

gray mural
fleet tide
gray mural
gray mural
#

This is going to cause you troubles when increasing the cost

#

and so -100 is not going to fit properly

hexed pecan
unkempt meadow
#

How would I, IN WORDS, make this happen?

set an inverse relationship between two floats within some parameters? I've made my spotlight angle be controlled via the mouse wheel, i.e. scroll up ads to the variable of angle upwards and vice versa, but I would like to make it increase in range the narrower the angle and vice versa

#

I made a primitive version with float switches but they go up in increments and it's kinda bad

#

I'm sure there is some kind of mathemathical way to do this but I'm dumb

hexed pecan
static matrix
#

ok so I currently have this

 for (int i = 0; i < Segments.Count; i++)
        {
            if(i==0){
                if(Vector2.Distance(Segments[i].transform.position, transform.position)>SegLen){
                    Segments[i].transform.position += Time.deltaTime  * -(Segments[i].transform.position-transform.position);
                    Segments[i].transform.right = Vector3.Lerp(Segments[i].transform.right, -(Segments[i].transform.position-transform.position),0.5f);
                }
            }
            else{
                 if(Vector2.Distance(Segments[i].transform.position, Segments[i-1].transform.position)>SegLen){
                    Segments[i].transform.position += Time.deltaTime  *  -(Segments[i].transform.position- Segments[i-1].transform.position);
                    Segments[i].transform.right = Vector3.Lerp(Segments[i].transform.right, -(Segments[i].transform.position-Segments[i-1].transform.position),0.5f);

                }
            }
        }

created by this code
but i wish the segments didn't go along the diagonals, and instead more closely followed the path, like the centipedes in rain world

slate imp
#

Hi, I'm trying to figure out how to reduce the size of my apk, so i found the following link (https://docs.unity3d.com/Manual/ReducingFilesize.html) but it says that i should have a breakdown of my build size in the console but it seems its isnt the cass... is it because its deprecated ? or is it somewhere else ???

Also, i found something about BuildOptions.DetailedBuildReport thing, but i dont understand why its in code and how to make it work

leaden ice
maiden fractal
# static matrix ok so I currently have this ```cs for (int i = 0; i < Segments.Count; i++) ...

This could definitely be written more clearly, I'm having hard time trying to understand your code but I guess what you are doing is move each segment towards the segment before. Is that right? If so, the segments will cut the corners and towards the end the effect will accumulate even more. For better results you may consider constructing a spline or polyline which all the segments follow instead of each other. There's definitely some much easier solution out there done by just modifying your idea slightly but I'm not aware how that would work. Actually I'm wondering whether something like this could work: so instead of moving towards the next point, you would move towards the direction from the last point towards the next point (see the sketch below). I figured this might not be exactly the working formula but the idea could be worth playing around. For example you could maybe also try to lerp a direction between the direction to the next point and the direction discussed earlier with different lerp factors to see where's the sweet spot that works the best. It is more than likely someone has figured out the mathematically correct way to achieve that but this is just my thoughts on the issue, I bet there's quite some resources available online on the same issue as well.

dim frigate
vivid halo
slate imp
vivid halo
#

Compiled Unity is not meant to be reverse-engineered

#

This is by design.

heady iris
#

and as you have already been told, this server does not permit discussion of reverse-engineering or decompiling Unity games.

leaden ice
#

See the top right (B)

dim frigate
#

Thanks

slate imp
fleet tide
long ibex
#

I'm in the Unity 6 preview, and I'm trying to use TextMeshPro, but for some reason I can add TextMeshPro components to my scene just fine but the package isn't listed in the package manager, there is no .asmdef that I can add to my project and I have no way of referencing it from my code, has something major changed in Unity 6 that I'm missing? 🤔

slate imp
heady iris
long ibex
heady iris
#

oh hey, you're right! I didn't know that

#

that's neat

#

but yes, good question...i don't see where to look now either

#

oh, no, there it is: I can still use the TMPro namespace just fine

somber nacelle
heady iris
#

(my IDE wasn't set up properly)

long ibex
#

found the issue, the UGUI package isn't being imported properly (or at all)

heady iris
#

well that's wonky

long ibex
#

it exists in my cache just fine, but for some reason it isn't being imported, so that's interesting

somber nacelle
#

make sure you have no compile errors. i've noticed that unity will fail to correctly import a package if it cannot compile

gray thunder
#

Just for that I would just start using UAE

long ibex
#

including the fact I can put text mesh pro components into my scene just fine and the work as expected

somber nacelle
#

weird. you could force a complete reimport by closing unity and nuking the Library folder

long ibex
#

yeah I was just thinking that, I hate to do it but it is what it is

#

yep, all back to normal, no idea how or why that happened

heady iris
#

I like to do that from time to time in case there's any...miscellaneous corruption in there

#

it also reveals how long cold builds are 😭

#

i need to get some shader variants under control

somber nacelle
heady iris
#

will have a look!

#

you know, there's one thing I don't get

#

assuming that both sides of a branch use the same resources, why not just dynamically branch on a uniform?

#

e.g.


float foo = -1;

if (do_foo) {
  // a ton of expensive math to set foo to something
} else {
  foo = 0;
}
#

that's not going to diverge, and it's not like one side is using a big texture that the other isn't

leaden solstice
heady iris
#

it's expensive when you start diverging, isn't it?

leaden solstice
#

If do_foo is a feature flag of sort then multi compile would remove that branch