#archived-code-general

1 messages ยท Page 310 of 1

swift falcon
#

thanks fam

untold siren
#

np

untold siren
#

if I'm using dictionaries for tutorial dialogue (string, int) is it more efficient to have one large dictionary or multiple small dictionaries? or negligible differences

spring creek
untold siren
#

gotcha, thank you

fervent arrow
#

Guys i dont actually know how to code so should i use visual scripting?

latent latch
#

visual scripting is more of a tool, but you need to know how coding works to really start developing with it

#

well, depends. Usually the ones who are creating visual scripts are those who have some idea of coding, making it easier for other developers to work with

untold siren
#

is there any instant suggestion on what to amend with my game? Raycasting works fine in the editor, however doesn't seem to be functioning correctly in my build (using mono, on Fedora Linux)

vagrant blade
untold siren
#
            var rayOrigin = activeCinemachineBrain.gameObject.GetComponent<Camera>()
                .ScreenPointToRay(Mouse.current.position.ReadValue());
            if (!Physics.Raycast(rayOrigin, out var hit, maxInteractDistance)) return;
            Debug.LogWarning("tag: " +hit.transform.tag);
            Debug.LogWarning("object name:" +hit.transform.gameObject);
            Debug.LogWarning("parent name:" +hit.transform.root.gameObject);
latent latch
#

could draw some debug rays to be sure it's correctly going into that direction

pulsar holly
#

I apologize if I already asked this, but how do I make clones do different things in unity?

untold siren
latent latch
untold siren
latent latch
#

right, or generate a mesh at the point it hits, but it may not be hitting is the issue too

rapid stump
#

Would this also work if the size is the size of the orthographic camera? Because it seems you think the canvas/map is being scaled, while it's actually just the camera that's scaling

untold siren
spring creek
untold siren
#

Fixed it, it was script execution order being a PITA.

rapid stump
#

Seeing as this didn't work, I might just figure out the percent increase of the deviation when the player scales and just correct the position manually with that percent increase when the player clicks XD Because this has been an issue for days, and it's getting OLDDDDD

#

Brute forcing is the only way I can think of solving this issue lol

#

Seeing as how when the player scales the camera up, the deviation of where the player clicks and where the destination was set grows, I can find that increase and offset the deviation

mild osprey
fervent arrow
fervent arrow
# rapid stump

