#archived-code-general

1 messages ยท Page 416 of 1

heady iris
#

indeed

#

It's totally fine to do that. You shouldn't be afraid of string names

latent latch
#

always afraid of string names

heady iris
#

especially if you include a little validation code

#

making sure that nothing shares a name, for example

molten sapphire
#

Hense the named enum approach. It will throw a compile error if I have collisions

steady bobcat
#

for a game I worked on we have lots of configuration for items with addresses and we validate them all at bake time

heady iris
#

One thing I don't like about using an enum is that changing the content in your game requires a code change

latent latch
#

I like string names if I'd some additional layer of identity instead of just assuming there's not another similar string in the whole project

heady iris
#

But it does provide some useful properties (like preventing repeated names)

wicked scroll
heady iris
#

a type that only accepts a fixed set of strings?

wicked scroll
#

e.g. in php you can have enums where the backing value is a string you define

plucky inlet
#

Why not just plan out your enums upfront. so you give more range in integers to add or remove more and dont just increment by 1

molten sapphire
wicked scroll
#

or yeah, in typescript you could use a union string type

molten sapphire
wicked scroll
molten sapphire
#

It's for a mini mobile game that I wrote back in college (Unity 2019). I'm currently working on porting it into Unity 6

heady iris
#

The asset is where the "soul" of the level lives

#

I can change the name, description, scene, etc.

#

but I never throw out the asset

latent latch
#

I still think for this scenario they'd probably be better off with some ID generation if they are trying to reconstruct this level

plucky inlet
#

are we still on the enum discussion? ๐Ÿ˜„

molten sapphire
#

I think so?

late lion
past elk
#

void OnAwake maybe?

molten sapphire
#

No the enum is fine, I just wanted the serializer to serialize it into a string matching the name of the enum value rather than using the ordinal

steady bobcat
#

just use the current unix time ms as a unique id! /s

late lion
molten sapphire
#

So TileType.Brush would become "Brush"

plucky inlet
fiery path
#

can u expose a nested array in the editor??

molten sapphire
latent latch
#

but arrays serializable by default inside of a mono if allowed public access, or by using [SerializeField]

wicked scroll
#

newtonsoft allows you to hook in easily and do that at serialization time, but there's no reason you can't roll your own

latent latch
#

Or, just plan out the project before hand so you don't need to change enums at all because you shouldnt

plucky inlet
#

As already mentioned, there is no good reason to use the builtin one and try to bend it to do what you want, unless you do realtime serialisation all the time or what not.

wicked scroll
plucky inlet
#

not to joy ๐Ÿ˜„

earnest gazelle
#
private void Start()
        {
            _sceneChangingHandler.SceneChanging += OnSceneChanging;
        }

        private void OnSceneChanging(SceneManager _, string oldSceneName, string sceneName)
        {
            _tools[Current].Exit();
            RaiseExitedEvent(Current);
        }

        protected virtual void DoUpdate()
        {
        }

        private void Update()
        {
            _tools[Current].Update();
            DoUpdate();
        }

        private void OnDestroy()
        {
            if (_sceneChangingHandler != null)
            {
                _sceneChangingHandler.SceneChanging -= OnSceneChanging;
            }

            var tools = _tools.Values;
            foreach (var tool in tools)
            {
                tool.Dispose();
            }
        }

In my ToolController, it works perfectly
I don't need to implement Dispose for my tools but I call it anyway, maybe some tools want to do something in this phase
thanks

latent latch
#

Let future devs handle the problems ;p

molten sapphire
tawny elkBOT
wheat cargo
#

Anyone know of a way to draw debug rays in screen space coordinates?

#

As in I'm debugging Screen Space - Overlay canvas, so I don't have a camera, but I want to draw debug rays in screen space essentially

steady bobcat
#

the scene view does have a camera you can access so maybe world to screen screen to world on that will do it

latent latch
#

One way about is using graphic raycasters and covering the screenspace with a Image UI component

wheat cargo
#

Okay thanks, I'll try these

latent latch
#

not too sure why Unity UI doesn't just have a overlay collider component

#

I mean, you can also just get mouse position as that is effectively screen space coordinates so I'm not really following with what you're asking

steady bobcat
#

sorry what are you reffering to?

wheat cargo
plucky inlet
wheat cargo
plucky inlet
#

or kind of picture in picture as a remote screen

#

Got it. Sounds like a good math task ๐Ÿ˜‰ But essentially you are just remapping your screen size - the position and size of the box to a new "normalized" position.

wheat cargo
plucky inlet
#

how about a simple debug rect?

wheat cargo
plucky inlet
#

oh wait, you are using UI Toolkit, not the good ol canvas UI,right

wheat cargo
#

Like in the log? yeah I could, but visually is a little easier to understand. I'm technically using both.

#

Or you mean create a dummmy rect transform?

plucky inlet
#

exactly, just a placeholder showing you the position of your mouse or maybe the calculated screenremap you are getting

plucky inlet
wheat cargo
plucky inlet
wheat cargo
#

Screen space is y up, but I think UGUI and UI Toolkit both use y down

plucky inlet
#

you mean, where the 0,0 origin is?

wheat cargo
#

Yeah screen is bottom left, UI stuff is top left

plucky inlet
steady bobcat
#

ugui is the same, if overlay then world pos is screen pos

wheat cargo
#

well doesn't ugui depend on the anchors?

plucky inlet
#

It does in case of position. but Y increase is always up

steady bobcat
#

anchored position is different yes, but .position is not this

#

so rectTransform.position = camera.WorldToScreenPoint() or something is valid

wheat cargo
#

Okay then UI toolkit is y down increase, with origin at top left

#

Thanks!

plucky inlet
#

Well I guess you have to work with bottom and left then to get the correct position from UGUI anchored position to UI toolkit visualelement style position using position: absolute

wheat cargo
twilit citrus
#

I'm having a problem with the Unity Physics package in Unity 6. When I install it I start getting the following error and I'm not sure how to resolve it.

1>Microsoft.Common.CurrentVersion.targets(2413,5): Warning MSB3277 : Found conflicts between different versions of "System.Numerics.Vectors" that could not be resolved.
There was a conflict between "System.Numerics.Vectors, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" and "System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".
    "System.Numerics.Vectors, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" was chosen because it was primary and "System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" was not.
    References which depend on "System.Numerics.Vectors, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" [C:\Program Files\Unity\Hub\Editor\6000.0.35f1\Editor\Data\UnityReferenceAssemblies\unity-4.8-api\System.Numerics.Vectors.dll].
        C:\Program Files\Unity\Hub\Editor\6000.0.35f1\Editor\Data\UnityReferenceAssemblies\unity-4.8-api\System.Numerics.Vectors.dll
          Project file item includes which caused reference "C:\Program Files\Unity\Hub\Editor\6000.0.35f1\Editor\Data\UnityReferenceAssemblies\unity-4.8-api\System.Numerics.Vectors.dll".
            System.Numerics.Vectors
    References which depend on or have been unified to "System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" [C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\PublicAssemblies\System.Numerics.Vectors.dll].
        C:\Program Files\Unity\Hub\Editor\6000.0.35f1\Editor\Data\UnityReferenceAssemblies\unity-4.8-api\Facades\netstandard.dll
          Project file item includes which caused reference "C:\Program Files\Unity\Hub\Editor\6000.0.35f1\Editor\Data\UnityReferenceAssemblies\unity-4.8-api\Facades\netstandard.dll".
            netstandard
            F:\Unity\TruckKun\Temp\Bin\Debug\Assembly-CSharp\Assembly-CSharp.dll
wheat cargo
#

I got it working, I essentially needed to flip the y by subtracting from the screen height and then use this method to convert the coordinates to panel space, the targetRect is the rect in screen space (y flipped) of the raw image (render texture)

public static Vector2 ConvertPositionToTargetRect(Vector2 sourcePosition, Rect targetRect)
{
    return sourcePosition - targetRect.position;
}
#

It doesn't work properly if the Canvas scalar resolution doesn't match the display resolution, so that's the next problem to solve

wheat cargo
#

Essentially search both in packages and assets folder for that dll

twilit citrus
#

It only shows up after I install the Unity Physics package

wheat cargo
winged tiger
#

Hi,

Why this sin slows down as the times 2 doesn't exist when Stamina reaches 0?
Stamina ranges from 0 to 1

float breathSoundFunction = Mathf.Sin(Time.realtimeSinceStartup * (2f + (2f * (1f - Stamina))));

Is this something to do with floating point wizardry?

