#archived-code-general

1 messages · Page 415 of 1

hollow ridge
#

ok i fixed it

#

well the bug

#

still dk how to make exceptions breakpoint

rigid island
#

iirc you have to do that through IDE

#

been ages since I touched VS though its somewhere there. No clue how its done in VSC

polar marten
#

you shouldn't change timescale

rigid island
#

where is the code question ?

latent latch
#

https://i.imgur.com/mSEdpa8.png
So I'm trying to do some sequential logic with the animator and I'm wondering how I'd go about checking that this clip here has ended in my script. Usually I just estimate the clip time, but I feel like I can just poll the value in the animator but I'm not sure what methods I should be calling.

polar marten
rigid island
#

not true

latent latch
#

I dont want to do callbacks

rigid island
#

animation event can get skipped if the transition is too early

latent latch
#

also yeah not always true if it gets interupted

polar marten
#

i think unfortunately this is the way it works

rigid island
#

your best bet tbh is probably the AnimationExit state on the animator

polar marten
latent latch
#

events could work here and it's probably fine, but I rather poll it instead of wait for a callback

polar marten
#

i believe it might have default end and start events anyway? i don't think it's supposed to be this cantankerous

#

well you can definitely poll the animation state

#

this only really breaks if you are in the rare circumstance where more than one animation state update occurs before an Update, such as with physics catch up.

#

does that evern happen? i don't think so

#

but in theory it can

#

the events are always correct

latent latch
polar marten
#

hmm i can't emoji react to nav's thing but OnStateExit is indeed the built in event

latent latch
#

I have trust issues with the animator stuff. I don't trust any of the logic executing gracefully and always worry about soft-locking by doing anything sequential

rigid island
#

yeah its a weird component. At the end of the day is just a FSM

lament lotus
#

I’m trying to make an object act one way when it touches on object, and then acts a different way when it touches a different object

#

I’m making a flappy bird-like game, and no matter what object the bird touches, it dies

latent latch
split junco
#

What to do when your script doesn't "update" in Unity. Like I made some changes in the script and there are no errors. But when I "run" it, Unity still prints out Debug.logs that I removed.

latent latch
latent latch
split junco
#

See line 24 has a different Debug.log

rigid island
split junco
#

I had this debug.log before.

#

I restarted Unity already. No change.

somber nacelle
# split junco

make sure that you've actually saved the code and that you haven't done something silly like turn off the automatic asset import

rigid island
latent latch
#

Hmm, couldn't say but perhaps this script isn't the current linked script unity is using

split junco
rigid island
split junco
#

Here's the bigger picture of the same script

somber nacelle
split junco
#

Uploaded a different pic.

vestal arch
#

make sure you've saved and recompiled

rigid island
#

make another change and save again

#

try trigger another recompile

wintry crescent
#

why oh why can I not declare things like that? It says that member with the same signature is already declared

vestal arch
somber nacelle
#

because they have the same signature, the parameter name doesn't really matter with regards to the signature

vestal arch
#

those signatures aren't exclusive

vestal arch
wintry crescent
somber nacelle
#

because the paramter types are different

#

and therefore they have a different signature

wintry crescent
#

removing the = null doesn't change anything

#

no but it's still the same isn't it

rigid island
#

ones IEvent and one is ICommand

somber nacelle
#

no because the paramter types are literally different

vestal arch
#

thonk so which one is called if passed a type that implements both interfaces?

latent latch
#

So the constraints here dont matter? Still the same signature?

wintry crescent
#

aaand now it doesn't work as well

#

goddamnit

hollow ridge
#

why is there no way to get the velocity of a rigidbody2D before a collision?
like I know theres collision.relativeVelocity but I don't want the relative velocity i want the actual velocity!
honestly a little maddening how restrictive unity can be with its physics system

somber nacelle
rigid island
split junco
#

Really dumb question: Usually Unity autocompiles but how do I compile by myself?

rigid island
#

its on by default

#

does Rider not show the Green lines like VS when something is saved vs Yellow unsaved ?

split junco
#

It has that asterisk on the file name. That shows it's saved or unsaved.

latent latch
#

you can turn on auto compile on play, but I would suggest to keep it on anyway because you want the editor to also update between changes

rigid island
#

anyway I would check if somehow your autocompile is off

split junco
split junco
rigid island
#

uhh I think Preferences ?

#

let me check

somber nacelle
vestal arch
#

@wintry crescent generics in methods are meant to link parameters together, or parameters with the return type
you're only using T once there, so it's not super useful
just use Action<IEvent>/Action<IProcedure> directly

vestal arch
rigid island
split junco
#

Sigh.

latent latch
#

oh it's in asset pipeline now wtf

rigid island
naive swallow
#

I have a custom Flags enum and I find myself using this pattern a lot to set or unset a flag based off of a boolean, is there a better way to do this? This feels kinda... smellly.

bool isInSlice = HorizontalSliceView.instance.ContainedInSlice(rendVis.rend);
if (isInSlice) rendVis.hideReasons &= ~RenderVisibility.HideReason.OUT_OF_SLICE;
else rendVis.hideReasons |= RenderVisibility.HideReason.OUT_OF_SLICE;

This feels like I should be able to do some sort of ternary but I can't really figure out how without making it worse

split junco
vestal arch
naive swallow
vestal arch
#

the conditional changes the operator, i don't think you can cleanly make that a ternary, you'd have to repeat the operands

unique delta
#

I have a foreach loop, which I want to be paused until smh happens. If i use an if statment with a bool, after the bool is true the loop starts over. I want the loop to continue from where it s been paused.

naive swallow
#

Coroutine

#

Put a WaitUntil yield in the middle of it

unique delta
# naive swallow Coroutine

I tried setting a infinite timer and when I change the int from the wait until into an smaller amount it just breaks.

naive swallow
vestal arch
#

can you show what exactly you did there? "it just breaks" doesn't give us any info to work with

dawn void
#

I've always wondered what the best practice for handling time limited actions in games are.
Like if I'm making a cooldown for my dash ability, it would probably e better to just store the Time.time
when you dash and then next time you click the dash button it compares that time to the current. as opposed
to making a timer that adds Time.deltaTime and so on.

But are there any scenario where making a timer is more effective? :3

naive swallow
naive swallow
#

That's not what I suggested at all

unique delta
naive swallow
#

I have no idea what "int" you are even talking about

#

Nothing in my suggestion involves any sort of ints

split junco
unique delta
#

I got it

#

thanks

somber nacelle
split junco
vestal arch
naive swallow
split junco
#

Wow. Isn't that expensive?

vestal arch
#

no, computers are really fast

naive swallow
vestal arch
#

WaitWhile and WaitUntil are shorthand for while (cond) yield return null; and while (!cond) yield return null;

somber nacelle
vestal arch
#

couldn't you have something like SetFlag(ref T bitfield, T flag, bool condition) for some T appropriate for the enum

#

and then the logic would be inside the method, no need for a ternary at the call site

naive swallow
#

At this point, it looks like any way to simplify this is rapidly making it worse

somber nacelle
#

sure, you can accomplish the same thing with an extension method too

vestal arch
#

you can modify this there?

somber nacelle
#

well you would return it, but yes

vestal arch
#

could you possibly not reference the bitfield twice with an extension method?

somber nacelle
#

what do you mean? 🤔

#
public static class EnumExtension
{
  public static T SetFlag(this T toModify, T flag, bool condition) where T : Enum { /* logic */ }
}

it's basically the same as your idea, but instead of ref it just returns the modified enum

vestal arch
#

with that you'd have to do bitfield = bitfield.SetFlag(flag, cond);, no?

somber nacelle
#

yes. which is a common thing to do with value types. but ref works too, it really just depends on what you would prefer

vestal arch
#

yeah just asking out of curiosity

somber nacelle
#

although ref does not work for properties, so the extension method would be useful in more cases

polar marten
#

haha