Wouldnt you want to set it to the mouse position instead of "position?" (Honestly i have no idea how c# works, i just started with unity)

rapid stump
# fervent arrow Wouldnt you want to set it to the mouse position instead of "position?" (Honestl...

I wish it was that simple ๐Ÿ˜…
Sadly because my minimap is a lot bigger than the screen, I need to use a camera that feeds its frames to a raw image component that lets the player see the minimap. And since that's how the user is interacting with the minimap, through a UI image, instead of the minimap itself, I need to do calculations that I don't understand and are frustrating me, to figure out where exactly the player clicked on the minimap.
And as you can see. I am failing XD

rapid stump
# mild osprey I haven't worked a ton with the orthographic camera, but if I remember how it wo...

In the video, I use the logic you mentioned, at least I hope I'm using it correctly XD And you can see that the positions that are set are not only incorrect, but also the distances are not consistent.
Lets say the player clicks on square A1, and the destination is set at B16 (because the position is incorrect). Now the player clicks on square A2, you'd expect the destination to move to B17, but now it's C20, or whatever.

That's why I'm just beginning to give up and want to brute force this stupidity XD Because at least, even with the camera's scale deviating the offset, it's consistent.

latent latch
#

Still, I've not really had any issues with a ortho/world cam like this

rapid stump
#

An overlay? What do you mean.
In the past I tried using just a simple scroll rect with the map inside the scroll rect, and whatever is outside of the viewport is masked. But I ran into a major problem with centering on objects within the map, like the players ship

latent latch
#

because you can just use screen coordinates and then translate it to local coordinates on the map

#

I dont believe you even need to set a camera for localpointinrectangle if you're using overlay I think

#

I had some examples from before, but I'm feeling like you should try something easier first and see if you can do it that way

#

and ditch the scaling stuff for now

rapid stump
#

I'm still not sure what you mean by an overlay.
Do you just mean putting the map into my 2D CanvasGroup and using a mask to make the viewport smaller?

latent latch
#

Give the minimap a canvas that supports overlay. Make the pivot on the minimap similar to the world map (perferably something like the bottom left so you can only have positive values that dont pass through the origin).

#

if the max x and y values are say 40x and 40y locally, add that to the pivot of where your mini map is and you would have the world location from the minimap

#

or however you're keeping track of the minimap's world pivot

rapid stump
latent latch
#

sort order will only affect other overlay canvas

vapid lynx
#
        {
            float[,] treeNoise = Noise.GenerateTrees(size, size, 0.5f);
            float worldX = 0;
            float worldZ = 0;
            Matrix4x4[] matrices = new Matrix4x4[size*size];
            Vector3 meshPosition = mesh.transform.position;

            for (int y = 0; y < size; y++)
            {
                for (int x = 0; x < size; x++)
                {
                    float rngGrass = UnityEngine.Random.Range(0f, 0.5f);
                    worldX = meshPosition.x + x;
                    worldZ = meshPosition.z + y;

                    if (treeNoise[x, y] < rngGrass)
                    {
                        Vector3 positionGrass = new Vector3(x, heightMap[x, y], y);
                        matrices[x + 10 * y] = Matrix4x4.TRS(positionGrass, Quaternion.identity, new Vector3(1, 1, 1));
                        //GameObject grass = Instantiate(grassPrefab, new Vector3(worldX, heightMap[x, y], worldZ), Quaternion.identity);
                        //grass.transform.parent = grassChunk.transform;
                        
                    }
                }
            }

            Graphics.DrawMeshInstanced(grassPrefab.GetComponent<MeshFilter>().sharedMesh, 0, grassPrefab.GetComponent<MeshRenderer>().sharedMaterial, matrices);
        }

Im trying to instance many many instances of the grass procedurally using the DrawMeshInstanced bc I read that it helps make stuff not as laggy. Here is my grassPrefab.

however I get mesh is null error and stuff and dont really know how to fix it

rapid stump
# latent latch Only the phone mini map should be the user's screen right? It will always render...

I don't understand anymore. I think I'm just stupid at this point.
I figured out how to put my minimap graphics behind the base UI, the buttons, panels, etc. But my problem rn is that the top of the panel shows the minimap canvas, when that should be showing my 3D water. No clue how to fix that. And also I can't change the canvas's anchor/pivot. I'm guessing I need to make make an empty parent that is 10,000x10,000 which is anchored to the bottom left that holds the entirity of my minimap graphics.

untold siren
#

one of my switch statements isn't calling break when the conditions are met, extremely weird.

                    case { x: 0, y: > 0 }:
                        if (!TutorialController.IntroComplete() && TutorialController.nextKeyToPress != TutorialController.NextKeyPress.Forward) break;
                        TutorialController.TutorialChecks["Forward"] = true;
                        break;
#

the value is not being updated anywhere else in my script

#

seems to be working for the remainder of my switch statements, which is practically identical

#
                switch (movementInput)
                {
                    case { x: 0, y: > 0 }:
                        if (!TutorialController.IntroComplete() && TutorialController.nextKeyToPress != TutorialController.NextKeyPress.Forward) break;
                        TutorialController.TutorialChecks["Forward"] = true;
                        break;
                    case { x: 0, y: < 0 }:
                        if (!TutorialController.IntroComplete() && TutorialController.nextKeyToPress != TutorialController.NextKeyPress.Backwards) break;
                        TutorialController.TutorialChecks["Backwards"] = true;
                        break;
                    case { x: > 0, y: 0}:
                        if (!TutorialController.IntroComplete() && TutorialController.nextKeyToPress != TutorialController.NextKeyPress.Right) break;
                        TutorialController.TutorialChecks["Right"] = true;
                        break;
                    case { x: < 0, y: 0}:
                        if (!TutorialController.IntroComplete() && TutorialController.nextKeyToPress != TutorialController.NextKeyPress.Left) break;
                        TutorialController.TutorialChecks["Left"] = true;
                        break;
                }
#

any suggestions?

cosmic rain
untold siren
#

the breakpoint at the condition states that the break in the switch statement reaches the conditions to do so though, that's the thing

#

there is nowhere else in my project updating these values

cosmic rain
#

I feel like I don't understand what the actual issue is...

untold siren
untold siren
cosmic rain
untold siren
cosmic rain
#

Try grouping the conditions in brackets. It could be that the order of operations is not what you think it is

#

Specifically, wrap the comparison expression in brackets

untold siren
#
TutorialController.IntroComplete()

will be false. according to debugger anyways.

TutorialController.nextKeyToPress != TutorialController.NextKeyPress.Forward

This will actually be true tbh so that's only one condition met

cosmic rain
#

Share the IntroComplete code

untold siren
# cosmic rain Share the `IntroComplete` code
        public bool IntroComplete()
        {
            return TutorialChecks["IntroductionComplete"];
        }

dictionary is created in start:

            TutorialChecks = new Dictionary<string, bool>
            {
                { "IntroductionComplete", false},
                { "Forward", false },
                { "Backwards", false },
                { "Left", false },
                { "Right", false },
                { "Jump", false }
            };
cosmic rain
#

Using strings as a key is kind of unreliable. But I don't see any typo.๐Ÿค”

untold siren
#
       private IEnumerator InputPrompts()
        {
            // kill me
            ImageTweening.ClearTextAlpha(ref tutorialTextHint, false);
            yield return new WaitForSeconds(2f);
            tutorialTextHint.text = InputPromptTexts[0];
            promptW.SetActive(true);
            ImageTweening.AlphaPrompt(ref tutorialTextHint, ref keyPressW, ref keyPressWalt, true);
            TutorialChecks["IntroductionComplete"] = true;
            yield return new WaitUntil(() => TutorialChecks["Forward"]);

this is the point where Introduction complete is set to true, and then waits until forward - but it seems to be listening for this before those text prompts and the yield return new WaitUnitl() seems to happen

cosmic rain
#

Set the value in the IntroComplete to a local variable so that you can see the value retrieved from the dict during debugging

cosmic rain
#

Same in your switch case. Set each of the conditions to a local variable and see if they have the expected value.

untold siren
#

goofy ass

#

yeah, this is really odd

#

looks like both the conditions to break are met, it just doesn't break

mossy snow
#

? it's working as intended

untold siren
#

oh my god I am dumb

#

๐Ÿ’€๐Ÿ’€๐Ÿ’€๐Ÿ’€๐Ÿ’€๐Ÿ’€

#

its that 6am dev brainrot

cosmic rain
#

Yeah, the second condition is false

untold siren
#

apologies for the waste of time lmao

#

dev sprints are frying my mind rn

#

well, even with the ! removed its still not breaking :p

mossy snow
#

that expression is still false

fervent furnace
#

false&&dont care =false

untold siren
#

realised I need to set the != to ==

mossy snow
#

that would still make no sense. It looks a lot like you're pressing the forward button on the forward prompt, and then are shocked that the forward button tutorial is being set as complete

untold siren
#

got it working e_sunglasses

#
if (!TutorialController.IntroComplete() && TutorialController.nextKeyToPress == TutorialController.NextKeyPress.Forward) break;

this was the statement that I needed

mossy snow
#

I don't think so, might want to check again. Does x: 0, y > 0 represent moving forward?

untold siren
#

Finally working as intended though

mossy snow
#

If it is, TutorialController.NextKeyPress has been designed terribly. Atm you can only complete the forward tutorial if you moved forward and the next expected keypress is NOT forward

untold siren
mossy snow
#

๐Ÿคทโ€โ™‚๏ธ if you're happy with it, great. But principle of least astonishment applies here, and my read is that TutorialController.NextKeyPress expression is so that you don't trip the other tutorials until prompted. Apparently it does not, so I would rename it at a minimum

untold siren
#
                switch (movementInput)
                {
                    case { x: 0, y: > 0 }:
                        if (!TutorialController.IntroComplete() && TutorialController.nextKeyToPress == TutorialController.NextKeyPress.Forward) break;
                        TutorialController.TutorialChecks["Forward"] = true;
                        break;
                    case { x: 0, y: < 0 }:
                        if (!TutorialController.IntroComplete() && TutorialController.nextKeyToPress != TutorialController.NextKeyPress.Backwards) break;
                        TutorialController.TutorialChecks["Backwards"] = true;
                        break;
                    case { x: > 0, y: 0}:
                        if (!TutorialController.IntroComplete() && TutorialController.nextKeyToPress != TutorialController.NextKeyPress.Right) break;
                        TutorialController.TutorialChecks["Right"] = true;
                        break;
                    case { x: < 0, y: 0}:
                        if (!TutorialController.IntroComplete() && TutorialController.nextKeyToPress != TutorialController.NextKeyPress.Left) break;
                        TutorialController.TutorialChecks["Left"] = true;
                        break;
                }

seeing as movement input is built like this, it stands out a tad since it's not consistent

mossy snow
#

no, I'm saying your NextKeyPress makes no logic sense as-is. If I have a tutorial controller that prompts "Press W to move forward" and it had a NextKeyPress property, my expectation is that NextKeyPress is W. But your logic will only mark the forward tutorial as complete if NextKeyPress is literally anything but W

untold siren
#

so its basically waiting for the introduction to be complete - and since by default the enum of nextKeyToPress will be forward, if those two conditions are true then it'll break out

#

but if the Introdution is complete, and the key is W - then it'll update the value and confirm that Forward / W has been pressed

lapis badger
#

@naive swallow

#

I found when it happens

#

If I change any script while playing the error occurs

#

even if I just add a comment

#

ping me back when you have some spare time

crisp comet
#

Hello all. Is there a way to make unity compile scripts faster? My unity just recently started taking ages to compile scripts for even the slightest changes in my code, and I have to wait twice the time coz I'm using ParrelSync. Any help?

#

I've also tried the fast script from the package manager but I didn't notice any change

cosmic rain
crisp comet
spring flame
spring flame
#

I mean many game design materials tell that people generally don't like, don't play and skip tutorials. That implicit unlock conditions are often annoying (e.g. having to click all of WASD to complete a movement step) is often annoying and that people generally opt out of tutorials if the game controls and control scheme is "universal", i.e. WASD + Space etc

untold siren
#

it's just part of my submission criteria unfortunately ๐Ÿ˜…

#

since its a uni project

spring flame
#

and often just a simple box with "< PREV | NEXT >" with information displayed is bettern than "milestones"

#

ah yes, if it's uni project then that's unfortunate

untold siren
#

I'll add an option to skip the basic controls either way

#

thanks for the input though, it is appreciated

astral axle
#

!code

tawny elkBOT
astral axle
#

I just stumbled into the weirdes issue I've encoutered ever working in Unity. An object is literarily losing its reference and getting it again during a single frame. https://gdl.space/utatapajow.cs

Note: This happens if the scene is reloaded. Not otherwise. The objects/scripts themselves are not set to "DoNotDestroyOnLoad". Ever scene reload should reset everything from start. Thats the intention anyway.

Anyone have an idea what is going on here?

simple egret
astral axle
#

THat is true. GIve me a sec

#

How is this even remotely possible. I'm not manipulating the object otherwise.

simple egret
#

There's one frame, 1616 vs. 1617

#

Where do you call NextScreen()?

astral axle
#

Its being called on a state change

#

hm you got me on to something now

#

Nope that was not it

#

@simple egret its being called on an event. I've checked and the event is fired exactly once

#

Seeing it only happens after the scene is reloaded it must be something happening there?

simple egret
#

When you execute SceneManager.LoadScene() it doesn't happen right away, so if you have code like this:

Debug.Log("a");
SceneManager.LoadScene("bla bla");
Debug.Log("b");

The scene will not be loaded when the second debug log is executed. Scene loads happens at the end of frame

#

If you need to execute code as soon as the scene is loaded, subscribe to SceneManager.sceneLoaded event and put your code in there

astral axle
#

This code is is executed way past scene loaded finished though

gray mural
#

Or use a coroutine to check for the scene being loaded

private IEnumerator LoadScene(string name)
{
    SceneManager.LoadScene(name);

    yield return new WaitUntil(() => SceneManager.GetActiveScene().name == name);
}
astral axle
#

it is loaded and interactible. Only when the user is trying to press the screen this happens. And it only happens if the scene has been reloaded. Not on first run.

simple egret
#

Then your object is just getting destroyed by something else. If you have a script on that object, implement OnDestroy() and put a log in it to see on which frame it gets destroyed

#

With the right settings a Particle System can destroy the object it's on when it finished emitting, so check that too if you have a PS on the vanishing object

#

"Stop Action" field set to "Destroy"

astral axle
#

OnDestroy is only called when scene reloads. Upon/after OnSceneLoaded the object holding screenObject is not being destroyed. I can clearly see it in inspector, the screenObject is in fact showing the current screen. For whatever reason the reference is just gone that split frame.

leaden ice
#

maybe share the rest of the code

#

and the full error

simple egret
#

Well if that object is being destroyed, but the script that holds a reference to it is not (it has DontDestroyOnLoad) then of course it'll lose the reference, and you'll have to find it back

#

Both objects need to be DDOL for references between them to be kept

astral axle
#

None of the scripts has DDOL. They are destroyed and supposed to be recreated from scratch onsceneload. Breakpoints show they indeed are there onenable once the scene has reloaded. As the log shows, it is there. Then its not. Then its there.

#

The scene should be fully reloaded. No states are saved.

naive swallow
lapis badger
#

Alright

#

thanks mate

astral axle
#

@simple egret the only thing I can think of is that the call to reload the scene is done in a Thread(). In there I call UnityMainThreadDispatcher to change scene (which works fine). Either way, object is there, not destroyed -> MissingReferenceException -> fine again.

#

The thread in question is a simple HttpListener (and a Singleton) but holds no references to anything except the SceneController.

I find it particularly interesting that the inspector shows the object all the time.

tardy crypt
#

is it bad practice to represent an initially unknown value in a float by initializing that float to float.NaN?

simple egret
#

Not at all, especially when you have the float.IsNaN(f) method to check for it

#

Do note that float.NaN != float.NaN!!!

#

So don't check whether it's NaN with equality operators

astral axle
#

I'm at at total loss here

dry sleet
#

Hey guys,
Is it possible to have lfs and yamlmerge together on .unity ?

ashen yoke
#

dont think so, lfs doesnt diff, it just checks hash afaik

dry sleet
#

If I have bigger than 100MB scene what should I do about that ? I should forget using yamlmerge on that ?

ashen yoke
#

the only downside is more stress on git, if youre ok with it then its fine

astral axle
#

LOL not even using SceneManager to reload directly makes a difference. This has to be a Unity bug with loading scenes.

dry sleet
ashen yoke
#

no because it has to diff larger files

#

yamlmerge only helps in automating merge for unity yaml, afaik

#

git still will diff the files

dry sleet
#

Thanks

exotic aspen
#

Howdy folks. How concerned should I be with garbage collection of orphaned stack-based objects? My target is mobile, so I'm attempting to be sensitive of garbage collection out of the gate, but am unsure if this will actually prove problematic in the long run. For example, I have numerous functions that instantiate new vectors to aid with computation for placement on a 2D grid. In one frame tick I might evaluate a 64x64 tile grid and so 4096 times a function will have declare a Vector2Int offset = new Vector2Int(someTile.x + propOffset, someTile.y + propOffset); and then use it in a calculation. I am guessing that all those objects will at some point get recycled? Or is the compiler smart enough to persist that memory forever due to its repeated use, thus eliminating the need for GC?

hexed pecan
#

Or before it

leaden ice
exotic aspen
#

Oh, good to know.

leaden ice
#

unelss they're fields on a class

#

Vector2Int is a value type (struct)

#

it doesn't get allocated on the heap

exotic aspen
#

My Lists incur a rather hefty GC penalty when using Linq I've noticed. So I've been trying to be more judicious on those. Particularly with the results of circle casts and whatnot.

leaden ice
#

yes Linq is a GC trap

#

avoid it for performance critical pieces

#

use regular for loops

fervent furnace
exotic aspen
#

I appreciate the insight.

last raven
#

is it possible to inherit from something other than monobehaviour if I just want to attach some data to object without behaviour?

#

I tried Component/Behaviour directly but they don't seem to work for non-built in components

leaden ice
#

If you want to attach your script to a GameObject, it must be a MonoBehaviour

last raven
#

yeah I just thought it's overkill since I don't want any methods

leaden ice
#

I don't see what the problem with that is.

last raven
#

I just want pure data

leaden ice
#

Then don't add any methods to it

last raven
#

that'd still make it check for existence of the methods, wouldn't it?

#

when calling updates/etc.

leaden ice
#

Sounds like you're engaging in some kind of speculative premature optimization

#

don't waste your time

last raven
#

so that information is cached?

leaden ice
#

It is not going to check if there is an update method every frame on every object

#

if that's what you're asking

rigid island
#

if its present but blank, it does call it

last raven
#

alright

mellow hill
# last raven is it possible to inherit from something other than monobehaviour if I just want...

You have a few options, you could just create a Monobehaviour and not use the methods (this makes things easier rather than fighting against Unity's architecture but you have some overhead). You could also create a POCO (Plain Old C# Object) and have your the bulk of your system in their and call it from Monobehaviour (So the Monobehaviour becomes more of a wrapper/entry point allowing you to attach the code to a game object/entity). You could also do the same thing with a ScriptableObjects and use ScriptableObject to write the core of your system and then call it from a Monobehaviour when you want to attach it to a game object. I personally prefer the second and third options as not everything needs to extend Monobehaviour but you need them if you want to attach logic to components

final junco
#

does anyone know what could be causing this to happen? The cube only goes trough the wall at a specific angle and only in this part and i have no idea why that is, i really dont understand

#

as you can see here in the second video if i do this in a different part it doesnt go through

#

its only at that metalic part that it does and it doesnt make sense because they both have a collider

rigid island
#

depends how ur moving the held object

final junco
#

the pre made collider of pro builder blocks

#

the way im moving the collider is by parenting the held object to an object called holdarea

#

heldObjRB.transform.parent = holdArea;

#

like this

leaden ice
leaden ice
final junco
final junco
#

only the heldobj

leaden ice
#

Ok the parenting isn't really doing anything here

#

except maybe breaking things

#

It's your heldObjRB.AddForce(moveDirection * pickupForce); that is doing the moving

final junco
#

no the parenting does kinda move the object, it makes it so it stays more in place, i can show the difference between having it parented and not having it parented

leaden ice
#

moving it via parenting is very bad

#

any movement from that will ignore physics entirely

#

you want to only move your Rigidbodies via the physics engine

final junco
#

hum yeah thats a problem

leaden ice
#

or you get things going through walls

final junco
#

but i really dont like the way the movement is being applyed without it

leaden ice
#

then fix that

#

AddForce is not the tool

final junco
#

like here

#

it just goes off the holdarea

rigid island
#

def switch it to .velocity

leaden ice
#

Yes, set velocity directly

final junco
#

heldObjRB.velocity = moveDirection * pickupForce;

leaden ice
#

you can do it like:

void FixedUpdate() {
  Vector3 diff = holdArea.position - heldRb.position;
  heldRb.velocity = diff / Time.fixedDeltaTime;
}```
Then it will always move exactly to the desired position each physics frame
rigid island
# final junco

on my pickup script the only thing parented to player is the "HoldZone" which just track the ideal position which rigidbody should reach

final junco
#

like this?

final junco
#

this is similar to a solution i had tried one time

#

the only problem i have with it is it makes the object like shake a bit but is certainly

rigid island
final junco
#

you can kinda see the box is trying to go towards me

leaden ice
rigid island
final junco
#

no

leaden ice
#

turn on interpolation

final junco
#

alright

#

still shakes a little but it certainly isnt as bad

rigid island
#

I use this method, not sure if its worse or better but its been good for me . I could be doing something wrong though ๐Ÿ˜›

    private void FixedUpdate()
    {
        if (currentObj)
        {
            Vector3 targetDir = pickupTarget.position - currentObj.position;
            float dirMagnetude = targetDir.magnitude;
            currentObj.velocity = amount * dirMagnetude * targetDir;
        }
    }```
leaden ice
#

How does your player motion work?

leaden ice
#

You're multiplying the diff vector by its own magnitude

#

which squares the length

rigid island
leaden ice
#

if amount is 50 then it's equivalent to dividing by Time.fixedDeltaTime

final junco
#

copying the source movement

#

made by a guy on github

leaden ice
final junco
#

i understand parts of it but not interelly

#

ill see

#

it doesnt use fixedupdate

rigid island
#

oh yeah just realized I have same issue going forward, but not backwards

final junco
rigid island
#

yeah must be the character controller being moved in Update maybe

#

while box is moving in fixed

leaden ice
#

yeah that's the reason - basically mismatch in cadence of motion

#

that's the problem with Update based movement in a physics game

final junco
# rigid island

and yeah in yours it is also going off the holdarea in backwards, but you dont notice it as much since it isnt going towards you

rigid island
#

gotta take ur wins where you can ๐Ÿ˜ฆ

final junco
#

maybe i should just make my own movement script but after my attempt at making this holdObject script im kinda terrified of that idea xD

rigid island
#

dynamic rigidbody based controllers are a pain

final junco
#

what could I do here to make it so if the value of diff is too high it sets it to a certain max amount?

#

because a problem im having now is that if im putting the block against the wall it eventually just flies off

#

or goes thought the wall

gray mural
final junco
#

thank you

astral axle
dusk apex
#

And what script.

dusk apex
thin hollow
#

Where can I read on some available solutions to implement gameplay modifiers? For instance, if I have a health component with int health value in it, and I want to make status effect that temporarily increases player's health, and another that cuts health in half, what are the common solutions to make system that could add modifiers to that int variable in the game?

I do suppose it would be saner to leave the original variable value untouched and only include modificators when you try to access it, rather than the modificators directly changing the value on being added\removed, right?

ancient magnet
#

Hey, my json is still empty after saving, what am I doing wrong?

    void SavePouchesToJson(List<(Vector3 localPosition, Quaternion localRotation, FFSPlateCarrierPouch.PouchType type)> pouchInfoList)
    {
        // Serialize pouch info list to JSON format
        string json = JsonUtility.ToJson(pouchInfoList);
        Debug.Log("Serialized JSON: " + json);

        // Define the file path
        string filePath = Application.persistentDataPath + "/pouches.json";

        // Write JSON data to the file
        File.WriteAllText(filePath, json);

        // Debug log saved pouches to file
        Debug.Log("Saved pouches to file: " + filePath);
    }
somber nacelle
#

well for starters, JsonUtility doesn't like an array or list as the root object when serializing like that. and also i'm not even sure if it can serialize tuples

ancient magnet
rigid island
#

oh yeah just noticed that

latent latch
#

I doubt you can serialize tuples since you can't on the editor in the first place

#

make it a struct

rigid island
#

make a nice struct/class

#

a list of tuple is def not something unity will enjoy lol

fervent furnace
#

if the buff affects "base status", i would prefer store them separately e.g. add 2 hp in 5s, 4 hp in 10s, 8hp in 15s, and you can have a priority to consume the additional hp that going to be timed out first, so when getting damage, you first consume from the 2hp.
for the others buffs that are plugged into some formula of calculating speed/attack etc, just store timer and "effect"

latent latch
# thin hollow Where can I read on some available solutions to implement gameplay modifiers? Fo...

What I like to do is treat my original values as modifiers too, but as a flat modifier. Beyond flat I also have % increase and some other basic value modifiers, but technically everytime I get a new modifier I do a full recalc with all modifiers and keep track as to what had applied them so when I remove them I know for sure it won't remove my base modifier. Current Health/Current Mana and anything that seems like a resource would not be affected by modifiers, only variables which have a max, so stuff like MaxHealth.

lapis cairn
#

Hi I am making a horror game and each room is a scene I have code that saves the scene name to a json file and that works fine on my menu I have a button to load the game how do I get the data from the json to load the scene name?

leaden ice
lapis cairn
leaden ice
#

however - between scenes it shouldn't get to that point

#

json is only for saving to and reading from a saved game file

#

between scenes the data should just live in an object in memory

lapis cairn
#

the code I tried to make is this: public void LoadLastScene()
{
string jsonFilePath = Application.dataPath + "/sceneName.json";

// Check if the file exists
if (System.IO.File.Exists(jsonFilePath))
{
    // Read JSON file
    string jsonData = System.IO.File.ReadAllText(jsonFilePath);
    Debug.Log("JSON data: " + jsonData); // Log JSON data

    try
    {
        // Parse JSON data
        SceneData sceneData = JsonUtility.FromJson<SceneData>(jsonData);
        Debug.Log("Scene name from JSON: " + sceneData.sceneName); // Log scene name

        // Access scene name
        string sceneName = sceneData.sceneName;

        // Load scene
        SceneManager.LoadScene(sceneName);
    }
    catch (System.Exception e)
    {
        Debug.LogError("Error loading scene from JSON: " + e.Message);
    }
}
else
{
    Debug.LogWarning("sceneName.json not found. No scene will be loaded.");
}

}

[System.Serializable]
public class SceneData
{
public string sceneName;
}

#

but it won't load the scene even though the name is in the json file

weary swift
#

Yo ! I have a question, sometimes I want to add null check or some debug messages into my code but I don't because it will only be useful during development time and not into the final build. I heard this wasn't a good idea and I saw something that could be useful. Is using conditional compilation a good idea for these type of stuff, so that there are only compiled while developing and not in the final build ? For example this (this is a really simple example, but the idea is the same) :

#if UNITY_EDITOR
      if (something == null)
      {
          Debug.Log("blabla");
      }
#endif
lapis cairn
#

it says the file does not exsit

#

but I am looking at it so it has to

leaden ice
lapis cairn
#

but it does this is what is says in it: {"sceneName":"Hallway2 Office Exit"}

leaden ice
#

you're jumping ahead

#

your code isn't even able to read the file

leaden ice
#

so what's inside the file is irrelevant

lapis cairn
#

oh ok

knotty sun
#

your path string is incorrect

lapis cairn
#

it's in appdata locallow

weary swift
knotty sun
lapis cairn
#

so how do I get it to read and then load the scene?

lapis cairn
latent latch
lapis cairn
#

what path is it then?

weary swift
#

I added something in my message, I forgot to precise that I don't want this code in the final build but only when i'm developing

knotty sun
weary swift
lapis cairn
#

ok thank you

knotty sun
#

you wrote the file so you should know where to

leaden ice
#

Application.persistentDataPath is the correct path for save files

latent latch
lapis cairn
#

and if i add that it should work

fervent furnace
#

using preprocessor directives (the #if you written) to differentiate different build target is common.

leaden ice
#

we don't know what that is

#

only you do

lapis cairn
#

thank you so much

#

I will do that now

weary swift
#

Or if it is overkill

latent latch
#

you usually don't want debug.log in your builds, so what you're doing is technically the correct way assuming you dont want to clean up your project between builds

#

or any error checking in general (usually project settings can remove it all for you too)

weary swift
#

Oh ok, I didn't know about this. So in theory this is the right way to go if I don't want to clean it myself ?

latent latch
#

right, the compiler will know to remove it when you build for your platform

#

also useful for when you are building multiple different platforms because sometimes you'll need different methods of serialization

weary swift
#

Yes I saw about this, this is cool

#

I will learn about the project settings like you said, and I'll probably use conditional compilation, thanks for the infos !

lean sail
#

This makes no sense

weak venture
#

is there an efficient way to do like filtered gravity? Like I want to be able to make the player a target of minor gravity for certain collectibles. I dont want to do a distance calc for every collectible and doing a circle cast every frame also seems maybe too wasteful? I can think of a couple ways to impl but wondering if someone has recommendation on good way

#

would it be preferable to set up the math such that everything is pulled but the magnitude of the pull is negligible beyond a certain distance?

#

it seems like im gonna need a distance value regardless if its gonna act like real gravity but maybe some estimation would be good enough and much cheaper

lean sail
weak venture
#

sounds good, thanks

ionic stone
#

Im trying to use sprite stacking in unity. As of right now i have the parts attached to a game object which is a child of the main object, the car. From what i know the only way to get that 3d rotation is by rotating each part as opposed to the game object. I have difficulties here, since the car(main object) rotates and changes its z rotation value. Am i supposed to counteract the rotation for the parts and somehow rotate them locally? Been trying to figure this out for a bit too long.

vapid lynx
#
        {
            float[,] treeNoise = Noise.GenerateTrees(size, size, 0.5f);
            float worldX = 0;
            float worldZ = 0;
            Vector3 meshPosition = mesh.transform.position;

            for (int y = 0; y < size; y++)
            {
                for (int x = 0; x < size; x++)
                {
                    float rngGrass = UnityEngine.Random.Range(0f, 0.5f);
                    worldX = meshPosition.x + x;
                    worldZ = meshPosition.z + y;

                    if (treeNoise[x, y] < rngGrass)
                    {
                        GameObject grass = Instantiate(grassPrefab, new Vector3(worldX, heightMap[x, y], worldZ), Quaternion.identity);
                        grass.transform.parent = grassChunk.transform;
                        
                    }
                }
            }
        }```
#

how do i instantiate the grasses more efficiently ๐Ÿ˜ญ

#

rn the prefab is just three planes intersecting

#

with a shadergraph

cosmic rain
vapid lynx
#

how else do i spawn it

cosmic rain
#

Why do you need to spawn it? Is it for procedural generation at runtime?

cosmic rain
#

And I guess you're not using the unity terrain?

vapid lynx
#

idk how to use it with my terrain mesh

cosmic rain
#

Okay. Then the answer is there's: no other way to instantiate it.

#

Is it causing a performance issue?

vapid lynx
#

a lot

cosmic rain
#

During instantiation?

vapid lynx
#

my gpu is running at like 60 ms or sum

vapid lynx
cosmic rain
#

GPU isn't related to instantiation.

vapid lynx
#

and im p sure im not instantiating grass for the same chunk every frame

cosmic rain
#

It's rendering that's the issue.

vapid lynx
#

i used a shader graph

#

to make like the grass sway

#

could that cause it?

cosmic rain
#

Before I proceed, did you actually profile and confirm that it's a GPU bottleneck?

vapid lynx
#

yeah

cosmic rain
#

That doesn't confirm anything. What is taking the CPU time in the hierarchy view?

vapid lynx
#

wait

#

how do i access the hiearchy view

#

in the profiler

cosmic rain
#

You'd need to go over the profiler manual and learn how to work with it, but since I'm in a good mood:

  • select a frame of interest by clicking in the CPU graph.
  • your profiler is already in a hierarchy mode, so it should show data right away in the bottom part of the window.
  • sort by "Time" and expand the topmost category as long as the element type has a big enough value(>1)
#

From what I can see, it looks like the editor loop is taking a lot, so perhaps there's no real issue here.

vapid lynx
cosmic rain
#

And you completely ignored the last step

#

Well, half of it

#

But yeah, it looks like editor loop is the problem here. Just to confirm: are you recording it during play mode?

vapid lynx
cosmic rain
#

Since most of it is being the editor loop, this test is not very reliable.
Can you take a screenshot of the whole editor window?

vapid lynx
mild osprey
#

I've been working on an implementation of the a* pathfinding algorithm, and it's been working as expected for the most part. I've configured it to avoid being near walls by putting negative weights near them, and positive weights in the center of the room. This works fine, but with anything bigger than a 1x1x1 cube, it starts running into issues with clipping, especially with dynamic objects (eg. doors). I've added a rigidbody to the mesh so that it should push itself away from objects it comes in contact with, but I think because of the forces that move it, it still clips through. Is there an approach I could take to avoid having the collisions happening in the first place or some other way of avoiding this behavior.

cosmic rain
# vapid lynx

Okay, now expand the player loop as I explained in the last step.

vapid lynx
cosmic rain
# vapid lynx

Can you stop switching between the GPU and CPU modules? I mentioned that you want to look at the CPU graph first.

vapid lynx
cosmic rain
#

Expand more

vapid lynx
#

wait i just want to ask a quick quesiton

#

there shoudlnt be another camera right

cosmic rain
#

Do you have another camera in the scene?

vapid lynx
#

i shoudnt?

cosmic rain
#

Well, it definitely renders another camera, so there probably is

vapid lynx
#

could that possibly be the reason

#

i think the grass model i imported from blender might have it

cosmic rain
#

Why won't you expand in order? There's "context submit" that has higher CPU time and you skipped it?

cosmic rain
#

Or just pause the game and search in the scene hierarchy

vapid lynx
#

like a while back

#

like unactive

cosmic rain
#

Delete it.

#

Why does it need to have a camera in the first place?

vapid lynx
#

It doesnt i just imported it from blender and forgot to delete the camera there

cosmic rain
#

It could or could not be related to the camera in the profiler, but it would definitely make it harder to look for the actual culprit.

#

One thing before optimizing your game: make sure your assets are standardized and optimized, and don't have issues like unneeded objects.

vapid lynx
tall scroll
#

unity, typically, is single-threaded right?

chilly surge
#

Not sure what you mean by "typically," but most Unity APIs can only be run on the main thread so most code are written single threaded sure. You can write multi threaded code in Unity though and lots of games make use of that.

cosmic rain
# vapid lynx

This could potentially indicate a GPU bottleneck.
It seems to be waiting for the render jobs to complete. You'll need to look at the other threads that it's waiting for.

tall scroll
#

typically as in if you don't call/run multi-threaded code as a developer

#

point is, is this code safe if I'm not as a developer implementing multi-threading (at this time)

public sealed class Singleton
{
    private static Singleton instance = null;

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}```
chilly surge
#

If you are accessing the singleton instance on multiple threads then yeah that can potentially get into issues like race conditions, but that's not limited to this piece of code in particular. Anything that can be mutated by multiple threads have potentials for causing hard to debug issues like race conditions.

tall scroll
#

yeah

#

but if I'm not running multiple threads, just using the unity API from a fairly intermediate level it should be fine right?

chilly surge
#

Sure.

tall scroll
#

XD

#

I'll take it lol

#

"Sure." beats anything discord.js so imma take it and run

chilly surge
#

Btw you can improve your code a bit by doing:

public static Singleton Instance => instance ??= new Singleton();
tall scroll
#

valid, I'll be on my way XD

oak panther
chilly surge
vapid lynx
tall scroll
#

ok I kinda knew the second but the first blew my mind

oak panther
#

I got it to work, I forgot to add it to the start function

#

new issue, why does it stager when i look around? ๐Ÿค”

prime sinew
prime sinew
#

what are you looking around with? mouse? keyboard? @oak panther

tardy crypt
#

My game has a Calendar that stores CalendarEvents in a sorted list to execute them as appropriate as time progresses. CalendarEvent holds an Action to call a function when the event is executed. I need the function of the Action to use a variable set of parameters. For example, in some instances, I need the calendar event to be able to call a function of signature Function(), in others, a function of signature Function(float), and so on. I'm looking for the cleanest and least annoying approach. Some possible solutions:

  1. CalendarEvent stores Action<EventParams> , with EventParams being a base class to something that I downcast. in each appropriate function. Downside: runtime, rather than compile-time type checking.
  2. CalendarEvent is itself a base class that stores an Action<T> where T is defined based on a generic parameter of the derived type. Downside: annoying to define so many classes.
  3. Pass a lambda with no parameters in to the CalendarEvent constructor to define the Action and rely on closures to define the parameter type. So, e.g., CalendarEvents.action = () => {TypeINeed.dosomething();}. Downside: can't access the closed-over variable once the action is set. Closures have funky behavior.
  4. Define no-parameter functions that access whatever state is necessary and put those into the Action. Downside: possible spaghetti code.

Any other approaches that are better than those above? If not, which is the best approach? Thanks!

prime sinew
#

please show me where if it's in there?

oak panther
prime sinew
#

please check?

oak panther
# prime sinew I might be mistaken, but I don't see mouse input in that code

public class PlayerCamera : MonoBehaviour
{
    public float senseX;
    public float senseY;

    public Transform orientation;

    float rotationX;
    float rotationY;

    private void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    private void Update()
    {
        float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * senseX;
        float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * senseY;

        rotationY += mouseX;
        rotationX -= mouseY;
        rotationX = Mathf.Clamp(rotationX, -90f, 90f);

        transform.rotation = Quaternion.Euler(rotationX, rotationY, 0);
        orientation.rotation = Quaternion.Euler(0, rotationY, 0);
    }
}
#

sorry my head slightly hurts

prime sinew
#

remove the Time.deltaTime from mouseX and mouseY

#

that's a common mistake. Even Brackeys got it wrong

oak panther
#

will note

#

that is so much better thank you

#

I have a violent idea

balmy hawk
#

I found this really good character controller and I'm trying to add a sword animation to it when ever you hit left click it plays the animation. But, when ever I try and do it, it just flashes for a second and only really plays when your jumping? Can anyone help?

oak panther
#

I never really got vectory3, I know that you have x, y, z but the code I have completely changes how It is being used.

moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;

move direction was given vector 3 and orientation is given Transform, basically what I'm asking is what axis is being used by what. Or what is is this line doing?

cosmic rain
# vapid lynx might be dumb but how do i do that

You can click the "Main thread" drop down to select different threads, but in this case it's better to use the Timeline mode to see all the threads. The one you're interested in is probably the "Job" threads.

keen lantern
#

Im currently developing a building system for my project and Ive been exploring methods to align the connection point game objects' positions with those of other game objects connection points, particularly for connecting two blocks side by side. Each block has six connection point game objects, one for each side of the block.

However, my current approaches are causing bugs and aren't giving the results Im going for. Im looking for advice on more effective methods to achieve this. Any ideas?

#

Let me know if you cant visualize what I tried to explain.

#

For what its worth, Im currently getting the parent of the connection point gameobject, calculating the offset between the connection point and parent, and the moving the connection point to match the position of the connection point of a different block that Im trying to build on, and then moving the parent to the connection point that moved using the offset.

vapid lynx
cosmic rain
vapid lynx
#

oh wait

cosmic rain
#

A lot of objects to be culled.

vapid lynx
#

like repeadly making instances

cosmic rain
#

Repeatedly making instances in itself is not a problem. Having a lot of objects with renderers is a problem.

#

Especially if there's no batching going on.

#

It's hard to say anything beyond that without seeing more details, like the amount of draw calls/batches and your scene setup

vapid lynx
#

I just make multiple instances of the grass prefab for each chunk once they are created

cosmic rain
#

That doesn't really explain much. At this point we don't even know if grass is the culprit.

vapid lynx
#

it def is because its only when i add the grass

#

it gets really laggy

#

else everything runs smoothly

cosmic rain
#

Well, then you might want to think about batching or gpu instancing it.

vapid lynx
#

thanks

cosmic rain
#

Then there are some other things:

  • seeing how shadows seem to be one of the issues, consider disabling the shadows casting from grass
  • consider changing the render distance of the grass
  • consider the shadows options, like cascades and shadow drawing distance
  • etc...
vapid lynx
#

ok the thing is i did disable shadows from grass

#

wait js wnana make sure

#

in the player settings, i have to check the static batching

#

right

tardy crypt
#

following up on my earlier question... I have a Calendar that triggers CalendarEvents. Triggering a CalendarEvent calls a member of type Action. I want to give the option for parameters for these events. I'm thinking of just giving CalendarEvent an ActionParameter member, so the method being called is of type Action<ActionParameter>. Then I can derive from ActionParameter as appropriate. In each event method, I will just do runtime type checking, e.g., if(!(param is typeINeed) throw new InvalidOperationException("wrong parameter type passed"); or something. Is this runtime type checking a bad idea? Any better alternatives?

cosmic rain
# vapid lynx in the player settings, i have to check the static batching

Assuming you're using the built-in rp, yes, but that wouldn't work for objects you instantiate at runtime. Nor do you want a lot of grass to be static batched anyway. Ideally you want it to be gpu instanced.

If the grass had shadows disabled, then it must be something else that is causing it. Hard to say without seeing the rendering stats.

vapid lynx
#

wait i think i fixed the problem

lean sail
# tardy crypt following up on my earlier question... I have a `Calendar` that triggers `Calend...

Not really specific to delegates, but once you start needing to check the type of every derived class, itll become really annoying and can likely be redesigned to not need this. Also it wouldnt make much sense to have a class be notified of an event, but then immediately throw an error because the type was wrong. It shouldnt have subscribed in first place.
How much can these parameters really differ?

mossy snow
tardy crypt
#

I'm not describing this correctly. Let me illustrate with some code:

class Calendar {
  SortedList<CalendarEvent> _events...;
  void MoveCalendarForward(TimeSpan amount) 
  {
    //foreach CalendarEvent e in _events within time span:
    e.Execute();
  }
}

class CalendarEvent {
  Action<EventParam> functionToRun;
  EventParam _param;
  void Execute() {
    functionToRun?.Invoke(_param);
  }
  CalendarEvent(Action<EventPara> a, EventParam p) {
    functionToRun = a;
    _param = p;
  }
}

abstract class EventParam { }

class Param1 : EventParam { int data; }
class Param2 : EventParam { string name; }

Then I can define CalendarEvents like this:

CalendarEvent newEvent = new CalendarEvent(Function1, new Param1(int1));
...
void Function1(EventParam p) { 
  //runtime type check
  //do something interesting with p
}

and then in some other part of my code:

CalendarEvent otherEvent = new CalendarEvent(Function2, new Param2(float1));
...
void Function2(EventParam p) {
  //runtime type check
  //do something interesting with p
}
mossy snow
#

this looks good to me, aside from EventParam which is a useless class that adds nothing

tardy crypt
#

how else would i pass in something to the function?

lean sail
mossy snow
#

option A) CalendarEvent becomes a generic class that implements an interface
option B) CalendarEvents implementations are concrete subclasses created to do something specific

#

A is closer to your current implementation, but B would be my preference for cleaner code

chilly surge
tardy crypt
#

yes, it would theoretically be possible to do something like assigning () => {capturedvariable.dosomethinginteresting} but I prefer making the information about the events explicit in this case

tardy crypt
chilly surge
#

Then you can still do it in a way that doesn't involve type checking parameters at runtime.

#

Instead of subclassing the parameter, you subclass the event.

tardy crypt
#

yeah that is probably the most straightforward approach

chilly surge
#

By subclassing the event it's also just basically reinventing lambda capture, but eh if that's more of your style then sure go for it.

tardy crypt
#

i went kind of crazy with lambdas and captures in an earlier project but they have their downsides. specifically, it's much harder to remove anonymous functions from a collection, it's much harder (impossible?) to obtain information about the captured variables...

#

and also captures have weird scoping rules

chilly surge
#

I disagree, because if you look at what happens to lambda capture, it just gets turned into a class with captured variables, so that's basically exactly what your CalendarEvent is.

tardy crypt
#

can you actually access this class?

#

can i for example save it in the middle of a running game so that after the game has resumed, i can place all of the lamba information back intot he calendar?

chilly surge
#

No you cannot serialize them, sure if you need to serialize them then you'd need to use an actual class, but that wasn't a part of the original question.

#

But I'm saying that "it's much harder to remove anonymous functions from a collection" is not exactly a lambda issue, you can remove them just like you do with a class.

tardy crypt
#

i mean if you hold the reference to the lamba, then you can remove it

#

but then you need to actually tarack that information

#

although i guess if i'm just adding "new calendarevent(...)" without a name, it's in the same place...

chilly surge
tardy crypt
#

true

chilly surge
#

But yeah I think that's a bit side tracked, sounds like subclassing the event should solve your issue.

tardy crypt
#

thanks guys

#

maybe something like this:

class CalendarEvent {
  public abstract Execute() {}
}
class CalendarEvent<T> : CalendarEvent
{
  Action<T> function;
  T param;
  
  void Execute() {
    function?.Invoke(param);
  }
}

and then just define subtypes as:

class EventType1 : CalendarEvent<ParamType1> {}
class EventType2 : CalendarEvent<ParamType2> {}

where I need the non-generic CalendarEvent class because I have a SortedList of those and I can't do a SortedList of CalendarEvent<T's> with the generic parameter remaining unspecified.

chilly surge
#

The generic is not needed at all.

#

The parameter should be implementation details of the subclasses.

chilly surge
#

Something like:

class AlarmCalendarEvent : CalanderEvent
{
    private AudioClip _sound;
    private float _duration;

    // ...
}

class ReminderCalendarEvent : CalanderEvent
{
    private string _message;

    // ...
}

calendar.Subscribe(new AlarmCalendarEvent(sound, duration));
calendar.Subscribe(new ReminderCalendarEvent(message));

And calendar just needs to loop over the events and call Execute() on each one, without caring about anything.

tardy crypt
#

ok fair enough, that looks good too

chilly surge
#

Alternatively CalendarEvent can also just be an interface instead of abstract class

tardy crypt
#

right, though tbh i think the logic will be the same for each event type

#

other than the execute thing

chilly surge
#

And alternatively instead of having a CalendarEvent at all, just simply have Action, and you do:

calendar.Subscribe(new AlarmCalendarEvent(sound, duration).Execute);

Which will also allow you to pass in lambda directly:

calendar.Subscribe(() => { ... });
mossy snow
#

no, that second thing leads you down the dark path of wtfery even without considering trying to serialize Calendar at some point

tardy crypt
#

that would be my opinion as well

chilly surge
#

Lambda just compiles to a class ๐Ÿ˜„

tardy crypt
#

there's other state i need, like the DateTime that the event happens, whether it needs to stop the clock, etc

mossy snow
#

and you forgot it's a Calendar, so actually it's calendar.Subscribe(someTimeParameter, () => { ... }); and then you need to store that in the Calendar and sort it, so now you have a class to hold your lambda's time and lambda ... but you already have that, so it's a design fail

chilly surge
#

No?

#

You can very well have Action<DateTime> and you subscribe with calendar.Subscribe(dateTime => ...).

tardy crypt
#

that's not... the right thing?

mossy snow
#

lol you need to think that through some more, unless you're going to execute all the events in order to try and sort them?

tardy crypt
#

the date time is the parameter you pass to calendar to sort it in the calendar

#

the dateTime would be a parameter you apss to the method when it's called

#

but you'd have to already know that value to sort it...

chilly surge
#

Ah you mean you need to sort the events first, then sure Subscribe(dateTime, () => ...) and sort based on the parameter is no different from Subscribe(event) and sort based on event.TriggerTime.

tardy crypt
#

you could do subscribe(dateTime, ...). i'd just prefer to have an explicit class to store the state rather than doing this kind of thing

#

lambdas are nice for some things but not explicit game state

#

anyway thanks again guys

chilly surge
#

It entirely depends on how autonomous the event is supposed to be. Is the event supposed to just be a handler that gets called without knowing when, or does the event also needs to manage its own call time?

#

But that's adjacent to lambda vs class.

#

Again, lambda just compiles to a class in the end. If you are writing a class just for capture and nothing else, then that's reinventing lambda. If you are writing a class for more reasons than that, sure that makes perfect sense.

tardy crypt
#

Thanks again guys.

runic nimbus
#

How can I "weld" one rigidbody to another so that they stick together as if they were parented?
Joints are no good for this.
Parenting basically disables collision for the child. (It's what I'm doing now)

#

I have asked this question before but the answer was inconclusive.

#

I really need this for my project, I'm kind of surprised there is no common way of doing it

steady moat
#

Like adding forces

runic nimbus
#

Again, joints, are no good. They have severe issues with tearing, and this is just not something I can accept in my case.

spring creek
lean sail
#

Why do you need seperate rigidbodies then if you dont want them to act as seperate rigidbodies?

#

just have 1 rigidbody with children colliders, sounds like what you need

lean sail
#

i see no part which needs to be a rigidbody

runic nimbus
#

What?

spring creek
#

So why do they need to be separate rigidbodies? And why does parenting not work?

#

Parenting would not disable collisions of course

runic nimbus
steady moat
# runic nimbus

You do not need anything else than rigidbody and collision.

runic nimbus
spring creek
#

The video made it very clear that they do NOT require rigidbodies after attachment. Imo

runic nimbus
# spring creek > until attached

Are you suggesting to destroy the rb once attached? Keep in mind that they can be de-attached too. That might be a hassle to set up.

spring creek
#

Or swap the object

runic nimbus
lean sail
#

making it kinematic should be fine too

runic nimbus
#

They are kinematic, and it has the issue of not colliding properly

spring creek
#

What do you mean by "not colliding properly"
That has not been explained

runic nimbus
#

One second

steady moat
#

Then destroy rigidbody if it is not working

lean sail
#

this is a separate issue then from what you asked initially. kinematic means its ignored from physics, its not going to handle collisions at all

#

it moves where you tell it to move, even if inside a wall

runic nimbus
#

Volume

runic nimbus
lean sail
#

Ah yea I just tested, having kinematic rb as a child still messes things up. You could have 2 versions of each part, one with a rigidbody and one without. Toggle either version when needed
This would just save you from storing everything you want about the rigidbody which probably isnt too much information

runic nimbus
#

Destroying the rigidbody did the trick. I don't think I'll be messing with default RB settings for this particular game so it's fine to just add one back.
Thanks all.

mild osprey
#

I've been working on an implementation of the a* pathfinding algorithm, and it's been working as expected for the most part. I've configured it to avoid being near walls by putting negative weights near them, and positive weights in the center of the room. This works fine, but with anything bigger than a 1x1x1 cube, it starts running into issues with clipping, especially with dynamic objects (eg. doors). I've added a rigidbody to the mesh so that it should push itself away from objects it comes in contact with, but I think because of the forces that move it, it still clips through. Is there an approach I could take to avoid having the collisions happening in the first place or some other way of avoiding this behavior.

fervent furnace
#

because the object rotates and you use path finding & physical system to move the object i.e. you move the object based on both geometric position and logical graph, unless your logical graph can tell the object the transform of obstacles (eg. navmesh) otherwise no way to solve.
to short: a set of vertices and edges cant tell you anything about obstacles in world space

chilly surge
#

Is there an API to multiply a Rect with a Matrix4x4 and get the resulting AABB rect?

#

My current code is just multiplying the four corners and then min/max the resulting points, which is kind of lame looking code.

vestal arch
#

there's a Vector4 * Matrix4x4 overload, maybe that could work?

chilly surge
#

Hmm, don't think that would work.

mild osprey
strange patio
#

is System.Serializable data goes wrong if iam make it array? in my script iam already attach all component but when play the only component that doestn null was rigidbody other than that goes null. This happen when i make it array or list

public class DashAttack : AnimationAction
{
    public float dashSpeed;
    public float shakePower;
    public DustEffect dustEffect;
    public GameObject swordEffect;
    public VisualEffect vfx;
    public Rigidbody2D rb;
    private bool isExecuted;
    [HideInInspector] public float direction;

    protected override void PerformAction()
    {
        base.PerformAction();
        if (!isExecuted)
        {
            isExecuted = true;
            CameraConfig.Instance.CameraShake(shakePower, 0.1f);

            if (swordEffect != null)
                swordEffect.SetActive(true);

            if (vfx != null)
                vfx.Play();

            if (dustEffect != null)
            {
                dustEffect.PlayDustEffect();
            }
        }
        rb.velocity = new Vector2(dashSpeed * direction, rb.velocity.y);
    }

    protected override void EndAction()
    {
        base.EndAction();
        rb.velocity = Vector2.zero;

        if (swordEffect != null)
            swordEffect.SetActive(false);

        isExecuted = false;
    }
}```
fervent furnace
versed loom
#

why do I get this error Script error (ConstantMappersData): Update() can not take parameters. on a scriptable object

lean sail
lean sail
versed loom
#

ik that, but i already changed the name of it, thanks ๐Ÿ˜„

strange patio
lean sail
strange patio
#

now the error fixed when i remake my list

lean sail
#

what goes null? this is very vague. Surely you have some null reference error on something

strange patio
#

im just dont get it what exactly happened, why it suddenly goes null even tho iam not touching the script at all

crisp comet
lean sail
#

you are right, multiplayer is not beginner at all.

swift falcon
#

Any indian? indie developer i want some help..

vestal arch
#

just ask about what you need help

swift falcon
#

breh

gray mural
#

Also Indians and indies are different people.

twilit scaffold
#

I must be tired. this amused me Way more than it should have.

#

My internal voice went all Barry White

solar wigeon
#

hello, i have a problem where my player is not accelerating to the disiered speed of 20. basicly its a dash script

#

i used

gray mural
tawny elkBOT
warm sage
#

Help with Unity Build Automation

normal arch
#

I don't think so

ivory smelt
#

Ayo, does anyone know why my game is stuck at 60fps regardless of the resolution or the target frame rate I set?
Ive also configured the default frame rate in project settings but it doesnt seem to have any effect at all.

void Update()
    {
        frames++;
        float currentTime = Time.realtimeSinceStartup;
        if (currentTime - lastUpdate >= updateRate)
        {
            fps = frames / (currentTime - lastUpdate);
            fpsText.text = Mathf.RoundToInt(fps) + " FPS" + " " + Screen.currentResolution.refreshRateRatio.value + " HZ" + " target: " + Application.targetFrameRate + " vsync; " + QualitySettings.vSyncCount;
            frames = 0;
            lastUpdate = currentTime;
        }
    }
public void setResolution(int index)
    {
        Resolution resolution = validResolutions[index];
        Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreenMode, resolution.refreshRateRatio);
        Application.targetFrameRate = (int)resolution.refreshRateRatio.value;
        QualitySettings.vSyncCount = 0;
    }

Everything else in the code is correct, just assume that validResolutions[index]; is the same as allResolutions

dull heron
#

maybe you have VSync enabled?

ivory smelt
#

not the case, i made sure to disable it in project settings

#

also its not my pc, I have a 144hz monitor and I am able to run other games at that framerate

knotty sun
ivory smelt
#

Its god damn huge to share the full code, i just picked the parts that have something to do with that

knotty sun
#

read what I wrote

ivory smelt
#

Ye, I was refering to this

knotty sun
#

exactly, where is the data your code is using? Without it your code is meaningless

#

and what I wrote does not ask you to share more code

ivory smelt
#

the data is the same

#

i have a filter i can toggle

#

so now its disabled

#

then the valid res are the same as all available res

#

like, the real problem is that the refreshRate is not changing, is there another funcion to do that, aside of the one i used in my code?

#

if i use a number lets say, 60 instead, something like this:
Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreenMode, 60);

#

it still wouldnt change the Screen.currentResolution.refreshRatio.value

#

thats the problem

#

data is not important in this case, as it happens with any value

#

probably should have explained that since the beginning haha

vagrant pelican
#

hey guys i want to set the time of my animation to the float value in the script how can i do this

noble quartz
astral axle
#

For some reason, first time I run a scene everything works. If I reload the scene, without any states being saved one script is just loses all its references. For no reason at all. I thought reloading a scene would reset everything. I can see the object in the active scene but "this" (refering to the object at hand is null. How is this possible?

lunar kestrel
#

Guys how do I make that some entities in my game spawn like in minecraft below some light level, I have scene (2D) and some rooms and how do I check if where entity wants to spawn there is light intensity 0.1? Do I need to make my own grid of light intensity or I can somehow grab it in different way?

arctic plume
#

Is there any way to detect a Unity button being held?
I'm adding mobile support to my project I wanna have it so the player shoots while holding a button but I can only seem to get it to happen when they let go

somber nacelle
#

use a component that implements the IPointerDownHandler and IPointerUpHandler interfaces or an EventTrigger component to get the relevant events

arctic plume
#

Is IPointerDownHandler not for mouse clicks?

prime sinew
#

if that doesn't work, there's always the EventTrigger component

#

with that, you dont need the Button component, an Image will do

noble quartz
arctic plume
#

@prime sinew @somber nacelle Thank you both very much, I got the button interaction working on PC so all I need to do now is check it still works on mobile, I appreciate your help!

eager cliff
#

how do people store data of item with code to apply when equip? I mean in many tutorials, people just use scriptable object to store some UI data (eg. name of item, description) and never store effect inside it. I wonder how people actually do this? I want to execute a specific code in many item when equipped. My current idea is, I can extend class from a base class and make every kind of item. Is there any better way (not making a hundred different class)? Thank you.

rapid stump
#

I... THINK this is a question for this channel?
I have a world space canvas that has fog of war tiles and a ship that the player controls. (All UI images within the world space canvas group)
The ship has a circle collider 2D property and the fog tile have a box collider 2D component
My problem is, collisions aren't detected between the objects.

The video shows that all my fog tiles have 2D box colliders, my shipSight has a circle box collider, the script that's supposed to handle collision detection and log any detected collisions is attached to my shipSight object, yet I get no logs.
(Not sure what's making my fog tiles fade out when I get really close to them, probably some residual code I need to find and remove XD )

#

I'm going to guess, even though the Canvas is world space, because they're UI image, collision isn't supported?

astral axle
#

How on earth is this even remotely possible. Notice the log time and the difference in framecount.

#

This event is fired ONCE on first load. Scene reload and same event and this happens.

gray mural
#

I don't think printing the frame count can give you a zero at the start

astral axle
#

No you are right. That extra integer is a separate counter and I missed adding a space. I've given up on this. I will take another route. For some reason, reloading the scene does not reset the state completely. Things work as intended on first load but never on second. I have no objects set to DontDestroyOnLoad. There is no reason for this.

#

In first load that event is correctly fired exactly once. On second load the calling function is called exactly once but the event is fired 4 times within a single frame. For absolutely no reason at all.

#

If this is not an engine bug I don't know. I've never seen this behavior before.

#

Has be a ghost object being kept alive. I have no explanation for this.

ionic stone
#

Using sprite stacking, i need to make the parts rotate individually on the z axis and not the whole parent game object. But the parent, car in this example rotates on the z axis when turning. How can i make it so the part 0-17 rotation would match the cars.

robust whale
#

I make animations with blend tree and I control the code in this way;

animator.SetFloat("xSpeed", playerMovement.movementInput.x, 0.3f, Time.deltaTime); 
animator.SetFloat("zSpeed", playerMovement.movementInput.z, 0.3f, Time.deltaTime);

But when I do this, it plays cross animation at first and then switches to side walking animation. I want the side walk animation to play directly. How can I solve this problem?

noble quartz
gray mural
astral axle
#

Thanks I already know which objects are null @noble quartz

#

@gray mural SceneManager.LoadScene

#

My humble take is that that method should reload the scene from scratch, as if I was starting the app again.

gray mural
#

Why would you reload the scene?

astral axle
#

In order to reset everything, which is the intention

gray mural
#

I see, it should reload everything perfectly

astral axle
#

Yes

gray mural
#

Do you even unsubscribe it?

astral axle
#

On reload?

gray mural
#

Please, share the code with the event

narrow summit
#

Is there some C# attribute similar to [System.Diagnostics.DebuggerHiddenAttribute] that hides methods from unity stack trace ? HideInCallstack doesn't seem to work

Nevermind, had to toggle the console window's option

astral axle
#

@gray mural if the scene is reloaded, are event subscriptions kept? The eventmanager and any subscribing object is destroyed?

gray mural
turbid hazel
#

I have this bug now on the latest unity 2022 version (had it before)

After restarting the editor, it grays out one of my scripts, and gives me an error ingame.
Now i would just need to delete the script and add it again, it would work until the next restart.

What should i do? Do you guys think just renaming will fix the problem?

gray mural
astral axle
#

@gray mural which they should be on scene reload?

#

yeah

gray mural
astral axle
#

Its very strange indeed

#

hm... the EventManager is a static class I see now

gray mural
gray mural
#

That's the same as DDOL

#

I haven't even considered this case

astral axle
#

me neither

#

Let me check

gray mural
#

Anyway, simply unsubscribe EventManager's events

#

Also, consider doing it always to avoid this kind of issues, even if you're sure everything's under control

astral axle
#

I will give it a try, this feels like at least a possibilty.

gray mural
#

I was just wondering why this would happen if you say you don't have DDOLs

astral axle
#

So unsubscribe in OnDestroy?

gray mural
astral axle
#

@gray mural well something changed! I still get two calls on the event for some reason though

#

But the missingreference is gone!

#

So BIG thanks!

gray mural
#

That's the the thing to celebrate if it still doesn't work

#

Are all the subscriptions to the event unsubscribed?

astral axle
#

yes

gray mural
astral axle
#

Hold on I'm revering all the crap I've tried to clean it up

#

FACK

#

that was not it. Still losing references

gray mural
#

What is that supposed to mean?

turbid hazel
astral axle
#

@gray mural the random lost reference that just happens seemingly between frames

#

basically what I'm trying to understand since yesterday ๐Ÿ˜›

gray mural
#

How would I be able to understand it without seeing the code?

astral axle
#

Granted

knotty sun
astral axle
#

yes

knotty sun
#

show me the declaration of the variable

astral axle
#

but thats the thing, even if I reasign it with FindObjectByType, some other object is also unassigned. And so on. I find it strange that a scene load comes with some state after reloading as everything works as it should on first run

#

public InterfaceControllerNFC InterfaceControllerNFC;

gray mural
#

It loses its reference? How is it assigned?

astral axle
#

originally in inspector

gray mural
#

So do you assign it somewhere else?

knotty sun
#

ok. try this
turn this variable into a property. in the set test if the value is null and throw an exception if it is.
Dont forget to add a field:SerialzeFiled attribute and reassign in inspector if necessary

gray mural
#

If not, then the InterfaceControllerNFC it references is destroyed

astral axle
#

It seems to. Why that is the case is beyond me

#

I mean it is destroyed when the scene is unloaded but should be loaded as per first round on scene load

gray mural
astral axle
#

Need a break. Thank you for the help @gray mural the eventmanager thing was definitely something ๐Ÿ˜„

crude mortar
#

unless you mean something else

knotty sun
gray mural
gray mural
last raven
#

you can add attributes to backing field by using [field: target modifier on attribute

#

I'm literally using serializable properties right now

gray mural
last raven
#

that's because that's the opposite of what you said

#

that's not auto field

gray mural
last raven
#

you mean you cannot serialize a property with an automatic backing field, so add a damn backing field

last raven
#

this property doesn't have automatic backing field

#

ok, sorry then, but that's who I replied to

#

and then you said you cannot

#

so I thought it was you

#

with automatic backing field you can, without just serialize backing field

gray mural
#

Yes, the property with the automatic backing field can be serialized using field keyword

[field: SerializeField]
public int MyProp { get; set; }

The property which implements the get and set cannot

[field: SerializeField] // doesn't work and throws a warning
public int MyProp
{
    get => _myProp;
    set => _myProp = value;
}
last raven
gray mural
simple sable
#

Hey guys. I have a bit of a problem and I can't seem to find a way to fix it.

I'm working on an inventory system with different item categories (multiple classes), organized through inheritance. Checking if an item is a consumable, for example, is straightforward (if(item is Consumable)), but I'm struggling with creating a list of item categories an item must have for certain actions. I don't know if using a serialized list of classes is something that even exists. And enums have problems as they lack hierarchical structure. Assigning categories via enums (e.g., ItemCategory.Fish) has limitations due to enum's flat structure which will have no idea that the item, while it is a fish, it's also a consumable.

I hope I made some sense here. Would appriciate some help/design ideas. ๐Ÿ˜…

fervent furnace
#

creating a list of item categories an item must have for certain actions
i dont think it is not gonna to work, you still need the class which holding the categories to implement the methods to call the categories in list

#

seems reimplement the same method everywhere is the only solution if multiple inheritance is prohibited, though composition can still be used in method body

public interface IFish(){
  void Swim();
}
public interface IConsume(){
  void Consume();
}
public class Tuna:IFish,Iconsumm{
  public void Swim(){
    SomeStaticHelperClass0.Swim(this as IFish);<--copy & paste
  }
  public void Consume(){
    SomeStaticHelperClass1.Consume(this as IConsume);<--copy & paste
  }
}
```the best way i come up with now
knotty sun
#

!code

tawny elkBOT
eager steppe
#

hey everyone, i wanna optimize the process of processing (chart)maps in my game
When processing a map with just over 1000 lines of text (so 1000 strings in the array) it takes around like 6-8 seconds but i would like to speed up the process to just under 3, anyone got any ideas on how to shorten said process:

https://gdl.space/uyohefuhoj.cs

#

no embed is crazy

simple egret
fervent furnace
#

multithread the parsing, though json utility probably wont support multithread deserialize
also this https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.ensurecapacity?view=net-8.0
and use switch case, but that reduces little, probably none
you cant optimize the sort so the only thing you can optimize is deserialization

Ensures that the capacity of this list is at least the specified capacity. If the current capacity is less than capacity, it is increased to at least the specified capacity.

simple egret
#

I see that you're deserializing the same payload twice but in a different type. See if there's a way to only deserialize it once, and switch on the type afterwards. An option would be to use a serializer that supports polymorphism, and have a single base class for the two note types.

NoteBase note = SomeDeserializer.Deserialize<NoteBase>(json);
if (note is TapNote tap)
{
    // do stuff with 'tap'
}
else if (note is HoldNote hold)
{
    // do stuff with 'hold'
}
eager steppe
eager steppe
fervent furnace
#

ofc if you parse 50% of them twice, you are using around 2 seconds more
didnt notice that at first

simple egret
safe shale
#

Hey people, first of all sorry i am not sure if i should publish this in code general or code beginner.
I have a doubt, lets say i have a MyPosition vector3, and have a OtherPosition vector3, i want to generate a new vector3, thats its in the exact same direction as OtherPosition (from MyPosition point of view), but at a specific distance, or within a range.
How could i do this efficiently? I have several ideas, like generating a vector3 converting to world to local position (from MyPosition point of view) and try to add or substract that vector3, but i really dont see that option very efficient.
I made a draw in ms paint to try to explain my idea better, its not very elegant, but i wish is understandable. Thank you all.

leaden ice
#

It's unclear if rotation of something matters or not because I don't see that shown in the image

safe shale
#

So yes, rotation would matter, at least from myPosition point of view

#

otherPosition would be static, most of the cases

leaden ice
#

You just get the local space position of the objective from the player's transform

#

Then use that to draw your compass

#

transform.InverseTransformPosition for the first part

safe shale
# leaden ice transform.InverseTransformPosition for the first part

Yes! i got that part, but now, what i want to know its to convert that local position to fit into a specific range/distance, like the part 2 of the draw shows, i thought i could simply grab LocalOtherPosition and subtract (or add) it with vector3.one until i get the desired position, with i think that would be performance expensive i am not sure, i wanted to know if there is a more efficient way to do it

sly comet
#
    {
        Debug.Log("Loading level data for scene: " + sceneName);
        if (File.Exists(savePath))
        {
            string encryptedData = File.ReadAllText(savePath);
            string decryptedData = Decrypt(encryptedData, encryptionKey);

            // Deserialize the JSON data into a single LevelData object
            LevelData loadedLevelData = JsonUtility.FromJson<LevelData>(decryptedData);

            // Check if the loaded level data matches the specified scene name
            if (loadedLevelData != null && loadedLevelData.sceneName == sceneName)
            {
                return loadedLevelData;
            }
            else
            {

                Debug.LogWarning("Saved level data scene name: " + loadedLevelData.sceneName);
                Debug.LogWarning("Saved level data does not match the specified scene: " + sceneName);
            }
        }
        else
        {
            Debug.LogWarning("No saved level data found at path: " + savePath);
        }
        // No data found for the specified scene
        return null;
    }```

My sceneName is Level 1
My loadedLevelData.sceneName is Level 2
I'm not sure where I'm going wrong. Level 1 and Level 2 are both saving great if I never swap scenes. As soon as I do it can't find them. It's like Level 2 overwrites Level 1 data and visa versa.
vestal arch
leaden ice
#

With the max range as the last parameter

#

Or clamp magnitude

#

localPos = Vector3.ClampMagnitude(localPos, range);

elfin tree
#

Is there a straight forward to exclude a child collider from being part of a rigidbody?

#

Basically I'd like to target a MonoBehaviour on the child that was hit, but it returns the parent (since it has a rigidbody)

leaden ice
#

if you're using a raycast you can get the collider directly with .collider on the RaycastHit

#

Be specific with what you're doing, as different properties on RaycastHit do different things.

elfin tree
#

OnCollisionEnter, sorry wasnt clear

leaden ice
#

if you did .rigidbody or .transform you will get the parent

leaden ice
elfin tree
#

ah thanks

#

exactly what i needed

leaden ice
#

Again make sure you use .collider if you want the collider you hit

#

.rigidbody and .transform will give you the object that has the Rigidbody

drowsy steeple
#

How would I make an editor script in Unity? Basically I want to make a script that I can run in edit mode, give it a file and then have it parse that file and do whatever else. I just don't know how to make it actually executable from the editor or how I would input the file that I want without the direct file path - I want to be able to input the file so that I don't have to go and edit the script every time I want to parse a new file

primal wind
#

Still baffled Unity's abstraction for open and save dialogs is EDITOR ONLY???

#

Like, come on

#

That's pretty useful for a lot of stuff

#

At least there are 3rd party libs

knotty sun
open sparrow
#

Hi there! How its usually the "Game State" managed? For example while my character its in combat i don't want it to be able to open the inventory, or if a cinematic starts I want to disable every action map. Should the input manager (in my case its handled by a scriptable object that throws events) be told that the player is in combat, or that there is a cinematic going on?

leaden ice
#

since you have these different "modes"

swift falcon
#

i want to make a active ragdoll character does anyone help me for that

rigid island
solar wigeon
#

can anyone help how to make a dash counter like after 2 dashes it has to wait for the dash counter the recharge

swift falcon
solar wigeon
#

i want a function that say everytime i do this then do this then if i do this again do this

latent latch
#

you need a timer that's for sure

lean sail
latent latch
#

either do it in your update loop provided, or use a coroutine

solar wigeon
#

i did something like this now i dunno how to minus the dashCount

simple egret
#

dashCount--; to decrement (subtract 1 from) a variable

solar wigeon
#

like this ?

simple egret
#

Yes, though you need to use else if for the last if statement, otherwise it'll run both at once

#

Dash count is 2, subtract 1, dash count is 1.
Is dash count equal to 1? Well yes! Decrement again

somber nacelle
#

i don't think that last if statement would ever be reachable if they used else if there since they return if dashcount is greater than 0 and if it isn't then they assign it to 2

naive summit
#

Yo guys quick question.
Idk if its a bug or whatever but im starting on a new code for me game, pretty simple item pickup and i got

[SerializeField]
private AudioSource PickUpSound;

but for some reason in the inspector i cant drag the sound on the Audio Source field even tho its there, why?

solar wigeon
#

this ?

somber nacelle
naive summit
solar wigeon
#

how should i fix it ?

simple egret
# solar wigeon this ?

What is this code supposed to do? Because the conditions are basically unreachable right now. Since you return; early if you have dashes left

somber nacelle
naive summit
solar wigeon
#

thats what i a mtrying to do

#

i am quite new so i dunno how am i supposed to do so

simple egret
#

Ah, so you should do this in the piece of code where you apply the dash to the player

#

Usually where you check for a keyboard or mouse input, however dash is activated for your game

naive summit
#

How do i assign an AudioClip to an AudioSource? Since i got this in my code

public class ItemPickup : MonoBehaviour
{
    public Item Item;
    public AudioSource PickUpLocationSound;
    public AudioClip PickUpSound;

    PickUpLocationSound.clip = PickUpSound;

    void Pickup()
    {
        InventoryManager.Instance.Add(Item);
        Destroy(gameObject);
    }

    private void OnMouseDown()
    {
        PickUpLocationSound.Play();
        Pickup();
    }
}

but the console is giving me 2 errors
Invalid Token '=' in class,record,struct, or interface member of declaration
and
Invalid Token ',' in class,record,struct, or interface member of declaration

somber nacelle
#

you have to do it inside of a method

naive summit
#

Im pretty new to c# programming, what would that mean?

somber nacelle
#

it means you cannot have logic directly out in the class like that. you have to do it inside of some method like Awake, Pickup, or OnMouseDown

naive summit
#

Oh, can it be in Void Update() ?

dusk apex
#

Statements should be made in the method scope.
...clip = PickUpSound is a statement. Initialization on declarations would be fine but this isn't a declaration.

somber nacelle
naive summit
#

I did it in Void Start() and it works fine
Thanks guys

rugged storm
#

hay what are the best practices for implementing a status effect system?

#

for a turn based game (turn order system intended to replicate Honkai Star Rail's)

#

in my inexperience my best guess would be having an abstract status class with methods such as OnHit OnAttack OnDeath etc... and then when a character does something it would go through a list of all their currently applied statuses and run the corresponding method but this seems messy?

latent latch
#

Rather, it depends on the behaviour of these methods as OnHit implies you have a target and you know the source unlike the other two

rugged storm
#

the method names are from the perspective of the character with the status for example say a status that makes the character do dmg to another random enemy when it attacks, or when that character dies it explodes or something, my system does allow me to see who killed a dying character so passing that information would not be hard just not sure if my way (of looping through a list of all statuses on the character) would be a good idea

latent latch
#

I think it's fine for a minimal implementation, but the more unique logics that you implement the larger your script may become, but since it's just a turn based game it's probably fine

lean sail
latent latch
#

I think for the best type of modular design comes down to a list of delegates perhaps,

lean sail
#

The thing I dont really like about delegates here is you already know exactly what you want to call the functions on. There is almost nothing else that needs to attach itself to this effect system

latent latch
#

Like maybe a dictionary of delegates and have these dictionaries dependent on the passing parameters (does the delegate need a target? does it affect global?)

rugged storm
#

What are delegates?

latent latch
#

function/method pointers with some c# sprinkled syntax

lean sail
#

it also adds some complexity because now effects need to be removed from the delegate chain. While if you had a list of status effects, then just looped through them, when a status effect is removed its just no longer in the list

rugged storm
lean sail
#

Its hard to say really without knowing your entire setup. In my case, my abilities wont ever go through the same system as my effects system. Because my ability itself is notified when it hit something. In your case it can make sense

latent latch
#

ultimately it comes down to grouping by parameters, some delegate groups are parameterless, some requires a ITarget, some require one or more ITarget

#

and probably much cleaner if you don't expect a return

lean sail
# rugged storm What are delegates?

if you used unity event, like button.onClick.AddListener, this is basically a delegate but unity's version. C# delegates are similar but different syntax. Another issue with delegates here is if you want to use a result from the method call. Im also considering how to handle this cleanly.
Lets say you have a status effect that makes the player take half damage. This is easy when you think about just a single function call. A method takes a float and returns a float
Doing this with delegates is still possible but when there are multiple methods all returning floats, they aren't added or multiplied together, you're just returned a single value from one of them. So now you need to handle this separately, which might involve looping through the list yourself.

rugged storm
#

I see thanks for all the help guys I think due to my lack of experience with delegates I'll just loop through a list of statuses when a possible condition happens and call the associated method, and as for items and passives I'll make them like unremovable invisible statuses

chilly surge
rugged storm
tired pecan
#

hi im coding my player basic input rn and i was wondering how to fix beeing faster if you move diagonaly. could somebody help me?

#

sry for interrupting

rugged storm
rugged storm
#

I'll let one of the more experienced people chip in too cuz I'm also inexperienced and prob can't explain aswell as them

lean sail
# chilly surge The way I would implement it is to have a class/struct representing all the comb...

im doing this with my stats class, so stuff like damage multiplier or reduction is already calculated when the player picks up items. My case might be a bit different from JKLJosh's because i also planned to have rng effects like "50/50 chance to take more or less damage from an attack". not exactly what ill have in game but just an idea.
This is probably something i just need to think about more because i havent really designed what i wanted yet

tired pecan
chilly surge
rugged storm
#

While I could hardcode stats that are that common for less common things I wanted to have a robust system that could do anything between just not making you take damage, to something as specific as multiplying dmg taken by 4 then evenly distributing it to all enemies and allies in the fight

chilly surge
#

That shouldn't be very difficult with something that represents all stats

#

You would simply have a property that returns a final damage multiplier taking into account all the sub stats (which are the implementation details of all stats) and that's it.

#

Effects modify sub stats, actions don't need to care and just look at the final multipliers.

latent latch
#

the very base of something to expand upon

#

may need a bit more logic to incorporate non-explicit values

chilly surge
#

The code is also extremely simple if you use C# record.
A record that represents all the sub stats:

public record Stats(
    float AdditiveDamageAmplifier,
    float MultiplicativeDamageAmplifer,
    float DamageReduction,
    // Whatever more stats
)
{
    public float FinalDamageMultiplier => (1 + AdditiveDamageAmplifier) * MultiplicativeDamageAmplifer / DamageReduction;
}

An effect just takes in a Stats and returns a modified version:

class SuperStrongDamageReduction : IEffect
{
    public Stats Apply(Stats stats)
    {
        return stats with { DamageReduction = stats.DamageReduction + 1f };
    }
}

Each round you calculate the stats by applying all the effects:

var stats = ...; // Create base stats
foreach (var effect in effects)
{
    stats = effect.Apply(stats);
}

And an action just takes in the stats and use the computed values:

void DoDamage(Stats stats)
{
    player.Hp -= 10 * stats.FinalDamageMultiplier;
}

All Stats needs to do is to decide how to calculate the final stats based on sub stats, it doesn't need to care about effects or actions; an IEffect just needs to take in a Stats and return a new one, it doesn't need to know how each sub stat interacts with each other or which actions to apply; and an action doesn't need to care about what causes FinalDamageMultiplier to be 2.0, just apply it.

rugged storm
#

Also what's best practice for even implementing abilities in my case when a "move" is preformed it creates a MovePackage that gets pass around and edited through the move's logic, it holds data about what happened as a result of the move, who used it, who was targeted, the damage it dealt and any other chatachters who will take or heal damage from it.

lean sail
rugged storm
#

(btw they are coroutines so i can pause them for stuff like animations later on or whatever)

lean sail
rugged storm
#

yeah im asking like just if i went about it in a good way, like if there are any big flaws with my system, etc etc or if theres some super ovbious better way of doing it that is the like "standard"

chilly surge
# lean sail ive yet to use record, is it just so you can use the `with` keyword here? or is ...

Records have a few things that are very useful, for example in this record:

public record User(string Name, int Age);
  • It has syntax sugar for constructor based on the properties you give it, so you can directly do new User("John Doe", 42).
  • It also has syntax sugar for desconstruct, so you can do var (name, age) = user.
  • All the properties are immutable.
  • It has value semantics, which means new User("Foo", 42) == new User("Foo", 42) will return true. This allows you to do comparisons, use them in HashSet<User>, or even use them as keys of Dictionary<User, ...>, without worrying about "oh no they have the same values but are references to different objects."
  • with sugar, so instead of new User(oldUser.Name, 69) you can just write oldUser with { Age = 69 } which is extremely convenient once you have tons of properties.
    And of course, you can add members, methods and what not just like a regular class.
#

The last point is probably the most relevant to the code above, otherwise it gets very annoying to write.

lean sail
#

thanks, from reading the docs i was kinda confused. I might try to rewrite part of my stat system to use this

lean sail
vapid lynx
#

Im trying to enable buyoncy in my game and i wrote this code:

public class Floater : MonoBehaviour
{
    public Rigidbody rb;
    public float depthBeforeSubmerge = 1f;
    public float displacementAmount= 3f;

    void Update()
    {
        if(rb.transform.position.y < 5f)
        {
            float displacementMultiplier = Mathf.Clamp01(-transform.position.y/depthBeforeSubmerge) * displacementAmount;
            rb.AddForce(new Vector3(0f, Mathf.Abs(Physics.gravity.y)  * displacementMultiplier, 0f), ForceMode.Acceleration);
        }
    }
}```
It works for the standalone scene with the water, but when I try making uit work in my game, the car just goes through the water. The same is for a simple cube (which floats in the sample scene). Can someone help me with why thats the case
lean sail
vapid lynx
#

The code is running

vapid lynx
#

ig i got lazy but ill do a trigger collider

vapid lynx
rugged storm
#

yeah that was my biggest issue i knew the solution felt bad but I'm not sure how else id do it?, elements are currently just an enum, what ways could i do it better?

turbid wyvern
cosmic rain
#

For starters share !code properly

tawny elkBOT
turbid wyvern
#

okay

cosmic rain
turbid wyvern
#

it continues to go past 20 when i look in the inspector

cosmic rain
turbid wyvern
#

well the number is changing as i hold down the right arrow

cosmic rain
#

Did you try debugging the intermediate values to see where the math goes wrong?

turbid wyvern
#

it just increases past 20

turbid wyvern
#

and it starts at 0 when i start the game

spring creek
turbid wyvern
#

Umm why cant i

#

sorry i just started making games in unity

spring creek
#

Use Debug.Log or other debugging tools to see the values actually being used

turbid wyvern
#

why not?

spring creek
turbid wyvern
#

i did and it still goes the newRotation value going past 20

spring creek
surreal swan
#

I have a gameobject in a game and the gameobject is enabled at awake/start. How do I find which gameobject in the game is activating it? How do I log something like this?

spring creek
surreal swan
spring creek
#

Not sure what you mean by that response

lean sail
#

You might be able to find it by right clicking the obj and clicking find references in scene

inland lion
#

Hey, I canโ€™t see my project, I accidentally closed it out and donโ€™t know how to get it back up. Any help?

spring creek
#

But layout on the top right will help

inland lion
#

Canโ€™t, donโ€™t have discord on my PC ๐Ÿ˜…

spring creek
#

Or go to windows at the top

inland lion
spring creek
inland lion
#

Oh I see!! Ty!

inland lion
#

Is there a Channel or identifying unity assets of some sort? I canโ€™t find something Iโ€™m looking for.

inland lion
#

Ok.

inland lion
#

I think I can help but I think I might mess up.

fervent furnace
#

!ide
Also code beginner

tawny elkBOT
hallow glade
#

Oop sorry

lean sail
#

I made a mistake before of not numbering my enums, now I wish to reorganize because I need to add new stats. Is there a way to keep the correct values serialized in unity?

inner ginkgo
#

I'm trying to use MongoDB with Unity but it keeps showing me that using MongoDB.Bson throws an error.

latent latch
#

everytime I try to make something it eventually becomes unusable because of my changes

#

every enum I do make is in a bitwise format incase I do need to eventually turn it into one of those enum types

lean sail
versed loom
#

Is unityengine.object serilizable in a generic struct that is on a scriprable object?

quartz folio
versed loom
#

I assign the object from a objectfield in uitoolkit

quartz folio
#

If this is Editor, why not use a property field?

versed loom
#

It was easier to use an objectfield than using that

twilit scaffold
#

Just curious., was there an official statement on the proceeding removal of support for VSCode? or am i just fully misunderstanding the state of things?

chilly surge
#

VS Code works, Microsoft has put out a new Unity extension.

twilit scaffold
#

Ok, misunderstanding it was then, it seems. thanks. i am using VS anyways, but i do use both. i consider it important that 'free'-er frameworks remain functional

chilly surge
#

Eh, depends on what you consider as "free" I suppose.

twilit scaffold
#

hence the quotes

chilly surge
#

C# Dev Kit is as "free" as VS is, they have the same license which is only free for individuals.

#

I'm not sure if the base C# extension works with Unity or not though, that one is actually free.

twilit scaffold
#

yeah, i fully understand the need to make money for developing these things, but i am borderline feeling nickel and dimed to death

chilly surge
#

Yeah it's a bit sad, for how much Microsoft wants to get rid of the "proprietary only" stigma of .NET, there is not even a free IDE that doesn't make you feel like a second class citizen.

twilit scaffold
#

well, at least the communities are keeping Codium and the other VS code based one (i forget the name. been sucked into a windows void) but, i think you have to use the MS license to enable plugin support anyways :/ IDK, it is a big subject ๐Ÿ™‚ I was just curious as to the future of VS Code and Unity. so, fingers crossed there is a decent one

latent latch
#
[Flags]
public enum PersistentEffectFlags
{
    None = 0,
    Interval = 1 << 3,
}

[Flags]
public enum InstantEffectFlags
{
    None = 0,
    Damage = 1 << 0,
    Healing = 1 << 1,
}

[Flags]
public enum EffectStatFlags
{
    None = 0,
    Damage = 1 << 0,
    Healing = 1 << 1,
    Duration = 1 << 2,
    Interval = 1 << 3,
}

Not sure of the ideal way to go about this, but since we can't override enums my next best idea is just to cast them all to a main enum (in this case EffectStatFlags) for when I deriving multiple different classes.

#

Kinda seems janky seeing that I leave out some entires but I guess it kind of works