wheat cargo
winged tiger
#

So Time.realtimeSinceStartup should be multiplied by 4

dense pasture
#

game runs fine in preview play mode, build/run is just crashing within a couple seconds of starting and there appears to be no logs

wheat cargo
winged tiger
wheat cargo
vestal arch
dense pasture
#

windows. all i found was player.log and theres nothing in there

dense pasture
#

oh wait that isnt even for this project

wheat cargo
dense pasture
vestal arch
# winged tiger Yes.

so what should the parameters be?
what's the max & min frequency, and how are they interpolated (linearly? or something else?)

winged tiger
#

linearly

wheat cargo
vestal arch
dense pasture
wheat cargo
winged tiger
dense pasture
#

Build completed with a result of failed again

wheat cargo
twilit citrus
dense pasture
#

there is nothing saying anything anywhere

#

console is empty

#

lemme try something

vestal arch
wheat cargo
winged tiger
#

as the code says

vestal arch
#

so what's the issue?

winged tiger
#

When stamina reaches 0 (code by logic evauluates to 2*2) Time.realtimeSinceStartup gets multiplied by 2

twilit citrus
dense pasture
#
Assets\_Game\Scripts\Util\ShowWhenAttributePropertyDrawer.cs(9,3): error CS0246: The type or namespace name 'CustomPropertyDrawerAttribute' could not be found (are you missing a using directive or an assembly reference?)
Assets\_Game\Scripts\Util\ShowWhenAttributePropertyDrawer.cs(9,3): error CS0246: The type or namespace name 'CustomPropertyDrawer' could not be found (are you missing a using directive or an assembly reference?)
Assets\_Game\Scripts\Util\ShowWhenAttributePropertyDrawer.cs(12,45): error CS0246: The type or namespace name 'SerializedProperty' could not be found (are you missing a using directive or an assembly reference?)
Assets\_Game\Scripts\Util\ShowWhenAttributePropertyDrawer.cs(23,43): error CS0246: The type or namespace name 'SerializedProperty' could not be found (are you missing a using directive or an assembly reference?)
Assets\_Game\Scripts\Util\ShowWhenAttributePropertyDrawer.cs(38,59): error CS0246: The type or namespace name 'SerializedProperty' could not be found (are you missing a using directive or an assembly reference?)
[ScriptCompilation] Requested script compilation because: Recompiling scripts for editor because player build failed.
vestal arch
dense pasture
#

i'm not getting any errors building that code

winged tiger
wheat cargo
naive swallow
dense pasture
#

aha

vestal arch
#

have you tried actually checking the relevant values?

dense pasture
#

there a way to exclude from build?

#

ah wait

wheat cargo
dense pasture
#

think i got it nvm

naive swallow
wheat cargo
#

or wrap in

#if UNITY_EDITOR
// editor code
#endif
dense pasture
#

yep thats the thread i found

vestal arch
#

@winged tiger have you tried Debug.Log($"{Time.realtimeSinceStartup}, {Time.realtimeSinceStartup * 2}, {<thing inside the Sin>}")

dense pasture
#

with the folder approach does it just have to be at the top level? or it skips any editor folders?

wheat cargo
#

can be anywhere

#

and there can be multiple

#

its a special name

naive swallow
dense pasture
#

thanks all โค๏ธ

#

its the Editor log btw

loud marsh
#

Can anyone help me with this? I get this error when building for Android. I already have Android SDK and accepted all of the licenses. It's so specific to 30.0.3 which I also downloaded as well.

vestal arch
latent latch
#

I'll probably be testing out in a bit but seeing if anyone has any experience grabbing the blend time quickly

tired shore
#

Is there a recommended way to remember and auto-select previously seelcted buttons in gui when navigating menus wth a gamepad? For example from main menu click on settings, and then when closing settings to return to main menu, the settings button should be selected instead of it jumping back to default of play game.

#

It can start getting messy when you deal with multiple panels and popups.

#

