#archived-code-general

1 messages · Page 135 of 1

pliant locust
#

yeah

urban berry
#

I'm in the middle of a "Reimport All" so my own editor is indisposed at the moment so I'm going strictly by memory

pliant locust
#

oh damn

urban berry
#

okay, so this is good news. The inventory slot IS being affected, just... not in the way you wanted

pliant locust
#

so how do i fix it?

urban berry
#

Argh This is really hard without a working editor

#

grumble

pliant locust
#

could we call and i present my screen or nah?

#

ugh damn

urban berry
#

I mean honestly right now I would be poking at the settings for the grid layout component

#

just to see if I can get the inventoryslot to change its spacing

#

and to do this when there are multiple inventoryslots attached

pliant locust
#

i dont know

#

i cant figure out how t ofix it

#

im tring everything

urban berry
#

ok that import is done

#

now I'mma try this out

pliant locust
#

kk

#

do u want the video im using

#

?

urban berry
#

I'm just duplicating your setup

pliant locust
#

oh ok'

#

Just use

urban berry
#

try stretching the width of your toolbar

pliant locust
#

UI - Image

urban berry
#

it's only set to 8px, I think

pliant locust
#

8.4

#

so set mine to any 8?

urban berry
#

yeah, something like that

#

no I mean, stretch it to like, 800px

#

just to see if it moves those slots apart

#

cause it should look sorta like this

pliant locust
#

800 goes WAY off my screen

#

i did 50, nuthin, 100, nuthin

urban berry
#

because this is my setup

#

could be that there's a canvas scaler at work

pliant locust
#

the child allignment is supposed to be set as middle center on the grid layout group

urban berry
#

like there's some settings here

#

I'm gonna try putting my grid layout object on the root like you did

#

oh yeah, it works...

pliant locust
#

bru-

#

what did i do wroongnggggg

urban berry
#

and I set the Child Alignment to Middle Center like you did

pliant locust
#

then what did i do wrong???

urban berry
#

the slots have nothing on them, just rect transforms

#

I'm gonna play Spot The Differences

pliant locust
#

thats mine

#

the exact same as urs

urban berry
#

how's the root of this UI set up?

pliant locust
#

root?

urban berry
#

got a screenshot of the canvas? also.... this is probably outside of the realm of code and more of a thing for #📲┃ui-ux

pliant locust
#

yeah here

#

here's the tool bar and inventory slot too

halcyon venture
#

will playerprefs be reset when i build into webGL? like rn in the editor i have some player prefs saved but when i build the game will they reset

crimson atlas
#

what's wrong with centipedePrefab = Resources.Load<GameObject>("Assets/Prefabs/Centipede/Centipede.prefab");?

urban berry
pliant locust
#

what do you mean narrow?

urban berry
#

I playerprefs saves to the registry and those values will stay until something comes along and overrides them

urban berry
pliant locust
#

well when i widen it it doenst fix anything

urban berry
#

how far are you widening it? it must be the width of a slot x the number of slots you want it to hold

#

so if a slot is 100px wide and the capacity is 8 slots then it must be at least 800px wide

urban berry
#

are you receiving an error?

knotty sun
urban berry
#

thank you, I practically never use that Resources folder and that never occurred to me

crimson atlas
#

where is the editor layout information stored?
is there a way to manually type the width of panels in pixels or something somewhere? even editing a file if necessary?

pliant locust
#

i cant fix it

urban berry
pliant locust
#

i dont know whats wronnggggg

#

im trying what u said and it's not working

urban berry
pliant locust
#

sorry moat

urban berry
#

this stuff is beyond my pay grade!

pliant locust
#

sorry 😭 lol

#

what if i send u the video i used?

urban berry
#

I wish you luck and I hope you can get it solved - I know how infuriiating it can be

pliant locust
#

would that help at all?

urban berry
#

I am, like many others in this channel, not an expert in UI We've definitely reached the meagre limits of what I know.

#

If you solve this thing you'll know more than I do

pliant locust
#

k

#

sorry for using ur time lol

#

have a great rest of your evening

#

thanks!!

urban berry
#

good hunting

#

you got this

jaunty sleet
#

Does anyone know of a way to move objects by script without playing the game? I want to do this to make a tool to help me make my game, and to save me from having to manually move objects

cobalt gyro
#

is there a way to search for a file via scripting

rigid island
cobalt gyro
rigid island
tropic quartz
# jaunty sleet Does anyone know of a way to move objects by script without playing the game? I ...

I haven't really dabbled with editor tools, but are you maybe looking for something like this?
https://docs.unity3d.com/ScriptReference/EditorGUI.PropertyField.html

Also if you just need to align a bunch of objects or randomize positions there are a few numeric field expressions for it.
https://docs.unity3d.com/Manual/EditingValueProperties.html

I've used them before to line up a bunch of objects without having to move them all manually.

warm stratus
#

hey, I have some red circles and i wan t to preserve aspect and be in the anchors points like the preserve aspect in Image but for parent gameObject someone knows?

urban berry
#

so that way they only have to be pointed to this one scriptable object and then they can get other scriptable objects via an enum

#

and in other situations where I needed even more modularity I used Addressables and stored addressable references and I have these scriptable objects loaded in advance during an init stage

#

so there are many ways to go about this

#

But I think if you're looking to say, throw scriptable objects into a folder and be able to search that folder and load them up, it probably won't work at runtime

#

you're better off serializing that sort of data in JSON and just export it separately because those operations will work at runtime

light rock
#

as long as they’re in a folder called “Resources” then AssetDatabase can find them at runtime

urban berry
#

...isn't AssetDatabase in the UnityEditor namespace?

light rock
#

nope it’s intended for runtime use

#

the restriction is that it’s limited to only folders labeled Resources, and subfolders

urban berry
#

TIL

soft shard
#

You sure? I dont think youd be able to make a build of your game if its using AssetDatabase code (outside a Editor folder)

light rock
#

i’ve definitely done it before

mossy snow
#

you're mistaken, if you actually make a build it would fail

light rock
#

ohhhh hang on

#

the class i’m thinking of is called Resources

#

but yeah that’s the class you want if you want to find assets at runtime

elfin tree
#

Hey, so I'm deforming a terrain at runtime. Since there are multiple terrains, it happens that the deformations are along the edges and go a bit too deep, creating a bit of a gap where you can see through. How could I, through code, blend the edges together or clamp them or something? Thanks!

heady iris
#

How are you doing the deformations?

cobalt gyro
light rock
elfin tree
heady iris
#

right, but what method are you using?

#

It looks like you're only deforming one terrain tile at once, causing the seams if your deformation tries to hit two tiles at once

elfin tree
#

A bit like a brush basically, but cause it would be too costly to just have one big terrain I think. I need to keep the terrain small and just use a bunch

#

So I'm trying to find a workaround to make the edges come together after deformation

heady iris
#

It collects heightmap data from one or more terrain tiles and gives you a texture

#

you then draw on that texture and send it back to be applied

tacit portal
#

when my game suddenly needs to load 5 mins for something, should i be concerend, or just restart unity? 😆

heady iris
#

(This is part of the Terrain Tools package)

elfin tree
#

I think maybe BeginPaintHeightmap

heady iris
#

well, here's an example of how I used it

#

i use this to stamp a texture into the terrain

#

"Terrain Add" is a custom shader I made to do that.

twin hull
#

maybe that?

shut elm
#

Hi, I have the problem that some time ago I probably coded a bug in the world generation that occurs in a specific case when unloading and reloading chunks. The bug causes a complete freeze of the Unity Editor. I don't have an error message and since the changes in this scripts were more than a month ago I have no idea where to look. How would you proceed in this case? Is there a way to at least find the "problem script" or something similar?

heady iris
# twin hull

that would be if you asked for an area that has no terrain on it

#

this is just an issue of needing to deform two piecces of terrain simultaneously

#

(which Terrain Tools handles for you)

twin hull
#

maybe make a thread? i'll want to know when you figure it out

mossy snow
elfin tree
#

Yeah I don't mind making a thread, just annoying that everything above wont be in it haha

swift falcon
#

Hello y'all, I want the trail renderer to NOT go through the lighter blue note, but rather be hidden/not visible/stop emmiting past it's position... and I don't know how to do this... Does anyone know?

soft shard
# tacit portal when my game suddenly needs to load 5 mins for something, should i be concerend,...

