#archived-code-general
1 messages · Page 226 of 1
in jan
oh idk i dont actually have student plan active rn
but also what would the point be of the student plan?
say quick question does anyone have an idea on how i can save a text to an object to reference later?
just extra assets bs really
ofc
this is #archived-code-general
i assume anyone here can
@spare island i think that answers your question. its the index of the player that left
but i don't think you need it
but you shuld be more specific on what text you wanna save and where , how do you plan on reading it @sudden zenith
whats the text for
etc
Okay it's just weirdly done. Either you use a list and pass around Player objects, or use an array and pass around indices. Now the backend has to shift all the player indices to the left when one leaves
so im trying to create a note and a calender. and in the date boxes are individual buttons. so after i input text in the note and click save, it is stored in the calender date
yeah i was able to print the displayname of a player who joined
the sample doesn't match a single thing of what i did
i know, that's bad
its also using LocalLobby
how does Destroy work exactly? Does it like immediately call OnDisable for all the scripts in the object, then queue up the destruction for actual end of frame?
aren't they just marked for deletion until GC comes collect
They're 'deleted' from the scene at the end of the frame is my understanding
OnDestroy() is called, I dont know about OnDisable()
documentation says it also excludes from rendering loop
but idk what is happenning to references during this
do exactly what hte sample does
imagine not building your own server system with go and SQL (sarcasm if you couldnt tell)
this stuff is all copying PUN and PlayFab. it's always going to be extremely clunky
let say i typed hello world in the note and want to save it under used to pull up the save input texts. can someone help me script this? 😅
why do I need to copy this LocalLobby class and such?
Seems like a lot of work for something I've already got working
woah, I didnt know unity had open source things
no offense, but what is that UI design
https://chat.openai.com/share/d3f09d7b-4f53-4ba8-b36b-0ac908420547
this is correct. by the start of the next frame, the component will actually be destroyed. Later update callbacks in the same frame will not observe the object as destroyed.
lol im taking a class no where as good when it comes to art
Should be easy to check with a few logs containing Time.frameCount to ensure it's all done in the same frame
I guess it does Destroy() -> OnDisable() -> OnDestroy() -> end of frame
more the colors
are citing GPT?
it's up to you. you have to maintain your own representation of a lobby i guess. i didn't author UGS, which I agree is a flawed API.
yeah please dont cite gpt
its rarely 100% right and can be suuuper dangerous if you take it as gospel truth
😅
Unity multiplayer has some sample projects where they showcase how to do things. This isnt some look inside unitys blackbox of code
ah
Im thinking those samples might be outdated, because theyre doing a bunch of stuff that would be far simpler otherwise
if i were you, i wouldn't use UGS
i don't think UGS is good
it's bad
it's worse than playfab and PUN
i have no idea what is and is not up to date. the whole thing is a wreck
well especially the documentation is garbage
i know why the sampel looks the way it does
i know why you are recoiling at it. you expect something simple to be simple, and it is indeed hard
confusing and messy
i am telling you that if you use the player left apis
i went for help but got roasted instead XD ngl im laughing so hard rn for the art on my end
you're expected to maintain your own copy of the model of the lobby. but you are overthinking this. you simply "sync" the list of players in the lobby at "the right times"
you don't care why they changed
sorry of course
could you clarify a bit more? what exactly do you want to happen
you can try to convince me that you care why they changed
and i'm telling you, you should statelessly examine the whole list every time @spare island and base your logic off of that
so lets say i have a game with 3 save button slots
a
b
c
and the things i typed are my data.
im trying to be able to save my notes in a button. so hypothetically i saved my notes in A and i clear my notes and type something else in B but want to go back to the saved note that is stored in A.
does this makes sense? sorry im bad at explaining :c
im confused, just have a text box on the note?
if you want to get the text from the text box you should be able to just save the textbox's value to a string
idk the syntax but it shouldn't be complicated
but wouldnt the string just keep updating when i type something else?
you could write to file
which isnt to hard, google that
that could save permanantly
that too
it only "saves" when you assign it to a string
string A = inputField.text;
are you trying to store the notes in memory or on the disk
memory
and gotcha
i never used unity before haha mainly just python before all this
i think i can actually work with that though ty guys
yep i need to make an interactive user interface but i wasnt allowed to use pygame haha
you could also do this with HTML but unity/c#/OOP is a good skill to know in general
heres a paper prototype that im trying to do
basically each calender date will store a note
yeah, thats prime OOP territory
yeah pretty much
havent learn object orientated programming yet. thats next semester so thought id get started
python has tkinter
i fucking hate it but it does.. exist
well im not allowed to use python like in general 😅
my options were html java bootstrap or unity weirdly enough
oh ok well tbh it would probably be easier done as a web app
but ive been lazy before and used unity as software dev too
mostly because i hate javascript
ngl same
hell u could even do this with c# winforms
Make it with WinForms and put Unity's logo as the app's logo, they won't suspect a thing
Hi I am working on a controller and wanted to "fix my timestep" to make my physics frame independant and I thought I figured it out last time I asked but I guess not 😦 and I was hoping someone could just skim my script (I know how bad it is T^T) and help me understand what im doing wrong
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Specifically my wall jumps break down entirely when dipping below 60 fps
id rather not hard set my fps if I can learn something
Hard setting framerate is not possible
Your link is a 404
yeah that was mb I just fixed it sorry
Why not simply use FixedUpdate
does setting targetframerate not hard set
cause I like to learn something when I do personal projects
its fun struggling to figure out where I went wrong
The thing to learn here is that physics belongs in FixedUpdate, not Update
The only way around that is to recreate FixedUpdate yourself in Update with a timer, which effectively will do the same thing
but I dont understand why?
I feel my walljumps especially should be fine as their velocity is being handled within a timer / time.deltaTime
am I misunderstanding deltaTime
It's a complicated explanation but you will never get consistent behavior in a discrete simulation without using a fixed time step
Possibly but you may also be misunderstanding that DeltaTime can't fix everything
Especially when it comes to second order quantities like acceleration
Because you will spend different times at different velocities if your time step is not fixed
To fully explain this I'd need to make a chart of position over time in a fixed vs non fixed time step simulation
But I'm on my phone right now so that'd be difficult
its ok lol
Suffice it to say there's a good reason Unity's default physics uses a fixed time step
so basically no matter what I should be using fixedupdate for physics instead basically
fixed update isssss
50 no?
should I touch it? like is there any reason to change the fixed timestep in unity settings?
you can still make decisions that will eventually affect physics
suck as reading input
you just want to perform the physics alterations at a constant rate
hence FixedUpdate
you might decrease the timestep if you're doing a game where you really really need more accurate physics, and other solutions (like using continuous collision detection) aren't enough
thank you ^~^
physics timestep isn’t a great way of making your physics more accurate
it's definitely not the most efficient way
halving the timestep doubles the cost of physics
if 0.04 sec is too wide, and 0.02 is accurate enough, then the problem isn’t the timestep
yeah
it'll fix a specific instance of a problem, but the problem will almost certainly show up elsewhere
if the issue with physics is accuracy, then you probably need something that is more robust
i wonder if Unity specifically chose 50 for the physics update frequency so that it'd be more obvious if your game depended on the physics rate equalling the frame rate
(rather than 60)
since 60 is a very common framerate target
like, if collisions are janky because of angles, you might want to lock to specific broad ranges of angles (not that you can in Unity’s base engine), but something like that
eg the problem itself is less sensitive to small changes in the input
quantize it!
I noticed that Nioh 2 only lets you walk or run
tilting the stick slowly doesn't give continuous movement speed changes
that probably makes things feel more consistent
i should probably do that with my input tbh
i'm busy stealing all of the design ideas from the game
feels like a good idea
(i was checking how the target lock camera feels)
Or maybe just because 0.02 is a nicer number than 0.01666666666666666666666666667
I have wondered about that too
i wonder if it should be 30 FPS for fixed update, and then the other frames for just rendering smoothly
I might be dumb, can I not just move my velocity change from within the timer to fixed update like if (state = jump){move}
From within the timer?
What is the timer?
just set how long the jump will last if you keep holding the button
you need to detect button presses either by polling in Update, or subscribing to an event for the button (eg InputSystem)
yeah I kept the timer and inputs in update
I just moved the velocity change to fixed update
i have methods for OnJumpButtonDown and OnJumpButtonUp
these are attached to InputSystem events
I am using Input.GetKey
then you need to poll that in Update
c++ has given me brainrot, how do I make a 2d array in c#?
then you should only do something based on that value in FixedUpdate
cause int[][] aint working
int[,]
that's a jagged array which does work
int[][] is an array of int[]
int[,] is a single 2D array
we’re talking about array support in C#
isnt that a pointer?
yes
which is better
Big one is how my timer is setup within update and then the small one is where I moved the velocity to no avail
no matter what values i set them to jump do not be jumping this way
and idk why again
because the state is active but the force isnt being applied at all
when you press jump or release jump, you should be logging the time of that input
then jump based on whether that input time is in a certain range relative to some value
fixed update? are you messing with time slow mechanics?
because this is necessary for buffered inputs and coyote time
just working on making my physics frame independant
"coyote time"
never done it before
its fun
yeah coyote time
that bit of freedom you have after leaving a platform or wall when performing a jump
you need coyote time for your game to not feel like ass
ok ill just redo the jump then
same for jump buffering
but what is it tho?
I assume its just an input buffer no?
is it making the input independant of frames?
look it up. video will explain better and faster
a period of time in which you are no longer grounded (or walled in my case) in which you can still input jump to perform that action while technically not being on either of those states
so a short time in which to the eye appears they are "grounded" but where simulation wise they are not, and during this time to appease the user, it pretends that the player is in the position they think they are?
which I actually shouldnt have to rebuild my controller for now that im thinking...
yeah basically
its just to make jumping from ledges feel better
its also like, crucial for the jump AWAY from walls if you have wall sliding specifically ONLY on towards input
when you press jump when jumping is illegal: buffer jump jumps if jump becomes legal in a short time afterward. coyote time jumps if jumping WAS legal a short time ago
so its just input "delaying" in order to account for the human reaction time?
it accounts for weird shit that happens
and reaction time
Can just check if you're still grounded and if you're jumping at the same time
no. you should check and log the last time you were grounded. and check and log the last time jump button was pressed
oh wait what type of jumping we talking about
so you can later compare
coyote time now
buffer jump allows jump if currently grounded AND lastJumpInputTime was a short time away from now.
coyote time allows jump if jump input now AND lastGroundedTime was a short time away from now
but im trynna fix the phyics of my wall jumps T^T
wtf is this font
oh yeah
i tried to make my desktop font the terraria font
but because I havent "bought" windows, I had to use a script
script made EVERYTHING the terraria font
i recommend making your visual studio font a monospace font
i spent like, 5 years of my life playing terraria
i think I will keep it in a font that brings me comfort
just saying, monospace fonts are useful when coding
ok plan B I am going to just move the whole ass timer into fixed update
the line is exactly as long as there are characters
lets you spot things that are off more easily
how do I digitize an analog input?
oh wait
i can just round the ho
another question
nvm ill work that out
Does anyone know any way to do hand tracking without using something outside of Unity or XR/VR stuff? The only solutions I've found are using Python outside of Unity and sending info to Unity, or having to use XR hand tracking with a controller, since the version without using a controller is deprecated as far as I can tell.
I just want to track the player's hands using only Unity.
Like, I want the webcam to track a player's hands.
hey guys how do i make a button hidden but still functional on click?
Make it transparent
gotcha thank you
are you in the middle of working on a game, or are you just starting?
this look so gross lol
while i am not sure what you are working on, the journey to nice looking UI is a long one
unity is not a good platform to generate My First UI Application
this is giving me retro point of sale restaurant dashboard vibes
lol its suppose to be a project that sort hardware inventory. this is the home screen it allows the user to store notes. and the side tabs has more of a drag drop function
for things like rams or products
believe it or not....since i have 0 art skills i was using krita and even then :3 ill accept shame
Middle of working on it
I think I found a solution, it'll just cost a lot lmao
But any free option would be nice
which middleware are you thinking of using?
and define "cost a lot"?
The OpenCV asset, it's around $50
okay
does it have to work?
opencv cannot track hands
i mean, it advertises that it can do a lot of things
including "tracking hands" but it can't track hands
what is the purpose?
I just need it to tell if a player's hands are bent and stuff
I don't need it to be followed 24/7
okay, what percent of the time do you want it to give you a correct answer
do you think
in order to meet your goals
Wdym correct answer
The goal of my game requires the player to do hand signs. So like if they wanted a thumbs up
okay
I want it to tell me if their thumb if up and only their thumb. Based off the asset it looks like it gives me 21 coordinates, which I'm used to
So as long as I have that bare minimum, I can work with coding in if fingers are bent
If that's not already in
okay
for the vast majority of users
it's not going to work
does this matter to you? does it have to work only for you?
Yeah it does, why wouldn't it work for other users
can you link me to what approach you plan to use that leverages opencv? then i can give a better explanation
You mean a link to the asset I wanna use or something else
hmm... i feel like you are at the very very beginning of this long journey
let me show you an example. here is someone who is using a neural network, which is a more sophisticated approach: https://victordibia.com/handtrack.js/#/ and you know, just from this, sitting here in my chair with my 1080p webcam, it has never detected my thumb, and it has never detected a thumbs up
it has never correctly detected all five fingers, and detecting hands occurs less than 5% of the time, and look how boldly this thing advertises that it works
i'm looking at the opencv hand tracking approach on https://medium.com/@muehler.v/simple-hand-gesture-recognition-using-opencv-and-javascript-eb3d6ced28a0 @final lotus and it will basically never work in all but the most exceptional circumstances, such as by being strongly lit against a white wall, and nothing but the hand is in the frame
opencv cannot track hands. you can use opencv to help a process track hands. which process are you planning on using? this is what i mean by approach. or maybe link to a specific piece of documentation that you plan to use, and i can look at its implementation
Ah. Ok
One sec
This is what I was looking at
Can anyone give me a tip in script architecture?
I want to create a 1vs1 platformer game, where players choose a character each round.
Now I got some problems with the player movement. I of course need it to have a great feel.
How can I do a player movement script, that is modifiable so I can create unique characters that may add to that movement and have unique abilities?
I just need it for the hands tho, and it looks like it covers it along with a bunch of other stuff
I would just make the variables each of your characters are gonna have public so they can be editted separately for new characters. Like ATK, SPD, etc. As for unique abilities, it depends on how unique
Unique abilities like teleporting, shooting, spawning things and whatnot
But lets say I have a PlayerMovemet script that has basic functionality every character should have. Do I make a new script for each character that inherits from the player movement script? Should I make the characters ScriptableObjects or smth? I'm overwhelmed with what the best options could be
I'm also trying to attempt something similar rn, my plan was to have it in the same script, and create a bunch of methods.
I don't think creating a new script would be that much better, aside from I guess being neater
Because those are all unique
Imo, you could do methods in PlayerMovement and have them be accessible only if let's say
think I want to make the methods for OnJump, OnMove, OnAbility1 etc. virtual so the characters can overwrite them
Your character is named a certain way or has a type
Oh
Yeah, that would probably be good
but I'm not really good at planning these things thats why I'm asking here xD
I get it lmao
My motto is just do whatever feels easier and clean it up at the end
If you find similarities so that you can shorten the code then nice
Unless ur doing something crazy like a lot of nested loops or w/e
Hi, anyone got experience making autotiling snapped to grid, voxel tiles?
Would using a Dictionary<Vector3Int,Block> a good idea, since the world is sparse?
Yes, you can also use the Grid component from Unity to handle all the grid/world conversion math for you
It's 3D tho
Oh wait it is
Well ok
Why would anyone roll their own grid then if there's Unity grid?
They don't know about Unity's, or they don't like how Unity handles Hex coordinates
that grid has been added not too long ago
That too
Oh but this is only for placement
I need a collection to have custom data for the auto tile/ruletile alg
Yes
It's not going to do everything for you, just handle the coordinate space conversions
You still need the dictionary among other things
I would maybe have virtual states and serialized POCOs in a generic character controller, and keep your input as something the character registers and unregisters, then you can have a different unique script for each character if they are vastly different such as how they move or how they are allowed to attack, cast spells, etc - you could have data such as stats about the character be scriptable objects if you prefer to organize your data that way and dont need to save those details to file, otherwise you could use something like JSON and a serialized POCO - you may also want to think about a more detailed breakdown of how you want your hierarchy to be setup, what you plan to replace/add to the hierarchy of a character - for my multiplayer game, I see the player and its hierarchy as a "node" and the model/rig is what is added or swapped from the "node", while the input and generic character controller sits on the node, it can then be any kind of character that fits the theme of my game, and a spawner can create a prefab of that generic controller, which I can inherit as whatever "character" I want to spawn as - however, many ways to skin a cat, and this way largely uses inheritance
okay, so what do you think this will do for you?
it's not going to work as well as it looks
it's going to work 1/20th or worse as well as it does in that video
so i suppose you can buy it, and discover it doesn't really work, and get a refund
it will only work on a clean background, with a high resolution webcam, where the whole frame is occupied by the hand
did you visit that handtrack.js link?
i guess what i'm saying is that hand tracking is a Hard Problem that you can't just blub your way through
Yeah I visited the link
Ig I'll just try it out and just refund if it doesn't work how I want
Thanks for giving me something to consider
👍
sorry if im breaking up another question but does anyone know why this coroutine is frame dependent? I'm trying to add force to the player over a period of time. I'm only testing it by tweaking the target frame rate using application.targetFrameRate, so perhaps I'm using that incorrectly, but I've tried every combination I can think of of using fixeddeltatime, deltatime, unscaleddeltatime and waitforfixedupdate() and I can't seem to get it working consistently. I've also tried using both forcemode.force and forcemode.impulse to no avail. Any help would be appreciated.
okjay
i will tell you now that's a waste of your time
it's not going to work
do you know how much hand tracking would cost?
a lot. like a lot more than $50
it's not going to even work blubbingly
that's why there are zero games, zero websites with this
you have to add forces in fixedupdate
For starters, yield null would make it update with the regular update. With continuous forces you want it to update at the fixed update rate, so either put it into a fixed update instead or yield until next fixed update.
I'll just mess around with it and fail for experience then lol
and refund if it's crap
Then you also shouldn't multiply force by delta time, although that wouldn't really break if it was in fixed update.@pine blade
yea sorry idk how to reply to two people at once but i've already tried using yield return new WaitForFixedUpdate(). Sorry this is probably even worser code since I've been tinkering with it.
Thirdly, you want to avoid using both force and velocity. Use one of them.
Your issue is probably a combination of factors. Changing just one thing while other issues are still there, wouldn't fix anything.
yeah I did try changing a lot of things, removing time delta time from all variables and switching out waitforfixedupdate etc. Two secs ill test out what you've suggested
ok so this hasn't worked. what do you think i've missed?
the velocity part wasn't vital anyway, so I just got rid of it for simplicity
If you're waiting for fixed update, probably want fixedDeltaTime I guess..
yep I tried that and just tested it again. still no luck 😦
Also, what exactly doesn't work? How is it different from before?
So im using it to move the player over a period, imagine it as a dash. Although its kinda unscientific, im literally standing at one side of the room, counting how many dashes it takes to touch the other wall, then lowering the frame rate and counting again. It's just giving me some small variance.
How are you lowering the frame rate?
I said in the original comment but im basically just changing Application.targetFrameRate. Is this not a good representation of different frame rates?
No, that should be fine.
If it's a really small difference, I can only guess that it's maybe one loop iteration difference. Which could potentially be due to where you're calling that coroutine from.
Try adding an int counter in the coroutine. Add to it every loop iteration and print it after the loop.
Then compare the number of several dashes and see if it ever deviates.
Well i say small difference but its usually one to two dashes extra at lower frame rates, so I feel like it shouldn't just be a simple one loop difference (i.e. one loop should only push the player a fraction of one dash). I thought it might be some sort of physics issue since some times in the editor i will lag a bit and the physics goes a tad haywire but I can't seem to replicate it consistently.
this is a good idea. thanks ill give it a shot
what is a POCO?
If there's such a huge difference, I'd also confirm wether you're starting the coroutine only once
Plain Old C Object.
A class that doesn't inherit from anything (except other POCOs)
So, not a MonoBehaviour or ScriptableObject or anything like that
yea i thought about that so I simplfied the logic. this is literally all im triggering and there's no way I could be doing it more than once. its in update(), is that wrong?
also, so do you mean like this?
Yes, because it's not aligned with fixed update. Try setting a flag(bool) and starting the coroutine in the fixed update instead.
Yes
hmm okay. I moved it to fixed update and its counting the exact same number of loops for every dash, even when changing framerates, but it's moving the player way further at lower frame rates. this is weird
Okay. Now that you confirmed that, you should confirm the forces used in the loop. You can add them up like you do with the counter and print them in the end.
Actually...
Nevermind. Just do that for now.
how would i go about measuring the force applied?
assuming rigidbody.velocity.magnitude would work, now im getting different readings at different framerates (though it's consistent between the same framerate), from like 1214 magnitude at 144fps to ~9000 magnitude at 20fps
Put the yield before the first AddForce call
When you start the coroutine, MovePlayer will run until it hits a yield statement
So the first AddForce will happen outside of a fixed update
Time.deltaTime won't equal Time.fixedDeltaTime
so you're going to get more force than you expected
(during a fixed update, Time.deltaTime is set to be equal to Time.fixedDeltaTime)
i just checked that it behaves like that in a coroutine that's using WaitForFixedUpdate, since I wasn't sure
ok so like this?
Yeah. Or you could just throw an extra one in before the while loop
Both will be equivalent here
Now, if you had more code after the while loop, there'd be a difference
What readings do you see now?
ok it hasn't resolved it completely but that has definitely dialled down the difference. now at 1214 magnitude at 144fps, and 1600 at around 20fps
so like 6 dashes to 4
nvmd its roughly the same i think. I was using the wrong dash version, not the one in fixedupdate
still a huge disparity it seems
I'd check the profiler to make sure you aren't making it take so long that it can't maintain 50 fixed updates per second
it should just run a bunch of fixedupdate ticks to catch up, but I think it gives up if it gets too far behind?
I'd also make sure there's nothing else framerate-dependent happening to your character
forceApplied is just repeatedly adding up the rigidbody's speed.
If something else is messing with your rigidbody's velocity, it would affect that tally
what are you trying to do? how is the dash supposed to work?
is this a 3d game?
do you intend for it to work like dashes i'm familiar with in other games?
yep its 3d, the intended functionality is that i can start the coroutine and then force is applied to the character every fixed update for a set duration, much like how it works in other 3d games
how do i check the profiler?
ctrl-7. you should read about it here https://docs.unity3d.com/Manual/Profiler.html
generally you can't model any of that correctly as rigidbody physics and you should use kinematic character controller or an asset like the more mountains ones and engineer it explicitly
dashes are often constant-speed
rather than accelerating over the duration of the dash
If the forces applied in the coroutine are different despite it looping the same amount of frames, then your "direction" has different magnitude each time.
there's a thought -- is direction a unit vector?
direction is the forward vector of the gameobject which is multiplied by a dash speed, whats a unit vector?
i'll measure direction for all loops, two secs
a unit vector is a vector with a length of exactly 1
Oh wait. You're printing velocity. I thought it was the force passed into add force.
transform.forward, Vector3.right, and new Vector3(1, 2, 3).normalized are all unit vectors
yea i asked cause i didn't know exactly how to record the force. so its just the direction then?
oh ok gotcha, so its a normalized form strictly for direction. yeah then is my gameobject.forward * dashSpeed one?
you can experiment with
it would have to be something like
public AnimationCurve dashSpeed;
public IEnumerator Dash(Vector3 direction) {
// call inside a fixed update to reduce latency
direction = direction.normalized;
var startTime = Time.fixedTime;
// initialize
rigidbody.velocity = direction * dashSpeed.Evaluate(0f);
while (true) {
yield return new WaitForFixedUpdate();
var speed = dashSpeed.Evaluate(Time.fixedTime - startTime);
if (speed <= 0f) yield break;
// you collided with something that changed your direction significantly.
// stop dashing
var currentVelocity = rigidbody.velocity;
// tolerance is from -1 to 1
if (Vector3.Dot(currentVelocity.normalized, direction) < tolerance) yield break;
// a collision may have perturbed your dash, you decide how you want to deal with that
rigidbody.velocity = speed * direction;
}
}
@pine blade
anyway i think you have a lot to work out
this isn't easy to do
Basically, I wanted you to confirm that the AddForce input doesn't change.
ok so no, the input isn't changing with the framerate
Okay, then to sum it up, AddForce is called the same amount of times with the same input, yet the traveled distance is different?
yep seems like it, if this is what you mean by just measuring the input?
Yes.
So, the only thing I can think of is that you're moving the object somewhere else.
Or interfering with it's movement in some other way
yeah must be. i'll try duplicating only the relevant code in an empty scene and see if im still getting variance
In my script, I want to instantiate a prefab in my scene, but using the Instantiate method inside the prefab. This is causing it to not instantiate the object in my scene like I'd like to. Is there a way around this?
Basically I want a prefab that'll let me instantiate objects in my currently open scene
It shouldn't really matter where you call Instantiate imho🤔
I think the prefab is not in the scene and nothing calls the instantiate
ok this is literally all my code in this empty scene and somehow the problem persists. when i click space at 144fps the box moves a tiny bit, if i switch to 20fps it flies off screen.
Interesting 🤔
What if you move the code to the fixed update?
Outside the coroutine
No, the whole dash logic
oh sorry my bad i misinterpreted "outside the coroutine" to mean the code you should move is "outside the coroutine" my mistake, two seconds
if(input)
{
dashTime = .25f;
}
if(dashTime > 0)
{
//Add force
dadhTime -= delta;
}
Weird. 🤔
I wonder if setting target frame rate messes with something else as well
While(timer>0)
Oh, that too. Didn't notice.
Keep looping until timer<=0
wait it should be <= or are you saying thats the issue?
is there a way to make a copy of a delegate?
I have a delegate where functions might get added to it while it is getting invoked, so I think i need to copy and split it
No, they're saying that a while loop would loop the whole timer in one frame. Use an if.
ok cool an if statement fixed it, thank god. thanks so much for the help guys.
yep looks like it, perhaps waitforfixedupdate() works differently?
I wonder if it's related to using target frame rate. They note that it doesn't work correctly on windows..?
so what would be the best way then to invoke a bunch of different movement over a period, rather than just one timer? apart from just brute force duplicating? a function would only work the first time right?
hmm maybe, i am on windows
If you really want to emulate frame rate drop, just add some heavy loop in update or something.
You could create a Poco that does that, then update a list of these objects in one MonoBehaviour manager.
oh true. okay this shouldn't be too hard now, thanks for your help dlich!
I still feel like a coroutine should work correctly in a real life scenario 🤔
hmm could be an issue with some physics or time settings on my project, i only made a new scene, not a new project, so maybe the issue actually did persist from the same problem.
Did you make any changes to the physics/time settings?
physics wise i only lowered the default contact offset, so i doubt that would have an effect. for time i had to lower the timestep a bit for more consistent physics, but even when I set it back to its default 0.02 there was the same issue so idk
Okay. Still I think it might be related to target frame rate. Maybe if you tested with an artificial lag instead, it would've worked.
It turns out it wasn't working because I was switching scenes the line above
Is there any way to switch scenes and then immediately load an object into the newly loaded scene?
yea i agree. Might have to dig out my old toaster laptop and see if there's any change. The whole issue is only relevant for different specs anyway. That said, I would probably use targetframerate to limit framerate in a settings menu for instance, so perhaps it would be an issue regardless.
I'd rather not make a new gameobject just to track which thing should be loaded
If you execute the instantiate after the new scene has finished loading, it should work.🤷♂️
It's on the next line after I load the scene so I don't think it's finished loading yet
Wait I think there's an event I can use
Yeah. It's probably not finished by that point.
Well I almost got it working
I just subscribed it to the activeSceneChanged event then unsubscribed when it executed
Only reason that didn't work is cuz I forgot to set a value
Not sure what channel this should go In but how do I access the vivox Audio Tap components?
Do i have to make my own instance of them? That doesn't make since though because you generally dont make instances of components like taht
gotta love this great documentation 👍
Oh i might just be on an old version i guess
Does anyone have samples for v16 vivox? I can't get it to work
why is Transform.right in world space?
Why wouldn't it be?
"right" in local space is kinda useless. It's always just (1,0,0)
That's Vector3.right
Why would we want another copy of that?
Knowing the world space direction that "right" is for a particular object is very useful
I thought local keeps the objects rotation, and world is relative to the world
What? This statement is extremely vague and kinda meaningless.
Yes, world space is relative to the world. transform.right is a world space vector. Where's the contradiction?
Not sure what "keeps the object's rotation" means in this context
It is the world direction derived from the local rotation. transform.right changes as the object rotates.
As praetor said, you need the world space vector most of the time. Local space would just be 1,0,0 which is not super helpful.
You want the conversion
Local and world would be with respects to coordinate systems where local would be with respects to the origin of your selected object alone and world would be with respects to everything having an effect on the selected.
Ok I get it just got confused for a second
I'm not sure why but for some reason my players movement vector is off.
void Move(float horizontalInput)
{
if (horizontalInput != 0)
{
transform.Translate(transform.right * horizontalInput * moveSpeed * Time.deltaTime;
Direction = (int)Mathf.Sign(horizontalInput);
// Flip the sprite based on the direction
spriteRenderer.flipX = Direction == -1;
}
}
Instead of moving along the red arrow its moving in some strange purpil arrow, not sure why
I have a MonoBehaviour object with [ExecuteInEditMode] Attribute. When i disable the object, it works as expected. But when i enable the object, the OnEnable also calls OnDisable after it.
Okey found it.
i have a question
if i have a file like this :
"blabla%%blalalalala&&
blaabla%%blalallalallalal
alala&&
blaablaa%%blalallalallalal
alaalalalalala&&"
and i wanna erase everything from the %% to the && (including them) leaving me with a list like this :
"blabla
blaabla
blaablaa"
how do do i do that... using code ?! (its a very large file so i cant just do it manually) (pls help idek what to search up)
i would just maintain a buffer of some sizes and read to it and process it, once the buffer is full then offload it to disk (probably to other file)
if && or %% is met->keep reading the file and ignore all the char after it until %% or && is met
but && or %% maybe separated to different "chunks" when you read the file eg
[......XXXXX&] [&YYYY.......]
an easier way to solve this is to move last few bytes to front of buffer
[XXX&]
then fill the buffer as usual
[XXXX&&YYYY..........]
in c there is mmap to read/write file as "pointer", in c# you have https://learn.microsoft.com/en-us/dotnet/api/system.io.memorymappedfiles.memorymappedfile?view=net-8.0 but idk how to use this
doesnt really have to be c#, i just need to dump the result into a new TXT file
and since it wont be running in Real-Time, I dont think chunking is that important.I just need to do that once with the info I got so it can be usable(the file is around 3.5mb).
3.5mb is small to me....it can be loaded to ram at once
yes, i just need a basic method (i really have almost no idea what u mentioned back there) to dump it into a new file or edit the already existing one
I have MainAssembly asset in the Scripts folder, then I also have Assembly Reference Asset in the Editor folder that references the MainAssembly. How come that scripts in the Scripts folder still do not recognize classess defined in the editor folder? Both scripts are shown to be compiled into the same dll file. If I create AssemblyAsset in the editor folder and then reference the asset on the MainAssembly, it works. but then I have a problem of circular dependency because Editor also needs to reference the script
The way that is simple enough and that does not load the whole thing in memory is to use a FileStream, and wrap a StreamReader over it so you can read the characters sequentially
i have searched far and wide
and decided to use regex to construct %%whatever&& and then replace it with "" so what i dont need is erased
just- idk what regex is and how to use it
I want to instantiate a Prefab GameObject that i dragged into the Inspector field, but it immediately becomes null. What could be wrong? Here's my code:
🤦♂️thanks
Hi, I have a sprite shape renderer that disappears and then doesn't reappear when the shape enters the player's view resulting in a player falling through the ground.
I've narrowed it down to the shape's bounds not being updated once the shape gets out of the player's view(becomes invisible).
Is this an intended behvaiour or is it a bug s shape renderers.
Is there a way to fix this or am I screwed?
I’m working on my grounding state system, and am seeking advice. My physics system and most entities want to query and populate a common GroundingState class, which mostly holds bools about if we are grounded, slope normal, touching walls, etc.
But then I have my player, who needs something that is basically an extended GroundingState (eg specifically jumpable ground, slippery floors etc).
I want to compose GroundingState into my individual PhysicsMover class (similar to Rigidbody API). But I am a bit confused how to do this best
if I use a generic, then i can’t freely access everything in the base class. If I use an interface, then I’m basically just writing the base class twice, once in interface form.
how do i do this?
rendering should have nothing to do with falling through the ground 🤔
I suspect there's more to this
I am using a polygon collider which disappears when there is no shape being rendered
can send you the whole script and inspector if you'd like, it's quite short
why does the collider disappear?
Is that due to code you wrote or something?
That's not something that happens normally
Sounds like the GameObject is being Deactivated entirely
shape is updating the collider, lemme install unity rq and will show you the inspector
Question, when I use NavMesh.AddLink it gives me a NavMeshLinkInstance, which has a field NavMeshLinkInstance.owner.
How can I read that field from OffMeshLinkData?
Basically, I'm making custom links and I need to know custom data about them during navigation.
nope, just becomes invisible and doesn't become visible again cuz the bounds are not updating
Sounds like you might have done something wrong or perhaps something didn't recompile properly. It works properly for me
here, there's a property that determines if the collider will be updated dynamically
What is wrong with not being able to access everything in the base class? Seems like it is just extended data that wouldn't affect the base class, right?
If you had something like this, what would be the issue you would have?
public class PhysicsMover<T> where T : GroundingState {
private T m_groundingState;
private void OnCollisionHitInternal() {
var someCollisionData = new CollisionData();
m_groundingState.UpdateState(someCollisionData);
}
}
If the GroundingState calculated its own state using the data from the PhysicsMover, then it doesn't matter how much you extend it. You could just make the UpdateState method virtual and do whatever you wanted inside of it. If you needed to use the extended data for some reason, you could derive from PhysicsMover with your CharacterGroundingState as the generic parameter, then override whatever virtual methods that you needed to override in the PhysicsMover since T will be the CharacterGroundingState
I am assuming that it updates the collider once it turns invisible and then there is nothing for the player to collide with
last thing, no, the object is still active in the hierarchy when it turns invisible as you can see here:
just to make some stuff more clear: physics engine only cares about the base class. other scripts care about the difference between classes.
physicsmover does not alter grounding state. It just holds the most base version so physics engine can access, and other scripts can populate and query whichever (derived) class they need
Oh I see, so basically the issue is the physics engine wouldn't be able to use the correct generic type
yes
some other solutions involve casting constantly
what I really have is:
PhysicsMover has ContactManager.
ContactManager has 2 GroundingStates, for current and last frame.
PlayerScript needs GroundingStateAdvanced : GroundingState.
EnemyScript needs GroundingState.
PhysicsEngine needs GroundingState.
I think you might have to go with the interface then, but you could also use inheritance in addition. For example,
public class PhysicsMover {
private IGroundingState m_groundingState;
}
public class GroundingState : IGroundingState { }
public class CharacterGroundingState : GroundingState { } // add / override what you need to
you would have to cast
wait wait
public class PhysicsMover<T> : IPhysicsMover where T : GroundingState {
private T m_groundingState;
public IGroundingState GroundingState => m_groundingState; // implemented by interface
}
public interface IGroundingState { }
public class GroundingState { }
public class CharacterGroundingState : GroundingState { } // add / override what you need to
Couldn't you just do this
i wonder if I could make:
abstract class ContactManager using GroundingState
class ContactManager<T> : ContactManager where T:GroundingState
i want to avoid interface because interface is going to require me to define most of the whole class twice
so I think normal inheritance is the right call
I think it's only annoying to use the interface because you already have written the PhysicsMover, if the interface had been mostly defined first, you could just use IDE to auto-fill it out in the class
maybe PlayerScript can maintain a field of type ContactManager<CharacterGroundState>
what? how?
well what are you saying exactly, are you saying you would have to actually implement the interface twice.. ?
interface IState { public bool Grounded; }
class State : IState {
public bool Grounded {get; set;}
}
or something
but for every field/property
if I inherit from an interface in my IDE, I can just press Alt + Enter on the class and it creates all the properties and methods for me and I just fill them out, like a template
really?
yes
huh, I gotta try that out
wow
how do i change my particle effect's particle start size via code? i debugged this way and the curve multiplier remains 1 every time the code runs
thanks for letting me know
i think I’m going to go for non-generic base class, then generic classes that derive from it
so we can copy implementation
bump
You are dealing with structs, so I believe you have to do
var main = particleEffect_BloodSplatter.main;
var startSize = main.startSize;
startSize.curveMultiplier /= 2f;
main.startSize = startSize;
Notice how your IDE is indicating that changingStartSize is unused, under the Debug.Log
What's the exact scenario that the collider disappears?
For me, if I get a log in OnBecameInvisible, then check back on the collider some time later, my rigidbody has still hasn't fallen through
have you tried replicating the scenario without your custom world generation script?
startSize is a struct. when you assign changingStartSize to it, you are copying the value. it is not a reference that updates when the value is changed. also, when using the particle system, each module is also a struct, you need to cache the module in a variable, then you can access and change any of its fields . . .
var mainModule = particleEffect_BloodSplatter.main;
var changingStartSize = mainModule.startSize;
mainModule.startSize = changingStartSize.curveMultiplier / 2;
guys how can i serialise a scriptable object class so that I can see its fields in the editor?
there's an editor script (somewhere) online you can copy/use to do that . . .
ok thanks man
NOTE: this is only if the SO is a field of another class. by default, you can see fields of an SO asset like any other class . . .
yeah that's what i have
would it be possible/sensical to do:
abstract class Base {
public State x { abstract get; abstract set; }
}
class Derrived<Tstate> : Base where TState : State{
public TState _state;
public State x { override get => _state; override set } _state = value}
}
}
would this work to try to expose a derrived class that is held, as well as a non-derived class from base class, without needing to cast anywhere?
I can't replace it cuz then it wouldn't happen, simple as that, here's the gen script
it works just fine till the play goes out of the view
what it's doing is basically adding new points to the closed sprite
the issue is that the new points don't become visible even tho they should, for whatever reason
i used this script and the multiplier remains 1?
i found it here as the expandable atttribute https://github.com/dbrizov/NaughtyAttributes#expandable
Attribute Extensions for Unity. Contribute to dbrizov/NaughtyAttributes development by creating an account on GitHub.
why don't you try disabling Update Collider and instead manually call BakeCollider() in your code
it's not the collider that doesn't appear tho
the shape it self doesn't become visible :/
Oh, I thought this was a collision issue
so your generation script is just wrong?
like, the actual mesh is wrong?
there is a BakeGeometry() method as well, not sure what that does
this is a different one but will work fine. you just need to add the NaughtyAttributes package to your Unity project . . .
no, both my mesh and the collider are fine, the issue is that when they get culled, even tho new points are generated the culling border just doesn't get updated and the min-max positions it's displaying are from the last generated points and therefore it never becomes visible again
never? Or does it become visible if you go into the previous generated point bounds
like how are you determining that its using the previously generated bounds
you can manually define the renderer bounds in code if needed
for testing, at least
by debugging the position
min and max
it stops updating when the terrain goes out of range :/
I am looking to visualise the path my enemies will take (using Unity navmesh package) with a line renderer. My navmesh gets baked right before I want to visualise it and when I try to calculate the path right after it gets baked the results are non existant. If I wait for 0.5s (using coroutine) the result is what I want but only some times. I assume that some calculations still need to be done so I am looking for some kind of event for the navmesh agent that notifies me when it's path got changed
For the record, the actual enemies that get spawned later always have the expected path while the linerenderer sometimes doesn't (the points are the actual points of the navmesh agent made for visualising it)
why isn't it possible to just disable culling for that object is what I am wondering :/
because they tunnel-vision their implementations a lot, sad
@gaunt blade here's the one with just the file: https://gist.github.com/tomkail/ba4136e6aa990f4dc94e0d39ec6a058c
good to know
I don't know what the best approach for this would be
custom bounds occured to me and were even recommended by praetor but the issue is that the player is traveling thousands of unitys/min and the x size of the bounds would be huge
the other solution would be setting it dynamically in Update() but is that efficient?
like the simplest approach that makes complete sense would be disabling frustum culling for that object, since that isn't possible I have to use a workaround
you could set it in Update but do a check for if the bounds center from the camera is some distance away from the camera X Y position
so it only updates if the camera is moving
Would be nice if someone took a look ❤️
camera is constantly moving, I am just worried if this approach is inefficient
I mean as in, literally not every frame
like you would set a threshold
and you should just see if it even solves the problem
then check the performance and determine if it's better to find another solution
I don't imagine it would be unperformant
it's just setting a struct
additional question
are bounds not updating when object is invisible an intentional behaviour or is that a bad implementation
because that seems very wrong to me
I tried the 2022LTS and 2023 latest and both did the same
so this was either never reported or intentional for some reason
Hey guys. I asked a question related to this yesterday but I am working with a line renderer. I want to know what collider can I give it that will collide with everything including other duplicates of this prefab. Currently I am using an edge collider 2d which collides with most things but does not collide with other edge colliders. Keep in mine I need to be able to instantiate this in code and the shape of the collider needs to be a little weird. Not a square or circle
It also can not be a mesh collider because I need a rigid body as well
maybe a polygon collider?
I will try that. Thank you
just a bump so that nephren sees it when he is back
Hi So I was having a problem with one of my unity scripts, it keeps giving me this error: "NullReferenceException: Object reference not set to an isntance of an object". the script is for a button, and I was told it might be because of how my elements are arranged, but was told to come ehre. Let me know if I should askk this question in another place in case this is not where I should. THank you, here is the code:
Is the button on the same gameobject as the GameStarter script?
GetComponent gets a component on the same object ONLY
so the script is a component of the button
Ok, show the inspector for the button.
yes, I had also found the problem. There evidently was a problem with the hierarchy, because I assigned the script to a new button and now it is working
This doesn't really make much sense...
yes I dont know. I had messed aournd with the button from before, and I added the same script to the "on-click" event section in that button. maybe that?
You added a SCRIPT? You have to add an OBJECT with the script to that section.
Hey how would you guys go about adding interactions to specific players? I plan on adding multiplayer and I have an interaction system using Interfaces. One of the interactions adds an item to the players inventory, but i'm not sure how to know which player interacted with the object.
Depends on how you want it to act.
You can do a raycast to face someone and enable a prompt.
You can do the same with a trigger area
You can show a list of teammates in the ui, and when yoy click their name (which is a button) it opens a menu.
You can reverse that and have a menu you access via button or hotkey, and then you select a player via dropdown
Etc
Etc
So it really depends on your goals
I was thinking for example there is a box in the middle and anyone can go up to it, hit the interaction button and the box would would respond by adding an item to that specific players inventory. I was thinking maybe giving each player a specific ID, and sending a signal containing that ID to know which player it was but i'm not sure if thats a good solution or not
That could work.
Players should definitely have unique ids already, even if not for this purpose.
I like your idea, i would just suggest a tweak where there are MULTIPLE boxes that all connect. So that you don't have to all go to one place, but however you want is best
Sounds great. Your definitely right about having an ID regardless for this purpose or not and thanks for the suggestion!
Just wanna let you know that your and praetor's recommendation worked.
I am still curious about the thing I asked but it's fine if u don't have time to look at it, thanks either way!
This is the implementation I used:
private void UpdateRendererBounds()
{
var b = _rend.localBounds;
var min = _groundShape.spline.GetPosition(1);
var max = _groundShape.spline.GetPosition(0);
max.y = 5000;
b.SetMinMax(min, max);
_rend.localBounds = b;
}
So I want to make a script where I search for the collision of two objects with two tags, and then destroy them, however the code has to be in a seperate script, since I will add on to the destroyobject funcion. I just have to know what I can use in the if function to compare two tags, and if they collided.
Thanks
Make the objects call a public method on this third script through a static accessor, rather than listening for it.
Or use events and subscribe to the objects, and then they invoke the event
Otherwise you'll just need to constantly compare their positions and see if they are overlapping
oh yes ok that makes sense
could you explain hopw to do that in a bit more detail? since I am a bit newer to unity
Ah, might want to move over to #💻┃code-beginner then.
But basically, for the first method, you would have a singleton pattern. I'm on my phone so it would be pretty tough to give example code sorry. But see this
https://gamedevbeginner.com/singletons-in-unity-the-right-way/
And call the third script (which I will call GameManager) like this
GameManager.Instance.ObjectsCollided(this, otherScript)
this is the object calling the collision out and otherScript is the second of the two.
Then the GameManager would know which things to deal with
The second method is a little more advanced but probably a bit more flexible.
See this:
https://gamedevbeginner.com/events-and-delegates-in-unity/
Thank you, yes you obviously can't provide an example code here, but the links are more than enough. Also you're right, code-beginner might be a bit better 😂. Thank you!
Hi, so i really didn't know where else to go as I asked and searched everywhere. I tried to create just a Debug.Log statement stating there was a collision. I tried to create a delegate, and that didnt work, and I tried to use both colliders and rigidbodies, yet no collision seems to be detected, what can I do?
Collision is detected via OnCollisionEnter(2D if 2d)
yep, I used that
you have to make sure you are satisfying all the requirements for it to happen
If you're lost you can show the code you have and the inspectors of the two objects and we can tell you what you messed up
where can i find all the requirements? the link below?
box's link will tell you
but it's basically:
- both objects have non-trigger colliders
- at least one object has a dynamic rigidbody
- the code needs to be correct
ok, Ill get back if I am lost
yes thank you, ill see
Is it possible to have a managed IBufferElementData type? What are the methods for altering the buffer? It doesn't look like I can use an Aspect and DynamicBuffer
Try asking in #1062393052863414313
got it thanks!
Hello that is kinda weird and i dont know why its not working. When i use it as a player on npc it works but when the npcs it uses on the player or on other npcs it does not work. but both are built exactly the same. It does not even come to the debug
protected virtual void OnTriggerEnter(Collider other)
{
Debug.Log("Trigger " + other.gameObject.name);
if (!other.CompareTag("Character"))
{
return;
}
var statsController = other.GetComponent<UnitStatsController>();
if (hitCharacterUnitStatsControllerList.Contains(statsController) || statsController == unitMainManager.UnitStatsController)
{
return;
}
hitCharacterUnitStatsControllerList.Add(statsController);
statsController.TakeDamage(damage);
}
not sure why this doesn't work. In fact it doesn't get set at all at the start inside the startedEffect bool lock.
either that or im calling the function wrong. idk
it dosent throw any errs btw
SceneManager.LoadSceneAsync("Meadows", LoadSceneMode.Additive);
AsyncOperation asyncOperation = SceneManager.LoadSceneAsync("Game", LoadSceneMode.Additive);
yield return new WaitUntil(() => asyncOperation.isDone);
i use this in coroutine and the code afterwards never executes
it seems to be continuously going down so imma try to clamp it
Can anyone that is familiar with navmesh agents look at this?
Anybody know why I get this error?
private NetworkVariable<Color> color = new NetworkVariable<Color>(Random.ColorHSV());
public override void OnNetworkSpawn()
{
camera.gameObject.SetActive(IsOwner);
playerBody.GetComponent<Renderer>().material.color = color.Value;
base.OnNetworkSpawn();
}```
I'm trying to make it so that the player body (capsule) has the same color body for all clients
#archived-networking but you also havent shown what the error is
im a goomba bruh
https://docs.unity3d.com/ScriptReference/Transform.RotateAround.html
Does this method eventually run into rotational drift problems? Was looking around for just answers of these type of issues where floating point precision can make rotational values desync eventually for prolong uniform rotations.
How do you even fix that problem in general without making it too snappy
https://docs.huihoo.com/unity/5.5/Documentation/ScriptReference/Texture2D.LoadImage.html
In this link under the code description a byte array is loaded as a texture into a Texture2D object. But it's supposed to be a 64*64 image. However there is nowhere this is specified so how does the Texture2D understand the image dimensions.
I also have this problem when trying to get the pixel data from an image as a matrix but all member functions give a 1 dimensional array instead of a 2d structure. So I am quite confused.
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
I suppose that the texture size data is contained in the bytes
// Create a texture. Texture size does not matter, since // LoadImage will replace with with incoming image size.
Or maybe not, hmm, good question
Maybe it expects the image to have a 1:1 aspect ratio?
im trying to use UnityYAMLMerge to solve my merge conflicts that i keep getting with scene files. However, when I tried it for the first time after configuration based on https://gist.github.com/Ikalou/197c414d62f45a1193fd by pulling main into my branch that's way behind and running git mergetool, it just throws up an error that says "Error parsing file '.\Assets\Scens\MyScene_BASE_2074.unity': could not find expected ':'
That isn't the actual scene file, it seems to have been created by the mergetool and it created something with a parsing error in it. How would I go about solving that?
Had force text asset serialization throughout the entire duration of this unity project existing, "Visible Meta files", using git
presumably fix the yaml syntax
that yaml file is massive and the error doesn't give any clue to where it could be happening. But what im concerned about is the fact that UnityYAMLMerge tool is the one that generated it, and even if i were to find the spot and fix it manually, can i have it continue the process? It just exits out and says "Was the merge successful? [Y/N]"
how can i find a single missing colon in 130k lines of yaml 
use a yaml validator
Validate, Verify and Reformat your YAML documents, optimized for Ruby on Rails
these files are being generated by the mergetool as soon as it runs so even if i fix this, when i try to rerun it it'll just happen again
the merge tool is just a helper to fix merge conflicts
you can also fix them yourself
once the conflict is fixed and committed, there will be nothing to merge anymore
i've tried that before
wanted to pull my hair out trying to figure out the yamls and which parts had to be taken or removed
thats why i set up the mergetool
yes indeed
but seems like it has a bug in it
so you will probably have to fix it manually this one time
you can also just take --theirs or --ours and fix the scene in Unity
yeah um
that is pretty annoying unfortunately
oh well
hoping that it's not a universal bug
I'm trying to sync the transform rotation of the player's head using this script I've written:
public class HeadDirSync : NetworkBehaviour
{
[SerializeField] CharacterIdentityLink clink;
void Update()
{
if (clink.hasLocalIdentity)
{
if (isServer)
{
RpcUpdateLookDir(transform.localEulerAngles);
}
else
{
CmdUpdateLookDir(transform.localEulerAngles);
}
}
}
[Command]
private void CmdUpdateLookDir(Vector3 euler)
{
RpcUpdateLookDir(transform.localEulerAngles);
}
[ClientRpc]
private void RpcUpdateLookDir(Vector3 euler)
{
if (!clink.hasLocalIdentity)
{
transform.localEulerAngles = euler;
}
}
}
clink is a PlayerIdentity object which connects the character to a player's identity. The character can be deleted at will but the PlayerIdentity object will persist until the player disconnects. The only part of it that's important here is the hasLocalIdentity property, which is identical to isLocalPlayer.
The script succesfully syncs the rotation of the head from the host to all clients but not in the reverse direction. Any glaring issues that might cause this?
ohhh
i'm stupid wait
I mistakenly called RpcUpdateLookDir() with the parameter transform.localEulerAngles instead of euler
Apologies for polluting the chat
// Get the movement direction by using the player camera
moveDirection = _playerCamera.forward * vertInput + _playerCamera.right * horizInput;
// Add force to the rigidbody based on our supplied speed
rb.AddForce(moveDirection.normalized * characterMovementSpeed * 10f, ForceMode.Force);
Theres an issue with this code where if the player camera is looking down, the player starts going into the air, I assume the issue because it's getting the direction on all axis or something, but unsure how to fix
You likely shouldn't be using the player camera to determine the forward direction of the player
Since you're looking straight down, _playerCamera.forward will be pointed straight down as well, and -_playerCamera.forward will be pointing straight up, so if you apply a negative vertInput you will be forced straight up.
what's a good solution?
You should control the vertical look direction with the camera but rotate the entire player object on the Y axis for horizontal looking
Then, use the forward direction of the player object
transform.rotation = Quaternion.Euler(xRot, yRot, 0); this is my camera rotation code
would I just make it parentobject.rotation = Quaternion.Euler(0, yRot, 0);
Yes
or add to it
accumulate
Then that would work I believe
no longer flying!
You want to ignore any vertical direction of the camera (X rotation)
You would need to rotate the camera like so:
_playerCamera.transform.localEulerAngles = new Vector3(xRot, 0, 0)
I did transform.parent.rotation = Quaternion.Euler(0, yRot, 0);
If you rotate the player object itself you'll want local rotations
oh so I'
Also you could do what osmal suggests and set the 'y' component of your moveDirection vector to 0
so I'd no longer account for the y axis since the parent is already rotated
transform.rotation = Quaternion.Euler(xRot, yRot, 0);
transform.parent.rotation = Quaternion.Euler(0, yRot, 0);
well this works
I suppose?
I've never done a character controller this way before but if it works go for it I guess.
transform.localEulerAngles = new Vector3(xRot, 0, 0);
transform.parent.rotation = Quaternion.Euler(0, yRot, 0);
this as well
That's generally how I do it
though I usually just use Rotate. So transform.parent.Rotate(new Vector3(0, horInput, 0)) but since you accumulate yRot yourself it's better what you're doing
FYI transform.rotation = Quaternion.Euler(xRot, yRot, 0); is worldspace (not relative to parent) transform.localEulerAngles = new Vector3(xRot, 0, 0); is modelspace (relative to parent)
(not sure which you want, just be careful of that stuff)
Im making a procedual walk/balance script and I want to keep the targets in a fixed location, and I did that, but for some reason its really jittery
public class BetterIKFootSolver : MonoBehaviour
{
public GameObject leftTarget;
public GameObject rightTarget;
public Transform hips;
public LayerMask ground;
Vector3 oldLeftPosition, currentLeftPosition, newLeftPosition;
Vector3 oldRightPosition, currentRightPosition, newRightPosition;
private void Start()
{
currentLeftPosition = newLeftPosition = oldLeftPosition = leftTarget.transform.position;
currentRightPosition = newRightPosition = oldRightPosition = rightTarget.transform.position;
}
void Update()
{
leftTarget.transform.position = currentLeftPosition;
oldLeftPosition = newLeftPosition;
rightTarget.transform.position = currentRightPosition;
oldRightPosition = newRightPosition;
}
}
thats the code
Try LateUpdate instead of Update
That's my immediate thought
Usually jittering means that something goes wrong in the execution order
Late update didnt fix it
Are leftTarget and rightTarget the red cubes?
yes
If you look closely, those aren't jittering
Yeah its just the feet
So the problem is elsewhere. How does the IK work?
Oh apparently you are using the Animation Rigging package
Is there a reason your animator's update mode is set to Animate Physics?
That means it will run in the physics loop and not in sync with the render loop
no, but the animator isnt doing anything so I dont see why that would be an issue
I can see if that'll fix it
it could also be where the script is placed maybe
this is where the script is placed
setting the update mode to normal didnt change anything
Not sure, I haven't really used Animation Rigging. You could ask in #🏃┃animation
Hi! I apologize, I'm somewhat new to this so I hope I'm in the correct category. Me and my friend have been creating a game using a car and map system, and recently we've attempted to complete an upgrade from Unity 2019 to Unity 2022. We have a floating origin system in-place currently, however whenever I reach position X coordinate of 1,000, it's supposed to go back to 0,0,0, however the map does but the vehicle is now not going back with it, falling off the map and breaking. I've attempted to diagnose this, and I still can't quite figure out the issue. Is there anyone who thinks they could be of assist to help me? Thank you all so much. 🙏
Code script: https://hastebin.com/share/kokorohano.csharp
What part of the script is responsible for teleporting the car?
I see some glitching at the 0:54 mark, is that supposed to happen?
No, It's not
One possibility is if your car is a child object of something - you are only moving root transforms and dynamic Rigidbodies do not respect the Transform hierarchy.
I'm not sure WaitForEndOfFrame is a prudent time to do be doing this either
that's usually reserved for specific rendering tasks
you wouldn't typically want to be moving GameObjects around at that time
There is of course also the disconnect between moving a Transform and when the physics engine syncs - which won't be until the next physics simulation step.
You almost definitely want/need a Physics.SyncTransforms() in there
Alright, I'll see what I can do. Thank you for the suggestions, and I'll see what I can accomplish with attempting to fix this
Using Debug.Break() when shifting the origin can help identify some issues
I'll run that and see what I can find
Ended up doing this. No warnings/errors ended up coming out when the game paused to shift the origin.
@hexed pecan Turns out it was the animator lol. I just didnt realize because changing Update to LateUpdate made it worse so when I set the Update Mode to normal, it looked like it hadnt changed anything💀
However, weirdly enough, I did notice that when I unpause the game that the vehicle moves with the map back. Almost like the pause helped it?
but changing it back to Update and setting it back to Normal fixed my issue, thanks
The pause shouldn't affect anything, it's just so you can inspect the problem better. After pausing you can use this button to go frame-by-frame
You originally said that the car is not moving back with the map, but it is moving back in the video 🤔
Yeah, I kinda just realized that too lol
Just in a bad position or not synced so it falls thru
The glitching I pointed out is a thing you should fix
My guess is that it isn't synced for some reason - Map + car moves back, but the car falls through the map for some weird reason
the map just stopped loading in lol
Yeah whatever is happening at 18 seconds must be fixed
That's the main issue IMO
Why is the terrain changing like that
Is there a better way to debug what is going on with that? I figured it would be Floating Origin
I should say I know it is Floating Origin - I disabled it entirely and the game ran fine once disabled
This thing that praetor pointed out is very relevant
#archived-code-general message
👍
The rigidbody might go back to its previous position even if its root transform is moved. So you should move the rigidbody itself with rigidbody.position
Is that something that changed when I upgraded from Unity 2019 to Unity 2022?
In your latest video I see the playerpos value text changing rapidly in the 0..1000 range
No, you just aren't supposed to move rigidbodies via transform
Wonder why it worked in 2019 then, really weird
Is there a way to check if a navmesh agent starts avoiding another agent?
I'm making an enemy AI and I want to stop the enemy if its going to try to walk around an enemy
I attempted to use this
rbs[i].MovePosition(rbs[i].position - _focusPosition);```
same issue
atleast i think i did it right this time
MovePosition isn't appropriate here
MovePosition cues up the movement to happen during the next physics update
simply rbs[i].position -= _focusPosition;
Ooooh alright
looks like the same issue happened again, car fell off map. it moved with map, but fell under it? dunno
Did you do Physics.SyncTransforms?
the map's collider movement won't be reflected until that happens
or until a physics simulation step.
Tried this for this bit of code that does the recentering
https://hastebin.com/share/adayeyebey.csharp
Still didn't work for that either, with Physics.SyncTransforms implemented
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Show this video but with current setup?
I graciously appreciate your attempts to assist me today. I hope I can get it working with your future advice, but I do have school tomorrow and will be heading out for the night. Thank you so much for your help today 🙏
I am looking to visualise the path my enemies will take (using Unity navmesh package) with a line renderer. My navmesh gets baked right before I want to visualise it and when I try to calculate the path right after it gets baked the results are non existant. If I wait for 0.5s (using coroutine) the result is what I want but only some times. I assume that some calculations still need to be done so I am looking for some kind of event for the navmesh agent that notifies me when it's path got changed
For the record, the actual enemies that get spawned later always have the expected path while the linerenderer sometimes doesn't (the points are the actual points of the navmesh agent made for visualising it)
https://media.discordapp.net/attachments/763495187787677697/1176551441234669578/image.png?ex=656f47ea&is=655cd2ea&hm=89d18b398d0bc133638d113b034f7b3ce04e1d7d64f29c9e6014052c0f9ff91c&=&format=webp&width=714&height=491
Hi all. Random question about grid/voxel based chunk system etc
Should a voxel/chunk be in 0,0,0? Or should it respect the quadrants, so -0.5 and +0.5 on each axis?
the center can be located at anywhere.
i am not sure how the -0.5 and 0.5 comes out since size of voxel may not be 1
Ok i meant, -voxelSize/2 to +voxelSize/2
how do i get emojis to work in TMP?
not code question
you need to find the texture of the emoji online and create asset iirc
where should i ask this question
i just wanna render all unicode emojis not make my own
Hello all, I need to open a webpage inside a scene something like a Webview/Iframe. I am Building my application for Mac, windows and WebGL. Need support in all three for that, I don't want to open the url externally , only inside my scene. Can anyone help me in this?
sounds complicated, you may need to search internet about the plugins/assets you can use or waiting for other suggestions
you dont want to write a html and css parser/renderer by yourself
You can't do that inside the game in WebGL. The best you can do is show an iframe element on the web page and position it on top of the game
Im using ImGui to render a little menu in my game, this menu has a input field and I have made it so whenever the user presses tab it auto completes the input field. This works fine but theres one annoying little problem. When I correct the input the cursor of the textfield stays at the same place it was when I want it to jump to the end of the text, I've tried using GUI.FocusControl but cannot get it to work, does anyone know how to do this?
void coverAndShoot()
{
if(nPCScript == null)
{
return;
}
bool check = false;
Vector3 playerPos = Player.position;
playerPos.y = 0;
if (coverPoint != null)
{
nPCScript.target = coverPoint.transform.position;
Vector3 coverPos = coverPoint.transform.position;
coverPos.y = 0;
if (Vector3.Distance(playerPos, coverPos) <= shootDis * coverDisMult)
{
check = true;
}
if (Vector3.Angle(coverPoint.direction, (Player.position - coverPoint.transform.position).normalized) <= maxCoverAngle)
{
check = false;
}
}
if (!check)
{
coverPointScript closestCover = getBestCover();
if (closestCover != null)
{
closestCover.coverer = gameObject;
coverPoint = closestCover;
nPCScript.target = coverPoint.transform.position;
}
else
{
confidentShoot();
}
}
}
Unity is giving me an error when i have the nPCScript.target lines on
more specifically
"
MissingReferenceException: The object of type 'NPCScript' has been destroyed but you are still trying to access it.
"
It's not showing me the line in the error but when I disable those lines it does not give the error
Ive also got other voids called at the same time that change the target and don't return this error, kill me
how is this happening I check if the script is null at the start of the void
is the nPCScript an interface?
its a monobehaviour that is attached to each of the NPCs that stores saved values
show NPCScript
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Maybe the problem is not in the first script you posted but rather in the other one but only when you have set the target.
the thing is it works perfectly fine in this void
void confidentShoot()
{
if(coverPoint != null)
{
coverPoint.coverer = null;
coverPoint = null;
}
if (playerDis < evadeDis + (evadeAddDis * confidenceMult))
{
state = 2;
}
else if (playerDis < shootDis + (shootAddDis * confidenceMult))
{
state = 0;
}
else if (playerDis > shootDis+ (shootAddDis * confidenceMult)+shootDisThick)
{
state = 1;
lastState = -1;
}
if (state!=lastState)
{
if (state == 1)
{
nPCScript.target = SetPos(Player.position);
}
else if (state == 2)
{
coverPointScript closestCover = getBestCover();
if (closestCover != null)
{
closestCover.coverer = gameObject;
coverPoint = closestCover;
nPCScript.target = coverPoint.transform.position;
}
else
{
nPCScript.target = Player.position + (-transform.forward * (shootDis + (shootAddDis * confidenceMult)));
}
}
else if(state == 0)
{
nPCScript.target = transform.position;
}
}
lastState = state;
}
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I dont understand. I have a class with like 15 properties all set like this :
[Serializable]
public class PlayerActionData
{
public string UID { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore)]
public string RemoveHexConverted { get; set; } = null;
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore)]
public int RemoveHexLayerIndex { get; set; } = -1; ...
...
}```
then when i create the object and set some properties i do JsonConvert.SerializeObject(data)
the problem is, that it is not ignoring the default values, most of the properties still are included in the serialized json string as -1 (null strings arent included) and some properties even though set to a different value dont even appear in the json.
All i need it to do, is if ints are -1 or strings are null just not to include them in the json at all
some properties work fine
well for starters -1 is not the default value for integers so that will not be ignored, it will only be ignored using DefaultValueHandling.Ignore if the value is 0
isnt setting it to -1 on definition implying that that is the default value?
no
no
you can use the DefaultValue attribute for it though
that is even demonstrated in the docs
https://www.newtonsoft.com/json/help/html/t_newtonsoft_json_defaultvaluehandling.htm
thanks, this should fix it
Is there a way for me to cast a component to a type determined dynamically?
depends on what exactly you mean by "determined dynamically"
That doesn't really make sense. The type is what it is. Casting it to a base or derived type doesn't change anything about it, it just gives you different access to it. But if you don't know what type you're casting it to in your code, that's not useful because you don't know what members you can access from it.
Yeah that is entirely correct. I did not need the derived type.
is anyone good with math in here? I need some help making a target object move in a stepping motion when the targets are too far away from the target goals
heres the script https://pastebin.com/u78Lk26U
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
what is a stepping motion supposed to be?
kinda like an oval rotation going to the target goal, like ya know, a step
Idk really how to explain it lol
Like a curved path?
um yeah I guess
I want to broadcast an event whenever this method is called on a derived class (without manually implementing the call in all the derived classes)
public abstract void DeserializeGameEntity(SerializableGameEntity serializableGameEntity);
Do I have any choice other than turn this into a concrete implementation and have the concrete method call another abstract method/broadcast the event instead?
Context is this is for a level editor, I want to avoid adding logic in game classes that is designed for the level editor, since it's not going to be shipped with the client.
I'd like to know if there are other solutions. Even if it's super ugly on the side of the level editor.
You get the vector from the unit to the target and the vector from the unit to the center. Then you add them together and divide by 2. That's your move direction.
doesnt ```cs
float leftDistance = Vector3.Distance(leftTarget.transform.position, leftTargetGoal.position);
float rightDistance = Vector3.Distance(rightTarget.transform.position, rightTargetGoal.position);
well, I guess not, just the distance lol
yea idk how to do that in code terms lol
To get a directional vector you need to subtract the position of the target from the position of the start. i.e.:
Vector3 targetDir = target.transform.position - player.transform.position;
Then you do the same for the center of your map (or whatever point you want your path to curve to) and merge them into one:
Vector3 actualDir = (targetDir1 + targetDir2) / 2;
You could use partial class, one part is the editor while the other is the runtime.
You could add multiple events in your base case which your editor register too.
You could use a Proxy to add behavior when a function is called. (You use the proxy and the proxy then use the actual object)
You could use a InternalDeserializeGameEntity which is private abstract while the DeserializeGameEntity is concrete and public and call the internal function + the event.
You could use the decorator pattern
You could use the visitor pattern
wow! Thank you -- investigating
Excuse me, can you help me, please?
I'm making a DK, 1st level works fine, but when I lose a life in the 2nd one it takes me all 3 lives! Naturally this is a Game Over so it resets score to 0 and takes me back to Level 1.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
you only ever assign lives to 3 inside of NewGame()
I tested it recently and 2nd level wont do that anymore, however, it still takes me 2 lives.
huh? you tested what recently? i was pointing out where you assign your 3 lives. now look at the only place(s) you call it
Sorry, I tested second level again
newgame
It is called in levelfailed
when lives <= 0
okay and have you bothered logging any relevant information there to see what the values of your variables are?
As far as I can see, you're always calling Invoke to load/reload a level
It's likely that lives gets modified multiple times while waiting for the invoke
You need some kind of condition that prevents modification of your lives if you're currently waiting for a level to be (re-)loaded
I will try that now
I will send the Mario script as well, it will say that when you touch an enemy, Mario will disable
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
My debug lives count, it will activate whenever I fail the level and tells me how many lives left I have, this one is from the 2nd level
well this only shows that it is counting down correctly. but just logging a single number like that with no context isn't very useful. we can't even tell if it is being called more than once in the same frame or even all on the same instance
it is being called more than once, actually, everytime I collide with an enemy in the 2nd level
This is the normal loading, it just says the remaining lives when I lose one and reloads the level
Mario is disabled BEFORE the reload and lives--
"Assets\SteamAchievementsForSteam\Scripts\SteamAchievementsAndStats.cs(107,37): error CS1061: 'Achievement' does not contain a definition for 'Identifier' and no accessible extension method 'Identifier' accepting a first argument of type 'Achievement' could be found (are you missing a using directive or an assembly reference?)"
Using this package: https://assetstore.unity.com/packages/tools/integration/achievements-stats-for-steam-246610
The above error appears in version 2022.1.23f1 in a project.
But it works fine on a fresh empty project.
Any ideas what coud be the cause?
do you have your own script called Achievement?
Is there an easy way to find that?(its not my project)
Ctrl+Click the Achievement that is the cause of the error
I will check, this might be it 😄
The error appears in the package
But it might be because its overwritten by another one that was already in the project.
Does anyone know how I can get my enemy navmesh agent to turn faster into the player?
I've messed with rotation, angular speed, etc for quite a while now. You can kind of matador the enemy, like move out of the way at the last second, and he continues on. I'd preferably want him to turn into the player. The enemy doesnt have a rigid body. If anyone has any ideas I'd appreciate it!
When the enemy has line of sight to the player, stop using navmesh and start using manual movement code that does what you want
Like move directly to the player
Wouldn't I lose obstacle avoidance?
If there's an obstacle then you don't have LOS
So you switch back to pathing
I'm using an aggro radius, not raycasting
Checking if the player is within a certain distance of enemy
Okay
Well if you want to check LOS you will need to cast to check
The reason your enemy is not attacking the player directly is because it's not recalculating a path fast enough
But it doesn't need a path if it can just walk straight to the player
I can switch to manual movement the moment before the enemy reaches the player, thanks for the idea!
What [Unmarshalled] (UnityEngine.Bindings) attribute do?
Hey I'm making a dialogue system in which dialogues are stored in ScriptableObjects.
After a dialogue have been played I save the instanceID of the dialogue's ScriptabjeObject in a list, and when I want to know if a dialogue have been played I check if the instanceID is present in the list.
Is saving the instanceID instead of a random int ID a good idea? I wouldn't want that to change or something
Any ideas on how to get rid of the skating at high movement speed? I had figured that the enemy would just move from point to point at that speed since no rigid body, but he just blows past the waypoint
Guess I might have to have a decelerate function or something
What's skating?
Overshooting?
I actually don't know, I don't use the Pathfinder component in my game
I just generate the path and make my agents follow it with my own code
Gotcha
I have patrolling integrated with pursuing so I am trying to balance :/ learning a lot tho through the struggle
if you're going to serialize what dialogue has been already used in the long run, you'd probably want to generate your own ID (at asset creation) or grab the asset ID and set it onvalidation
I was expanding on a FSM and I thought about two cool features I can't quite figure it out myself. If you can help me out I'd love it.
- Toggling state: Let's say I wanna disable the ability to run. How would I do it since in state/factory for returning states switching it is openly declared?
- What if I don't want to centralize variables inside the player controller? ie jump height, jump time move to the jump state and same for respective variables?
Thanks
With the second option you mean getting the asset ID with Object.GetAssetID and fetch it to a variable inside the ScriptableObject?
What's the difference between checking the ID fetched to the variable or checking it directly?
can someone explain why if I cast a collider, the normal of te raycathit2D which is made can be allong the direction of the cast?
like casting by (1,1), and then the surface normal is (1,0), which isn't directly opposed., but how
Hi, im new to Unity, and i apologise if im interrupting something, however, i have a problem, that i don't seem to be capable to solve with my limited knowledge. I would like to create a reference between a Rigidbody2D, and a variable in my code, the Visual studio that i use tells me that 0 references to unity have been made, and whenever i run my project, my code doesn't assign to the Rigidbody2D, could someone please explain to me what i could try to, or what possible errors i might have?
thanks
by the way, what are you referring to when you say "Visual studio that i use tells me that 0 references to unity have been made"
because it sounds like you might be referring to code lens, which does not tell you about references to unity objects, it tells you how many places that variable/property/method is being used in the code
ah, thank you
here is a picture of my code
you did mean the Unity message | 0 references part, right?
could you suggest anything i could write to change it so that it works?