My current method is to have a script for each panel that has the default selected as a priority stack (because sometimes the default for a panel can change like main menu default being "Continue Game" if you already have a save, but "New Game" if you haven't played before) and then also a list of which buttons it should "track", and then whenever the panel is disabled, it remembers which was the last selected, and then when the panel regains focus it selects the last selected if there is one, or looks at the default stack. Is this a common solution? Am I overthinking the problem or missing some built in Unity functionality that handles this situation?

latent latch
#

Should just cache the values in some list of structs if the question here is you want to remember the history of all last Focus'd buttons

#

or for every multi-select panel make a script that incorporates a list of buttons and have a property "LastFocusButton"

winged tiger
winged tiger
winged tiger
# winged tiger

it's clearly visible that the frequency plummets at 0 stamina, when it should be the highest

#

oh my, it looks like that, because the phase increases as the multiplier grows!

radiant scaffold
#

Hey gang! I'm running into an issue with the TextMeshPro Font Asset Creator where once I generate the font I get all the letters EXCEPT N and T despite the letters being in the generated atlas, any ideas?

#

The text that I'm typing out vs the atlas

#

found it out, it was an issue with bolding I guess ๐Ÿ˜‚

flat zodiac
radiant scaffold
#

This is definitely not the best way to handle a grounded state, we usually use rays for that because all it takes is your collider to slightly leave the other to trigger an exit. Use a raycast that goes a bit down from the feet so you won't get false flags

naive swallow
#

Regardless of whether you are still touching a different object also tagged floor

naive swallow
#

Try logging other.name inside the exit function

#

see which object you're stopping colliding with

jaunty sundial
#

@leaden solstice yes there in same script but exist separately from the other classes so it should be fine no

naive swallow
leaden solstice
flat zodiac
#

Those green planes where tagged floor

naive swallow
flat zodiac
#

ok

naive swallow
#

So the code's doing exactly what you told it to

#

It's calling that function when you stop colliding with something named Floor

sharp sable
#

private async UniTaskVoid Start()
is this the right approach for replacing async void unity events when using UniTask ?

snow umbra
#

what are the benefits of state machines, especially for a platformer game with many monsters

latent latch
#

Less comparisons for the most part, and helps prevent odd cases you could run into otherwise, ex. being able to crouch and swim

#

However, similar to abstracting logic with classes, you may find yourself rewriting similar code for different states because you've converged the states too much

dense cloud
#

I'm reading through the doc for the new input system but the first thing that was introduced was this

#

this looks similar to the old input manager of getkeydown, getkey etc

#

i'm guessing this isn't the right way to use the input system?

#

I'm still quite in a blur with the newer system, but I figured since I'm just prototyping, implementing the input system seems overkill for the time being

latent latch
#

There are methods with the input system that allows you to just poll the input too if you prefer

#

Usually you have to poll the mouse movement too regardless... not sure about gamepads though

#

otherwise you can make any button into some callback/event

dense cloud
#

what does polling input mean?

latent latch
#

if(A key is pressed)

dense cloud
#

does it mean just accepting input without setting up action map?

#

ah

#

gotcha thanks man

#

I only have a superficial idea on how the input system works, but it's not my current focus now. I'll learn it later

latent latch
#

I tend to ignore it for smaller projects and that I'm too used to just doing it the old fashion way

#

but if you wanted your code to look nice and organized you'd use it. Also helps to quickly swap out keybinds

dense cloud
#

I did hear a lot of benefits from talking to people here about the new input system, and it's a direct improvement from the old one

#

but yeah I think I'll just stick to the old method for smaller scale/prototypes for the time being

#

thanks again ๐Ÿ‘

quartz folio
dense cloud
#

thanks for the heads up

unique delta
#

Can you break a coroutine from another function?

potent island
#

In the coroutine check if its false

#

If it isnt then break the coroutine

thick terrace
#

you can call StopCoroutine from anywhere you like

potent island
chilly surge
#

Be mindful that StopCoroutine is not cooperative, so the coroutine being stopped might not have any chance of doing clean up if it needs to.

#

What @potent island described is how cooperative cancelling works, the only issue is that Unity's coroutines don't support them natively so you have to reinvent them yourself.

#

If you use UniTask, you would get to do cooperative cancellation like rest of the .NET world.

thick terrace
#

or Awaitable or a regular C# task, you don't need a library for that

chilly surge
#

I haven't looked into Awaitable but I heard the cancellation is a mess. You can use regular C# tasks, but you need to reinvent all the stuffs that coroutine has, which is part of what UniTask gives you.

thick terrace
#

Awaitable provides most of the same stuff as UniTask, and you can freely mix and match with regular tasks

#

you can use a regular cancellation token with Awaitables

#

nothing wrong with UniTask but it's not true to say that you need an extra library to get cancellable tasks when Unity does nearly all of that out of the box these days

chilly surge
#

Well that (you need a library to do cooperative cancellation) wasn't what I meant but sure.

#

The more important point to note is just the difference between cooperative cancellation and not

#

Which is especially problematic with coroutines due to their inability to return values, so a lot of coroutines are written with some state containers, and stopping the coroutine like that might cause the containers to be in an invalid state.

merry pendant
#

Hey there, does anybody know how to switch the Mask of a layer to another AvatarMask?

indigo orchid
plucky inlet
indigo orchid
plucky inlet
indigo orchid
plucky inlet
indigo orchid
plucky inlet
#

WaitForSeconds?

indigo orchid
#

this deals with showing/updating healthbar

indigo orchid
thin aurora
# unique delta Can you break a coroutine from another function?

See conversation above. Consider using a CancellationToken. These are general tokens that inform when something gets cancelled so you can pass that into a coroutine and occasionally check if it's cancelled. Stopping a coroutine with StopCoroutine isn't graceful and can lead to issues if data is being handled.

#

You don't need to use awaitables or whatever for this to work, CancellationTokens often go hand in hand with it but you can just use them completely separate

#

Note that Unity has its own share of tokens available, such as [this one](#archived-code-general message), which you can also use. Additionally, you can combine tokens in case you must listen from multiple sources.

plucky inlet
indigo orchid
plucky inlet
indigo orchid
indigo orchid
plucky inlet
#

yeh, thats my suggestion, if you can rely on the coroutine being your leading method in that case and nothign else happens in parallel

indigo orchid
sharp sable
#

I have a problem with material transparency. Most of the game objects should be opaque all the time. But cursor, that player uses to place those objects into the scene needs to be transparent. And from what i found, you can't just turn surface from opaque to transparent at runtime. And if I understand it correctly, setting material surface to transparent for all materials to control transparency through alpha channel will cause performance issues. As Unity will have to perform transparency tests for everything in the scene, even if alpha always stays 1.0 for most of the objects.

#

Is there a better solution than making duplicate for every material with transparency enabled, to use those specifically for cursor ?

random drift
#

Hey guys, is anyone here familiar with how Lethal Company does their procedural generation?

eager fulcrum
#

Hey, in Unity I have a huge 2d array. I also have a scriptableobject TileSO for all different tile types. Each TileSO has a different int id
What would be faster, to just store TileSO[,] or have int[,] that would store the ids of these tiles and then have a dictionary of <int, TileSO> and find needed tile by its id?

leaden ice
eager fulcrum
#

storing ints instead of whole objects

vestal arch
# eager fulcrum storing ints instead of whole objects

you'll still need to have the object somewhere, aka the dictionary
TileSO would be a class, a reference type, so it wouldn't be much bigger to store a reference than an int (2x for 32-bit architectures, equal for 64-bit architectures, most likely.)

sharp sable
#

make a public interface that is agnostic to how the data is stored, and implement that dictionary approach if it ever becomes justified

#

it does sound like an unnecessary overcomplication

vestal arch
#

also possibly a premature optimization

vestal arch
eager fulcrum
leaden ice
vestal arch
#

hey, it wasn't stupid, it just lacked background knowledge.
but yeah, the array would just hold references to existing objects; each entry in the array is not necessarily a new object.

TileSO x = ...;
TileSO[] arr = { x, x, x, x };
```this would have the footprint of - a single `TileSO`, and a 4-member array of references
pine carbon
#

How can i get the position of a Plane struct

swift aspen
dire nimbus
#

Hey guys so I'm trying to create a wave based spawn manager that spawns navmesh agents along a certain navmesh surface. But I'm always getting the following error:

Failed to create agent because it is not close enough to the NavMesh
UnityEngine.Object:Instantiate<UnityEngine.GameObject> (UnityEngine.GameObject,UnityEngine.Vector3,UnityEngine.Quaternion)

Anyone have any idea how to deal with this? I'm using a simple wave based spawn manager that uses a logic similar to the one given in the Junior Programmer pathways with some alterations made by me and i've used it previously in another small project I made. The main difference to that one is that I'm not just spawning random enemies that follow the player. I want the enemies to spawn in a certain area in front of the player and I want them to patrol that area so the player can shoot at them, when theyre all destroyed a new wave spawns. Thanks for any and all help in advance.

leaden ice
dire nimbus
# leaden ice Sounds like you're not spawning it close enough to the navmesh or the navmesh is...

The navmesh I'm sure is there because the enemies "spawn" but they don't move. What I do is that I generate a random spawn position and check to see if that position is valid and return that vec3 to another method that instantiate's the prefab. What I'm maybe thinking is causing the problem is the fact that i'm doing a random.range to get the x and z values because I want them to spawn in a certain area and then i'm hardcoding the y value as 0.5 bc currently i'm using primitive cubes for the enemies that's the height at where they're not clipping into the ground

hexed pecan
leaden ice
dire nimbus
# hexed pecan How do you check if the position is valid?

I have a vec3 list where I'm saving the valid positions then I go through that list with foreach and check a minimum distance from those saved positions to the new one. If it's smaller than that min distance I do a recursive call to the same generate spawn position method to get a new position else I save that position in the list and return the position to the actual spawning method

dire nimbus
# leaden ice Enemies spawning doesn't mean the navmesh is there... And wdym primitive cubes ...

I meant to say that I'm pretty sure that the navmesh is there because I baked it into the scene and set it up properly according to what I've looked up. Or am I missing something else? I made prefabs of enemies with the script for their ai, which is very simple as of now, and they also have the navmesh agent component and I made them primitive cubes that I later will replace with models

hexed pecan
dire nimbus
hexed pecan
tepid charm
#

alright

heady iris
#

(and the documentation has changed a fair bit in recent versions)

pine carbon
#

ฤฐ am trying to make a runtime transform tool and doesnt work properly it moves when i first click it even if i dont move my mouse

heady iris
#

You're computing the offset based on the physics raycast, but then you add the offset to a point that's produced by the plane raycast

#

Those don't line up.

pine carbon
#

Ohh i understans

#

Thank you

#

ฤฐt works perfectly noe

dense fog
#

did somebody know haw to attach game object to object thats prefab and have script with : public GameObject Player? becouse idk haw to attach gameobject to this code

heady iris
#

You can't reference scene objects from assets.

#

More accurately: things in an asset can only reference:

  • its contents
  • other assets

Scenes and prefabs are both assets!

#

So an object in a scene can have a reference to other things in the scene, as well as to prefabs. But it can't reference things inside other scenes or things inside prefabs.

dense fog
#

chat gpt tells me that i can use "FindObjectOfType<T>()" is it true?

heady iris
dense fog
#

okey i will read this

#

btw sorry for my english, im not from US

dense fog
steady bobcat
heady iris
#

Ah, that is important -- you'll see a warning if you use it in new versions of Unity

#

I'm having a mildly interesting problem with a [SerializeReference] field in the Recorder package

#

I have a script that reserializes all of the assets in my project. I figure I might as well just keep everything up-to-date, rather than having Unity update serialized data piecemeal over time

#

For some reason, though, my recorder settings asset keeps changing

#

The managed reference IDs keep going up!

#

I don't see this happening with anything else in my project

wheat spruce
#

is it possible for a script to rename an object whilst the game is in the editor mode? I've got these prefabs which contain a scriptable object, and it would be helpful if these prefabs always have the name in the SO whilst im editing the scene

#

its quite tedious having to go and rename 20 or so different objects myself (especially if I ever change the names later)

naive swallow
wheat spruce
#

that might be a bit too involved for what I need, I was hoping for something just like void Awake() { gameObject.name = SO.Name; } but in whatever method would allow the editor to call it

naive swallow
#

Yeah, you'd just do a rough editor script like I said so you can run it in edit mode without doing any custom inspectors, then you could just do a FindObjectsOfType and call a function on em

heady iris
#

That's the least spooky way to do it

naive swallow
#

Yeah, this is the way to make it less involved

hexed pecan
#

I might add to that, you probably need to SetDirty the child if you want the name changes to persist

wheat spruce
#
  [MenuItem("MyMenu/UpdateTechTreeNodeNames")]
  static void UpdateNames()
  {
    int count = Selection.activeTransform.childCount;

    for(int i = 0; i < count; i++)
    {
      Transform child = Selection.activeTransform.GetChild(i);
      CanvasNode cn = child.GetComponent<CanvasNode>();
      child.gameObject.name = cn.Node.Name;
    }
  }```This works
indigo orchid
steady bobcat
heady iris
#

otherwise, it will work Sometimes (tm)

#

the worst kind of working

plucky inlet
quick elbow
#

Anyone using vcontainer and know how to add a new LifetimeScope for a scene and register it as a child of my root scope that is in the DontDestroyOnLoad scene? I'm a bit confused by the vcontainer documentation

heady iris
#

Huh. I spent a good while chasing this issue down today

#

Note: OnDestroy will only be called on game objects that have previously been active.

Never knew that.

#

This was causing me to miss unsubscribing something that could subscribe in Awake or in a public method

hexed pecan
#

Oof, that's good to know

heady iris
#

It was causing dangling event listeners when changing control schemes whilst a menu wasn't open

naive swallow
#

Definitely filing that into the ol' mental toolbox

heady iris
#

(since that caused all of my individual action displays to be destroyed and recreated)

naive swallow
#

I've never stepped on that specific rake but it's definitely something I would eventually hit

heady iris
#

I can't just subscribe in Awake, because I could miss a control scheme change that happens before the input action display appears

naive swallow
#

Ghetto fix: Instead of having the object start disabled, have it start enabled and disable itself in start. That way it receives OnDestroy callbacks

heady iris
#

It's spawning in parented to a deactivated object

naive swallow
#

dang

#

Double ghetto fix: Spawn it in without a parent, then set the parent

wheat cargo
#

I tend to subscribe to events in OnEnable and unsubscribe in OnDisable, but for slightly different reason. OnDestroy doesn't get called immediately when calling Destroy. It gets called at the end of the frame.

#

When you call Destroy it disables the object immediately though

heady iris
#

Destroying the attached Behaviour will result in the game or Scene receiving OnDestroy.

????

#

very weird line

#

I guess I'll subscribe and unsubscribe in OnEnable and OnDisable, and also manually update in OnEnable

#

There's no point in updating the inactive action displays anyway

wheat cargo
#

Yeah in my opinion event subscriptions in Awake and OnDestroy can be unreliable and can cause weird bugs.

heady iris
#

Almost everywhere else does OnEnable and OnDisable, yeah

#

ah yes

#

this script has another alarming piece of code

#
[NonSerialized] private InputAction inputAction;
#

It bricks if you remove the [NonSerialized] attribute

#

because Unity still serializes private fields (for the sake of hot-reloading, I'm pretty sure)

wheat cargo
#

Like if I'm subscribed to an event and unsubscription in OnDestroy this can happen:

Destroy(myObject);
meEvent.Invoke();

myObject will still receive the event

It's strange so I avoid it completely

heady iris
#

this wound up causing it to insert a bogus object

heady iris
#

notably, while the game is shutting down..?

#

maybe it's just anytime you destroy something at the end of the frame

wheat cargo
wheat cargo
#

There is DestroyImmediate(), it's really only reccomended for the editor though

heady iris
wheat cargo
heady iris
#

: )

#

try switching the inspector to Debug mode

#

you'll see private fields pop up

#

I believe it was also interacting badly with having Domain Reload disabled

hexed pecan
#

Are you using a hot reload package?

wheat cargo
#

Yeah but I thought that's for serialized fields marked as [HideInInspector] as well

#

Debug inspector will obviously show those even if marked as hidden

hexed pecan
#

We aren't just talking about it showing in the inspector, but the value being saved

#

And persisted

wheat cargo
#

Yeah that's fair, not at my pc right now so can't test it

#

Yeah it apparently does

heady iris
#

It's very sneaky

wheat cargo
#

I never use play mode hot reloading, I have my settings set to stop playing and recompile

steady bobcat
#

ive never had it work it just breaks everything. only sbox does it well imo

sudden cloak
#

hello im trying to figure something out from the reusable stat machine video(from i heart gamedev) and that is how to make it so that child game objects are able to change the state of the parent game object for example lets say you have 2 trigger box as children. one is for taking damage and the other for a melee hit ( i know the one receiving the melee hit should call trigger but lets say the one doing the hit call it). if either of trigger box activate i want the player to go to idle state for example how would i go about doing that?

wheat cargo
steady bobcat
wheat cargo
sudden cloak
#

im not sure what mean can you clarify

sudden cloak
naive swallow
#

The Animator isn't a 3D specific thing

wheat cargo
pure basalt
#

can anyone tell me whats wrong with my script after i click left shift i dont sprint..

somber nacelle
rigid island
#

cant even tell if that float is supposed to be setting some type of variable you haven't specified

steady bobcat
#

yea it doesnt do anything from what i can tell

karmic stone
#

how do you make it so when using SendMessage() with PlayerInput (new input system), that the method gets called both onpress and onrelease?

#

right now, it only gets called when i first press the button, and never when i release the button

rigid island
somber nacelle
#

i'd bet that the input action is set to pass through

karmic stone
#

sorry, moving there

unkempt meadow
#

Why does this not work?:

yAngle = Vector2.Angle(mousePosition1, mousePosition2);

#

where mouse positions are converted to world space

naive swallow
#

What doesn't work about it

rigid island
#

just gets an angle

unkempt meadow
#

yeah I know, mouse positions are converted before that

naive swallow
unkempt meadow
#

those are converted variables

steady bobcat
#

do dest - source, normalise and use mathf atan2

rigid island
#

they still havent said whats wrong

quartz folio
#

you're asking people to make a whole bunch of assumptions about what you think is wrong

unkempt meadow
steady bobcat
quartz folio
#

What are you expecting it to do? You have two world-space positions

unkempt meadow
quartz folio
#

It'll be the angle they make with the world origin

unkempt meadow
#

but I get a ''random looking'' number

rigid island
steady bobcat
unkempt meadow
# rigid island vector2 is already omitting the z position as 0

I am confused by 2d tbh...what I want is I place position 1. I place position 2.
if:

  1. position 2 is directly to the right of position 1, I'd expect an angle of 0
  2. position 2 is directly above position 1, I'd expect an angle of 90
  3. position 2 is diagonally above and to the right, I'd expect 45
quartz folio
#

Your expectations are wrong.

unkempt meadow
#

I don't care about 180 vs 360 or negative numbers, it will work out the same

quartz folio
#

You want to compare the angle between Vector2.right and (B-A).normalized

unkempt meadow
#

2d confuses me

steady bobcat
# quartz folio

that image helped me too i miss understood it too ๐Ÿ˜†

unkempt meadow
#

there you go

#

thanks guys

#

let's see if it works

steady bobcat
#

I usually use atan2 myself to achieve the result or dot product

unkempt meadow
#

it works better than what I had but it still sometimes doesn't work...hmmm

steady bobcat
#

I do:

Vector2 dir = (b - a).normalised;
float angle = Mathf.Atan2(dir.x, dir.y) * Mathf.Rad2Deg;

i think this is correct?

naive swallow
unkempt meadow
#

I did what the person above suggested

unkempt meadow
#

Okay, so just adding ''SignedAngle'' instead of ''Angle'' solved it

wintry crescent
#

Say, when I open up a prefab in edit mode, what's the exact OnValidate behaviour? Is it called on ALL scripts on ALL childobjects of the prefab? Only the active ones? Only the ones I click on? Only the ones which have their values changed?

I'm looking for a way to have a callback on every script in a prefab whenever said prefab gets opened. That callback could potentially include a Resources.Load thingie inside, so I'd rather not have it run too often

steady bobcat
wintry crescent
#

I do wonder out of curiosity, how that onvalidate works exactly tho

steady bobcat
#

i think i had this same desire once and i forget how it works...

#

i know at least on any var change in inspector its called

wintry crescent
#

I once did a buunch of instantiate and destroy inside onvalidate and when sliding a variable it completely KILLED my poor cpu

steady bobcat
#

on validate may be called if you added a new prefab instance but i dont think it is just by opening it in a prefab stage

wintry crescent
upper pond
#

Im trying out state machines, and I have a problem where every time my character goes from the airborne state to the grounded state (where WASD force is applied), it's velocity is always set to zero, instead of maintaining it. What could this be?
I know it is nothing to do with deltaTime, but dont know how else to debug it

rigid island
upper pond
rigid island
#

you have to explain the problem a little more

upper pond
#

I figured it would be maintained in the rigidbody

#

I have tried saving the velocity right before leaving the airborne state and setting it upon the grounded state being active, but have had no luck

rigid island
upper pond
rigid island
#

aslo you should not be adding time.deltaTime inside AddForce

#

rigidbodies already move on a specific tickrate

upper pond
#

where should I?

#

ok

#

is the tickrate not tied to FPS?

rigid island
#

yes but the whole point of Time.deltaTime is to achieve a similar consistency

#

so your values change at the same rate no matter fps

upper pond
rigid island
#

if its not mentinaing velocity its either colliding or you have somewhere where rb.velocity = vector3.zero ๐Ÿคทโ€โ™‚๏ธ

upper pond
eager steppe
#

hey guys, weirdly couldn't find much on the internet but do you know how to stop the OS toolbar from "freezing" your game's state?

of course in this test case, im impatient as fuck so i didn't wanna let it ride for the entire map, hence i failed the map, but it could. and a player has before; so it proves to be a little problem.

focus checks and making it run in the background doesn't seem to help nor prevent things. i attatched an example to show what's up (if im using the wrong terminology here, lmao)

rare thorn
#

Hello! Sorry if this is the wrong channel. Im struggling a bit with organizing my scripts on my gameobject. Its not really a problem that there are so many, but im starting to lose the overview a bit.

Most of these are individual moves for my character. Any way to organize this better?

leaden ice
#

why does every move need to be a component?

#

What does the code on these actually look like

rare thorn
#

I can share a code snippet if that elaborates more

leaden ice
#

or even ScriptableObjects for the moves

#

with a list of instructions

rare thorn
#

Sorry can you elaborate on what a POCO is? Also for clarity, the base component is not actually attached to my game object, since the components all inherit from it anyways

#

Also, hypothetically, lets say i 2x or even 3x my amount of components on my object. Would this cause any issues? Or will it just be a bit messy

rigid island
rare thorn
rigid island
#

if its just container of data/run specfic functions with data then yes SOs are far superior than making everything a component

#

if data is meant to be mutable copy it from SO to POCO

rare thorn
#

Sorry im very unexperienced when it comes to SO's. I will share a code snippet, maybe that can clarify what the best cause of action is for me

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

public class BasicAttack1 : AttackBase
{

    // Start is called before the first frame update
    void Awake()
    {
        attackanimation = "BasicAttack1";
        attackKeyCode = KeyCode.Mouse0;
        SeriesLink = 0;
        soundeffect.Add(Resources.Load<AudioClip>("Audio/Sound Effects/attacksound"));
        stateRequirement.Add(pawnstate.Grounded);

    }

    public override IEnumerator ActivateHitboxes()
    {
        PlayAttackSound();
        overrideStartAttack = true;

        MoveCamera(new Vector3(-1, 10, -1), 0.1f);
        //CanBeCancelledWithAttack(true);
        yield return new WaitForSeconds(0.1f);
       AddHitBox(id:0,radius:0.4f, position:Vector3.forward, damage:15,KnockbackDirection:Vector3.zero);
       AddHitBox(id:1,radius:0.7f, position:new Vector3(0,0,2), damage: 15);
       AddHitBox(id:2, radius: 0.4f, position: new Vector3(0, 0, 2.7f), damage: 15);

        yield return new WaitForSeconds(0.03f);

        DeleteAllHitboxes();

        yield return new WaitForSeconds(0.05f);

        CancelAttack();
    }
}
#

!code

tawny elkBOT
latent latch
#

Component idea is actually pretty neat

#

True composition approach

leaden ice
#

especially since they're coroutines

#

Maybe to organize them better you could put them on a child GameObject or something

rigid island
#

shouldn't those be in an array though why are they all plopped on the gameobject

rare thorn
rigid island
#

these can be easily done as SOs unless you need specific MB functions

rigid island
#

yeah like Monobehaviour

#

Update and all dat

rare thorn
#

Ah, i really dont know if theres anything specific in Monobehaviour required

rigid island
#

unless you need those methods, probably no reason to have them be MBs

latent latch
#

SOs weren't always a thing and I'm pretty sure a lot of this was pretty standard before

#

just that nowadays SOs can make the inspector easier to navigate cause it does get pretty crowded very quickly

rigid island
#

seems simply enough for a POCO before SO tbh

#

SOs basically just make POCOs into tangible assets on disk

latent latch
#

true, pocos must always be instantiated though for some reason

rare thorn
#

Ok! Thanks all. Ill look into turning them into SOs or POCOs tommorow. If i feel like i end up in rewrite hell, i will probably attach them all to a new script that has an array container for them instead :)

rigid island
#

I think when you do Create asset is the same as creating the instance

#

but yeah SOs are mix of like static pocos and unity objs its weird

latent latch
#

SOs will allow you to say make an empty list of abilities on a component, and it can contain multiples or none SOs

rigid island
#

yea basically you can cycle through them

#

as assets

latent latch
#

list of instances

rare thorn
#

Is this not possible with monobehaviour?

rigid island
#

you can but you need MB to be on a gameobject

#

SOs live on Disk

#

therefore can be placed onto any MB that have the field for it

rare thorn
#

Ahhhh

#

And SOs can run Coroutines?

rigid island
#

indeed nvm

latent latch
#

Can they? I think you need to run them on a mono

rigid island
#

wait

#

pretty sure they did but now you make me doubt

#

might need to be MB actually

rare thorn
#

Ah thats annoying, i use coroutines for basically everything atm

rigid island
#

I mean there is always Awaitable and async

latent latch
#

You can stick monos on anything. It doesnt need to be the exact instance

#

er coroutines*

#

Like you can even make a singleton that you just run coroutines from other sources on

rigid island
#

tru

rare thorn
#

Ah ok!

rigid island
#

coroutine can be modular you can pass all sorts of stuff like Func and all that maybe adapt it to whatever

#

or again use true async

latent latch
#

You may be able to define the enumerator on the SO, but start the coroutine on the mono caller

rigid island
#

yeah cause StartCoroutine needs MB to start it on

rare thorn
#

Ah makes sense. Anyways, ill look into it tommorrow, i have ideas of where to look now. Cheers! :)