Depends on whats being loaded, you could try restarting the engine, if it doesnt solve the problem, you could try checking the profiler and "background tasks" window to see what might be taking the time, if its editor-specific it could just be a slow in your workflow, if it happens at runtime too, that could indicate a performance problem, likely if this didnt happen before it could be related to a memory leak (for example, unmanaged events) or a editor window doing work on the main thread or something else

elfin tree
#

still not sure where to start, cause in your case you were applying a really specific shape

heady iris
#

you would run a blur shader on the texture

elfin tree
#

on the heightmap you mean?

heady iris
#

yes

#

the heightmap data gets put into a render texture

elfin tree
#

that sounds like a pretty daunting task

#

pretty bad with shaders usually avoid them

heady iris
#

start by just getting it to set the height to a specific value

#

then you can worry about implementing something more complex

#

(so, a shader that just sets the color)

elfin tree
#

yeah.. might end up doing that

#

still hoping to find something similar to what i'm trying to do

shut elm
elfin tree
#

so at least i have some building blocks

mossy snow
heady iris
#

hit pause in the debugger, they mean

shut elm
#

I'm pretty new to unity, how can I attach a debugger?

heady iris
#

you'll do it through visual studio.

shut elm
#

ohh, alright

#

thank you <3

#

I get the exception "Frame is not in module" when trying to pause the visual studio debugger, what does that mean?

heady iris
#

you might be pausing on the wrong thread, or something like that

#

i haven't used visual studio much recently..

#

or it's just pausing outside of your code

shut elm
#

hm okay

#

okay, if I watch the taskmanager unity uses more and more ram, so I think there somewhere a infinite loop. I guess I will search for that manually

molten temple
tropic quartz
shut elm
molten temple
#

omg its working

stoic wing
#

Haihai! Looking for a little help within the animator for Unity. Basically I have a paramater set to the angle of a bone. When the angle changes, the bone changes. I want to convert this paramater into ∆ so I can then say "if [∆ paramater] is greater than 0.3 (since it's a float) then xyz" but I'm unsure exactly how to convert this float point to ∆

heady iris
#

I don't understand what "a parameter set to the angle of a bone" means

#

Is this an animator parameter that is controlling a blend tree?

stoic wing
#

So I'm using the VRChat SDK for this so there may be some missing context. Within the SDK they have their own Bone system. In this, there is an aplility to set a float based on the angle of a bone. In this screenshot, I have used "Jiggle Test_Angle"

heady iris
#

ah, okay.

#

sounds like you just need to add a transition based on that parameter, then

#

so that the transition is possible if the parameter is greater than 0.3

stoic wing
#

The problem with that is the ground 0 needs to be fixed whereas the ground 0 in this case can change. To explain it more simply, I need something that says "is it moving"

heady iris
#

"the ground 0"?

#

oh, you're asking for a way to measure the rate of change

stoic wing
#

Like the basis, like a base number where if its moving its higher or lower but if its not moving it's equal

heady iris
#

i don't know if you can accomplish that with just the animator

stoic wing
heady iris
#

I actually detect something like that on my VRC avatar by just using a very loose physbone

#

if it deflects far enough, then I figure it's moving fast enough to count

stoic wing
heady iris
#

I use the _Angle parameter

#

i use this to detect that I'm swinging my fist

stoic wing
#

So what I'm concerned about is this. I'm using the bone as a 3d bell on a choker. I basically want to make an animator that says if the bell is moving, turn on/play an audio source for a jingle but if the velocity is high enough to play a longer version of that jingle. I'm concerned that if I get turned upside down or made to where it's not movingbut at a high angle it will still play the sound

#

I think I'm overcomplicating things as usual 😂

heady iris
#

oh yeah, that's exactly the kind of thing I detect

#

just turn off gravity on the invisible physbone

#

it will deflect based on how fast it's getting moved

#