...(this ref T flags, T flag, ...) where T : struct, Enum {
...
   flags = (T)(object)((int)(object)flags | (int)(object)flag);
#

something like that

naive swallow
#

I'm just gonna stick with the if/else

polar marten
#

lol

#

or use unsafe I guess

split junco
magic tusk
#

I want to notify the user when they don't have connection, I have two methods in mind

  1. I have everything go through some kind of internet related abstraction and notify the user in case of a failure
  2. I just run like a 5 second timer that runs some kind of ping
    (picture related to first method)
#

I understand that in a perfect world the first option would happen, but what are arguments for and against either method?

#

and if there are better ones that would be better!

leaden ice
vestal arch
magic tusk
vestal arch
#

if your game inherently uses the internet, you should still probably check for a connection even if nothing's actively using it

#

(hence the heartbeat; it's a check for an active connection)

leaden ice
#

That's kinda separate from the "heartbeat" thing

magic tusk
#

right, thanks

pulsar plinth
#

so I'm learning how to create Unity menus and I've made a serializable class called RectCollisionMask, which inherits from CollisionMask
RectCollisionMask has its own properties which, inside an OnGui() function inside a PropertyDrawer class, can be accessed through the SerializedProperty.FindPropertyRelative() function, however its derived properties such as Position can't be found through it.

#

HOLD UP, I just put the incorrect names

fallen hatch
#

I'm having a real issue in my script, so may a kind and gentle unity netcode user help me?

tawny elkBOT
fallen hatch
#

so I have a first script assisgned to a game object synchronized via network object, it rreferences the variables for the names displayed on a leaderboard

#

everyone is getting a tag when spawning so this works very well (the owner of the server which is the first one to spawn will always get the tag 1, and the cients 2, 3 and 4 in order)

#

So the owner (with tag 1) is able to change the network variables

#

as he is the owner of the server

leaden ice
fallen hatch
#

oh yeah

#

I'll transfer all

hexed pecan
#

Oops necropost

latent latch
#

speaking of enums, I've been in situations wanting to extend enums, but can't really do with that c#. Best case is remaking the enum and point the previous values at it, but that's not workable with the editor serialization

#

ten buck says odin fixes that issue

still jungle
#

some source code generation Enum would be expandable but it would be up to you to implement it and show in inspector

stray quiver
#

Excuse me, guys, I want to ask if anyone has experienced rendering a texture with post processing enabled but it's not transparent in Unity URP? If you know the solution, how can I make it transparent?
I'm currently using Unity 6

somber nacelle
#

this is a code channel

polar marten
#

they are a code smell

modern creek
#

I have an animator controller that has .. a bunch of ways to call "move" and "idle" via SetTrigger("Idle") or SetTrigger("Move"). Move loops until it gets an idle call.

Somehow I have a situation where there's a move but it fails to loop, and I'm having some trouble debugging it. Is there a way to see what triggers are currently set on an animator controller..?

vestal arch
#

just open the animator pane

#

triggers only last for 1 frame though. they're bools that automatically turn off

#

so you'll only see it active for that 1 frame

polar marten
#

i mean precisely for the reason mao has described. the way they interact with unity is also kind of radioactive

vestal arch
#

(or until it's consumed? not sure)

polar marten
#

they are serialized by value, which is implied when it's only declare by field order without values, and that's never what you want or meant

#

they can't be added to easily for other reasons

modern creek
#

hm.. I cannot figure out why this one particular trigger isn't looping in this very specific situation..

polar marten
#

you are almost always using them as sealed interfaces

vestal arch
#

check the animator pane to debug in general, see where it's stuck/looping

polar marten
#

aka states. they kind of make sense for options, but you might as well just use a bool.

modern creek
#

bit more zoomed in:

#

and the code I'm moving the toon around with

#
        public virtual IEnumerator MoveCoroutine(List<HexPoint> path, Action moveDoneCallback)
        {
            EntityAnimator.SetTrigger("Move");
            Sequence _moveSequence = DOTween.Sequence();
            _autoCompleteSequences.Add(_moveSequence);
            float timeStamp = 0f;
            foreach (HexPoint p in path)
            {
                Vector3 moveTo = p.WorldPosition;
                _moveSequence.Insert(timeStamp, EntityMesh.transform.DOLookAt(moveTo, UnitRotationTime).SetEase(Ease.InOutCirc));
                _moveSequence.Insert(timeStamp, transform.DOMove(moveTo, MovementTime).SetEase(Ease.Linear));
                timeStamp += MovementTime;
            }

            _moveSequence.AppendCallback(() => EntityAnimator.SetTrigger("Idle"));
            _moveSequence.AppendInterval(UnitDelayAfterMovementTime);
            _moveSequence.OnComplete(() => CompleteSequence(_moveSequence, moveDoneCallback));
            _moveSequence.Play();
            yield return _moveSequence.WaitForCompletion();
        }
#

(I snipped out some logging, but at runtime it's properly calling the triggers for move and idle)

vestal arch
# modern creek

have you selected the object the relevant animator is on? rather than the animator controller asset

modern creek
#

lemme double check - i may have selected the prefab

#

ah, i had - ok, this might be helpful but .. maybe not, I just see a blue bar rotating under the state I care about (ie, I can see it's going from move -> idle, but I can't really tell why)

#

oh interesting.... if I click on "move" in the animator it just zips back to idle after one iteration

vestal arch
modern creek
#

hmm.. the weird thing is I'm not mucking with the transitions at runtime or anything like that

modern creek
#

this is my runtime state

#

whatcha mean the conditions? on all the transitions?

vestal arch
#

yes

modern creek
#

hm.. i might be at my expertise limit - someone else did this controller - but it looks like the other meshes in my game.. in fact it looks like none of these should work since they all go from move -> move out -> idle

eager fulcrum
#

Hey, so I have a simple animator controller, with one 2D blend tree with animations for my 3d human.

I want to "task" animations (like sawing, throwing, fishing) etc to that, and I want to either play them by name or by id or something else. How can this be done? After the task is finished I want to go back to original blend tree

latent latch
#

By using the blend tree

eager fulcrum
#

thanks

#

will ask there

vestal arch
modern creek
#

Aight, this is still a good lead, thanks.

#

I suspect that I might be setting some of these triggers wrong. In any case.. more detective-ery

#

Oh, maybe one more question - sometimes I set the trigger ("Idle") and it stays, other times it disappears. Is this normal functionality?

vestal arch
#

it's reset automatically when consumed by a transition

modern creek
#

but not when looping on itself already, right? that's it

#

If I'm in "Idle" and I set the trigger - then trigger "move", the idle trigger doesn't get consumed until looping once on move.. so that's what's causing it to get "late set"

somber tapir
#

Will this work in a ScriptableObject or will it cause trouble in a build?

somber nacelle
#

provided you aren't trying to access that anywhere in a build it would be just fine. and the only reason it wouldn't be fine to access it in a build is because that field simply won't exist in a build

calm echo
#

!code

tawny elkBOT
hushed pawn
#

So I'm adding new things to a Scroll View's Content child object, they do show up in the Hierarchy. Content has a Vertical Layout Group and a Content Size Fitter component so it should be updating its size based on its children but that doesn't seem to happen unless I manually go into the Hierarchy and duplicate one of those existing objects. So in other words, the Content's Content Size Fitter doesn't update when I add things from code. I've tried Canvas.ForceUpdateCanvases(); and LayoutBuilder.ForceRebuildLayoutImmediate(grandparent), and disabling/enabling the VerticalLayoutGroup component on Content. Any ideas for what to try?

cold parrot
hushed pawn
#

That makes some sense as there are Scroll Views nested inside another Scroll View. And the top level Scroll View has a Vertical Layout Group also

#

But, problem is, that doesn't work. Rebuilding the layout doesn't resize the Content objects.

#

I can provide a video in the form of a gif if that's helpful.

lapis spade
#

can i show off what ive learnt here over the course of a month? or would that count as a showcase or something?

#

either way, unitys been really fun so far!

hushed pawn
# hushed pawn I can provide a video in the form of a gif if that's helpful.

Said gif. Showing that there's nested ScrollViews with Content Size Fitters and Vertical Layout Groups on the Content of each scroll view. When I move an object between inventories, they are created in the Hierarchy, but are unable to be displayed due to the Content not resizing correctly. Just unsure of how to resolve this, everything I've tried hasn't worked.

hexed pivot
#

hello! not sure if this is the right channel, but im trying to query lobbies using their service web api, but when i make the request i get an error asking me for a service-id header? don't see anywhere that mentions it in the docs, ive tried my service account key and secret key but then just get an internal server error when i try anything, anyone got any ideas?

hushed pawn
leaden ice
#

Provide some context please about which APi you're talkin gabout and the details of how you're doing it

hexed pivot
# leaden ice Provide some context please about which APi you're talkin gabout and the details...

Sure, I’m using Unity’s Service Web API, specifically the Lobby v1 endpoint. For the request the docs says I need a Bearer auth token to make the request, so im getting it with a service account through the Authentication Token Exchange API, which seems to be working fine. When I make the query request with the bearer token I get an error back saying I’m missing the service-id header, which I don’t see anywhere on the docs that mention that

leaden ice
hexed pivot
leaden ice
#

not sure if the link went to it

hexed pivot
#

ah i see what part your talkin about, that should be what the token is for but i guess i haven't tried the Base64 encoding for my key and secret key yet in the service-id header, ill give it shot tommorow morning

fallen pasture
latent latch
#

Is this like tetris

#

Looks like you'll need a grid regardless

#

Time to learn 2D arrays

calm echo
#

If you show your setup I can point out the issue

upper pilot
#

How do I make multiple sprites clickable as 1 sprite?
Ideally if it worked with world space canvas/UI, but I can try other things.

Basically I have a map which has a name tag(world space canvas UI) + some sprites(regular 2d sprites) for specific area of the map.
I want a player to click on the area(like trees/rock/building) to interact with it, right now I made it work with name tag since it's a canvas so I can detect mouse clicks easily.
But those areas consist of multiple smaller sprites and attaching "onclick" even of any sort to all sub sprites seems like a lot of unnecessary work.

kind willow
#

I don't get the exact issue but you can mark any image as non raycast target and you can add transparent sprites of any shape to be clickable

upper pilot
upper pilot
#

Or another way:
Can I detect a sprite with a mouse?
If yes, can I detect multiple sprites with a mouse as if they were 1 sprite?
My current solution is to simply place a collider/UI on top of my sprites

#

Thanks, earlier I thought that this is meant for something else, but this seems exactly like what I need based on the description 😄

warm badger
#

I have script with IPointerDownHandler. I wanted to avoid the touch or pointer to work when the touch is over another UI, i found i needed to use EventSystem.current.IsPointerOverGameObject...but fortunately i found that if I put any UI element under the gameobject the script is attached to(in hierarchy order), the UI will work as a blockage....i was happy...but my main project is in unity 2021.3...in this 2021.3, this doesn't work..meaning if i touch over that UI which i put below the script's gameobject, the script still works(i.e. the pointer is being recognized)....qhy it is different in 2021.3.? is there no way other than using EventSystem.current.IsPointerOverGameObject?

trim schooner
#

If you don't need to interact with the UI, disbale the raycasting on either each individual element, or all of it

warm badger
# trim schooner If you don't need to interact with the UI, disbale the raycasting on either each...

maybe i couldn't make it clear...actually i have a button on the screen...i dont want the IPointerDownHandler script to work when i am touching on that button...i just want that to work when i touch where there is no UI on the screen...In unity 6, when i put a UI element(panel is my case) under the script's gameobject(hierarchy order), touching on anything wwhich is under the panel...the touch doesn't work...I want this, i dont want it to work when i touch over any UI...but in unity 2021.3, even if i do the same, the script still works touching on any UI element

hushed pawn
still ermine
covert dust
#

Okay, this is probably gonna be real stupid.

I have a TextMeshPro object and on it a Content Size Fitter component so that the UI element resizes to take up exactly the amount of space the text element wants. What's the least pain in the ass way to have an UI image object resize itself to act as background for the dynamic text?

I tried parenting the image to the text and making it stretch to fit, but unfortunately that forces the image to render in front of text. Kinda wacky that I don't get to manually set render order in this simple scenario.

hushed pawn
covert dust
#

And then what?

#

how do I make the image follow the dimensions of the text element without having to hack that in? Or do I have to?

hushed pawn
#

Set the text to expand, the size fitter should make the image expand which will make the text also expand.

#

But you want the actual text to decide the size of the element. Hmm. Probably gonna have to make your own thing then.

covert dust
#

Sheesh

#

I'd imagine a dynamic size label isn't a rare use case

#

weird to see it being completely unaccounted for

covert dust
#

let's try

hexed pivot
calm echo
thick sinew
#

Anyone happen to know if its possible to use vscode with unity and have workspaces not break the relationship between the applications?

leaden ice
prime lintel
#

Im a little puzzled as to how I can have a stack overflow when setting a bool member of an object in my dictionary.

#

What have I done wrong to cause this?

leaden ice
#

That's a red herring

prime lintel
leaden ice
# prime lintel

looks like UpdateMobTracking is calling itself recursively

#

You have an infinite recursion

#

probably on line 139 there?

prime lintel
#

I see, thank you

#

Oh my god

violet nymph
#

Anybody know any good methods on making a grid snap system for objects of all sizes (1x1x1, 1x2x1, 2x2x2, 1x2x2, so on, just any sizes that are "stable", no halfs or anything?

Additional information on what I would like: A placement system where you can place objects on any sides of an object, it will snap to the closest 1x1x1 grid (as that's the smallest block I will have), for objects like 2x2x2, you could fit 8 1x1x1 in the same space, you won't be able to place objects inside each other (I know how to do this part, just not the snapping and such), this will be in VR, so it will need to be optimized as well (Which is why I mention below the method I said wouldn't be performant, as it requires being performant for VR on standalone quest 2 and up), if you need additional information, just ask any questions, and i'll answer them, as this is the best I can do to explain it.

The only method I can think of is using cubes as snapping points, but, it wouldn't be performant, and not very dynamic/easy to add onto with new blocks and such that players can use to build, it would work I'd assume, but, I would like a better method of doing this, possibly more dynamic than something like snap points would be.

tepid crane
#

Hey, im reworking my enemy AI from a jumbled mess of if checks to a state machine. I dont have a lot of experience working with them though and im jumping between tutorials, documentation and forums to figure it out. Currently i have one set up that correctly changes between states when a bool is set to true but i'm confused as how i am to port the existing code to them. If anyone is willing to help i can provide more info with screenshots and some more explanation.

#

here are some for now:

#

Im just not sure where its best to put the behaviour and references for NavMeshAgent, the animator and such

#

right now im thinking a GetComponentInParent in each state but im not sure if thats the correct way to do it

burnt briar
tepid crane
#

oh, well i have even less experience with enums tbh so im guessing its going to be a long night

leaden ice
#

enums are super simple

burnt briar
#

enums are easy. They are like named ints but you can easily understand them as they will be in english instead of remembering what a number means.

tepid crane
#

could you provide a simple example so that i have a place to start understanding how i would implement it?

burnt briar
#

1 min work at most

tepid crane
#

alright going to check that out, ill be back if i have trouble

#

alright i think i understand the basis now but how would they help in this problem?

burnt briar
#

Instead of checking multiple booleans, you will only need to take care of a boolean. It will remove logical errors as your state will be clearly defined. Nobody likes 10+ bools to handled and checked so that you reach a particular state.
Improves readability of the state machine in code and in inspector as it will be a single item on inspector instead of X number of bools.

polar marten
polar marten
violet nymph
# polar marten what kind of game are you making? most of the work isn't in aligning items to a ...

Well the part of the game I want help with, is the building, players will be able to place blocks on top of each other, on the sides of them, etc, build maps and so on, it's vr, so you just grab blocks and place them down somewhere and it will snap to the nearest block on the faces dependent on the size of the object so you can place 4 1x1x1 on a side of a 2x2x2 block, so on for other blocks

tepid crane
violet nymph
#

I'm not sure how to go any further, it basically subdivides it based on a 0.25 (the scale of a 1x1x1), so a 2x2x2 is a size of 1, which 1/0.25 is 4, so 4 new faces you can place on the centres of

violet nymph
#

It's just building

polar marten
#

you are describing something that takes weeks of work to develop

#

so i am eager to help lol

tepid crane
violet nymph
polar marten
#

don't get hung up on the multiple sizes of blocks. try to get the interaction right

#

you have to make decisions like rendering a ghost object, when to snap versus when to magnetize to the user's hand, etc.

violet nymph
polar marten
#

how to orient

#

yeah

violet nymph
#

I'd say I can orientate based on their controller orientation

polar marten
#

snapping an object to a grid is Mathf.Floor 3 times

#

it's not the challenging part

polar marten
#

there are like 5 generations of AR/XR featuresets in Unity

#

so you have to make a decision about which one to adopt

#

you have to decide how to use input system, whether or not to use tracked pose drivers, etc.

#

all the interaction stuff is much harder and much more subjective

violet nymph
#

I'm just using Oculus for the vr side, and xr interaction manager for interactions

#

I already understand interactions

#

I have a good understanding on how to grab blocks and so on, but, not placing them

polar marten
#

okay well, should i hold a controller button in order to hold a cube? how close should my hand be to a cube to move it? can i move it after it has been placed? how do i highlight that, when there could be a "deep" number of objects? etc. etc.

polar marten
#

the hard part is having an opinion ahead of time about how all the interactions should work. because they are all going to be very tightly coupled together

#

interactions in the sense of, like where do the blocks come from? what if you want to use two hands at the same time to build? can you do that? does the orientation of the controller allow you to set the orientation of the block? is that going to appear in the ghost that is pinned to a grid position? etc. etc.

#

there's so many questions

violet nymph
#

I would just do them based on controller binds, such as grip to pick them up, you can pick them up after placing, your hand needs to be in a small distance from the closest point to bounds, then you grip, and it will pick it up, go smaller in your hand, then you can throw it again to place it somewhere and it will snap

polar marten
#

throw it?

violet nymph
#

Blocks would be purchased from an inventory sort of thing

#

Yeah, you could either place it normally, or just throw it, wherever it lands, it will calculate the snapping point

polar marten
#

it's going to take you like 3 days of solid, nonstop work to implement that

violet nymph
#

Not a problem for me

#

I'll do the work

polar marten
#

because all the interactions are very tightly coupled

violet nymph
#

It doesn't bother me

polar marten
#

so you need to write all this stuff up ahead of time

violet nymph
#

Alright, i'll start planning things so it will all be solid and probably put it in some notes or something on how it will all work

polar marten
#

i mean it feels like they are decoupled. but if you get rid of the grid system entirely, you see that it's an immense amount of work left over right?

burnt briar
polar marten
#

if you use the word "just" this is going to be hard

#

you have used the word just like 10 times

violet nymph
tepid crane
#

ok so i have the references i need set in each script state?

polar marten
violet nymph
#

Some blocks will be locked to the base map

violet nymph
polar marten
#

write the simplest possible way you can think of to keep track of blocks. data structures and stuff like that can be revisited later

#

your interactions for a 3x3x3 building space will not scale up to a 10x10x10, BUT. there IS NO GAME for building 10x10x10 spaces, if that makes sense.

#

there's a reason there is only 1 minecraft

violet nymph
#

All blocks will be even sizes, so, you'll be able to place them without any overlapping, I'm not sure what you exactly mean about the spaces and such though

#

Is it possible to make Mathf.Floor to not go to ints, instead, go to increments of 0.25

#

Or another method will have to be used

violet nymph
vestal arch
#

or Floor there would also work

violet nymph
#

I was definitely overthinking everything

burnt briar
tepid crane
#

i started doing this

vestal arch
violet nymph
vestal arch
#

it's not really a specific formula

#

just kinda something you can pick up with experience

#

not really math heavy

#

the logic being; floor/ceil/trunc/round work on increments of 1, so if you want a different increment, you have to scale that increment to make it 1, then scale it back

violet nymph
#

Yeah, I'll have to actually look into methods for math, as, I haven't done so yet

polar marten
polar marten
# tepid crane

i think you should use a behavior tree.
this script isn't really a ChaseState. it's part of an Enemy script, which you have spread out onto files that end with *State.cs

#

which is okay this stuff is kind of hard lol

#

@tepid crane you should decide what it is you are trying to decouple from what

#

i mean, what is it that you want to reuse exactly?

#

or change later?

tepid crane
#

im trying to phase out the enemy script

polar marten
#

hmm why though

tepid crane
#

and replace it with the state machine

#

for ease of future expansion

#

so yeah I'm just splitting it into states

polar marten
#

you're really spreading it out onto files you are calling states

#

but this is just the same file split up

#

which is okay

#

it's okay.

tepid crane
#

yeah but with a lot less if checks and the ability to change states later

#

like if i want to have a ranged enemy the idea is i turn up the attack range stat and replace the attack state

polar marten
#

what kind of game is this?

tepid crane
#

an fps taking inspiration from cruelty squad

polar marten
#

are you using an asset or the really nice unity ECS example to set up the fps elements of your game?

tepid crane
#

no its all made from scratch

#

some based on tutorials but most just on documentation

polar marten
#

cool. well i think you have your work cut out for you
fps games follow a lot of tradition.
the enemies are almost all scripted by authoring a bespoke script for each one. i think this is because everything is so tightly coupled

#

for example a ranged versus melee enemy will move around the world with respect to the player very differently

#

so they basically do not share anything in common in terms of behavior

burnt briar
# tepid crane

Have a manager. When a state is done with its work. It will only inform that it is done. Not what is next.
The manager will decide which state is next and tell that state to start working.
A state should not be informing what is the next state.
This will allow you to have more states and you will not need to go and change code again and again for every new state.
https://gameprogrammingpatterns.com/state.html
This will help you

polar marten
#

state machines are truthfully kind of a code smell

#

this is why you basically never see them in any real APIs

#

and whenever they do appear, they are sort of worthless.

#

at least in my experience, it has always been, "the name that the programmer assigned to this collection of behaviors isn't any less useless just because it has the string State prefixed to it"

#

for example, i know you know nothing about grpc connections.

Connecting, Idle, Ready, Transient Failure, Shutdown

what do these states mean? i have bad news for you. the names are terrible. and this was designed by google.

tepid crane
#

i mean i see it being better than my earlier solution but i don't know how good it is compared to even better ones

polar marten
#

so you are kind of trying to shove a problem that even a bunch of full time google engineers couldn't get right into your "develop a whole fps game" problem

burnt briar
polar marten
#

and yeah. i mean, you're here. you're showing a State class that you are calling a State but is really your Enemy script chopped up

tepid crane
#

chopped up in different states though

polar marten
#

yes but it hasn't helped you, it has only actually made things harder

#

this is a subjective opinion

tepid crane
#

will it not be better later on though?

#

i truly don't know any better sorry if i sound stupid

polar marten
#

no no you're not stupid at all

#

it was the right instinct to ask about this

#

it's smart to have posted an actual bonafide snippet of what you're doing

polar marten
#

it can help with modeling enemies in platformers

burnt briar
#

Doc, i think you saying something very wrong in my opinion.

polar marten
#

it really depends on the game and the goals

burnt briar
#

It never depends on the game. State machine can be used for almost everything.
A game after all has states. A start, a middle and a end.

polar marten
#

i'm really saying that almost every way it is implemented does not help people. of course, having an intellectual model of states is useful, but if i were only to talk about the aesthetic/psychic experience of what helps you program, you know, provigil is going to help you more than state machines

#

i'm just kidding

#

there can be an objective assessment - most implementations of state machines, including the one that is right in front of us - do not help the people implementing them as an alternative to whatever code they wrote first

#

the subjective assessment - don't use them at all - yeah. i mean, you shouldn't follow the kind of brain dead tutorials that talk about making csharp state classes or whatever

#

does csharp even have sealed interfaces? i don't think it does

tepid crane
#

i dont know half these words tbh

polar marten
#

lol

#

it's okay. all i'm saying is that you should probably try a behavior tree asset. especially one that is already focused on FPS games

#

there's little in common between a melee and ranged enemy in an FPS. you should think very deeply about your expectations for what you will reuse anyway

burnt briar
polar marten
#

i'm really not trying to discourage you, it's the opposite. i think you have a great instinct, you were writing something about States, and your code didn't feel right, and you posted it, and indeed, it looked like you were spreading out your enemy script

polar marten
# tepid crane

this snippet in particular. it's very illuminating of the problems that the state abstraction introduces

burnt briar
tepid crane
#

welp i have to go either way, thanks for helping, if you can point me in a better direction i will check chat logs a little later 😄

polar marten
#

personally i think you should author your enemy behaviors, as much as you can, as something that is occurring in a coroutine. this is a totally different approach, but looks al ot more like what your original enemy script probably was

#

if you want a name for something reusable, you know, it's just a method. just call it. i woudln't overthink it

#

coroutine = IEnumerator or something declared async

thorny lagoon
rigid island
#

stick to one channel

#

also at very least make some attempts / tell us what debugging steps did you take..

thorny lagoon
rigid island
thorny lagoon
#

and it shoots backwards

#

when i walk forward and sides it works

rigid island
#

send the code with a proper site !code

tawny elkBOT
rigid island
#

dont use PasteBin , like ever

thorny lagoon
rigid island
#

jesus is the language that diffcult for you to select

#

wait nvm

#

Draw your direction and see whats happening

#

Debug.DrawRay(bulletSpawn.position, shootingDirection * 100)

devout field
#

TL;DR: I need to rotate a Vector3 by an angle and for some reason it's getting rotated wrong.

I need to delete voxels around small area where I click. They're represented by an array, so to use that position where I clicked for array, I need to find it relative to the position of the object. But that is not enough, since the object can also be rotated, I need to kinda unrotate it back. You can see the method RotateVector() in the first image I added, which I tried to use to rotate it back and THAT where I have the problem. I added a video to show how it looks like, I am literally clicking everywhere and only a small chunk on the corner got deleted. Maybe the problem is in my RotateVector() or that I need to rotate it by something else instead of -transform.eulerAngles to unrotate it? Or I am doing it wrong way at all? In addition, sometimes that works and sometimes it doesn't. And it makes me even more confused.

heady iris
#

you should use Debug.DrawRay to figure out what rays are actually being casted

devout field
polar marten
#

the rotation isn't what you think it is

polar marten
#

what is your goal i mean

devout field
polar marten
#

what are you trying to do?

devout field
polar marten
#

well this is the road to be less confused about what is going on

devout field
polar marten
devout field
hexed pecan
polar marten
hexed pecan
#

You can use transform.InverseTransformPoint

#

To convert from world to local

devout field
polar marten
#

do you remember from web development how there is something like onclick = function() { ... } ?

#

that exists in unity too

#

it's much simpler

#

it's called event system and it will make your life a lot easier

devout field
#

So you want me to add OnPointerClick() for the object's script for this?

polar marten
#

i mean you have to do literally everything in the little tutorial it wrote up for things to work

hexed pecan
polar marten
#

i asked it to start from zero on purpose

#

if you want ot make a game where you shoot terrain and it blows up

#

you should probably start with an asset, especially one that is part of a bigger FPS package

#

because that's probably what you want right?

devout field
devout field
polar marten
#

hmm... okay well teardown is an fps no?

polar marten
devout field
polar marten
#

i think the raycast is working

#

i think there's a lot going on

#

and you need a robust way to express what you want

#

it's simpler to have scripts with OnPointerClick methods.

devout field
#

ok

hexed pecan
#

Do we even know that the ray is the issue? Draw the ray and see, like Fen suggested

polar marten
#

i don't think the ray is the issue

#

there's stuff about a rotation in there that doesn't really make sense

#

it's fine

#

i would approach things in a more literal way. the trick is to know how to click on game objects

hexed pecan
#

They are already clicking on an object

#

Just need to use InverseTransformPoint to get the correct local pos

polar marten
#

the user is reinventing eventsystem

hexed pecan
#

I haven't seen what ApplyImpact does with the value, though

devout field
wheat cargo
#

This is a theoretical question. Are instance id's reused after an object is destroyed. The reason I ask, is if they are not reused could you theoretically run into a situation where you can run out of instance ids if you generate tons of objects throughout the lifetime of the application?

leaden ice
#

It's not documented whether they are reused or not

wheat cargo
leaden ice
#

It's almost certainly not something you need to worry about

#

If you're creating that many objects you're sure to run out of memory before something like this is a problem

polar marten
polar marten
#

i wouldn't use it as an actual identifier

wheat cargo
#

So I guess the answer is no they are not reused

#

unless it overflows

#

Interesting that they mentioned it is different on 32-bit vs 64-bit, because the managed side always returns a 4 byte integer

polar marten
#

i don't think the unity staff member answered the question correctly lol

#

so it's really hard to say

wheat cargo
#

Lol you are probably right

polar marten
#

you'd need a $5k source license

steady bobcat
#

probably due to the use of say long in cpp where its often not 64 bit but 32... (why typedefs such as int64_t exist to avoid this)

#

and ofc unity can do whatever they want to a value sent from native to managed code

leaden ice
#

he said "unless you run it long enough that it overflows"

#

sounds like there's nothing stopping it from overflowing

cold parrot
hexed pecan
devout field
hexed pecan
#

Just ImpactPos = transform.InverseTransformPoint(ImpactPos);

wheat cargo
cold parrot
devout field
hexed pecan
#

Yeah

hexed pecan
#

@devout field If there's still an issue after that, show the ApplyImpact method

rigid island
thorny lagoon
#

im walking backwards and shooting

#

i have to go rn

rigid island
hexed pecan
# devout field Yeah there is still an issue.

Pretty sure that you should convert from local coordinates to voxel coordinates here.
Unless your local coords match up perfectly to the voxel coords: zero is at center and voxels are 1x1x1 units in size

devout field
wheat cargo
hexed pecan
devout field
thorny lagoon
rigid island
#

cant tell which way you're supposed to be looking

#

just make the shootDirection come from camera.forward

#

the point of DrawRay is to visualize better , you know for a fact no physics is a affecting your rigibody dir and wat you're seeing is actually the direction its trying to shoot towards

thorny lagoon
rigid island
#

maybe replace Vector3 shootingDirection = CalculateDirectionAndSpread().normalized;
with shootingDirection = cameraObj.transform.forward
see what happens

#

find the point of unexpected values

fervent coyote
#

Creating a starving mechanic for my game, in game it correctly adds but also removes the effect afterwards... why?

{
    Player_StatusEffectAdd("Effect_StarvingRisk");
}
else if ((Player_Calories > 650 && Player_Calories < 250) && Player_HasStatusEffect("Effect_StarvingRisk"))
{
    Player_StatusEffectRemove("Effect_StarvingRisk");
}```
soft shard
# fervent coyote Creating a starving mechanic for my game, in game it correctly adds but also rem...

You could try adding debug logs before and in your statements, to make sure your "calories" is expected values, its possible theres a frame where your else-if becomes true, although if im reading your code right, it doesnt look like your else-if CAN ever become true, since the variable could be above 650, but if it is, then its impossible to also be below 250, and vice versa, if the value is below 250, its impossible to also be above 650 - which suggests to me your else-if may not be running, and possibly the issue is somewhere else in your code? (logs or breakpoints should help in debugging that)

fervent coyote
#

It's running, in the game it constantly let's me know that 'Starving' was added, and it never appears in the status effect window I made

cosmic rain
fervent coyote
#
if ((Player_Calories <= 650 && Player_Calories >= 250) && !Player_HasStatusEffect("Effect_StarvingRisk"))
{
    Debug.Log($"Adding Starving Risk @{Time.timeAsDouble}");
    Player_StatusEffectAdd("Effect_StarvingRisk");
}
else if ((Player_Calories > 650 || Player_Calories < 250) && Player_HasStatusEffect("Effect_StarvingRisk"))
{
    Debug.Log($"Removing Starving Risk @{Time.timeAsDouble}");
    Player_StatusEffectRemove("Effect_StarvingRisk");
}```
Here's how it is now, it still doesn't work

But I have noticed it never 'removes' it in the debug, but it also constantly adds it for some reason (but it also never shows???)
#

OK

#

I feel stupid

#

Because I figured it out and was a completely unrelated issue

soft shard
#

Happens, least you found the source of the problem

fervent coyote
#

What happened is it removes effects if the duration is 0 (Because I'm using the same system as bleeding effects, poison, etc)

I put a sloppy fix for this: Player_StatusEffects.RemoveAll(x => x.duration <= 0);, but because the durations of these effects are set to 0 (Because they're not supposed to go away), it removes them anyway

queen kayak
#

So started the day cussing unity for not having a double precision coordinate system in 2025. Ive had to work around this before but making a game at solar system level scales, and not being able to just rely on origin shifting due to having to calculate orbits accurately for all bodies even at large distances.... tried a few options, first tried just eating the precision loss of distant objects and keep as much action closer to the origin as possible... Did'nt work well as orbits would degrade due to the poor precision. Tried a tile based system and simulate every body in a local space... was to expensive.... Finally decided to keep a double precision state of position for every body, act my physics logic out on that, and every frame cast that value to a local single precision float with origin shifting..... Somehow this is faster than when i just used single precision.... How is it faster to calculate in double precision, then cast to single precision to update transform every frame?? So Confused.

safe dock
#

im working on multiplayer, and the character controls the other players movement, not their own. ive been struggling on this for an hour so i just decided to come here

safe dock
#

oh my bad

#

im new to this server

woven pendant
#

hi, i wanna make the button "E" click this button on this world space canvas instead of having to use left click, how would i do that?

#

also, is it possible to be able to click the button with a pointer locked mouse?

#

sorry for the insanely laggy footage

woven pendant
#

is it not possible?

woven pendant
#

webfiorfnbhgeyihcjd

edgy ether
#

ok maybe im overthinking this, but im doing an foreach in an update, but you know there's the usual "dont change items in a list while you're using that same list" error/warning screaming.

i want to use a new temporary list for my list so like foreach (var player in Players.ToList())

but im using this in a fixed update so my concern is that if this creates a buncha new lists somewhere i can't see. how do i know if they get removed/cleared? im worried that this could scream memory leak

lean sail
vestal arch
#

the gc collections might be an issue; can't say for sure without profiling though

#

could you elaborate on what exactly the foreach is for?

lean sail
edgy ether
woven pendant
vestal arch
lean sail
woven pendant
#

that sucks

#

thanks anyways

edgy ether
# vestal arch could you elaborate on what exactly the foreach is for?

oh was making a level mechanic. players would grab onto an object and it moves them for a specific amount of time as if they were winding up then it launches them. but since the variables are all within the mechanic itself i was making dictionaries to keep track of multiple players 's progress that's using that one component

#

after the player completes the whole mechanic, they are removed from the list/dictionary

#

other than that if there's nothing in the list it's not going to iterate through the list.

vestal arch
#

so is it a list or a dictionary..?

edgy ether
edgy ether
#

i ended up using both because it was a bit easier to iterate through a list. but i can't just simply do remove all because not everyone finishes at the same time

vestal arch
#

RemoveAll isn't Clear

edgy ether
#

i mean it works and all, i was mostly just worried about garbage piling up

vestal arch
#

it removes stuff that matches the given predicate

edgy ether
#

but i was more worried about a whole bunch of empty lists being made and them not being removed

#

but if .ToList() create a temporary list to iterate one time then throws it away, that gives me relief

vestal arch
#

i mean it technically doesn't throw it away; it's still there, and then when after a while the gc removes a bunch of them at once
they do pile up a bit, but not infinitely as a memory leak

edgy ether
#

oh ok well that's fine

#

scens get reloaded alot so i guess i wont worry too much about it

#

but perhaps i should make something that keeps tracks of all the created lists just in case lol

#

a list of lists if you will lol

vestal arch
#

keeping that list just makes them not get freed

edgy ether
white dew
#

i'm following git-amend's command pattern tutorial, and I can not for the life of me figure out what's going wrong. I have these two classes that implement the ICommand interface which only has one method public abstract Task Execute()
Here are the classes

using UnityEngine;
using static System.Activator;

public abstract class ActorCommand : ICommand 
{
    protected readonly Actor actor; 
    protected ActorCommand(Actor actor)
    {
        this.actor = actor; 
    }

    public abstract Task Execute(); 

    public static T Create<T>(Actor actor) where T : ActorCommand
    {
        return (T) CreateInstance(typeof(T), actor); 
    }
}

public class PoisonCommand : ActorCommand
{
    public PoisonCommand(Actor actor) : base(actor) { }

    public override async Task Execute()
    {
        var damage = Mathf.RoundToInt(actor.MaxHealth * -.1f);
        actor.ChangeHealth(damage);
        await Awaitable.WaitForSecondsAsync(1f);
    }
}```

when I try to call `ActorCommand.Create<PoisonCommand>(this)` it throws me this error 
```MissingMethodException: Default constructor not found for type PoisonCommand```
any thoughts?
thin aurora
#

I'd try doing a full recompile and then try again

white dew
#

alright ill try that out

thin aurora
#

It's surprising this is even possible in Unity, if that's the problem.

#

Alternatively try wrapping the parameter of CreateInstance in object[]

return (T) CreateInstance(typeof(T), new object[] { actor }); 
#

Another thing is explicitly specifying the constructor to use. 1 sec

#

Not sure why it's so hard to find this attribute

#

You can try marking your constructor with this

white dew
#

ill read over that link too

#

thank you for you help!

thin aurora
#

You're welcome 👍

somber nacelle
thin aurora
#

I am aware of that

somber nacelle
#

okay so then surely you know it isn't included in unity so they wouldn't be able to mark the ctor with the attribute

thin aurora
#

Because it's not possible to add the package even though it's supported by Unity? I'm confused what the problem is

#

It was one of the possible solutions. It ended up not being required

#

And thankfully, because this seems to be specific to ActivatorUtilities and not Activator, which despite the weird wording is actually quite a bit more complex of a system. I didn't realize it wasn't for Activator until after posting

languid hound
#

Just curious is there any actual benefit to using the new FindObject(s)OfType? Like a performance benefit or something?

#

I'm gonna use the new version anyways because warnings irritate me but it feels like it was a pretty unnecessary change lmao. FindObject(s)OfType was so much nice to type

somber nacelle
languid hound
#

Ohh I see thank you!!

#

Still relatively new to Unity 6 so I didn't realise it had a sort mode

thorny lagoon
#

it gives me 5 error

vestal arch
#

you gotta define cameraObj

#

nav wrote that as a placeholder to make it obvious what it's supposed to represent

thorny lagoon
vestal arch
#

then use that

thorny lagoon
vestal arch
#

you didn't use that

#

it's playerCamera, isn't it?

thorny lagoon
#

oh yeah

#

it works but now spread is broken

steady bobcat
#

Not your problem but do Invoke(nameof(ResetShot), 1f) if you must use it to call something after a delay

#

or use a coroutine/async method only and stop using Invoke()

thin aurora
#

Or use Time.time and use timestamps the proper way (see example code in the documentation)

steady bobcat
#

some logic it would be better for so you can simply deny an action if enough time has not passed

thin aurora
#

I mean the main issue is that delay logic is now tied to firing logic and hardcoded behaviour

#

A timestamp just means that you can set various timestamps for a delayed action like when a cooldown ends or when to fire again

#

Then it's a matter of checking these in an Update and behaving accordingly. For example, if your burst fire weapon has to fire its next shot at some point you can just check if the timestamp passed from Update and fire it again. You can block all other actions that can't happen during this period simply by checking if the timestamp is set

steady bobcat
#

Personally id have an async function do the whole process and delay within it.

thin aurora
#
public class Example : MonoBehaviour
{
    private float? _nextBurstFireTick = null;
    private float _burstFireInterval = 0.1f;
    private bool IsBurstFiring => _nextBurstFireTick != null;
  
    void Awake()
    {
    }

    void Update()
    {
        // Fire the next shot
        if (IsBurstFiring && Time.time > _nextBurstFireTick)
        {
            Fire();
            _nextBurstFireTick = Time.time + _burstFireInterval;

            // Additionally you'd increment some counter here to ensure we stop firing at some point.
            if (HasShotThreeTimes())
            {
                _nextBurstFireTick = null;
            }
            return;
        }

        // Start burst firing
        if (PressedFire())
        {
            Fire();
            _nextBurstFireTick = Time.time + _burstFireInterval;
        }
    }
}

Semi pseudo code, gets you an idea of how Time.time can very easily be included with a system so you can separate the burst firing logic

#

Additionally, it's very easy to include additional steps such as being able to configure shot count and all that through variables. Not necessarily tied to the feature, but you get the idea

#

The convenient thing about this is also that you're not hard tied to an interval. If for some reason you want some sort of cooldown, you could just decrement the value of _nextBurstFireTick instead of extra steps to get it working
And also, if you had to tie a visual indication of the time left, you can just get the difference _nextBurstFireTick - Time.time and use the result in some progress bar for example
And lastly, if it matters to you, this is very multiplayer friendly since you just need to inform users of the next timestamp in most cases.

#

@thorny lagoon

azure frost
#

So, continuing on this project... I'm getting close. The swim controls are EXACTLY what I want, but now the animation is bork'd.

thorny lagoon
thin aurora
#

Regarding your use of Invoke and possibly improving on the whole system that waits for shooting/burstfiring

thin aurora
#

Apart from all the points explained in the messages? 🤔

#

Note this was more a follow up comment on the use of a Coroutine/async method and not necessarily to your problem. You're free to use whatever you want

#

Invoke is whack though, I would consider something else. I explained thoroughly why timestampt benefit your flow a lot better

valid coyote
#

How can i append a FixedString inide a Job with "some word"? If I do .Append("some word") it breaks the Job because it treats "some word" as string. Is there a work around?

leaden ice
valid coyote
leaden ice
molten musk
#

I really need help i need to work out what the max speed a gameobject on a 2d plane can go so as not to overshoot its target

#

maxSpeed = Mathf.Clamp(rb2D.velocity.magnitude * (CalculateDistance(transform.position,desiredPosition) / slowdownDistance), 0, maxSpeed);

this was as close as i got but it doesnt work

leaden ice
#

An object in motion will generally move forever in that direction until some force stops it. So any speed will always overshoot the target

#

Maybe you have drag enabled?

#

And you want to calculate how far it will go with drag?

#

Also we have no idea what CalculateDistance or slowDownDistance does

molten musk
#

the object will try and match the maxspeed using its deccelaration variable

#

there is no drag

#

float slowdownDistance = (rb2D.velocity.magnitude * rb2D.velocity.magnitude) / (2 * decceleration);

#

calculate distance simply finds the distance between two points

#

I just need a method of making sure it deccelerates to stop at the position im trying to get it to

leaden ice
molten musk
#

no?

leaden ice
#

Then you can stop on a dime

#

and there's no minimum distance you need to stop

molten musk
#

decceleration is constant

leaden ice
#

And what is it? How is it used?

#

This is all missing information from the question

molten musk
#

this is more of a maths/physics question then unity specific

#

i need to know at what distance to slow down so i dont pass the target

#

given a speed and decceleration

leaden ice
#

You have:

  • Some starting velocity (the initial jump speed)
  • Some constant acceleration (gravity or your constant deceleration factor)
molten musk
#

float slowdownDistance = (rb2D.velocity.magnitude * rb2D.velocity.magnitude) / (2 * decceleration);

i believe this is correctt

leaden ice
#

Heightpeak = ½ * (vtakeoff² / deceleration)

molten musk
#

but then i need to dynamically set the max speed so as to not overshoot

leaden ice
#

i.e. at what distance to start decelerating?

molten musk
#

i can try just using that

#

ok now its not setting the target position correctly

#

it gets it here

leaden ice
#

!code

tawny elkBOT
molten musk
#
// Your code here
void Update()
    {
        if (!player.gameObject.GetComponent<NetworkObject>().IsLocalPlayer){
            return;
        }//DO NOT RUN IF NOT LOCAL

        if (player.selected.Count == 0){return;}
            if (player.selected[0].GetComponent<Ship>() == null){
                return;
            }

        if (Input.GetMouseButtonDown(1)){
            player.selected[0].GetComponent<Ship>().moveShadow.SetActive(true);
            startMousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            player.selected[0].GetComponent<Ship>().desiredFinalPosition = startMousePosition;
        }
        if (Input.GetMouseButton(1)){
            player.selected[0].GetComponent<Ship>().desiredFinalRotation = GetRotationToTarget();
        }
        if (Input.GetMouseButtonUp(1)){
            player.selected[0].GetComponent<Ship>().desiredFinalRotation = GetRotationToTarget();

            Vector3 position = startMousePosition;
            Vector3 direction = GetDirection(player.selected[0].transform.position, position);
            Quaternion rotation = GetRotationToTarget();
            
            Ship.Order newOrder = new Ship.Order(position,direction,rotation);

            player.selected[0].GetComponent<Ship>().NewOrder(newOrder);
        }
    }

gets it here

#

(thnx btw)

leaden ice
#

I don't really know what I'm supposed to do with this

molten musk
#
// Your code here
    public void NewOrder(Order newOrder){
        orderList.Add(newOrder);

        if (orderGiven){
            return;
        }
        orderGiven = true;
        foreach (Order order in orderList){
            Debug.Log("Pos: "+order.position);
            //debug.Log(order.direction);
            //debug.Log(order.rotation);
        }
        NextOrder();
    }

why is the given position wrong?

#

its like .53 instead of -6.9

leaden ice
#

presumably you passed in the wrong position

molten musk
#

i suppose but i cant work out where

#

the move shadow has the correct position but it isnt being passed into the ship correctly

#

player.selected[0].GetComponent<Ship>().desiredFinalPosition = startMousePosition;
Vector3 position = startMousePosition;
these two are identical though

#

it should be the same value but its not

#

wait

#

found it

#

new Ship.Order(position,direction,rotation);

public struct Order
{
public Vector3 direction;
public Vector3 position;
public Quaternion rotation;

    public Order(Vector3 v1, Vector3 v2, Quaternion q)
    {
        direction = v1;
        position = v2;
        rotation = q;
    }
}
#

position and direction are swapped

leaden ice
#

v1 and v2 are so useless

#

or just skip the constructor for thie struct and use an object initializer

molten musk
#

ive been doing this for 6 houtrs i code bad when im frustrated

#

almost got it i think

rigid island
#

narrowing down the issue was part of the fix

molten musk
#

nope still stuck lol

hexed pecan
#

For some reason though, it's broken for structs in VSCode...

heady iris
#

infinite pain loop!

#

my favorite

molten musk
#

yeah

#

i really need help with this one i think im so clost but i cant get this last bit to work

vestal arch
hexed pecan
#

Well, I don't see people doing new Vector3() { x = 1, y = 2, z = 3} 😄

#

Just unnecessarily verbose

vestal arch
#

yeah, because Vector3 actually provides that constructor, so why use the assignment form

hexed pecan
#

That's my point?

#

They made a constructor for it

#

I'd like to do the same for my struct

#

It used to be present in VSCode but now it's just gone 🤔

vestal arch
#

where's the option? never used autogen before

hexed pecan
#

Rider and VS give a proper UI for it though, where you can select what members to include with checkboxes

#

Wait that just makes an empty constructor now... huh

vestal arch
#

i swear i tried that. now it shows up lmao

#

code actions on the field works

#

seems to only work for single fields though

#

oh if you select multiple fields, it'll gen for the selected fields

#

wait nvm i don't know how this behaves 😭

#

for int x, y;, cursor behind x -> C(int x), cursor behind y -> C(int y), cursor after the semicolon -> C(int x, int y)

hexed pecan
#

Okay so if i want a (x, y) constructor here, I need to first generate a constructor for x

vestal arch
hexed pecan
#

And then add y to it from here

vestal arch
hexed pecan
vestal arch
hexed pecan
#

Thanks for pointing that out, didn't even realize that fields have constructor quick actions too

#

Bit of a hack since you have to add each one separately but it's better than nothing

#

Structs usually don't have many members anyway

hexed pecan
#

I see, yeah that works if the fields are on the same line

vestal arch
#

or if you select multiple fields

hexed pecan
#

I like how rider does it

vestal arch
#

as in the second screenshot

hexed pecan
#

I see now, yeah that's closest to what I was looking for, ty

polar marten
vestal arch
late lion
sleek bough
vestal arch
sleek bough
unkempt swallow
#

idk where to put this so here it goes, im working with an asset, it comes with a Climbable.cs, it inherits(?) from the class Grabbable.
So when i put it on a gameobject i should see all the options that Grabbable has (public) in the inspector right? if no, whatever.

What i dont understand why i have the same script on two gameobjects but one shows me everything and the other one doesnt 6221_Dead_inside any advice?

vestal arch
unkempt swallow
#

no change sadly

vestal arch
#

what about Custom Hand Pose?

unkempt swallow
#

none of the options change anything

late lion
unkempt swallow
#

they are the same exact script, thats why im losing my mind over it

#

oh wait

#

i found something, it has a custom Editor script, ClimbableEditor

#

i did not even know something like this is possible , but thats the cause of my problem

heady iris
#

Yeah -- you can write a custom editor for any type

viscid plaza
#

TransientArtifactProvider::IsTransientArtifact call is not allowed when transient artifacts are getting updated

#

I get this printed 6 times to the console. No clue what it means.

hexed pecan
#

Try reimporting your assets/nuking your library

stone atlas
#

SO i have 2 problems with this virtual gallery that I am making which is annoying me a bit.

  1. For some reason, I am unable to jump in this art gallery, I have tested it on another scene and my jumping mechanics works perfectly. And i've tried changing some settings and making sure the layer I am on in correct. but it doesnt work.

Any new knowledge would be great since I started learning unity a couple days ago.

Fixed the wall problem

wheat cargo
#

Get it in update and cache it for FixedUpdate

#

Ohh nevermind you are doing that, my bad

stone atlas
#

no worries, thnks for the future knowledge

wheat cargo
#

Also might want to move the Jump to FixedUpdate, but it might be fine since it is an Impulse force

tawny elkBOT
stone atlas
#

Oh alright, im sorry ill do that now. and ill try the debug thing

hexed pecan
#

Also, using GetKey in FixedUpdate is fine. GetKeyDown is not

wheat cargo
#

Thoughts on this method to get root canvas?

private Canvas GetRootCanvas()
{
    return transform.root.GetComponentInChildren<Canvas>();
}
lean sail
wheat cargo
wheat cargo
stone atlas
hexed pecan
stone atlas
#

YEa im pressing space and nothing is coming up in the console. So maybe its jut that it doesnt thhink im grounded

#

my debug log in question

lean sail
wheat cargo
stone atlas
#

Alright, its not the layer thats the problem. my whole asset has the layer "whatIsGround" and I still cant jump for some reason.

hexed pecan
wheat cargo
wheat cargo
#

I'll change the code to traverse up the heirarchy instead

hexed pecan
#

Where are you calling this code?

#

Like how often

#

I have the same concerns as bawsi

wheat cargo
lean sail
wheat cargo
#

I mean this is in the Show method of TMP_Dropdown, so it's definitely done in other UGUI components.

// Get root Canvas.
var list = TMP_ListPool<Canvas>.Get();
gameObject.GetComponentsInParent(false, list);
if (list.Count == 0)
    return;

Canvas rootCanvas = list[list.Count - 1];
for (int i = 0; i < list.Count; i++)
{
    if (list[i].isRootCanvas)
    {
        rootCanvas = list[i];
        break;
    }
}

TMP_ListPool<Canvas>.Release(list);
wheat cargo
stone atlas
#

Yes my ground object is on the that layer and has a collider

naive swallow
wheat cargo
#

They did in screenshot above a bit

naive swallow
#

Ah, I had to scroll a bit before the code, I stopped scrolling when I saw the code

stone atlas
lean sail
wheat cargo
lean sail
#

i could see that being reasonable then

waxen oak
#

Anyone that could help me get into c# coding?

naive swallow
tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

wheat cargo
naive swallow
# stone atlas im using "whatIsGround"

So, the issue is your log in Jump isn't getting called, right? Try putting a log before the condition Jump is called in, log every part of that statement

stone atlas
thorny lagoon
waxen oak
wheat cargo
stone atlas
#

its telling me that im ready to jump but i just cant

waxen oak
wheat cargo
#

I would also change it to Input.GetKeyDown for jump

stone atlas
#

so maybe its my ground check not working properly?

wheat cargo
wheat cargo
wheat cargo
stone atlas
#

i was so confusedl ol

wheat cargo
#

my bad, I'm dumb

naive swallow
waxen oak
wheat cargo
past elk
#

how i can rotate a gameobject around itself randomly

#

it is for a dice

wheat cargo
naive swallow
#

If it has a rigidbody, rigidbody.angularVelocity = Random.insideUnitSphere * forceMultiplier

#

It'll get it started spinning in a random direction with some amount of force

naive swallow
#

Then you can do Transform.Rotate instead, but you'll need to put it in update and run it every frame

waxen oak
wheat cargo
past elk
#

no, i dont drop it

#

it is floating

#

transform.Rotate(Vector3.left * rotationSpeed * Time.deltaTime + Vector3.up * rotationSpeed * Time.deltaTime + Vector3.forward * rotationSpeed * Time.deltaTime, Space.Self);
i have this, but it is think it is to complex

naive swallow
past elk
#

yeah

naive swallow
#

If you want it to be random, you're going to need randomness

past elk
#

how i can do it

wheat cargo
# past elk how i can do it

I would just fake it, add a rigidbody, turn gravity off, freeze position, add torque in a random direction, then after some time lerp rotation to a random face side

runic island
#

Weapon handler: https://pastebin.com/n6sqE2zX
script attached to projectile prefab: https://pastebin.com/ETr8dur8

I have a prefab for the projectile that has the above script, is rotated 90 on the X axis. It's a capsule so it's facing the long sides along the Z axis which is what I want. The collider is set to trigger and it does have a rigidbody.

The firePoint empty gameObject has a (0,0,0) rotation and is a child of the player, so it should have the same rotation as the player.

For some reason when I instantiate this it's just putting the capsule facing up and down. (Like a default capsule) Rotating it in any way in the prefab makes no difference. What am I doing wrong here? I swear I had it working yesterday and now it's just messed up again. Any help is greatly appreciated!

wheat cargo
runic island
crude creek
#

Hi! anyone knows what the problem here is?

lean sail
#

also that font is horrible, i highly suggest changing it

crude creek
#

isn't a jagged array a matrix?

#

i'm trying to crate one, is it the same thing?

wheat cargo
#

Also I don't think Unity can serialize multidimensional arrays, not sure if you are expecting to see it in the inspector

lean sail
# crude creek isn't a jagged array a matrix?

its an array of arrays, where the arrays are allowed to be different sizes. Hence why it also doesnt allow u to input the size in the 2nd brackets
scroll up slightly in the link i sent. Maybe you want the multidimensional array

naive swallow
#

There are matrices in C#, but the notation is different:
https://www.w3schools.com/cs/cs_arrays_multi.php

crude creek
crude creek
#

but with different values for hight and width

#

I think I found how to do it

lean sail
#

id hope so, considering i told you exactly where to look on that page i linked and digi linked one too. Its just a multidimensional array

lean sail
crude creek
#

I think this might be it, thanks!

midnight hazel
#

I'm having an issue using alpha in TMP text, the following code does not work to fade the text, what should I be using?

private void ShowMessage(string message)
{
    Debug.Log("showing message : " + message);
    messageText.alpha = 255f;
    messageText.text = message;
}
IEnumerator FadeOutMessage()
{
    yield return new WaitForSeconds(3f);
    float currentTime = 0;
    float alpha = messageText.alpha;
    while (currentTime < messageFadeSpeed)
    {
        currentTime += Time.deltaTime;
        messageText.alpha = Mathf.Lerp(alpha, 0f, currentTime / messageFadeSpeed);
        yield return null;

    }
    messageText.alpha = 0f;
    yield break;
}```
rigid island
midnight hazel
#

I was thinking it was running when it wasn't being called, that fixed it thanks

past elk
#

i can use a animator for a image?

wheat cargo
past elk
#

and then if it is posibble change the sprite

wheat cargo
# past elk something like this

Yes you can create an animation that modifies it's scale over time, but I personally would just write a script that does this

past elk
#

with a coroutine maybe?

wheat cargo
#

Nothing wrong with animator, but I personally prefer a code approach

past elk
#

okey

#

i think i will use code to manage it better

hexed pecan
#

You can still sample an AnimationCurve if you want

wheat cargo
#

It drives me slightly insane that there is multiple ListPool implementations in different namespaces.

past elk
#

i finally do with animations

#

i understand it better

earnest gazelle
#

Hey, I want an event function before all OnDisable and OnDestroy
I would like to call some stuff when a scene is unloaded before all OnDisable and OnDestroy or even before all OnDestroy

past elk
#

you mean before the scene be charged?

heady iris
#

i know VRChat has their own

earnest gazelle
#

I know I can check null but it is awful, I need to do it for every gameobject

late lion
earnest gazelle
#

[DefaultExecutionOrder(-999999)] It is like adding a script in the script execution order section of project setting?

molten sapphire
#

Just curious but is there a way to get Unity's JSON serializer to serialize an enum as it's name instead of as it's ordinal? I can't find any forum post detailing how to do this.

(For context, I'm trying to export level data from a custom made level builder)

wicked scroll
#

oh jk, you can't do that in C#

wheat cargo
plucky inlet
molten sapphire
wicked scroll
#

do you just want the string for readability?

plucky inlet
#

[JsonConverter(typeof(StringEnumConverter))]

wicked scroll
#

they're using unity's json, not newtonsonft

#

but that is a solution

molten sapphire
wicked scroll
#

unity's is faster but as you're finding, it's also limited

#

I would wager that most real projects end up using something else, whether custom or newtonsoft or EasySave

wheat cargo
wheat cargo
#

Like create your own LoadScene method that invokes your custom event

earnest gazelle
#

OK, I implement a custom scene management and before calling load a scene, raise an event SceneChanging something like it and listen to it

molten sapphire
# wicked scroll do you just want the string for readability?

No, more so for reliability. If for some reason I changed the indices of the enums, the values in the level data would no longer correspond correctly. And the ordinals are completely arbitrary it would be VERY difficult to fix/remap the values.

wicked scroll
late lion
#

Or don't remove or reorder the enum ever. Consider it a breaking change. Mark unused values as deprecated.

heady iris
#

enums are kind of scary for that reason

wicked scroll
molten sapphire
heady iris
#

they're great until you store an enum value

wicked scroll
#

they aren't scary if you give them values catshrug

wheat cargo
heady iris
#

I use SO assets in many places you might otherwise use an enum

#

my old settings system had a bunch of enums for different settings

#

now it does not

molten sapphire
wicked scroll
#

you have to do the same thing with the SO if you want to persist a reference to it though...give it a value (ID)

molten sapphire
#

The goal is to make it very lightweight

wicked scroll
#

well none, really

heady iris
earnest gazelle
#

In Exit method of thees tools, I handle it but I do some other stuff like set active some gameobjects,etc.
I call Exit of the current tool in OnDisable of ToolController but it is clear it can throw missing reference exception for those gos
I can add a new method for example Dispose and implement it in tools and just unsubscribe those input events but it is messy

latent latch
#

Problem with using types for identity purposes over enums is they can bloat up your project

wicked scroll
#

if you want canonical string names, you should do what Fen is talking about

heady iris
#

I should probably store base64-encoded text instead of hex

wicked scroll
#

if you don't mind them being integers and don't need to associate extra data with them (or value the slight compression gains you get there), enums will get you there too (just make sure you define their values)

heady iris
#

or just go to a binary format

molten sapphire
heady iris
latent latch
#

if you do want to change ordering of enums, define larger values instead of incrementing by 1

heady iris
#

It's very convenient: the asset's identity is defined by the asset database GUID

#

I have other places where I just generate a random GUID (e.g. inside of individual components)

molten sapphire
heady iris
molten sapphire
#

Which makes that approach very fragile

wicked scroll
#

you just have to make sure that you don't define overlapping ones

heady iris
#

It's fragile because you're throwing assets out..

#

You can always manually assign a GUID, of course

#

You need to figure out what uniquely identifies a "thing"

molten sapphire
heady iris
#

that could be the name of the thing, or a sequential ID (much like default enum values), or a GUID that's generated randomly upon creation

wicked scroll