latent latch
#

ye, but if you aren't having problems with your setup just keep going

lucid brook
#

I got a dumb quick question, I need to check if the player is strafing so I wanna check the X of the input vector but is there a way to make sure that value is always positive, even when the player is holding down A/the joystick to the left? I remember having that figured out on a previous project but I'm completely blanking on it now lol.

rigid island
lucid brook
#

that was it

#

thanks

#

ugh I hate how brains just decide to forget stuff

rigid island
#

mine has to do it a thousand times and only remember it for a month or so UnityChanLOL

indigo orchid
timid briar
#

@rigid island hi are you quite good with coding

alpine pagoda
#

does anyone know how to use json in unity

rigid island
alpine pagoda
#

cause the dialogue web is gonna be massive so a json file would be the best for it

rigid island
rigid island
#

doesn't sound like you're sure how you want to use json

alpine pagoda
#

make the json file

#

and then import it into unity

rigid island
#

You can make json file in pretty much any text editor

#

most apps export to json

alpine pagoda
#

o seriously??

#

omg wait ur right

rigid island
#

yes json is just a text formatted special way

alpine pagoda
#

i js did it

#

omg ty

rigid island
timid briar
#

I need help making a scrip

somber nacelle
#

!ask

tawny elkBOT
#

:thinking: Asking Questions

:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐Ÿ”Žโ”ƒfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696

timid briar
#

@somber nacelle I need to create a money script so player van buy weapon off wall

soft shard
midnight hazel
#

Hello. I have a scriptable object that works well, but I want to add a regular class to the same script to store information at runtime. Does anyone have any examples of how to do this? Should I be using a second script to store the class info instead?

thick terrace
mossy glacier
#

my textures in unity is ~80x larger compared to the file size in disk. the image dimension is only 458x356 px . how comes it 600kb in unity? Based on the inspector, it shows Compression as "Normal Quality". and max size is 512. Do i really have to lower the max size to 64 to get decent build size of texture?

steady bobcat
#

btw you can only "down size" with sprites but textures you can have unity resize up/down to the nearest POW2

#

so fix your sprite to be pow 2 externally @mossy glacier

mossy glacier
#

When i fix my sprite to be 512x512, the size is still very big, from 8kb in disk to 256kb in unity build

thick terrace
#

graphics cards can't render PNGs though haha, you can set it to a compressed format but you shouldn't expect it to be as small as PNG

steady bobcat
#

This is also why it wise to use spritesheets for stuff like this as the sheet can be pow2 and you can have many sprites in it at varying size!

mossy glacier
#

hmm i see. i dont know how to use spritesheets in unity yet. i'll look it up