(also, i dunno if you're already there, but !vrc would be the appropriate server to ask this stuff in)

#

er

#

!vrchat

tawny elkBOT
heady iris
#

i keep forgetting that one

stoic wing
#

Ah, thank you!

wild bane
heady iris
#

is setting the layer of the object the controller is on not enough?

#

includeLayers is just for extra control

wild bane
#

I need this extra control

heady iris
#

why?

wild bane
#

Some runtime flags can arbitrary change whether the CharacterController can or cannot collide with other colliders

#

And creating a new layer for every flag combination is simply impossible in this case

heady iris
#

actually

wild bane
#

Makes no sense for includeLayers not being exposed for CharacterControllers

heady iris
#

the docs say that it does have includeLayers

#

only in 2022.2 onwards

#

but that's also the case for colliders

#

wait

#

🤦‍♂️

wild bane
#

You sent the Collider page, not CharacterController

heady iris
#

whoops, sorry

wild bane
#

But yes, it is a newer Unity feature then

heady iris
#

i must've tabbed over or something

wild bane
#

Time to update

#

Ty 🙂

heady iris
#

no, no, it's not on CharacterController

#

I had wound up on the Collider page and got confused

wild bane
#

It is on the CharacterController, but it is listed as something inherited from the Collider class

heady iris
#

oh right! it derives from Collider

#

i forgot that

#

task failed successfully

wild bane
#

I hope my project doesn't break with the update

storm aspen
#

for a hero shooter would i use multiple imput action frames for each hero

heady iris
#

i bumped to 2023.1 on macOS and i'm having some issues with the editor hanging. maybe I shouldn't have done that...

#

the longer I wait the more annoying it'll be to re-apply my changes on top of the old 2022.2.x commit

wild bane
heady iris
#

it also likes to crash when exiting play mode

#

as it just did

crimson atlas
#

which one is more performant?
!myList.Any() or myList.Count == 0

rain minnow
crimson atlas
#

count it is then

#

dude it's like 15 seconds every time i save script and go back to unity
also another good 15-20 seconds to enter play mode
is there a way to reduce those times?

eager yacht
#

You can basically remove the enter play mode time by disabling Reload Domain in the settings https://docs.unity3d.com/Manual/DomainReloading.html just have to make sure to abide by a few new requirements (mainly around things like statics), but I disable it in every project. I keep the Reload Scene option enabled just so that my objects are reloaded.

crimson atlas
#

awesome. just turned it off

#

what about some "incremental build" stuff.
does it apply to the visual script saves i do? or is it just for actual game builds?

eager yacht
#

That's for actual builds

#

Rebuilds the parts that changed since the last build, instead of the whole game again

crimson atlas
#

so can't avoid the 15s after saving scripts?

rain minnow
#

You can use assembly definitions . . .

eager yacht
#
  1. Faster CPU, helps to a certain degree
  2. Smaller codebase
  3. Proper use of assembly definitions (misuse can make it worse)
nova axle
#

Hello, I'm trying to make my inventory work with an XBOX controller. Specifically, I want to show description of hovered items. I use IPointerEnter/IPointerExit to show desc. when hovered over with mouse. These however don't fire up when I use controller's UI navigation. Best I can think of is check for changes in an update loop but that seems stoopid. Any pointers would be highly appreciated.

eager yacht
#

If the item inherits Selectable, you can utilize the existing navigation system with overriding OnSelect and OnDeselect (item selection is when the navigation sets a new obj as active)
https://docs.unity3d.com/530/Documentation/ScriptReference/UI.Selectable.OnSelect.html
https://docs.unity3d.com/530/Documentation/ScriptReference/UI.Selectable.OnDeselect.html

Or I think you can use the interfaces to piggy back off of a selectable already on the same object (like a button), although I haven't used these on their own myself.
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/api/UnityEngine.EventSystems.ISelectHandler.html
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/api/UnityEngine.EventSystems.IDeselectHandler.html

nova axle
#

Now I have to wonder. Are both necessary? IPointerX for mouse and ISelect for navigation? Or would ISelect suffice by itself?

eager yacht
#

Select for mouse (without a prior element selected) requires a click, so most likely the former

nova axle
#

Isn't "select" the same as "hover" though? It works as such in my case. PointerEnter fires when mouse is hovered over button. OnSelect fires when I navigate to the button via Dpad, none of which actually 'press' the button actually. Or am I missing something?

#

The only difference being the UI navigation requires some initially selected element to "kick off" from.

crimson atlas
eager yacht
#

Select is when the object is active with the event system, hover is its own thing. So when you click a button, it sets that object as "selected" and now you can arrow around to other elements through the nav system. Or if you use gamepad, and manually set some object as active with the event system, it functions the same way when you dpad around.

#

So yeah basically your second message

nova axle
#

So, to further try to draw connections with stuff I'm more familiar with, would selected be similar to focused? E.g. in the HTML environment?

eager yacht
#

Yeah basically

nova axle
#

Alright, that gives me a better picture. Anyways, I really appreciate the help. It works wonderfully now.

crimson atlas
#

is there a most popular way of storing settings in a file?
seems unity doesn't have an ini parser?

rain minnow
dusky lake
rain minnow
heady iris
#

json would be ideal for storing settings

eager yacht
heady iris
#

as in, a single, coherent specification

#

as the wikipedia page notes, there are many dialects

#

there are definitely ini formats

eager yacht
#

True, most games I see with it (a ton of games, even in recent years) tended to use the basic structure of a few headers and basic keypairs. Or they just shoved all of em in a single header LUL

#

Ark does the single header approach

zinc flare
#

hi, Ive come to a massive roadblock with my procedurally generated game, and I need help. I'm trying to procedurally add a stylized grass shader to a mesh, but nothing ive tried has worked. ive tried many different shaders and placing methods. I need ideas on how to begin rendering and placing this much grass automatically

thanks

heady iris
#

is the problem in putting the grass shader on the mesh, or about placing the mesh?

zinc flare
#

putting the grass on the mesh

dusky lake
#

Hey, what would be the least expensive conversion of NativeArray<float3> to Vector3[]? Linq Select and then ToArray() is awfully slow and I'm new to the NativeArray stuff

crimson atlas
#

is there a way to freeze my game and then check the runtime value of the local variables of a function i'm trying to debug?

crimson atlas
#

thank you!

cobalt gyro
#

if i want something to change color should i make the base asset white/monochromatic

lean sail
leaden ice
rough fjord
soft shard
#

Im working on FSM AI and so far have implemented 2 working approaches but im not sure if my second approach has any drawbacks over the first - the first approach has states as just classes and specific "types" of AI create instances:

public class FSMState { ... } //virtual funcs
public class IdleState : FSMState { ... } //override funcs

public class SomeAgent : Mono
{
IdleState idle;
AttackState att;

void Start()
{
idle = new IdleState(this);
att = new AttackState(this);
}
}

The second approach turns FSMState into a scriptable object instead, that way SomeAgent can hold a List<FSMState> which can be assigned from the inspector, then I dont need a super specific type of AI to test states, the SO base also has the same virtual functions for transitions and updates/coroutines, are there any drawbacks to using SO's in this way as opposed to new instances in super specific scripts? Does it make sense to use both approaches, having SO's for generic enemies and regular classes for super specific AI like bosses?

tiny mantle
#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

tiny mantle
leaden ice
tiny mantle
leaden ice
#

that's all you care about right now

#

since you said "it's not spawning objects"

tiny mantle
#

yeah

leaden ice
#

so.. do it

#

see what happens

#

does it print? How many times does it print?

#

that will tell you a lot

tiny mantle
#

I have it log the spawned tiles when it creates them already

leaden ice
#

you're doing this: Debug.Log($"Tiles: {spawnedTiles}");

#

which tells you nothing

#

doesn't that just print List[]GameObject or something

tiny mantle
#

I should log it with the position too, right?

leaden ice
#

No you should put a log where the Instantiate is

#

to make sure it's getting called and how many times it's getting called

#

get rid of the log in Update

#

to remove spam from console

tiny mantle
#

Should i also have it say where it spawned the object?

leaden ice
#

if you want sure

#

but that's not that important yet

#

we just want to know if it spawned at all first

tiny mantle
#

no spawning

#

not a single debug.log message came through

leaden ice
#

that tells us a lot

#

now time to put another log here:

GenerateInitialTiles```
#

print out tileDistance

#

so we can see if for (int i = 0; i < tileDistance; i++) is even going to do anything

#

perhaps tileDistance is 0 for example

tiny mantle
#

where exactly should i put it

leaden ice
#

before the loop

tiny mantle
#

which one, there are two

leaden ice
#

there is only one loop

#

inside GenerateInitialTiles

tiny mantle
#

it prints out a single zero

leaden ice
#

so tileDistance is 0

#

hence the loop never even runs one time

#

that's why it's not working

#

set tileDistance to something higher than 0 😉

tiny mantle
#

wait, line 14 was already

    public int tileDistance = 50;
leaden ice
#

that number is meaningless, you set it in the inspector

#

that number is only the default for when you create a new instance of the script

tiny mantle
#

i set it to 50

#

now i just need to find out why they spawn together

#

they are supposed to be multiple tiles apart

leaden ice
#

keep debugging 😉

tiny mantle
# leaden ice keep debugging 😉

I found out why, I promise i'm not stupid, I just went to working on Unreal and I wanted to make a 2d game, unreal doesn't have 2d, so I tried to remember what I could for Unity

leaden ice
#

I was not thinking/accusing you of stupidity 🙏

tiny mantle
#

this game is cursed

#

My computer is possessed

swift falcon
#

The more ide's I have open the more demons start swirling around my pc.

eager ingot
#

Anyone know how to increase both acceleration and deceleration at the same time with addforce? I tried adding drag, but that just makes the acceleration far, far slower than it should.

lean sail
#

Not really sure what else this question is supposed to mean. If you add more force, you get more velocity. If you add more counterforce, you get less velocity

eager ingot
#

I see I see. I managed to fix that issue, but now I have another issue: I am using addforce for jumping, but after doing a completely normal upward arc, it chooses to float down instead of fall down

lean sail
#

theres a few reasons it could appear to float (but i assume you just mean slowly falls),
like your object scale is too large,
you adjusted gravity,
you have an upwards force being applied which counteracts gravity,
you have a super fast brain and it just appears slow but it is you who is fast

eager ingot
#

That's how I fixed the weird movement lol

lean sail
eager ingot
#

Yeah. I tried methods that didn't involve addforce, but every single one of them resulted in my character teleporting through walls

#

Even changing velocity lol

lean sail
#

both are almost the same anyways. You can achieve the exact same results, the only difference is addForce happens during the physics part

eager ingot
#

Another issue I had was that I really have no idea how to use velocity in terms of jumping

lean sail
#

most just add an impulse, addForce allows u to input what ForceMode you want

eager ingot
#

Yeah, I currently use the Impulse forcemode for jumping

eager ingot
#

A constant, steady slow fall instead of a gradually increasing one

lean sail
#

i assume you still have drag set then

eager ingot
#

Yeah. I wanted to see if adding an extra force would offset it.

lean sail
#

why add drag then in the first place if you are just gonna need to offset it

lean sail
#

imagine if you were running around with a parachute at all times, and instead of taking it off, you asked a friend to help push you around

#

that is essentially what you are doing with drag

eager ingot
#

Like it's like walking on ice without drag

lean sail
#

so you do need to offset it..

cunning escarp
#

Is there a way to get the SpriteRenderer.color in HSV values instead of in RGB?

lean sail
frosty pawn
#

Hello. Is there a way to copy values from one ScriptableObject instance to another (of the same type). I mean it should be just copying it's serialized data but I see no methods for that.

What I'm trying to achieve is:
I clone my original SO on start by Instantinate() method and I want to be able to apply changes I made during runtime back to original instance. So by default changes can be made in runtime and they won't override original values but if I want I can do it.

cold egret
#

- I struggle to find any information of yield return allocations. What factors affect allocation size when using yield?

cold egret
frosty pawn
cold egret
#

- Ah. In editor you can modify the asset only after you load it. In game objects it's resources/adressables. In editor it's asset database. As for saving an instantiated SO, i haven't heard of any way

frosty pawn
#

I'm asking how can I copy values from one instance of SO to another, not about how to modify assets which isn't loaded

tepid geode
#

is it possible to use properties package with builtin components? for example if I try to set anything on Transform it doesn't work. property bag is there, just doesn't contain any properties.
package works fine with everything in my assembly, just not with engine ones. is there any additional steps to setup it for engine classes?

cold egret
frosty pawn
cold egret
#

- Well, the article i linked should solve this in the dirtiest, but the easiest as well way. In a nutshell, it serializes the instance and loads it back immediately. Of cource the class has to be serializible, which i believe it already is

leaden cipher
#

is 0.2 seconds good for coyote time?

royal pulsar
#

Is inheritance generally a better approach than interfaces when making a FSM?

loud wharf
#

I'd probably say yes.

hollow hound
#

Trying to use OverlapCircle (https://docs.unity3d.com/ScriptReference/Physics2D.OverlapCircle.html) with this overload:

public static int OverlapCircle(Vector2 point, float radius, ContactFilter2D contactFilter, List<Collider2D> results);

like this:

            var colliders = new List<Collider2D>();
            Physics2D.OverlapCircle(
                transform.position,
                3f,
                ContactFilter2D.NoFilter,
                colliders
            );

Getting:
Cannot resolve method 'OverlapCircle(UnityEngine.Vector3, float, method group, System.Collections.Generic.List<UnityEngine.Collider2D>)', candidates are:   int OverlapCircle(UnityEngine.Vector2, float, UnityEngine.ContactFilter2D, System.Collections.Generic.List<UnityEngine.Collider2D>) (in class Physics2D)   int OverlapCircle(UnityEngine.Vector2, float, UnityEngine.ContactFilter2D, UnityEngine.Collider2D[]) (in class Physics2D)   UnityEngine.Collider2D OverlapCircle(UnityEngine.Vector2, float, int, float) (in class Physics2D)

mellow sigil
#

ContactFilter2D.NoFilter is a method

#

If you don't want to filter the results then just use OverlapCircleAll

hollow hound
hollow hound
mellow sigil
#

What says? AFAIK OverlapCircleAll is the recommended method

marsh wadi
hollow hound
hollow hound
marsh wadi
#

dont know, but i wouldnt dig too deep, if it works it works, something like new ContactFilter2D().NoFilter()

marsh wadi
#

I created a custom log handler to forward logs from Debug.Log and friends to Unity.Logging, like so:

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void LogFormat(LogType logType, UnityEngine.Object context, string format, params object[] args)
{
    switch(logType)
    {
        case LogType.Log:
            Log.Info(format, args);
            break;
        // .. other log types here
    }
}

// .. somewhere in start
Debug.unityLogger.logHandler = new RedirectLogger();

However I get strange results. The first time after compiling it works for some of them (as in first image). When I then stop play and play again, none of them work anymore (?!) (second image).

I'm sure it has something to do with the object[], but I'm a little confused here... Unity.Logging.Log.Info and friends don't take params, just a regular object[], so I don't really understand its behavior here.

#

Perhaps a code-gen issue... it looks like it creates a function expecting only one argument when the params are forwarded 🤔

ashen yoke
#

do you have assembly reload disabled?

#

forgot InitializeOnLoad?

marsh wadi
#

I suppose that could explain why it only breaks the second time

#

although it's very strange to have only part of the code working, no?

ashen yoke
#

breakpoint in assignment, ensure it does it

marsh wadi
#

I can break in the code, it just works properly the first time I play after compiling for the Info message (but not for the warning message)

ashen yoke
#

ah right

#

im confused why not just use Debug.logger

#

nvm

marsh wadi
#

it's for a dedicated server build

ashen yoke
#

let me check how i did my logger maybe ill get ideas

marsh wadi
#

ha, actually, the first time when it works, I can't break on the Info one, so there's definitely something related to that (I have no idea how it succeeds to replace only half a function though!!)

ashen yoke
#

i dont think agressive inline is the cause, method probably wont be considered for inline

marsh wadi
#

agreed

ashen yoke
#

all symptoms tell me there is something there dangling from previous playsession

#

still trying to access dead objects

marsh wadi
#

yes, this seems to be the case; if I put the breakpoint on the switch statement it doesn't work even the first time after compiling

the interesting part is also that the "previous" playsession has the same code.. I guess it's very likely this bug won't reproduce itself once I quit the editor

#

if it doesn't I'll write a bug report

ashen yoke
#

you are loading assembly over existing?

#

or just modifying cs file?

marsh wadi
#

just modifying the file

ashen yoke
#

you refresh asset db?

marsh wadi
#

anyway the real issue for me is that I can't forward the logs because it just writes me System.Object[] instead of using the array contents.. I'll have to come up with something else I guess

marsh wadi
ashen yoke
#

is there something in log that should look into an array?

#

is format?

marsh wadi
#

it uses code gen to create the proper overloads, so it just takes the object[] as an argument for the first format item

ashen yoke
#

why not interpolated strings?

marsh wadi
#

i suppose I could work around it with a switch statement for the number of items in the array, which makes me cringe, but if it works ^^"

marsh wadi
#

I created this monstrosity, which does the job 😅 😅

switch(logType)
{
    case LogType.Log:
        switch (args.Length)
        {
            case 1: Log.Info(format, args[0].ToString()); break;
            case 2: Log.Info(format, args[0].ToString(), args[1].ToString()); break;
// ... etc
}

it doesn't accept objects either so a manual ToString() was necessary

marsh wadi
ashen yoke
#

barely any

marsh wadi
elfin tree
#

Looking to blend/stitch/adjust the height maps of theses two terrains at runtime.
Currently the two terrains start flat, and then get deformed, and I'm stitching AFTER the deformation. (image of the result below)

I did try a bunch of things but nothing worked out so far, last attempt didn't seem to do much but maybe I'm missing something?

public void StitchToBottom(Terrain terrain, Terrain bottomNeighbor)
    {
        TerrainData data = terrain.terrainData;
        int resolution = data.heightmapResolution;

        // Take the top y-column of neighbors heightmap array
        // resolution pixels wide (all x values), 1 pixel tall (single y value)
        float[,] edgeValues = bottomNeighbor.terrainData.GetHeights(0, resolution - 1, resolution, 1);

        // Stitch with other terrain by setting same heightmap values on the edge
        data.SetHeights(0, 0, edgeValues);
    }

Also tried with SetHeightsDelayLOD but I think that's just a performance thing, shouldn't matter when it comes to it working or not. Maybe the fact the terrainData is duplicated prior affects it?

warm stratus
#

Hey, how to get the width and the height of a rectTransform like this with code? i tried .rect.width but it seems like it s not right

trim schooner
#

.sizeDelta

#

or something like that

trim schooner
#

googling unity rectransform height width in code will get you the answer

leaden ice
#

it also kinda depends which coordinate space you want the answer in

#

.rect will give you canvas space size (which further depends on the canvas render type)

daring cove
#

Hey,

I'm trying to add a Listener to a button that changes the vehicle in the game.
The SpawnVehicleByIndex method is not registering in Unity as shown in the picture.
The user can't click on the button.

Ideas 🤔

// the button is being generated here
Button button = Instantiate(prefab, transform).GetComponent<Button>();
// setting up the button with the listener
button.onClick.RemoveAllListeners();
button.onClick.AddListener(() => { SpawnVehicleByIndex(vehicle.index); });
public void SpawnVehicleByIndex(int index)
{
    GameState.Singleton.selectedVehicleIndex = index;

    MissionAssembler.Singleton.DisableVehicle();
    MissionAssembler.Singleton.UseVehicle(GameState.Singleton.selectedVehicleIndex);
}
leaden ice
#

it's a runtime only listener.

daring cove
#

The image is taken at runtime

#

I'm not quite sure what a persistent listener is

rain minnow
#

When you add a listener using code it does not appear in the inspector . . .

leaden ice
rain minnow
#

Persistent listeners are methods attached to an event (the button) using the inspector . . .

daring cove
#

Okay I see now.

but the method is not invoked by clicking the button

#

is there a way to log all listeners?

leaden ice
daring cove
#

The method has a Debug.Log in it but I removed for display

#
Debug.Log($"SpawnVehicleByIndex '{index}'");
leaden ice
daring cove
#

When the user clicks the button it does not go in to the clicked state.
The user has to hold TAB to see a menu where the button is could this be causing this?

#
// simplified
bool isActive = Input.GetKey(KeyCode.Tab); 

menu.SetActive(isActive);

if (isActive) Cursor.lockState = CursorLockMode.Confined;
else Cursor.lockState = CursorLockMode.Locked;
wild bane
#

When setting a CharacterController transform position directly, then moving it with "Move" at the same frame, the transform position is restored to the one before setting the transform position. Is there a way to fix it?

heady iris
#

If you want to teleport a CharacterController, disable it before you set its position

#

then reenable it

wild bane
#

That is what I'm doing. I just wasn't sure this was the "right" way to do that

leaden ice
#

or perhaps there's another UI element blocking things

wild bane
# heady iris then reenable it

But looks like it is preventing the character from activating some physics triggers. I'm still not sure if that is the reason, tho

heady iris
#

i forget how character controllers interact with colliders in general

#

i.e. if they trigger physics messages, as a rigidbody would

leaden ice
#

they don't

wild bane
heady iris
#

is this in FixedUpdate or Update

wild bane
#

Update

heady iris
#

hm, dunno, would have to look closer

wild bane
#

And yes, if you keep enabling/disabling the CharacterController, it will fail colliding with some physics triggers

#

I've just tested it

heady iris
#

wait, do you mean it won't collide, or that it won't receive physics messages?

wild bane
#

Wont receive OnTriggerEnter/OnTriggerExit

#

In my case, OnTriggerExit

#

Sounds a bit random, but when I don't disable the CharacterController, it doesn't happen at all

daring cove
lapis sierra
#
        {
            // Get the current stage and mission from GameDefinition
            int currentStage = GameDefinition.currentStage;
            int currentMission = GameDefinition.currentMission;

            // Get the currentValues based on the current stage and mission
            currentValues = GameDefinition.stageMissions[currentStage, currentMission];

            // Return the currentValues
            return currentValues;
        }```
I get an error code: CS0120 in the line             currentValues = GameDefinition.stageMissions[currentStage, currentMission];
I have been diggin abit and I cant find any solution can anyone help me out here?
warm stratus
# leaden ice .rect.width should be correct

ok i hope it s correct, i did all of my code with that, i did that

logoParentRectTransform.anchorMin = new Vector2((1-(sizeX / logoParentRectTransform.rect.width)) / 2, 0);
            logoParentRectTransform.anchorMax = new Vector2(1 - ((1-(sizeX / logoParentRectTransform.rect.width)) / 2), 1); ```

but idk why the value on the picture (anchor X) Xmin not = 1 - Xax
#

What?? i did just a variable to simplify my code and it works ?? that s strange but cool

heady iris
#

those formulas are very hard to read

#

one minus one minus uhhh

#

i don't know

#

break them up

warm stratus
warm stratus
#

ok i have this code, but it don t work for the second part

private void Awake()
    {
        RectTransform logoParentRectTransform = logoParent.GetComponent<RectTransform>();

        if (logoParentRectTransform.rect.width / ratio > logoParentRectTransform.rect.height)
        {
            float sizeX = logoParentRectTransform.rect.height * ratio;

            float anchorMinX = (1 - (sizeX / logoParentRectTransform.rect.width)) / 2;
            logoParentRectTransform.anchorMin = new Vector2(anchorMinX, 0);
            logoParentRectTransform.anchorMax = new Vector2(1 - anchorMinX, 1);
        }
        else
        {
            float sizeY = logoParentRectTransform.rect.width / ratio;

            float anchorMinY = (1 - (sizeY / logoParentRectTransform.rect.height)) / 2;
            logoParentRectTransform.anchorMin = new Vector2(0, anchorMinY);
            logoParentRectTransform.anchorMax = new Vector2(1, 1 - anchorMinY);
        }

        logoParentRectTransform.offsetMin = Vector2.zero;
        logoParentRectTransform.offsetMax = Vector2.zero;
    } ```
#

this code should do like preserve aspect on an image but for a RectTransform here

warm stratus
warm stratus
vestal summit
#

yo! How am I supposed to ignore a layer in a Physics.Linecast. I used the layermask on it but it ignored every single layer for some reason

leaden ice
#

but do it properly 😉

#

(show what you tried and explain what you want)

wind palm
vestal summit
#

I don't use java

wind palm
#

That's not Java

#

If you know the ID of the layer you can make that more performant too.

var mask = ~(1 << layerId);
leaden ice
wind palm
vestal summit
#

nah sorry bro I thought that was java for a sec

fervent furnace
#

~ <- this is bitwise not operator....

vestal summit
#

kinda tired rn didn't even look

leaden ice
#

var is not valid Java. or at least it wasn't 10 years ago when I did Java

wind palm
#

Also it would be JavaScript not Java I believe

fervent furnace
#

a more advanced way to ignore some target layers is (-1)^(some layers) and everybody will ask why dont you just use ~

night sparrow
#

does anyone have an easy wat to check collision with circle circumference?

#

i don't care about what's inside the cricle, i want to test if there's any object in it's circumference, like a raycast, but circular

vestal summit
#

I'm trying to prevent the linecast hitting some layers

leaden ice
fervent furnace
#

circularcast

vestal summit
#

instead of preventing the linecast from hitting the assigned layer it ignores everything

leaden ice
#

Give more information if you want help with it

vestal summit
#

ok gimme a sec

night sparrow
leaden ice
leaden ice
wind palm
night sparrow
#

so you're suggesting getting all the colliders and then filtering by distance, that can work

vestal summit
leaden ice
#

a layermask tells you which layers to HIT, not which to IGNORE

#

it can be used to ignore things by excluding them from the mask

wind palm
night sparrow
#

i don't care about the middle

vestal summit
leaden ice
#

so it's hard to help without any details

wind palm
leaden ice
# vestal summit

note that you also have that if statement inside which is checking a tag

vestal summit
#

if that's what you need

leaden ice
vestal summit
#

OH SHIT

#

dude my brain

#

I can't

#

6 hours of sleep ig

night sparrow
leaden ice
night sparrow
leaden ice
# night sparrow yeah

you could do:

  • OverlapCircle then filter by distance
    OR
  • two overlapCircles and take only the objects that are in the larger circle and NOT in the smaller circle
#

e.g. with HashSet.ExcludeWith

night sparrow
night sparrow
leaden ice
#

because they don't really account for the size of the thing

night sparrow
leaden ice
#

if any are within the ring, you're good

wide dock
#

Ok, I've been struggling with this for a while now...
Loading Scriptable Objects with Resources.LoadAll sometimes just works and sometimes not.
It worked for a while and then it stopped, now I'm getting the second Exception more often than it actually works properly. The instance get's called by my AssetPostProcessor to check for any new Scriptable Objects.
Any ideas what might be causing that (and more importantly - how to fix this)?

jaunty needle
#

How do I get a random rotation on this axis?

#
    {
        while(true) 
        {
            Vector2 randomPos = new Vector2(Random.Range(minWidth, maxWidth), Random.Range(minHeight, maxHeight));
            
            Instantiate(beanPrefab, randomPos, Quaternion.identity);
            yield return new WaitForSeconds(spawnDelay);
        }

    }
#

Instead of Quaternion.identity

leaden ice
#

should be faster that way hopefully anyway?

jaunty needle
wide dock
#

Or are you talking about something else entirely

tropic quartz
#

I'm not entirely surei t's what you wanted tho

jaunty needle
#

I want to spawn the beans

#

with a random rotation each time

#

on that axis

night sparrow
wide dock
tropic quartz
# jaunty needle on that axis

Oh. I mean you could just randomize a number and set transform.rotation if they don't need to move.
You can get a reference through newBeanOrWhateverName = Instantiate(...)

leaden ice
night sparrow
jaunty needle
tropic quartz
heady iris
#

you give it an angle and an axis

#

it gives you a rotation around that axis

stoic vault
#

trying to write a limit framerate script to cut down on performance load but so fari its not working help?

heady iris
#

just set Application.targetFramerate

#

that's it

stoic vault
#

where do i type that in?

stoic vault
heady iris
#

well, you need to put it in a method...

#

put it in something that runs at the start of the game

leaden ice
stoic vault
#

thanks i'm super rusty i just had to add code into the script i already had

#

it worked btw lol

rugged storm
#

this script is for passing in my of map data(a Element[,]) getting the groups of elements as lists of dictionaries, and then identifying it's edges but I'm having trouble with the last step, if a shape has a vertical pillar of elements with a thickness of 1 it seems to hang but I cant figure out where as the only while loop has a limit

I think I may fix it on my own after more trouble shooting but another pair of eyes could help(I've already been troubleshooting for like a day)

https://pastebin.com/fLcbFmCi

leaden ice
#

infinite loop right here

#

nothing can possibly change because there is no content to the loop

#

(line 131)

#

oh i'm an idiot didn't notice it's a do/while

#

There's another while loop on line 41 though @rugged storm

rugged storm
#

i dont think this loop would be causing issues as i thoght that part of the script was done but ill check it and place a limiter on it

#

checked it but it still seems to hang when there is a 1 element thick column of elements

leaden ice
#

are you getting the log on line 134?

jaunty needle
#

guys please help fast how do I make two 2D colliders not collide with each other but collide with other stuff

jaunty needle
#

pls I only have 58 minutes

rugged storm
#

like unity just freezes up what it does when a while loop goes on infinity, and i have to force close it,

rugged storm
#

i'm not getting any debug logs

leaden ice
#

the maxIter thing?

jaunty needle
#

i said 2d

#

there is no matrix in 2d

leaden ice
#

there is a matrix in 2d

#

and it works the same exact way

jaunty needle
#

damn

#

yes yes I am

#

thank you

rugged storm
leaden ice
#

I recommend attaching the debugger and pausing while it's frzoen to see where the thread is

rugged storm
#

You can do that???

leaden ice
#

yes

rugged storm
#

alright will try

#

ik about the debugger and use it sometimes but did not know you could just pause it at anytime to find the current thread

cedar solar
#

hi i was trying to make a different background ambience depending on your current location but at some point the "background sound" stops and I'm struggling on making a loop. Can anybody help me pls?

rugged storm
rugged storm
#

how do i know which one is the main one? this is the screen i have rn

leaden ice
#

It will be called Main thread or something along those lines

#

go into the dropdown and look at all the threads

rugged storm
leaden ice
# rugged storm

just look through all the ones that aren't clearly the wrong thread 😉

#

.e. ignore the iothread, reaper, burst threads etc

rugged storm
#

i think i found it,

#

its on like 167 if (nextPoint == startPoint || (pointsOnEdge.Contains(nextPoint) && !resultGroup.Contains(nextPoint)))

#

everytime I unpause and pause its stuck there? waaaait is me modifying I during causing this?

leaden ice
#

i.e. the startPoint is never being reached
nor are edge points

jaunty needle
#

i'm sorry

#

like this

rugged storm
#

It shoudl just drop out and fail if its not reached

#

ahhh i think I never reaches Neighbors.Count + currentIndex; Because i %= Neighbors.Count;

jaunty needle
#

anyone pls

leaden ice
jaunty needle
#

I have like 34 minutes left this is so scuffed

jaunty needle
leaden ice
#

Time.deltaTime

heady iris
#

time for a format string

jaunty needle
#

yes

#

pls

#

i remmeber that

#

but forgot it

heady iris
#
timer.text = $"{timeLeft:N0}";
#

$ enables string interpolation. Anything in {curly braces} gets evaluated and turned into a string

rugged storm
heady iris
#

so it uses a variable named timeLeft

#

after the : comes the format specifier

#

N0 means it's a number with 0 decimal places

jaunty needle
#
    IEnumerator DecreaseTime()
    {
        while(true)
        {
            timeToPlay--;
            yield return new WaitForSeconds(1f);
        }
    }

Nevermind I am doing it this abhorrent way

heady iris
#

I forget if rounds up or down

heady iris
rugged storm
# leaden ice `i %= Neighbors.Count;`

i set a int pointer = i and change and use that now so it no longer hangs, the do while loop fails all the time tho but gets caught so i still def have some code to fix, but now i dont have to force close unity when things break

#

this whole things was just to make the 2d array of my map data into polygon collision but honestly at this point it might of just been faster to make my only phsyics engine that direcly checked map data..

#

@heady iris the other day you said that polygoncollider2ds cant be convex but i dont get why not? it appreats to work fine

#

without the graphics so you can better see the colider

#

now i just need to properly draw the edges instead of just the positions of each block along the edge

heady iris
#

I said that the algorithm you showed -- sorting the points in a clockwise fashion -- would not work for non-convex shapes

rugged storm
#

OOh

heady iris
#

(most random shapes are non-convex)

#

convexity basically means that there aren't any insets

#

i'm not sure if you'd actually call non-convex shapes "concave", actually..

rugged storm
#

and now it does, well it support shoapes without strctures like these, i just noticed thoes two white squares, im not sure whats causing them to appear, maybe related

#

Oh i figured it out thoes should be rendered red it was a glitch with my draw world script, but they actualy should not as only the elements which are on the edge of thier current body should be red and there are no elements in thoes locations

#

(It rendered white becuase i was adding the color read isntead of settings it, on the black elements it was black+red which si red becuase black is 0 but the sky color, cyan+red=white)

#

it seems pointsOnEdge is not being properly set

rugged storm
#

actually nm i was wrong i think part of the issue is that im adding current point twice to currentEdgePoints

full nacelle
#

How can i make Image with fill type Radial360 to start filling at custom angle, e.g. 35°

leaden ice
full nacelle
#

I didn't think about rotating image 👀 Thanks 👍

marble halo
#

So i've got a problem where explosions hit a single enemy multiple times because of the limb hitboxes

heady iris
#

you'll need to filter out duplicates from the same enemy

#

this can be as simple as ignoring a collider if you've already seen one with the same Enemy component on/above it

marble halo
#

I was thinking of having it work like tf2 where the capsule around the character takes explosion damage

heady iris
#

oh yeah, that's a reasonable plan.

potent sleet
#

and not the capsule

heady iris
#

you would want to make a separate layer for the big collider

marble halo
#

but im not sure how i can do this with IDamageable

heady iris
#

do what?

marble halo
#

wait i think i have an idea

deep cobalt
#

Hello, I am overriding the GameObject's transform position(because have a script simulating custom physics for it), but I want to be able to drag the gameobject in the editor, but since the position is overridden by my physics, trying to drag the gameobject with the move tool in the editor doesn't work, the object's position is locked.

Is there a way to get the event or value of the editor's move tool if the user drags and moves it by one of the axes? (so then I can add that to my physics object's position)
Thanks

marble halo
#

Have the enemy bones on a different layer so hitscans can hit them

languid mantle
#

Hello, My name is Daan and i am working on a game that has gardening aspects. I am trying to get the tiles to dynamically update like in Stardew valley, where if you have two tiles with a one tile seperation (that are ready for planting) and you place another between them. They all connect to make a larger bed. However my code isnt working exactly how id like and i dont know why. You can see in the image that they dont always update properly. If youd like more info please just let me know, here is my code in paste of code -https://paste.ofcode.org/RkZmYKBPzkghHY8y5XdNkd

I think that should work. I hope i did this right, im new here so if not please let me know as well.

#

I have been trying all day to fix this and i got it working with just the initial dry tiles. But then i wanted to update it so that the dry, tilled, and wet tiles all update and you can have dry tiles attached to wet tiles etc. But now if i place a dry tile next to another dry tile they both update without either being clicked and turn into tilled tiles. I am very confused

leaden ice
# languid mantle Hello, My name is Daan and i am working on a game that has gardening aspects. I ...

Delete all of your code and use Rule Tiles
https://learn.unity.com/tutorial/using-rule-tiles

Unity Learn

Rule Tiles are scriptable tiles written in C#, which are smart enough to use the appropriate adjacent tiles, and handle tile animation, boundaries, and collisions on the fly. In this tutorial, you will set rules on a tile and experiment with the properties and settings of a Rule Tile.

languid mantle
#

😂 No way, I cant believe ive spent two days on this and there is already a system in place. Well thats helpful, thank you. I will give it a shot :)