rare thorn
#

Hello! Suddenly ran into a very strange problem. My sound effects are no longer playing, but i havent touched anything except restarting unity ๐Ÿ™ƒ . Heres the code that run the sound effects

    void Awake()
    {
        soundeffect.Add(Resources.Load<AudioClip>("Audio/Sound Effects/Paste25"));

    }

  public override IEnumerator ActivateHitboxes()
  {
      PlayAttackSound();

      yield return null
}
  public void PlayAttackSound(int soundeffectnumber = 0)
  {
      GetComponent<AudioSource>().PlayOneShot(soundeffect[soundeffectnumber]);

  }
#

I have a debug sound that plays correctly in case no sound effect is present

#

But i dont understand why every other sound effect broke

soft shard
# midnight hazel Hello. I have a scriptable object that works well, but I want to add a regular ...

When I use ScriptableObjects, I usually have a setup like this:

[CreateAssetMenu()]
public class SomeDataSO : ScriptableObject
{
public SomeData data;
}

[System.Serializable]
public class SomeData { ... }

That way the data can be set in a scriptable object, assigned to a object reference through the inspector, and then something using it at runtime can use serialization like JSON or copy each field into a new object to make a copy of the data without affecting the scriptable object, if it needs to be saved at runtime, it can be saved to a file and reloaded later, for example:

public class SomeMono : MonoBehaviour
{
public SomeDataSO so;

SomeData clone;

void Start()
{
var json = Newtonsoft.JsonConvert.SerializeObject(so.data);
clone = Newtonsoft.JsonConvert.DeserializeObject<SomeData>(json)
}
}
soft shard
rare thorn
#

Nvm i found the issue, it was really stupid sorry :P

soft shard
#

Glad to hear you figured it out

midnight hazel
rare thorn
#

And i havent saved since i transferred stuff to a list

soft shard
rare thorn
steady bobcat
rare thorn
#

And in game it looks like this

steady bobcat
#

remove it

rare thorn
steady bobcat
rare thorn
#

Nope, not as far as im aware

steady bobcat
#

then click that element and remove it and you should be good

rare thorn
#

Ok thanks! Its a bit annoying since it added it to all my components that inherit from the base where i added the list ๐Ÿ™ƒ

steady bobcat
rare thorn
#

I think i defined it like this originally

    public List<AudioClip> soundeffect = new List<AudioClip>();

Then changed it to this

    public List<AudioClip> soundeffect = new();

Then tried to change it to this

    public List<AudioClip> soundeffect = null;
steady bobcat
#

Hmm it should have been empty then always. If you reset the component it will go back to defaults:

rare thorn
#

Ah thanks! Ive never used reset before, so that is very handy

#

Is there an easy way to reset several or globally all components?

steady bobcat
#

Well you can select multiple and reset in bulk. (You can also define Reset() to run code on reset)

soft shard
# rare thorn Is there an easy way to reset several or globally all components?

You can Ctrl + Click or Shift + Click if everything is next to eachother in a list, and if they have similar components editing the inspector will apply the same value to all selected - however some fields might have a dash, meaning the selection for that field have different values and changing it will change all of them

rare thorn
#

Ok! Thanks everyone! :)

vestal arch
thorn ravine
#

Hi, if I write one of usefull commands in any unity chat is it visible to everyone or just me?

vestal arch
#

it's visible to everyone; it's just a normal message

thin aurora
#

As in here?

thorn ravine
vagrant blade
#

This is discord, anything you post is visible to anyone with access to the channel.

#

Which, in this channel, is accessible to everyone who's joined this server.

soft shard
#

The only messages that are not visible to everyone is the built-in slash commands if you start a message with /

thorn ravine
#

What is the best practise to use those commands, I don't want to interrupt people by chating commands in some chats?

thin aurora
#

You can use private threads and DMs for private chatting

thin aurora
thorn ravine
vestal arch
thin aurora
#

Make a thread with the big button on top of the page

vestal arch
#

or from the plus on the side of your chatbox

soft shard
thin aurora
#

I guess we only annoy the moderators with these threads though

#

Sorry mods

vestal arch
thorn ravine
soft shard
#

Discord has some interesting features and they often add new ones with updates, so always something new to to learn about lol

oblique basalt
#

I have an array of Nodes with a worldPosition property.
How can I generate an array of worldPositions from the array of Nodes? I think I can use linq to do it really easily but I'm not familiar with it

vestal arch
#

yeah with linq you can do Select(node => node.worldPosition), for example

#

that uses a lambda, do you understand those?

oblique basalt
#

ahhh I did the same thing but with Where for some reason whoops

oblique basalt
prime lintel
#

Hey friends, I think I did something wrong, something basic, but I can't tell what it is. As you can see here in the debugger it says I cannot reach this breakpoint. And following my order of operations, it does not seem like I had, but the data in m_curAnimate has mutated from its initial value of 'Idle 1' to 'Idle 2' without me setting it to change anywhere in my code.

private void DoAttack(Transform target)
{
    var animator = m_context.m_mob.m_animator;

    switch (m_curAnimate)
    {
        case m_idle01Name:
            Debug.Log("Idle01");
            if (Vector2.Distance(m_context.m_mob.transform.position, target.position) > ((CamoBoss)m_context.m_mob).m_dashThreshold)
            {
                m_curAnimate = m_dash01Name;
                animator.SetBool("PrepareDash", true);
                animator.SetBool("Attacking", true);
            }
            else
            {
                m_curAnimate = m_walk01Name;
                animator.SetBool("Walking", true);
            }
            break;
        case m_idle02Name:
            Debug.Log("Idle02");
            animator.SetBool("Walking", false);

            break;
        case m_dash01Name:
            Debug.Log("Dash");
            animator.SetBool("PrepareDash", false);

            break;
        case m_walk01Name:
            Debug.Log("Walk");

            break;
        case m_attack01Name:
            Debug.Log("Attack01");

            break;
        case m_attack02Name:
            Debug.Log("Attack02");

            break;
        case m_attack03Name:
            Debug.Log("Attack03");

            break;
        case m_attack04Name:
            Debug.Log("Attack04");

            break;
    }
}
#
public override void HandleAttack(Transform trans)
{
    // Lock movement during Awakening
    if (m_context.m_mob.m_animator.GetCurrentAnimatorClipInfo(0)[0].clip.name == "P1 Slumber" ||
        m_context.m_mob.m_animator.GetCurrentAnimatorClipInfo(0)[0].clip.name == "P1 Awakening")
    {
        m_context.m_mob.m_aiPath.canMove = false;
        return;
    }

    // Lock Movement
    if (m_context.m_mob.m_animator.GetBool("Attacking"))
    {
        m_context.m_mob.m_aiPath.canMove = false;
        m_context.m_mob.GetRigidbody2D().linearVelocity = Vector2.zero;
        return;
    }
    else
    {
        m_context.m_mob.m_aiPath.canMove = true;
    }

    AttackSettings(trans);
    DoAttack(trans);
}
vestal arch
steady bobcat
vestal arch
#

@oblique basalt are you familiar with any other languages?

prime lintel
steady bobcat
#

er

prime lintel
#

Though the mutated data is still a mystery

vestal arch
#

lol

cosmic rain
steady bobcat
prime lintel
prime lintel
cosmic rain
#

Unity console

#

Not in the ide

prime lintel
#

Not there either

cosmic rain
prime lintel
steady bobcat
#

usually for me a restart of both us sufficient

#

Sometimes when you press play it decides the breakpoint will work ๐Ÿ˜

#

Debugging mode is enabled right? @prime lintel

cosmic rain
# prime lintel

Yeah, so:

  1. Make sure the ide is configured correctly.
  2. Check the script file in the inspector and see if the code corresponds to what you see in the ide.
marsh light
#

Hey, how can I run the game in two instances? I see all the youtube videos on multiplayer do it, i have no idea how as they don't explain it

prime lintel
cosmic rain
vestal arch
cosmic rain
prime lintel
#

๐Ÿ˜ญ alright then

marsh light
cosmic rain
tawny elkBOT
prime lintel
#

btw any suggestions or guides on creating enemy AI in a 2d game?

cosmic rain
marsh light
#

tsym

timid comet
vestal arch
#

please don't crosspost

wheat cargo
#

How can I find the screen space dimensions of a RectTransform no matter the scaling settings on the CanvasScaler?

heady iris
steady bobcat
rare thorn
#

Hello! Ive been struggling with letting my program work when i build it, i just get an entirely Orange image when the program starts. I can hear the sound effects from my game, which indicates its working correctly, so i suspect its a camera issue.