#

I came from working in C and making games from bare scratch so thats probably why that carried over. Thank you again!

heady iris
#

ha :p

#

If you know what you're doing in general, but don't know much about unity, I'd suggest skimming the !learn material

tawny elkBOT
#

🧑‍🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

heady iris
#

just to learn what's out there

neat python
heady iris
#

well, also use unity learn

#

but follow throughly from the beginning

neat python
#

So I should use unity learn? Got it

leaden ice
#

Unity only inlcudes the assemblies included in the chosen .NET profile

#

sure, just find a dll and drop it in

plain hare
#

Anyone here using Rider ?

heady iris
#

ask your question.

plain hare
#

Is there any point in starting Unity via Rider Debug Mode ?
(i'm used to doing this with Unreal Engine 😄 )

plain hare
#

So assuming Rider is connected per say to the Unity editor, when Unity crashes i should have a proper report on what's what and what caused the crash without starting the Editor via Rider ?

leaden ice
plain hare
#

hmmmming oh

leaden ice
plain hare
#

cheers, i thought it would be similar to UE

leaden ice
#

Very little will be similar to UE

plain hare
leaden ice
#

In Unity if your C# code "crashes" it's usually going to cause little more than an exception to printed to the console

#

it will not generally crash the editor

#

if the editor crashes that's usually due to a bug in the editor itself, and you can certainly submit those crash reports to Unity

plain hare
#

monkaHmm true, thanks for your insight

civic folio
#

What is { get; private set; } used for?

leaden ice
frosty pawn
#

how would you name t in such functions like Lerp where t is inside [0, 1] but when I can't name it like that because it is more like a progress

frosty pawn
#

so progress it is 🙂

civic folio
leaden ice
#

also this way allows you to have a public getter but private setter, for example

heady iris
#

public fields mean that you can't trust that a field won't just...change

somber nacelle
#

using an auto property instead of a field will also allow you to refactor later to add validation code or something without having to change other objects

hard viper
#

well the whole point of making a variable public is because you do want it to be exposed and change externally

potent sleet
#

directly changing value externally 👎

leaden solstice
#

Point is separating interface and internal data layout 😄

hard viper
#

i like directly changing values. I have always hated defining a whole extra method just to change something. It might as well be public at that point lol

#

the benefit being being able to search for changes, ig

leaden solstice
#

What if you want to change it's functionality, it is easier when you already have it as property

#

Otherwise you gotta update all the usages

hard viper
#

you mean change what the property means?

#

or change what happens when you update that property?

ashen yoke
#

in case of a field you cant separate those

potent sleet
leaden solstice
ashen yoke
#

hating properties is a weird thing in c#, i would understand hours long arguments over this in other languages but in c# its deeply ingrained

#

so much that people expect that if something is a property it is intended for public access, and rarely you see public fields, in statics for example

light rock
#

heres what i do: i have a public field -- when it comes time for me to add validation, i just turn that field into a property. just faster to code that way

wide terrace
leaden solstice
#

Yeah C# property is much convenient compare to Java etc

ashen yoke
#

sure you can have a public field and then later encapsulate it with a property, but at that point that field was already read/write and a whole codebase grew around it with assumption that it will always be read/write

leaden solstice
ashen yoke
#

so to avoid all of that confusion it is simpler to make it a property from the start, and read only if its intended to be readonly

potent sleet
ashen yoke
#

in my code if anything is accessible from outside in the main codebase and not utility tooling, its a property

hard viper
#

I think the answer is to have good foresight over what you will need.

ashen yoke
#

clairvoyance you mean

hard viper
#

writing a method just to read and to write for every single public field you put into a class is lunacy

light rock
light rock
#

i agree with snoop

#

also i feel like this discussion is getting out of hand at this point. no?

hard viper
#

it’s just unnecessary. If you know that updating a field might lead to some additional baggage in future, then you should probably dress it up for future.
But not every field needs that

light rock
#

properties in c#

ashen yoke
leaden solstice
tropic quartz
#

I think only learned about properties after I took codecademy courses on my freetime, I rarely see them mentioned in context of Unity.
But I'd imagine that they make any kind of big project (especially with multiple programmers) far less nightmarish, since you know nobody can write to that thing that should only ever be read etc.

Reduce the risk for errors and don't usually take that much time to set up either.

I should probably use them more often.

pure dragon
#

whats the best way to make a state machine where the states can be easily changed?

potent sleet
#

not best, just easiest

pure dragon
#

public Dictionary<string,ICommand> moveCommands => new(){ {"run" , new RunCommand()}, {"walk" , new WalkCommand()}, {"jump" , new JumpCommand()}, {"teleport" , new TPCommand()}, };
this is what i have so far, its going to be compositional and the states call these commands via the dictionary. There must be another way to do this other than using strings though, right?

ashen yoke
#

strings are fine, enum is fine

#

in case of strings wrap them in static class

#
static class MoveCommand
{
    public const string Run = "run";
    public const string Walk = "walk";
}

fsm.SetState(MoveCommand.Run)
#

functionally identical to enum, almost

#

with strings you can add insert runtime generated states if needed

steel elk
#

If you want to give a named value to something for ease of use use enum, if you want to display the value to the user use string, don't use strings for internal values which aren't displayed

ashen yoke
#

or editor created states

#

since you dont rely on hardcoded values

#

but for it to work you would also need to have transitions

pure dragon
leaden solstice
#

Child.. enums? 🤔

pure dragon
#

and you also i dont think can use polymorphism for enums

orchid grove
#

is there an easy way to make movement not fps dependent?

pure dragon
leaden solstice
orchid grove
#

alright

#

im not a programmer myself, but a friend i know is and hes struggling with it a lot but refuses to ask for help anywhere

rugged storm
#
    private static void DiscoverAndAddElements()
    {
        // Get all types in the assembly that inherit from Element
        Type elementType = typeof(Element);
        Assembly assembly = Assembly.GetAssembly(elementType);
        Type[] elementTypes = assembly.GetTypes()
            .Where(t => t != elementType && elementType.IsAssignableFrom(t))
            .ToArray();

        // Create instances of each element type and add them to the dictionary
        foreach (Type type in elementTypes)
        {
            if (Activator.CreateInstance(type) is Element element)
            {
                elementTypeDictionary.Add(element.ElementID, type);
                //elementDictionary.Add(element.ElementID, element);
            }
        }
    }```
i have this script, in the final if statement how could I sort out specific things that inherit from a seperate class that also inherits from element?
#

like say i dont want to add any thing that inherits from the "Seeds" Class and the but the seeds class it's self inherits from Element

#

also ingeneral is this a good way to go about getting everything that inherits from a specific class and putting it into a list without hardcodeing them into a list?

winged mortar
#

Make the seeds class abstract and check whether the type is abstract or not

ashen yoke
#

IsSubclassOf

ashen yoke
hollow hound
#

Is there a way to use Random.Range(float, float) with exclusive max/min? Or is there some analogue?

winged mortar
ashen yoke
ashen yoke
#

float.epsilon? some other value?

hollow hound
ashen yoke
#

so if max is 0.88213991 it should not include it, but 0.88213990 is ok

hollow hound
#

if max is 1f, I don't want to get 1f.

ashen yoke
#

but 0.9999999 is ok

hollow hound
#

Yes

#

Well, I'll use NextDouble()

ashen yoke
#

i really dont know, i dont even know how to clamp it

#

since what do you clamp it between

#

1f - float.Epsilon equals 1, so you would need to if it with direct comparison, and then clamp it at some arbitrary lower value

#

i may not understand something but this seems like undefined territory riddled with float precision issues and weird arbitrary constants

steel elk
lean marlin
#

I am planning a livestreaming screen sharing environment. Is it possible to integrate zoom for the screen sharing on the screens that will be in the building? If not...what are the options to get screensharing into the environment. Any help is appreciated.

leaden ice
hollow hound
ashen yoke
#

lets look at how they did it

leaden ice
ashen yoke
#

that is also .net 7

#

nvm they are identical

steel elk
#

Would clamping between 0f and 1f - Mathf.Epsilon not work

ashen yoke
#

no

leaden ice
#

1 - Epsilon will not work

leaden ice
ashen yoke
#

ok so what they do is they store internally the values as ints

hollow hound
ashen yoke
#

and the internal max int is ensured lower than the max bound

leaden ice
#

when you say 1 - epsilon what you actually want is float.BitDecrement(1f)

ashen yoke
#

then they InternalSample()*(1.0/MBIG)

#

to convert to double

hollow hound
ashen yoke
#

so yeah having it as int bypasses all clamping problems just by the nature of it

ashen yoke
#

not in standard either

rugged storm
ashen yoke
#

all calling reflection api and retreiving same data

#

anyway doesnt matter not an issue at this point

#

i think ive seen unity providing a central reflection data class somewhere in changelogs

steel elk
worn holly
#

How can i make it so that, in a swipe-detector code the swipe isn't only registered when the touch ends? Like to detect the swipe without taking your finger off the screen?

ashen yoke
#

you can track position delta, have some thresholds for velocity difference between current and previous, test for magnitude and direction

#

also a timer

hollow hound
#

Is it posiible to create generic type based on the class type?
I want method in parent class that return object of the parent class and overridden method in child class that returns object of the child class.

ashen yoke
#

you can construct generic types and use them in activator

#
Type t = typeof(List<>).MakeGenericType(typeof(int));
hollow hound
#

I want something like this:

   public record Base
    {
        public float FloatField;
        
        public virtual T Foo<T>() where T : Base
        {
            return this with { FloatField = 0 };
        }
    }

   public record Child:Base
    {
        public string StringField;
        
        public override T Foo<T>() where T : Child:Base
        {
            return base.Foo() with {StringField = ""}
        }
    }
ashen yoke
#

return base.Foo<T>()

#

where T : Child

#

should work

#

i just dont understand whats the point

#

it already inherits Base and has access to its members, why does it have to be generic?

#

and it wont work

hollow hound
#

I want it to return Child in Child class

ashen yoke
#

you cant override and change signature

heady iris
#

are you trying to make the return type more specific?

#

i'm not sure if that'll work here

#

covariant return types let you make a derived type's overriding method return a more specific type than the parent type's virtual method

hollow hound
#

Looks like what I need. Thanks, I'll check it

heady iris
#

and I believe unity is on C#9.0 right now

hollow hound
#

Getting "Target runtime doesn't support covariant return types in overrides." 😢

heady iris
#

what's your api compatibility level in the player settings?

#

might change if you target .NET Framework instead of .NET Standard

hollow hound
#

Where should I change it?

heady iris
#

project settings -> player

hollow hound
neat lagoon
#

It's not ideal, but you could do something like this instead, assuming you don't want to bypass the safeguards.

public record BaseRecord {
    public float floatField;

    public BaseRecord Foo() {
        return this with { floatField = 0f };
    }
}

public record ChildRecord : BaseRecord {
    public string stringField;

    public new ChildRecord Foo() {
        return (ChildRecord)base.Foo() with { stringField = "" };
    }
}
crimson atlas
#

why is not allowing me to override (to save) this reference to this debug TMP field?

soft mica
#

Is there a built in method somewhere which would allow me to find the SkinnedMeshRenderer component on an avatar from one of its children, even if the root of the avatar is itself a child of another object?

I know transform.root exists, but that won't work if the root of the avatar is a child of another object.

And I know I I could traverse up the hierarchy to find the first parent that contains an animator and then search for the component in the children of that, though that would probably traverse the armature first which would be a lot of work for nothing. I guess I could look at only those children that are direct descendants of the avatar root to figure out which one has the component.

But I'm kinda hoping and thinking that Unity has a method already built into it for this specific case.

Specifically what I am trying to do here is I am trying to allow a component on a child to access one of the avatar's blendshapes. Hence the need to find the skinnedmeshrenderer component.

And I don't want to just have a field that I have to fill in in the inspector because that would require me to fill that in for every avatar I create, which is just extra work for nothing and another potential bug in the long run.

heady iris
#

there can be many skinned mesh renderers

ashen yoke
#
EditorApplication.delayCall += () => { SceneView.FrameLastActiveSceneView(); SceneView.FrameLastActiveSceneView(); };
steel elk
ashen yoke
#

.net standard is just as old

heady iris
#

oh, do i have them backwards

#

i struggle to keep those things straight

ashen yoke
#

its the same thing but standard is more limited due to cross platform

heady iris
#

.net this, .net that

#

To minimize the garbage collector overhead, avoid methods such as Assembly.GetTypes and Type.GetMethods() in your application, which create a lot of C# reflection objects at runtime. Instead, you should scan assemblies in the Editor for the required data and serialize and/or codegen it for use at runtime.

#

😬

ashen yoke
#

c++ style reflection when

heady iris
#

does c++ actually have it now

ashen yoke
#

always did with libraries

heady iris
#

ah, right

ashen yoke
#

you just scan code construct reflection data as code at compile, access it at runtime

kind niche
#

just wondering, is it possible to have markers and clips on the same timeline trackasset?
figured it out nvm 🙂

steel elk
wild drift
#

What's the modern/correct way to rotate an empty along 1 local axis, i.e. the equivelant of edit only X, Y or Z euler value directly?

heady iris
#

transform.Rotate is an option

wild drift
#

I cant get it to do a local rotation

ashen yoke
#

it has an override

#

public void Rotate(Vector3 eulers, Space relativeTo = Space.Self);

wild drift
light rock
leaden ice
#

doing Space.Self is the default

outer juniper
#

I want to make custom navigation movement depended on navmeshagent. Like I want to keep doing best use of navmeshagent's pathfinding and local avoidance. What to do in that case?

outer juniper
#

also determinism is another thing to worry about

rigid island
#

make your own a* pathing?

wind palm
# outer juniper I want to make custom navigation movement depended on navmeshagent. Like I want ...

I've recently done this for vehicles as NavMeshAgents are worthless due to the turning behaviour, and it's nothing less than a pain.

If you use this as a resource:
https://github.com/Unity-Technologies/UniteAustinTechnicalPresentation/blob/master/StressTesting/Assets/Scripts/Utils/PathUtils.cs

What you have to do isn't pretty either. Due to the current unreliability I have required to temporarily result to try/finally statements which I will eventually weed out.

using var result = new NativeArray<PolygonId>(maxPathLength, Allocator.Persistent);
using var query = new NavMeshQuery(NavMeshWorld.GetDefaultWorld(), Allocator.Persistent, maxPathLength);
        
var from = query.MapLocation(start, Vector3.one * 10, agentId);
var to = query.MapLocation(end, Vector3.one * 10, agentId);
var status = query.BeginFindPath(from, to, areas);
int maxIterations = 1024;
...

var pathResult = query.GetPathResult(result);
var straightPath = new NativeArray<NavMeshLocation>(pathLength, Allocator.Temp);
var straightPathFlags = new NativeArray<StraightPathFlags>(pathLength, Allocator.Temp);
var vertexSide = new NativeArray<float>(pathLength, Allocator.Temp);

try
{
    int straightPathCount = 0;
    var pathStatus = PathUtils.FindStraightPath(query, start, end, result, pathLength, ref straightPath, ref straightPathFlags, ref vertexSide, ref straightPathCount, maxPathLength);
    if (pathStatus == PathQueryStatus.Success)
    {
        path = new Vector3[straightPathCount];
        for (int i = 0; i < straightPathCount; i++)
        {
            path[i] = straightPath[i].position;
        }
        return true;
    }
    path = default;
    Debug.Log($"Nav query failed with the status: {status}");
    return false;
}
finally
{
    straightPath.Dispose();
    straightPathFlags.Dispose();
    vertexSide.Dispose();
}
GitHub

Contribute to Unity-Technologies/UniteAustinTechnicalPresentation development by creating an account on GitHub.

outer juniper
#

Looks like DOTS

#

if only there was more guides and proper Hybrid approach

#

I have a game where around 5000 units will be common

#

but dont know how to keep it at 60 FPS at as much as low-end devices possible

wind palm
outer juniper
#

yeah that too. I can hardly reach 2000 with all crazy optimizations possible

#

like turned off animator

#

at far distance

leaden ice
#

especially on mobile

outer juniper
leaden ice
#

RAM is not going to be the limiting factor

#

CPU is

#

and probably GPU too

wind palm
leaden ice
#

8GB+ is plenty of memory for 5000 objects

#

it's not a problem of memory

wind palm
#

Which they do not

leaden ice
#

no but many do

outer juniper
#

isnt 2-4 GB common for mobile? Even less on older mobiles?

rigid island
outer juniper
#

rare to see 4GB

outer juniper
leaden ice
#

anyway it doesn't matter

#

DOTs is not going to use significantly more memory

#

it is going to make significantly more efficient use of both your CPU and your memory though

wind palm
#

The first midrange phone I just checked out had 6GB, being a Samsung.

#

Samsung's £250 phone has 4GB however.

rigid island
outer juniper
#

3 GB my phone

leaden ice
#

ok I really don't see why we're discussing phone memory, it's not really relevant

rigid island
#

Profiler tools will be your best friend

wind palm
outer juniper
#

Anyway I couldn't get working with DOTS too much. Really feels soooooo complex

leaden ice
#

yes it has a learning curve

outer juniper
#

want to do Hybrid approach but all tutorials and guides outdated

#

even few new ones got deprecated stuffs which were months ago

wind palm
#

If you learn in a side project, you can learn how to implement a hybrid approach

outer juniper
#

i want to do slow transition to DOTS

#

hold on lemme show a script

wind palm
#

Anyhow, I provided a hint in the direction you want for a custom navigation on a navmesh; linking someone's work who works for Unity.

outer juniper
#
public void InitializeUnit()
    {
        id = idCounter++;

        string gameObjectName = gameObject.name; // Register stuffs

        string[] gameObjectNameParts = gameObjectName.Split();
        if (gameObjectNameParts.Length != 0)
        {
            gameObject.name = gameObjectNameParts[0];
        }

        gameObject.name += " " + id;
        units.Add(id, this);

        // from here I want to reference to a entity somehow be it be through Entities.Add() or Get an Entity from pooling
        // after that call OnSpawnEvent

        OnSpawnedEvent?.Invoke(this);
    }
wind palm
outer juniper
#
private void OnDestroy()
    {
        units.Remove(id);
        // later remove reference from 
        Destroy(gameObject);
    }
wind palm
#

You'd probably have better luck using Regex

outer juniper
#

I want easy access between Entities and MonoBehavior. Like I want to call old MonoBehavior stuffs from Entities and vice versa

wind palm
#

PraetorBlue would probably be better here to help you if they're around, in this regard.

outer juniper
#

@leaden ice clue?

leaden ice
#

is there a question here?

outer juniper