#

Heres my build settings

#

And heres my camera settings

#

I tried searching for the issue online but no solutions :(. The game works perfectly fine in the editor

#

Heres what it looks like when the build finishes, and after the splash screen has popped up

steady bobcat
rare thorn
rare thorn
steady bobcat
#

yay

white crescent
#

Hi I trying to make a procedural animation with a spider, but I'm confused about zigzag legs pattern, how can I make this in the code?

hexed pecan
#

Having the legs alternate?

white crescent
hexed pecan
#

It's easier to help if you show what you currently got

#

Including code and gameobject setup

#

Basically you can get every other leg by checking if its index is index % 2 == 0 or index % 2 == 1

white crescent
#

so far I've only done the target script, is circles attached in body and the legs follow it when the distance is so big

white crescent
hexed pecan
#

Well, I don't know portuguese

white crescent
karmic stone
#

is there any noticible difference between [SerializeField] private float and public float for game design?

#

i mean for global script variables

naive swallow
#

Serialized private fields can be set by the inspector.

Public fields can be set by anything.

karmic stone
#

i guess that was a pretty dumb question of me now that i think about it XD. Was not thinking in code when i asked

heady iris
#

that usually implies that it's something that everything in the game can see

#

(and access, directly, without any help)

karmic stone
#

but what would be a better term to define them so other people have a better understanding?

heady iris
#

Those are fields

#

a kind of member

#

It is true that variables declared inside of a function are called local variables

karmic stone
#

when learning programming, i was taught any variables declared in a class but outside of a method were global variables, so those are callled "class fields"? or just fields

vestal arch
heady iris
#

C# doesn't really support truly global variables

#

imagine something like

karmic stone
#

ohhhh, ok ok thats explains things in a way i understand

heady iris
#
public global int foo;

public class Whatever {
  public int bar;
}
#

(there is no such keyword)

vestal arch
# vestal arch "global" tends to mean something that doesn't really have a specific owner. loca...

if it were say, python, you would have 3 levels, or in js, you would have 3-4 depending on the environment

# python
x = 0 # global var
class C:
  y = 0 # class var
  def m():
    z = 0 # local var
def f():
  z = 0 # local var
``````js
// javascript
globalThis.w = 0; // global var
let x = 0; // module var (or global, if modules are not used)
class C {
  y = 0; // class var
  m() {
    z = 0; // local var
  }
}
function f() {
  z = 0; // local var
}
karmic stone
#

yeah, ive never dealth with declaring variables outside of a class (i was taught in java)

#

delt

vestal arch
#

yeah java doesn't really have globals either

heady iris
#
public class Foo {
  public int field;
  public int Property => 123;
  public int Method() { int localVariable = 100; return localVariable; }
}
karmic stone
#

yeah i understand the difference now, ive never seen global variables before, because i havent had a use for them yet. My thinking was always in java, even when using other languages,

#

thank you for the info

naive swallow
steady bobcat
#

C and cpp allows declaring functions and vars outside a class/struct

vestal arch
#

most oop languages being c# and java

steady bobcat
#

we all know c and cpp dont follow the rules

vestal arch
#

i mean, if c/cpp are oop, then so much else is that i feel it starts becoming meaningless, no?

#

c/cpp don't need objects if you don't want them

#

you can't do that in java or c#

indigo tree
#

That is the entire readon cpp exists

vestal arch
#

so is cpp oop

rigid island
#

You can code in OOP in c though no ?

vestal arch
#

you can, but the language doesn't force you into oop

naive swallow
#

You can code OOP in any language that has the concept of a class at all

rigid island
#

yea thats what i was thinking ^

#

but was thinking polymorphism but that makes sense

vestal arch
#

my thoughts being; if you use that as the metric, then so much becomes oop, what's the point of the distinction

heady iris
#

oh no! ontology!

wintry crescent
#

if eventToInvoke is null, what will happen here? My project has plenty of errors right now so I can't check for myself, but I'd like to know while still writing this class. For reference IProcedure : IEvent and they're both interfaces

naive swallow
wintry crescent
#

can't do T is IProcedure sadly

naive swallow
wintry crescent
naive swallow
#

If eventToInvoke is null, then it isn't an IProcedure

wintry crescent
#

but it should always be of type T, right?

#

that's my point

naive swallow
#

Yes, so it's an IEvent

wintry crescent
#

no, T derives from IEvent

#

so does IProcedure

naive swallow
#

No, T is an IEvent

#

IProcedure is also an IEvent

#

so you can pass an IProcedure to something that expects an IEvent

wintry crescent
#

yeah I know, but I want this specific function to only allow IEvents that are not IProcedures, is there a way to limit that?

naive swallow
#

Don't pass an IProcedure to it

#

Or make a different interface implemented by everything that implements IEvent except IProcedure

wintry crescent
#

I work in a team, and I can't guarantee that nobody will pass a IProcedure to it, I want to make it impossible or at least throw an error

vestal arch
wintry crescent
#

I really need IProcedure to derive from IEvent everywhere other than this function

naive swallow
vestal arch
#

could make an IInvokable that extends IEvent and make other stuff except IProcedure extend that

naive swallow
#

Always better to make invalid options impossible rather than checking if it's correct after you get it

worldly stirrup
#

I keep getting precision errors that result in a value not being calculated as zero

naive swallow
worldly stirrup
#

what if i need to check if a value is greater or less than 0?

coarse cape
#

Have been working with unity for a while and this thing has bothering me since beginning. is there a reason why GameObject has a getter to itself?

naive swallow
worldly stirrup
naive swallow
worldly stirrup
#

im not comparing, im dividing

naive swallow
#

Yeah, but when you go to use the result, you should be using approximately to check the value

naive swallow
worldly stirrup
naive swallow
worldly stirrup
#
        {
            if(hasJumped){
                hasJumpedFromCeiling=colls.rotation==180;
                hasJumpedFromwall=colls.rotation%180!=0;
            }
            colls.rotation = 0f;
            rotationDirection = 1f;
            Debug.Log(rb.linearVelocity);
            velocity= rb.linearVelocity/  velocityMultiplier;
            changeDominantRay = false;
        }```
#

the problem occurs on velocity=rb.linearVelocity...

#

when colls.rotation is 180 and rb.linearVelocity.x is 0, velocity.x isn't zero

naive swallow
wintry crescent
#

Is there a way I can have an Action<MyInterface> that implicitly accepts adding Actions that don't take any parameters? it'd make things much simpler for me

#

nevermind, got it working

pulsar plinth
#

is there really no way to mark a built-in unity class/struct as System.serializable?

#

it'd be massively convenient to be able to do so for Unity vector classes

steady bobcat
pulsar plinth
#

alright, thanks

naive swallow
#

Pretty sure vectors are already serializeable

pulsar plinth
#

they aren't

#

they aren't System.serializable

steady bobcat
pulsar plinth
#

it's different to Unity serializable

wintry crescent
#

How can I generalize those 2 functions into one so that I don't have code duplication?

        protected static bool ValidateListener(Action<IListenable> listener)
        {
            if (listener.Target == null)
            {
                return false;
            }

            if (listener.Target is Object o && !o)
            {
                return false;
            }
            
            return true;
        }
        
        protected static bool ValidateListener(Action listener)
        {
            if (listener.Target == null)
            {
                return false;
            }

            if (listener.Target is Object o && !o)
            {
                return false;
            }
            
            return true;
        }
naive swallow
#

They're visible in the inspector, which would mean they're serialized to the meta assets

pulsar plinth
somber nacelle
#

what are you using to serialize that doesn't support serializing a vector3

wintry crescent
#

Vector3 should be serializable, I'm pretty sure

pulsar plinth
#

saving files in a secure way

naive swallow
wintry crescent
somber nacelle
somber nacelle
#

do not use BinaryFormatter, it is incredibly insecure

wintry crescent
rigid island
pulsar plinth
#

btw yes it is indeed

somber nacelle
#

if only there were some sort of link that explained why it is insecure andsome alternatives to use

wintry crescent
rigid island
somber nacelle
#

but also if you want to serialize to binary, i personally recommend messagepack

pulsar plinth
steady bobcat
somber nacelle
pulsar plinth
#

but thanks

somber nacelle
#

you should learn to read before trying to use unity tbh

naive swallow
pulsar plinth
#

ah, I see

steady bobcat
#

if you want it to be efficient then json and xml are off the table

#

blah blah newtonsoft conversion issues blah blah

pulsar plinth
#

I'll read further into it

wintry crescent
#

knew it wouldn't be this easy lmao

somber nacelle
#

Try specifying the type arguments explicitly

steady bobcat
wintry crescent
#

and it has no T

#

Because the action has no T

#

that's the whole point

pulsar plinth
rigid island
wintry crescent
#

unless you meant like this?

somber nacelle
#

Action and Action<T> are not interchangeable

wintry crescent
rigid island
#

mb

somber nacelle
wintry crescent
#

does converting an action into an action T like this
(Action<T>)((_ => myPlainAction.Invoke) preserve the target for the purposes of checking if it isn't null?

wintry crescent
rigid island
somber nacelle
wintry crescent
#

I'm making an event system where I dont want to bother with deregistering listeners

#

and if I check the target and it still exists, it should be fine for my purposes

heady iris
heady iris
#

it's the instance that a method is being called upon (if one exists)

wintry crescent
#

what, what if I have code in brackets there instead? or a static function?

heady iris
#

then there is no target

wintry crescent
somber nacelle
#

and if you subscribe a static method then the Target is null

#

which breaks your entire system

heady iris
#

and if you add multiple listeners, it doesn't make sense at all

#

i'm not sure what happens there

#

It is true that it's the listener in a subset of all possible cases

wintry crescent
somber nacelle
heady iris
#

ah, there's the definition

wintry crescent
heady iris
#

i was having a bit of trouble pulling that up

wintry crescent
#

I guess I can just make a ValidateActionTarget function...

heady iris
#

you can accept System.Delegate

#

that's the base type for any delegate

wintry crescent
#

oh yea that does work, niceeee

heady iris
#

otherwise you would need to have a separate implementation for every number of generic arguments

#

I've also thought about an event system that doesn't require explicit un-registration

rigid island
#

public static bool Validate(this Delegate listener) :X

heady iris
#

You could have a singleton that notes down every time an object says it's subscribing to something, and then unsubscribes everything when that object reports that it's being destroyed

#

basically, GC for your event listeners

somber nacelle
#

yeah that would likely be better than this current implementation which will break if you decide you want static subscriptions or to subscribe multiple methods to a single delegate

heady iris
#

You could also create a "conditional action" type

#

basically, an action, plus some information about when you can use that action

#

or you just wrap the listener in another delegate type

#

ooh, that could be a use for the add and remove accessors!

somber nacelle
#

or a bastardized event bus that basically just takes an object (which you would pass this) and the desired Action and throws it into a list, then you could just null check the object passed

heady iris
#

lists are scary because you could trigger a concurrent modification exception from literally anywhere

#

I remember seeing someone implement a modification-safe list that'd avoid that problem

somber nacelle
#

ah yeah, probably wouldn't need a list just a dictionary<object, Action> and each time something is subscribed it gets thrown into the relevant Action.
of course none of this matters for anything that doesn't inherit from UnityEngine.Object considering other objects don't suddenly turn up null

heady iris
#

"null-ness" was a huge mistake

#

should've just been a Valid property

wintry crescent
#

why can I add a [CanBeNull] to a parameter function of type T, but I can't make its default value be null?

#

default as the default value doesn't work, because I can't check if eventToInvoke == default

#

or rather, my real question is, how can I make sure that this T IS nullable and I can check it for null?

#

I know I can just make a parameterless function but this frustrates me!

latent latch
#

Never seen that one before.

somber nacelle
# wintry crescent

just because T is constrainted to an interface doesn't mean that only reference types can be passed here

latent latch
#

usually I'm being forced to use default or so VS tells me

wintry crescent
#

wait that doesn't work EITHER??

wintry crescent
rigid island
somber nacelle
somber nacelle
wintry crescent
somber nacelle
#

sure but what type is that null supposed to be

#

how can it know because you literally just passed null

latent latch
#

Can you add like a class constraint to the interface to infer the nullability

wintry crescent
#

wtf

wintry crescent
#

interface IEvent : class?
: object?

latent latch
#

I'm just thinking out loud here

wintry crescent
#

:(

wintry crescent
somber nacelle
#

T is not a type, T is a type parameter. you didn't tell it what type you are passing

#

if you cast the null to IEvent it will work because it knows that you are passing a null IEvent object

#

but if you just pass null then it doesn't know wtf you want

wintry crescent
somber nacelle
#

this just sounds like a whole lot of bullshit just to avoid unsubscribing your events like a sane person

wintry crescent
#

that's invoking the events

somber nacelle
#

then you need to specify a concrete type when invoking the method otherwise you're gonna have a bad time

steady bobcat
#

this is still a problem? just do your own event dispatcher

wintry crescent
heady iris
#

now you just have to unsubscribe that one...

#

๐Ÿ˜‰

#

actually, I do something like that in my code -- a "one shot" list of actions

wintry crescent
#

I solved that part

#

new problem:
inside the function
public static void AddListener<T>(Action<T> listener) where T : IListenable
I cannot do (Action<IListenable>) listener because it throws an error and rider suggests
listener as Action<IListenable> but that results in a null value

#

Like I'd assume that Action<T> where T : IListenable would be convertable to Action<IListenable> but clearly not...

heady iris
#

You generally can't cast Foo<Child> to Foo<Parent>, no

#

This is where you bump into covariance and contravariance..

#

although isn't that just a way to allow for implicit conversion?

somber nacelle
#

pretty sure you would need Action<in T> for that rather than just Action<T> to support contravariance

heady iris
wintry crescent
#

I tried Action<IListenable>)(Delegate)listener which makes no compiler errors but... well I'm glad it doesn't work

wintry crescent
heady iris
#

Just throw out the generic type parameter entirely, actually

wintry crescent
#

this is my dictionary:

protected static readonly Dictionary<Type, List<Action<IListenable>>> listeners = new();

and this is my function:

public static void AddListener<T>(Action<T> listener) where T : IListenable
{
    if (!listeners.ContainsKey(typeof(T)))
    {
        listeners.Add(typeof(T), new List<Action<IListenable>>());
    }
    listeners[typeof(T)].Add(listener);
}
heady iris
#

All you care about is having an IListenable

#

You'll lose the ability to compute typeof(T), but you can just figure that out via reflection

wintry crescent
#

and I really need the T because not all actions require T in the first place

#

some listeners ignore the T object entirely

#

can I change my Action<IListenable> in my array to Delegate?

#

would that work?

heady iris
#

But you aren't using the generic type parameter at all here (other than to get a Type object)

wintry crescent
heady iris
#

Does that even compile? You're storing the action in a List<Action<IListenable>>, but you're trying to put an Action<T> into it (where T derives from IListenable)

wintry crescent
#

yyyyyyy yes I have Action<IListenable> in that cast I'm just experimenting with Delegate now so I had to recreate that code back to send it to you lmao

#

sorry

heady iris
#

You can't really do this type-safely. Every kind of action demands something more specific than an IListenable

steady bobcat
#

I have an idea, have the subscribers de sub and stop this madness ๐Ÿ˜

heady iris
wintry crescent
#

XD

heady iris
#

you can throw that out entirely and retrieve a type from the action

#

Type type = action.Method.GetParameters()[0].ParameterType;

wintry crescent
#

if I remove T I have no way to get the type I need

heady iris
#

Yes you do. I just showed you how to get it.

wintry crescent
#

But it's not action<T> anymore

#

it's action

heady iris
#
 void Test(System.Action<IConfigurable> action)
        {
            Type type = action.Method.GetParameters()[0].ParameterType;
        }

wintry crescent
#

and I have 2 functions

#

one is Action<T> and one is Action (without the T)

heady iris
#

well, yes, you'll need separate code for a zero-argument function

wintry crescent
#

so I can't use that approach in the latter case

heady iris
#

those are fundamentally different from a one-argument function

wintry crescent
#

that's why I want to pass in T, so that there is no problem

#

and both functions can work in the same way

#

and when I change my function to take Action<IListenable> then I can't pass in functions that need an argument that derives from the IListenable

#

or can I

#

okay, the above would work, if I just passed in the Action<IListenable> but I'd rather have it as it is at the bottom

#

is THAT at least doable?

#

that's an example usecase of my event bus

heady iris
#

You can get a little further if you use a generic type parameter on your "add listener" method, but then you run into the exact same problem when you try to put into a list of Action<Parent>

#

The reverse is legal via contravariance

#
void Test(Action<SomeConfigurableThing> action)
{
}

void AddMe(IConfigurable arg)
{
}

void Test2()
{
    Test(AddMe);
}