#archived-code-general
1 messages ยท Page 272 of 1
Okay well is there a way to bake only certain parts or limit the range?
probably yeah using volumes n whatot
check here too https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/api/Unity.AI.Navigation.NavMeshSurface.html
I thought this would have been most people's answers.
And you're right -- too much of a headache.
you wouldn't be developing your game around hitting a framerate target without audio to begin with, even if it did help
Of course not :p
I'm having some issues with my content resizers. I have a method that attempts to iterate all the GOs in a transform and calculate the minimum size needed based on the max/min X/Y of everything contained. When I use a layout group, the layout group doesn't update their sizes until the end of the frame, so calculating the minimum size doesn't work until the next frame.
The advice I've seen indicates that I should use LayoutRebuilder.ForceRebuildLayoutImmediate(transform as RectTransform); but this isn't seeming to work in this one situation, and I've even double checked that the GO is activeInHierarchy.
I've tried a number of various "solutions" on the forums, including calling force rebuild twice, calling Canvas.ForceUpdateCanvases() before it, and enabling/disabling the GO in the lines immediately before this, none worked.
What else can I do, aside from using a coroutine to wait one frame to do this (which is going to lead to a one-frame flicker of these items.. not a huge deal but still annoying)
(code available upon request but it's a bit long)
Is it possible to override the AudioSource volume limit of 1?
prob not if the range is 0-1
yes but it will have no effect. if you want something to be "louder than" 1 because you have some falloff or distance-to-the-listener things going on, you'll have to do that math yourself
Why wont the spear script get the reference? (part show in vid, full script is spawner script)
Spawner script: https://gdl.space/ewoyoyijop.cpp
Warning script: https://gdl.space/emebefeluf.cs
@rigid island @modern creek Could I use the AudioMixer component perhaps?
if you're looking to make something louder why not boost the original audioclip ?
I mean, you can use an audiomixer, sure? But I don't know what you're trying to achieve so I don't know if it's a good/bad idea. ๐
If you have non-spatial sound then .. yes, what nava said. If you do have spatial sound then just place the audiosource closer to the audio listener
indeed. if you need boost audio, Audacity has a neat Normalize feature to bring all clips to max loudness
think normalize only brings the peaks up to max
I like the idea of giving the player the option to turn the sound effects up to 200%.
so how loud its perceived will depend on a lot of thigns
Is there a way to get objects in a radius / is there a way to get navmesh sources by radius?
100% just seems so, typical, lol.
Oh maybe it was just Gain forgot which one hehe
yes Overlapsphere
uho
but you need colliders
was just pointing out it does not limit or compress, so heavily compressed audio will sound louder then more dynamic audio even if both are normalized (sorry i am ultra picky about audio, was my past career)
Gain on the mixer
Also #๐โaudio
This... doesn't look like it would compile? Why do you have internal as your access modifier on warning? You also don't (in general) check for == null in unity, since it doesn't work like you think it might (it checks if an item is null OR if it's been destroyed that frame)
They do have colliders
that makes sense
What does this even mean, though? 100% is "full volume"
Yeah
Boosted above unity
It's not an abnormal concept in audio engineering
And VLC has it
so overlap should get ur radius u want
Don't think too deep into it I just want that number
I guess I just don't really know what the OP is looking for aside from not liking 100% as the max volume. If you want it louder, the user needs to turn their physical volume up. If you want the audio clips themselves to be distorted, then you have to modify the clips in an external problem. If you want an awful audio experience just play two clips at the same time? shrug
If you play two clips separated by a tiny amount you'll get the effect you might be looking for, but.. uh.. it's not really going to sound "good" i think?
And I have found that in the Audio Mixer
No
yeah audiomixer is what you're looking for I guess.. although I still struggle to understand the use case aside from this โ๏ธ
It's just "nice" and I'm putting off more pressing work and this seems a reasonable distraction.
I thought internal would work just as public, just that it doesnt show up in the inspector, since i wont use it in the inspector, i used internal.
the scrip can both compile and run, but yea spear i nthe Warning script is always null.
reason i checked for null is that.. well... i had an error with it not getting the reference, which i thought. Actually idk what i was thinking, i just had no clue how to solve this.
!code
You can make your own value that goes from 0 to any number and sclae the 0 to 1 by that
And again, ask in #๐โaudio
If you want something to be private, make it private (and set it with a public facing method). If you want it to be private but want it in the inspector, use [SerializeField], that's what it's for.
๐ 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.
You're also getting your warning component off of a prefab, it seems, instead of instantiating one? I'm not sure if that's what you're trying to do
Maybe it would be more helpful for you to describe what you're trying to do.. your code is a little.. broken? which is fine, but it's hard to understand what you're trying to do from the code alone
also @terse surge just fyi this is... never going to work:
bool TrueFalseGenerator()
{
float randomFloat = Random.Range(1f, 3f);
if (randomFloat == 1)
{
return true;
}
else return false;
}
You don't compare floats to integers, and also.. random.range with two parameters is going to generate a random float between 1.00000000 and 3.0000000000 (ie, maybe 2.583284834, 1.3472763472893, etc).. it's just never going to be even close to 1.0000000
if you really want a "true false generator" with this code:
private bool GetNextTrueFalse() => Random.value > 0.5f;
my code is indeed broken.
What the spawner is supposed to do is spawn a warning symbol (gameobject looks like !! but with a gradient and all that fancy stuff) and a spear (well katana). the game object plays a sort of blinking animation, then sets the canMove in the spear script to true.
Basically what it would look like in game, is you get a warnign symbol o nthe side of ur screen, then a spear is launched towards the other side if the screen.
For this i have 2 prefabs, the warning prefab (again, looks like this: !!) and the spear prefab (which is a katana).
Spawner spawns them at the same time, passes some values on to em, and yea thats it.
When the warning sets canMove to true it destroys itself i nthe same method, and the spear destroys itself after 7 seconds.
this together should total a clean attack which the player has time to dodge.
currently, i have a problem with the referencing as you can see
and also... the spawn location in the else statement in the spawner script, but first id like to solve the reference thing
description of what im trying to achieve ^^
k, that's helpful.. can there be more than one warning at a time? I suspect yes
i did notice i got only the return from the if statement.... 3rd problem ig
it's fine, you're here to learn ๐ but it's important to understand the why
when i got the reference error i believe it was only one error, i can try removing the if name != null and see if that helps
a random float between 1.0 and 3.0 isn't "1 or 2", but rather it's a random float that could be 1.000000000 or 1.000000001 or 1.0000002 or 1.000000003 or 1.0000000004...... with a few million options up to 2.999999999999
ohhh, yea i see it now, haha sloppy error on m yside, originally this method was used to generate a float in some other code of mine, but when i copied it over and changed the values i forgot it was for generating.. well a float
I don't mean one warning in your compiler, I mean more than one warning monobehaviour
i nthe script itself?
in the game
SpawnAttack() - if this happens twice, does the user see two warnings on their screen?
ok, here, lemme try to sketch out some code and make this a bit easier for you.. you'll need to fill in the deets yourself:
well after ti happens once, the game pauses as it usually does automatically when an error occurs so i never tested
also this should fix the 1 to 2 generator
private void SpawnAttack()
{
Vector2 warningLocation = ...; // calculate these like you did before
Vector2 spearLocation = ...;
Warning newWarning = Instantiate(warningPrefab, warningLocation); // you don't need the quat.identity parameter
Spear newSpear = Instantiate(spearPrefab, spearLocation); // Just instantiate a "Spear", not a game object that you get the component of the spear from after.
newWarning.Initialize(newSpear);
}
//////
public class Warning : MonoBehaviour
{
private Spear _spear;
public void Initialize(Spear spear)
{
_spear = spear;
}
}
this "fixes it" but is still bad because it's like 10 lines where 1 would do and is also hard to mentally understand (it's hiding a cast from a float to an int, so it's not really clear). Just use my code above, it does the same thing and much simpler
โ๏ธ
Also, just get into the habit of naming your methods with verbs - "TrueFalseGenerator()" is a thing, not a verb, so a reader would expect this to return a thing called "True False Generator"
btw I kept working on this - I got the terrain generating again and now can create a 32x32x32 chunk but the heightmap seems completely messed up - still getting the same leaks from the native arrays :/
oh sorry, must have missed it. does it generate a new one every time the bool is used or..?
yes, and really it could even be better as a property and not a method:
public bool NextBoolean => Random.value > 0.5f;
note the lack of () after the name.. so you'd just use it like this:
if (NextBoolean)
{
// do something 50% of the time
}
shouldnt andom.Range() be andom.Range(0, 1) ?
changed to .value, sorry
why
although I think range() with no parameters is 0,1, but as always, check the docs
range of 2 options and a Random.value > 0.5 are both 50 50 chance
https://docs.unity3d.com/ScriptReference/Random.Range.html
So you're actually right with your above code - Random.Range(1, 3) == 1 will get you true 50% of the time.. but is.. kind of ugly for reasons that are hard to explain in a nutshell.. take my word for it now. ๐
value is nice since you can do percentages of chance easily
yes and if you really want to get fancy lemme sell you my optimal weighted list generator ๐
already got one, have it as a extension method on lists
https://github.com/cdanek/KaimiraWeightedList
(I probably hawk this at least once a month lol)
(it's not really for sale, I was just teasing)
ok so i think i get this, since i dont really need to access the gameobject itself there is no need to store it in a variable, rather id just store the script
yes, and you can get the gameobject if you ever need it with newSpear.gameObject
(GetComponent() is slow and in general you don't want to use it)
dam no gifs
hmm i see
i kinda alr used it a bunch in my code ๐
it's fine, it won't matter until later in your career.. but you may as well get in the habit of avoiding it
but then... why did name != null not work? sure its slow but eventually it has to work, no? lols
it's not really "slow" per se, but if you do something silly like have a GetComponent() in Update() for hundreds of game objects, your game is going to crawl and you're not gonna understand why
i do indeed try to keep in mind all the tips i recieve here, but i plan on expanding my game jus ta wee bit so it might come back to bite me
not really sure - but i only glanced at your code.. try to implement the code i gave you above and then see where you're at, maybe describe your problem again
although originall the games intent was just so i learn how to make a game
i do have to get back to work a bit so someone else might have to take your ball and run with it
๐
on one hand, don't use GetComponent() (or any of the find game object methods) because they're slow; on the other hand don't optimize your game prematurely (or probably ever) since YAGNI.. and if you do, you'll know
Does it really matter if it only gets run once?
no, that's fine
I'm trying to figure out how to use NavMeshBuilder.BuildNavMeshData but I don't know what the position property should be
It says it's supposed to be the origin of my data but I don't know the origin
why not just BuildNavMesh
I get large lag spikes?
Is there a way to define an area?
Oh btw, I'm trying to update the navmesh when the user opens a door
if ur doing this in the editor whynot use the Navmesh volumes
ohh this is runtime ?
during runtime
so use a volume and bake that if u want a particular area , no
hmm I'll check
anyone knows how to solve this error? how am i gonna give it transform if im still at the part were im instantiating it
do volumes update dynamically?
You give it the Transform of the parent. If you're trying to give it a Position, you need to also provide rotation.
Look at the docs for the forms that take position/rotation https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
Oh you mean like bake at runtime ?
yes... I don't want to bake the entire map during runtime
Navmesh needs to update when a door gets opened/closed
ohh maybe set navmesh surface on Volume mode instead?
I need to check again if it bakes for ALL
Ok it works
define your size here
this should only bake a certian area
proof ๐

still mind boggling this function is async but not the BuildNav
I tried implementing it but I get lagspikes with this and the navmesh isn't updating correct, I'm not sure if I missed something. Here's the code
private NavMeshSurface surface;
private NavMeshSurface GlobalSurface;
void Start()
{
GlobalSurface = GameObject.Find("NavMeshSurface").GetComponent<NavMeshSurface>();
door = transform.parent.GetComponent<Door>();
surface = door.GetComponent<NavMeshSurface>();
}
public void Animation()
{
surface.BuildNavMesh();
GlobalSurface.UpdateNavMesh(surface.navMeshData);
door.IsPlaying = !door.IsPlaying;
}
}
Is this correct?
Animation() gets called with an animation event
basic stuff but did u make sure the function is running ?
put debug.log
I know it is cause I get lagspikes when I open the door / close it, I've been using the script for a while
the lag is normal from BuildNavMesh
its a synchronous function
why did unity did that, i have 0 idea
I don't think I got lagspikes when I didn't include UpdateNavMesh
use both in a coroutine should at least help with freezing
I have a mobile game that rebuilds the navmesh frequently, I have never noticed any lag in it
same but also have another project where i needed Coroutine to mitigate the sync call
I'm reasonably sure you just use UpdateNavMesh to make changes to an existing navmesh
also, I see you have a "surface" and a "global surface"
I do..
I use Surface and Children btw
I haven't done anything other than one large navmesh that gets updated, so I'm not familiar with how that'll behave
(since i haven't needed to do anything else yet)
I might have misunderstood the concept, is the surface component only meant for baking the navmesh or does each surface hold it's own mesh?
How would I make it so the distance between the mouse and the player doesn't affect the projectile's speed? I've been trying to figure it out but can't. In the clip you can see that the bullet is a lot faster when your mouse is far away while you shoot and really slow when it's close
https://gyazo.com/9a5a15373234c6f4f58aed3925c7d2ee
private void shootBullet()
{
if (onShootCooldown) return;
onShootCooldown = true;
Invoke(nameof(removeShootCooldown), shootCooldown);
var currentPlayerPos = gameObject.transform.position;
var newBullet = Instantiate(bulletPrefab, currentPlayerPos - Vector3.back, new Quaternion(0, 0, 0, 0), null);
var bulletRigidBody = newBullet.GetComponent<Rigidbody2D>();
var mousePosition = Input.mousePosition;
mousePosition = mainCamera.ScreenToWorldPoint(mousePosition);
var bulletDirection = mousePosition - currentPlayerPos;
bulletDirection.Normalize();
bulletRigidBody.AddForce(bulletDirection * 20, ForceMode2D.Impulse);
}
I'm pretty sure UpdateNavMesh causes lag spikes since I don't get spikes when I comment it out
but I'll put it in a coroutine
lol bulletDirection.Normalize(); you are not actually normalizing
its an async call it should be in coroutine anyway
eg
IEnumerator Start()
{
var surfaceBaking = surface.UpdateNavMesh(data);
yield return new WaitUntil (()=>surfaceBaking.isDone);
Debug.Log("Done");
}```
how else would i do it then?
bulletRigidBody.AddForce(bulletDirection.normalized * 20, ForceMode2D.Impulse);
causes the same problem
How so?
should work fine
It modifies the struct in place
should not do, now you are normalizing which means distance is not a factor
Your mousePosition's Z value is probably at the camera
Make sure it's zero
omg new Quaternion(0, 0, 0, 0), null); whyy
true, my bad
Yep, zero quaternion is not valid
quaternion default is not 0,0,0,0
i tried doing that already but it didnt fix anything
You sure? Can you show updated code?
ill redo what i did earlier gimme a sec
Should set Z to zero after the ScreenToWorldPoint
Or you can just set bulletDirection's Z to zero before normalizing it
oh my god it's working now idk what i did differently from last time but who cares ๐
thank you
nvm i normalized before setting z to 0 before
If a coroutine is awaiting another and externally that other gets stopped by StopCoroutine I believe the first never stops awaiting, can someone confirm?
I still get lag spikes for some reason
IEnumerator Bake()
{
var globalSurfaceBaking = GlobalSurface.UpdateNavMesh(surface.navMeshData);
yield return new WaitUntil (()=>globalSurfaceBaking.isDone);
Debug.Log("Baking Complete");
}
public void Animation()
{
surface.BuildNavMesh();
StartCoroutine(Bake());
}
It's the conclusion I'm coming to seeing my "bug"
and the navmesh doesn't update correctly...
it's not in the right place
or rather
the right place doesn't change
oh- hmm
actually
surface.BuildNavMesh();
should also help if u put in coroutine
since its a synchronous call (it could freeze the code if takes long until done)
Should be easy to test definitively with a new script. I do agree itd be unintuitive but at the same time, it sounds odd that you await a coroutine from a coroutine and pass that reference elsewhere so it can be stopped
it seems to copy the current data, insert the new data and place it over the old which cause a lag spikes... like the nav mesh puts another surface ontop of the surface
oh if you keep baking certainly
I think it does additive baking
how many navmesh surfaces did put ?
hopefully not 1 on each object..
uh.. well, 1 surface on each door, 1 surface for the game
but I am only opening one door
https://docs.unity3d.com/ScriptReference/AI.NavMesh.html
I didnt do too much with building navmesh at runtime but I believe you can just remove the old surface easily
I know I can delete the data but the issue is that it tries to regenerate the map considering the lag
I didnt see the original issue, but building a navmesh is not too cheap. Relatively speaking
Especially if it's a large surface
Well that's why I want to bake smaller parts where needed
What was the original issue? I dont really see why you would ever need a navmesh surface on a door
You could likely just throw a navmesh obstacle on it and call it a day.
the nav mesh surface is used to define a region that gets a navmesh built for it
you don't put it on the door. you put it on a region of your level
just use a navmesh obstacle with Carve enabled and it'll work perfectly fine
Carve actually punches a hole in the navmesh.
Isn't obstacle just for avoidance like something dangerous?
Thats just one usecase for it
you should read the documentation before you continue
gonna be damn difficult to walk through the door then
Non-carving obstacles are avoided by agents, I suppose
they try to steer around the obstacle
There is no sense of "dangerous" to your navmesh agents, although in real life itd be pretty dangerous to constantly walk straight into doors
yes at most you have area cost but thats avoiding a certain area if lower costs are available
Well using an obstacle for something like a temporary fire is ok
Yeah Im thinking of experimenting with that to make bots avoid certain areas temporarily
And not getting in front of the main player when hes aiming his gun
Need to do some performance testing, though
Might get too expensive especially if I want different factions to avoid different areas, having to activate/deactivate and move them around all the time
Interesting thought but also keep in mind if the gun moves onto the enemy, the enemy will instantly try to depentrate and it may look weird
Yeah it needs to be different for enemies/friends
Not sure if it carves instantly or in the next frame or at the end of the frame
Gotta experiment
I'm not entirely sure how the "areas" work but maybe you could define a danger zone
Like the walkable and jump default areas (or layers?)
I an experiencing a problem, it appears the gravity isn't the cause of the sliding up the slopes, it looks like that was already happening. When I remove the gravity from the movement code it just lowers in intensity. Here is my script: https://hastebin.com/share/wemekasewe.csharp. Here is a video of the issue: https://streamable.com/2m5w7u
I think those are just for NavMeshModifier, which doesn't seem to update the navmesh in realtime unless you rebake it
But ideally yeah a zone with a high area cost would be better than just outright carving it out
one possible issue is that you're using slopeHit.normal even when the raycast might've missed
I don't know what values get put in when that happens. Maybe just Vector3.zero
You should make sure you're actually hitting the slope here
How do you exclude objects from the navmesh?
Although, given that you're going downhill properly, you probably are!
also, I can't really tell what the problem is by looking at that video
what is the unexpected behavior?
sliding up the slopes, that isnt my input.
Yeah, it doesnt miss the slope
also, you still have gravity in your movement code
did you just set gravityMultiplier to zero?
ah, you don't use the gravity field, I see
I thought that was modifying velocity at first
One reason you could be going faster uphill would be if the controller was trying to move into the ground
it'd get pushed back out
I'd use Debug.DrawRay to visualize the velocity vectors.
but it still seems really weird for you to be forcibly moving uphill...
Does this go away if you set the acceleration to a huge value?
no
The acceleration also doesnt seem to be doing anything
Yes, I set it really high and the player still moves instantly.
well, you do expect the player to accelerate really quickly when it's high :p
but I'd also expect this...
I just implemented this and it's pretty dope
planeVelocity = Vector3.MoveTowards(planeVelocity, desiredVelocity, acceleration * Time.deltaTime);
to completely kill your planeVelocity when you're not trying to move
so your velocity should be made up strictly of normalVelocity
and that shouldn't make you go up hill at all!
maybe unless normalVelocity is a huge vector pointing into the slope...
the character controller might depenetrate by moving up the slope
Debug or draw those vectors to see what's up
The yellow line is the velocity vector debugged: https://streamable.com/1liay8
Oooh, yeah, I get it now
When you get onto the slope, some of your forward velocity is now perpendicular to the surface's normal vector
So now it's part of normalVelocity
And nothing ever reduces normalVelocity
Its going directly into the normal
The CharacterController responds to that movement by sliding forward a bit
Try doing that first, yeah
You'd want to do that if you're grounded and the velocity points into the floor
How can I know if the velocity points into the floor?
You could test if Vector3.Dot(normalVelocity, normalVector) is negative
I suppose that, if you're grounded, you should always kill the normal velocity
This will make you briefly lose speed when you hit a slope, though
you'll lose the part of your velocity that doesn't align with the floor
You could fix that by remembering the normal vector from last frame and rotating your velocity accordingly.
That'd be great for something like Tribes, where you slide around and conserve momentum
Hi! I need a bit of help lol
My goal with these functions is to spawn islands within the bounds of my mapPanel object, which is 10,000x10,000. Spaced apart, and far enough away from the objects edges to where the islands don't get cut off.
https://pastebin.com/zg0UsJnz
With my current variables (SpacingXOffset, SpacingYOffset, PaddingXOffset, etc) the maximum and min X and Y coordinates are
minXCoord: -4666.667
maxCoord: 4666.667
minYCoord: -4696.97
maxYCoord: 4696.97
Some islands STILL spawn outside of those bounds, although the position is calculated like this
float randomX = (Random.Range(-panelWidth / 2 + paddingX, panelWidth / 2 - paddingX));
float randomY = (Random.Range(-panelHeight / 2 + paddingY, panelHeight / 2 - paddingY));
I don't believe my collision detection function (IsPositionValid())would impact the positioning in this way, so I don't understand what the issue is.
Like right now, with this code I had 3 islands spawned at below X -4800 which is outside of the bounds I defined
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.
The sliding is fixed now, thank you!
if not, this shouldn't be too hard
Quaternion.FromToRotation(oldNormal, newNormal)
basically
There isnt a velocity loss, I did this:
if (IsGrounded() && Vector3.Dot(normalVelocity, slopeHit.normal) < 0)
{
normalVelocity = Vector3.zero;
}```
I think I found the problem
Although, I am experiencing a new problem when trying to apply gravity. Sometimes the gravity works, but other times it doesn't. I'm also not always sticking to platforms, instead I am flying off of them a bit. The code for the gravity is the same as in the script I sent, but in Update() I have velocity += gravity;. Here is a video: https://streamable.com/et4xl3
You might need to "look ahead" a bit to get ready for a downward slope
Although, this looks more like gravity just isn't working at all (in some cases)
Maybe your grounding check is too eager, and you're killing your normal velocity when still a decent ways into the air
So I need to up the distance the groundcheck ray can shoot?
Yeah, um, increasing the distance of the groundcheck ray just makes the player float higher.
Reduce, not increase!
too eager to say that you're grounded, I mean
One thing that might be useful to you is https://docs.unity3d.com/ScriptReference/Rigidbody.SweepTest.html
oh wait, this is a CharacterController. d'oh
I was going to say you could use this to test if you'd hit the ground by moving down a tiny bit
You could just use the controller's isGrounded, but if you completely remove your normal velocity, you might not actually hit the ground when you move
which would make isGrounded return false
I'd reduce the raycast's length and check if your velocity is pointing towards the surface you hit. Apply gravity before you do the grounding check
this way, IsGrounded() won't return true immediately after you jump
CapsuleCast would be appropriate though, right?
SweepTest is useful if you have multiple colliders on the RB
Im using CharacterController
True that. I make sure to always visualize this kind of things
Even made a gizmo function for drawing capsules
(Basically just three Gizmos.DrawMesh calls, 2 for the caps and one for the center)
Can be used to draw a spherecast too
I reduced the raycast length to 0.6 and started applying the gravity before the ground check, and now this is whats happening: https://streamable.com/qj0l9h
Btw, the randomly floating into the air while on the flat platform was me jumping.
So you're popping a bit into the air when you come off a ramp
yeah
it makes sense from a physics perspective (you suddenly went from a ramp to a flat plane, and you had a fair bit of upwards velocity!)
but it's not exactly what you want as a player
This may help with that
You'd rotate the velocity vector to follow the ground
would I just get the oldNormal by logging the normal at the end of PlayerMove(), and the newNormal by logging the vector at the beginning?
Yeah
This should only happen if you're actually on the ground, or your midair velocity will get messedu p
of course, deciding if you're on the ground will be a bit tricky...
This reminds me of the KinematicCharacterController package. It has a "force unground" method that explicitly sets your grounded status to false
it's important when jumping
If you were grounded on the last frame, and you haven't deliberately ungrounded (like by jumping), rotate your velocity to match the normal vector of the ground under your feet
Should I do this in its own function or no?
It could be done separately, yeah
Something like this? ```cs
Vector3 RotateVel(Vector3 vel)
{
if (groundedLastFrame)
{
var rotation = Quaternion.FromToRotation(oldNormal, newNormal);
var rotatedVel = rotation * vel;
return rotatedVel;
}
return vel;
}```
Yeah.
That'll keep you from rocketing into the sky when a ramp ends
The other option would be to always remove your normal velocity as long as you're grounded
Yeah, always removing the normal velocity fixes it when going onto a downwards ramp, but not when leaving an upwards ramp.
Oh wait, RotateVel() is also doing nothing.
Here is my script rn: https://hastebin.com/share/otoyovanow.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Log to check when it's actually running.
What do you mean?
stick a Debug.Log in the method to check when it's being executed
and also log the old and new normals
Here is what those log when changing between the platform and steep slope.
What do you mean? Isnt it executed every frame?
only when groundedLastFrame is true
that could be messed up
er, I should say the actual rotation only happens if that variable is true!
the method is indeed called every frame; my bad
Okay, logging that, here is a video: https://streamable.com/hc75en
stack unity child game objec
I personally have separate logic for sticking to the ground when walking over a ledge or entering a ramp
When the player becomes ungrounded, I use a physics cast to check if there's still ground a bit below me
If yes, snap to that hit position
Hey y'all question about statemachines. In your opinions is component based or event based better to implement?
only things referenced in scenes in build get included in the build
so if a asset is not referenced by a scene but in a bundle it only ends up in the bundle
then make sure that scene is not in the build list
the scene ends up in the bundle then all assets that scene references end up in the bundle
you can end up with duplicated assets of some of those assets are also in scenes that are part of the build
What would event based even consist of? A state machine usually directly calls the state's functions. You would need other code which listens to these events which is basically just a layer of abstraction.
I made my states inherit from mono for the ease of setting up in inspector
i would be making much smaller bundles
Hey guys, quick question, how can I access the green axis shown here in code ?
Component based the state machine stores every state like a game object and event based would process state changes through the state machine but store the states as classes like you said. I probably implemented the component style one indirectly idk lol I'll test them in a prototype project
its transform.up
that will get you a directinal vector pointing in that direction then you can add it to the world position of that object to put it in the same spot
A component wouldnt be a gameobject, it is just a component, which is still a class. Im unsure how events would really help or be different here. It would just directly end up calling the enter, exit, update methods on the current state. It being a component has no affect on if you can do it, it just provides a much easier way to define what states are used
Fair enough, thanks for the feedback!
The behaviour I want is working with this :
arrowInstanceGOParam.transform.Translate(Vector3.up * arrowSpeed * Time.deltaTime, Space.Self);
Which is super weird I know
Why is that weird?
yes that works because its translate works in local space
so (0,1,0) is the direction of that green arrow
ooooh
transform.Up gives that local direction in worldspace
like if instead of translate you just did
transform.position += Vector3.up * arrowSpeed * Time.deltaTime
it would be incorrect
since its world up, and transform.up was required
Well not confusing, but I want to "store" this axis at a given frame
So the arrow in question will only follow the localspace green axis
why is that?
oh thought for a seceond you had it has a child of the character
its fine as long as its not a child of anything with rotation
yes
It is as a child of another gameobject
This is my issue
I use the parent to place the arrow correctly
so make it not be a child of the game object when you fire it
un parent it, or instantiate a new arrow to fire and hide it
can you get rid of all parents?
SetParent(null) will do t hat
though the more common approach is to disable it and create a new arrow in its spot
and fire that
can someone help explain why my grapple gun script doesnt work
its a bit long so @ me if you can help so I can send in DM
thats too much committment
post !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.
with links
and explain "doesnt work" mean in this context
very doubtful someone will take time to DM
Only DMs I slide into nowadays are my Wife's
wops
no errors
does "links" not mean anything to you ?
just not doing anything
my b
thought u were talking to someone else
ur the only one who posted question about code lol
last msg was 4 hours ago lol
I be a bit acoustic fr
yeah my acoustics act up too, too many concerts ๐
alr so what is supposed to happen and what is happening instead ?
its supposed to grapple
but it doesnt do anything despite 0 errors
well are you sure the code is even running?
yeah
how do you know?
put in variables and stuff
Often the reason something doesn't work has nothing to do with errors
have you written any Debug.Logs in the code?
no
wdym put in variables
I would definitely start there. Write a debug log BEFORE the raycast, and after it
filled them out in the inspector
alr
the one after should log the raycasthit
will try
that doesnt mean script is running lol
but yeah put some debug.logs and also would , screenshot and show inspector for what ur trying to Grapple on
alr
inspector whie debug runs
what
ur supposed to look at the logs in the console window
and show where you put the logs in code
didnt you ask for inspector?
Inpsector for the Object you want to grapple on
not the script
wht u tryina swing on?
screenshot its inspector
fully
Well, collider was important to see
would debug.log(hit) show the name of the object the raycast hit?
I think you would want hit.collider.name
how it be feeling asking for advice on dsicord
well wanted to make sure it had a collider and the layer yes
alr thnx
alr so for some reason nothing shows uip in the console
when doing it on the swing points
show where u put the debug.log in script
so its not debugging when doing it on Cube(3) ?
yeah
I renamed the ones in the grappleable layer to swingpoint but samething
nothing appearing in colsone
fuck
console
is it logging for other colliders?
You didn't do the debug BEFORE the raycast, just to verify it's actually doing it.
Also, do a Debug.DrawRay
Just plug in everything from the raycast, and you will see exactly where the ray is going
alr im just gonna scrrenshot your messages and do it tomorrow bc my mind is blacking out and I got class tmrw
thnx for thr help
How do I modify object's RectTransform?
RectTransform imageTransform = (RectTransform)image.transform;
Rect imageRect = new() {
width = tr.rect.width,
height = tr.rect.width/image.sprite.rect.width*image.sprite.rect.height,
};
// below is compile error, said they are read only
imageTransform.rect = imageRect;
(image.transform as RectTransform).rect = imageRect;
yes .rect is readonly
how do I modify it's RectTransform.rect.width and RectTransform.rect.height?
just use the sizeDelta
sizeDelta is... using it's own anchor right and not parent's?
Do I also change the position using anchoredPosition?
yes
how to modify this so that i can use random.range?
Like a random element from the array..?
does Unity not support prepaid subscription in-app-purchase?
What are you trying to randomize?
I could only possibly imagine you'd select a random string name before passing it to the function.
Unity? Like subscribtion for the developers and purchases inside the editor??๐
ah nope, I mean for product store subscriptions in android and IOS
Why would that depend on the engine?
It's all up to your app and the publishing platform.
And ads providers.
Google mobile ads for example has a plugin for unity. And even if the ads provider of your choice doesn't have explicit support, you could probably write a native plugin to support it yourself.
i wanna be able to pass in 2 numbers as a range to play a random clip from the sfxsounds array in my audio manager
Well, them do that.
Get a random number in range and use it as an index to get an element from the array.
how to do that in this kind of array tho
get the length as your max in Range
Random.Range can return you the int as a safe index
how to return the index of an array element with its name
I use Unity engine and InAppPurchase package from Unity, but seems it's not support for prepaid subscription. I found some the same questions in unity forum and still got no clue
wdym its name ?
i wana do something like this
pretty sure that error on Random is ambiguity between UnityEngine.Random and System.Random
range2 isn't a safe max index though, I would do int index = Random.Range(min, sfxsounds.Length)
should use the .length of array
what type is randomclip ?
not gonna work cause its gonna select sounds you dont want
wdym? so put only sounds you want in array?
or make another list , where are you getting that range2 int anyway
its an audio manager it has all sounds
so where is range2 come from as long as you're certain it wont ever be above your array size, you should be fine
btw cntrl + dot to fix the ambiguity for Random class
Ok, so in this case unity is your provider of the ads. But prepaid subscription doesn't have anything to do with ads. It's a separate system. You can use unity in app purchasing package to implement the subscription purchasing and confirmation mechanism. Then you just use that data to decide wether a user should be shown ads or not.
actually I'm not asked about the ads. I just need to know Unity has support for prepaid subscription or not in their IAP package
Well, did you check the iap package documentation yet?
I think prepaid subscription isn't any different from a regular purchase. What matters is how you treat it in the app.
yeah, Unity hasn't mentioned about it in their documentation or forum. so I'm confused about it because I have an error regarding it
"product isn't found". I'm already have that subscription item in google play console, but the unity API give me that error
have you ever implemented IAP package from unity?
I have a while ago.
especially for subscription product?
I have the same issue with this topic:
https://forum.unity.com/threads/are-prepaid-subscriptions-supported.1519978/#post-9570754
What are you using code wise?
๐ฅ
yeah sure, we can also see similar problem in other threads. just type "prepaid subscriptions" in the search input, its flagged as a bug
That doesn't answer my question.
what do you mean by "using code wise"?
Ok so, I've got a point, and I want to find the nearest location to that point that can fit a circle of size X
I guess you're defining stuff in the inspector. That somewhat limits what you can do.
But here's a post about a similar issue and it seems to be resolved:
https://forum.unity.com/threads/unavailable-product-for-google-subscriptions.1298436/
please read it carefully
or maybe try going hardcore and call the billing 5.0 API in the google play sdk directly ๐
iirc, people used to use that way before unity's billing API exist
the solution on this thread is updated the plan to auto-renewing ๐
I'm not expert on writing a bridge plugin from Java to unity, so I avoid that ๐
Iterate over a direction, using the radius as a fixed step size, fire a ray upwards with the length of the radius and if you dont hit anything you can fit.
purple: known
blue:known
then you can form a right triangle with
width - r |\ r
|_
red line
I see. They did mention that it's gonna be supported in v5.@still depot
Can't you handle it as a one time purchase though? It's basically the same.
this sounds like a hack but XD
- connect 1 to 2 with a spring joint
- disable 2's gravity
- simulate physics for a couple of seconds
me neither ๐
well, I think you'll need to wait until unity integrate billing 5.0 then, or there should be paid 3rd party iap plugin in asset store which updates their plugin faster
I didn't explain it well, what I meant was I have point 1 but I want to find the nearest point to it that fits a circle (which happens to be point 2)
you just need to find the length of red line
connect 1 to 2 with a spring joint
this should be
connect 1 to a sphere or circle collider with a spring joint
I think I found something that works
yeah, I think we can use one time purchased and handle the duration manually by checking the buy date. but it looks like a cheating the way ๐
haha yeah, have you any recommendation for the 3rd party IAP? I will look forward for it
What is it?
well, it's not actually what I was asking, just an alternative solution to the design problem I was trying to solve lol
I don't unfortunately
but the Simple IAP System seems to be still active, you can ask in the forum if it support prepaid subs
the player is a ball that can change sizes and I'm trying to see if they have room to grow to a bigger size. My solution is to cast up/down and take total distance, then repeat left/right
Could also just do an overlap sphere at the predicted sphere center.
With the predicted scaled radius
alrighty, thanks
How do I get players to align on slopes as they run?
how to make sure land sound effect only plays once i land on the ground
Use the normal of the slope, which you probably already have from any grounded checks
You could add a cooldown but I'd try to find out why its calling OnCollisionEnter so many times. At least it sounds like its playing some audio a lot. Do you have extra colliders?
Add debugs to see how many times it's even playing. Not really sure what that first code screenshot is for either tbh
Hello guys, so I'm currently working on my new project. And I need some help with coding, so here is the thing. I need that when I throw a grenade and it explodes the monster turn In to a ragdoll, and not just keep running. But I tried many times and couldn't find any actual help. Any ideas how to fix that?
how to fix what
are you trying to fix your existing code or implement it from scratch
Thats the point, Im trying to figure it out whats wrong
I even wrote the Debug that whenever grenade explodes near the Monster ir will respond
But there it goes nothing
๐ฅ
I'll send you in Dm
Also what kind of code do you need? Grenade or the monster
why would you dm me
im not your personal coach
you are in public server, asking in a public channel for help
then ask here isntead of sending dms to some random people that you didin't even ask if you can dm them
dont ask to ask
Bro my code is too big to send in discord
Also
!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.
bullshit
the ones related to the problem?
then what is the problem
The thing is that when i throw the grenade and it explodes the monster doesnt die
๐ 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.
is this chat gpt code
then i wont help you with that
why not? ๐
chat-gpt in 99% when used by begginers
genreates bullshit
do you even understand the code he generated?
or you just blindly copy&pasted that
Sort of
that's a terrible way to learn thnigs
So im here to ask for help
Sure
The tutorial is from brackeys
the code isn't from brackeys
then you are watching tutorial but you are ignroing the tutorial and doing codeo n your own
right
no bro
comments are good. those comments are useless
yup never said comments arent good
just clarifying
int myInt = 0;
//increasing my int by 1
myInt++;
that is a terrible comment
for instance
Grenade is from brackeys and the monster script is from chatgpt
Im just trying to combine these things in to a normal thing
that code has nothing to do with explosion
you are detecting if the grenade touched the Rigibody
not if it exploded
you should do a Phsics.OverlapSphere for instance
you can easily tell chatGPT code from human code because chatGPT regularly adds lots of useless comments.
in Explode() method
Combining anything with ChatGPT code will not produce a normal thing
I see
well even without the comments
4 foreach loops + non cached anything
anyway, that code has nothing to do with Explosion. It is triggered when grenade object entered the trigger
but that could be incompetence. No human would go out of their way to type out a ton of comments which are useless
yup
// Destroy the character GameObject
Destroy(gameObject);
so usefull
Thanks for help
so I've been needing some help getting down a loop point system for my game
I've got an audio manager alongside a class to play the music I want when the scene starts
here's the audiomanager
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MusicSelecor : MonoBehaviour
{
[SerializeField]
private string TuneName;
[SerializeField]
private string IntroName;
[SerializeField]
private float IntroTime;
private float MaxVolume = 0.4f;
private bool IntroDone = false;
private void Start()
{
AudioManager.instance.Play(IntroName);
AudioManager.instance.SetVolume(IntroName, 0);
StartCoroutine(AudioManager.instance.FadeAudio(IntroName, -1, MaxVolume));
StartCoroutine(StartMainTheme());
}
private IEnumerator StartMainTheme()
{
yield return new WaitForSeconds(AudioManager.instance.GetTimeLeftInTrack(IntroName));
AudioManager.instance.Play(TuneName);
AudioManager.instance.SetVolume(TuneName, MaxVolume);
}
}
the idea is we wait until the song intro clip has been played and then we play the lopped rest of the tune
[this is assuming that we can loop the song at the end of the audio file]
the issue is that my current method is inconsistent, and I am unsure as to why
using UnityEngine;
using UnityEngine.Audio;
[System.Serializable]
public class Sound
{
public string name;
public AudioClip clip;
[Range(0f,1f)]
public float volume;
[Range(0.1f, 5f)]
public float pitch;
public bool loop;
[HideInInspector]
public AudioSource source;
}
this is the record base for every sound
why not just make all the data as a scriptable object
I intiially wrote the code as part of a tutorial
so this records the information for each sound and then the AudioManager generates the assosiated entries as audio clips
in any case that stuff works
but the audio intro to main tune does not
what would be a good way to check if there is a position above or below that could be jumped to?
if(IsWalking){
var EyeCheck = Physics2D.Raycast(transform.position + (transform.right*LookDirect)+(new Vector3(0,5)), -transform.up, Mathf.Infinity, 3);
if(EyeCheck && !IsLeaping){
if(Mathf.Abs(EyeCheck.point.y - transform.position.y) > 10){
LookDirect *=-1;
}
else{
LeapPoint = EyeCheck.point;
IsLeaping = true;
}
}
if(!IsLeaping){
transform.position += (transform.right*LookDirect).normalized/40;
}
}
heres what I have now
does not seem to work
What's 3 supposed to be? The layermask?
yeah
has worked for me before but I can try an explicit one
So you only one to hit the first 2 layers?
it seems to have worked in the past but maybe i'm crazy
Might want to double check it. Layermasks are bit masks, where each bit corresponds to a layer.
You probably had something on the default layer and it was hitting it.
Might want to debug what your rays hit.
yeah that seemed to work
i think ill just use explicit layer from now on
As for your initial question, maybe replace the magic numbers with an empty transform parented to the character.
Wdym by "explicit layer"?
like using a variable set to the layer mask instead of an int
can I somehow disable a scene with a SceneInstance type, but not unload it completely? I load scene with additive settings by addressables and all working good, but I can't figure it out how to just disable loaded scene for later use or something like this
I can enable, load, unload, but not just disable them after using
Put all the scene objects under one parent and deactivate it๐คทโโ๏ธ
Yeah, scenes don't have a "disabled" state
a scene is just a mega prefab that tries to destroy everything that is not DontDestroyOnLoad when it loads in
and unity has a couple small tools to keep track of the current scene loaded, and loading them
Has anyone ever seen this issue? Trying to set some platform settings in a plugin, but it seems the settings don't realy stick. I click apply. Navigate to something else, come back, and the choices are gone.
Anything showing up in the console?
nope. console empty
everytime I use goto I feel like im channeling a dark art
I'd look at the .meta file and see if anything changes when you hit apply
(and maybe changes back!)
I'd also peek at the "Asset Postprocessors" list to see what could be modifying the asset. I wonder if the ReactionMusic plugin is doing anything funny to it
and i'd also try duplicating a DLL (or creating a new one) and seeing if you can modify its import settings
thank you. I think that sent me on the right track. I ended up deleting the meta file, right clicking the plugin in the project folder and reimporting...and now it seems to be happy again.
Generally yeah goto is to be avoided, there are very specific situations it's good but most of the time you'd just be raising eyebrows.
goto is great when you need it
Dijkstra was an idiot
djikstra considered harmful
Like so many academics with little or no practical experience, they only deal in theory and absolutes not in the real world and praticalities
love to see someone try to program in Cobol (which in '68 was probably the most used language) without using goto
If you need to use goto then it's time you refactor your code, because nobody needs that
there ain't any
if you think about using goto then your code architecture is bad
no matter what edge case is it
sure you can better use goto, to break out of nested loops for example
It's literally used in C#'s source code.
goto was wildly dangerous at the time that was written, c# is a significantly safer language to do it in, if you are so inclined
The issue here is having nested loops
so what
So I guess C# and Microsoft has bad code architecture then.
how did you connect that
with what i said
in assembly for example of course you need to use goto
im talking about C# and Unity
the best use of goto is goto case in switch statements and i swear nobody knows you can even do that
never scanned a pixel image?
the best use of goto in Unity is to never use them
period
Not assembly, literally the high level C# code of .NET's runtime and BCL.
Ever heard of having a positive flow in your code with no more than 3 nested braces? If you are an experienced programmer all your code would look like this
and im talking about Unity
this is ridiculous
in any modern langauge only thing i use labels for is labled breaks in loops
Clean Code isn't a holy text
Lol
It's not hard to have consistency like that
Goto is a great way to ruin readability
if you are using goto in Unity, i'd say you just aren't experienced enough or you lack knowledge about how to make proper code architecture
goto when I can't be bothered to make methods for readability
Hi I'm working on a custom package for my essential starter tools, the sorts that I can use in every project, my problem is that one of these tools needs to be customized per project and that's not easy if it's sitting in the packages directory, is there a way I can have the package place a folder with these specific assets into the assets directory? Similar to installing an exported package maybe?
I don't have a single goto in any of my code, Unity or regular C# otherwise, and I can still see legitimate use cases of goto. I see people really think in absolutes.
there is absolutely 0 usefull use cases for goto in Unity. If you are forced to do such thing then something went wrong
actually, you're just not an Experienced Programmer
so you must be wrong!
There's 0 reason to use goto. Please share your examples and I will be sure to explain why it's a bad use case
Sorry, clearly my code architecture is wrong.
so why are you guys having a pointless nerd war over goto when literally 99% of you are on the same side of it
goto is absolutely not something that I use frequently, but it can express some ideas in a way that's much easier to parse
I'm looking at code from Animancer right now
They were joking, just to be clear
it has a method that looks for an AnimancerState in a variety of different places
in each place that it succeeds, it uses goto to jump to the end, do a few things to the state, and return it
You could define a local function and then return the result of applying it, sure
sounds like where i would use a local function
But I think it very clearly expresses the intent of the programmer.
Breaking out of a nested loop without having additional bool checks
i've shipped many titles with couple of game studios, never used and seen any goto from other programmers and probably will never see it
"In this situation, go to here"
I can see it useful for coroutines assuming you don't want to be making methods for them but otherwise eh
some langauges have that as a labeled break statement and only works in that context, go for exmaple can do a
break outerLoop where outer loop is a label above a loop
if goto didn't exist in Unity, then I wouldn't even notice
Great.
Glad to hear it.
Stop shitting on other people for thinking differently.
And if you say nested loops are bad then you dont do game dev I suppose
what are you like 10 ๐
dont be mad
java has this
L0:{
your code, if fails then break L0;
}
```used this design in some of my java code
Fen is a Ten
i see
This kind of "X considered harmful" argument makes you sounds like you've gotten all of your opinions from hot takes on Reddit
Hi I'm working on a custom package for my essential starter tools, the sorts that I can use in every project, my problem is that one of these tools needs to be customized per project and that's not easy if it's sitting in the packages directory, is there a way I can have the package place a folder with these specific assets into the assets directory? Similar to installing an exported package maybe?
Hate this clean code propaganda
i brought that tome up earlier (:
This is a help channel, I'm helping you trying to understand why goto is not good practice and you should not use it ๐คทโโ๏ธ
they are just closed for wisdom
Also please share your examples of use cases because I still haven't seen one
and passive-aggresive with cringe jokes
bool[][] grid
int x;
int y;
for (x=0;x<grid.GetLength(0);x++)
for (y=0;y<grid.GetLength(1);y++)
if (grid[x][y]) goto found
:found
The label is right after the goto which is readable
If not, stop trying to defend it and maybe consider that it's in fact not a good idea rather than responding with "muh stop being so shitty"
Clear case of using a separate method to return the result
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
tryAgain:
if (!prev.MoveNext())
return false;
if (!map.Invoke(prev.Current))
goto tryAgain;
return true;
}
I consider this to be easier to read than a while (true) and a break
making method is physical goto, make your eye and cursor goto line A to B
so you advocate introducing inefficiencies into the code to prove your point?
This could pretty much be a method though which you can return from, but if you just wanted to do it all in update I can understand.
Ever heard of inlining?
goto ๐คฎ
It is a niche feature that is not often needed or useful.
If you really care about those nanoseconds use that
careful, some people love goto and you might get linched
But banging this "goto considered harmful" drum isn't useful
GOTO ๐คฎ๐คฎ๐คฎ๐คฎ๐คฎ๐คฎ
Never thought I'd see a worse argument than when people defend #region
<@&502884371011731486>
Do you make games?
No
This is completely out of control. Good day.
i already blocked that guy a while back
You could do something like what TextMeshPro does.
which one
But I don't really see how that is related to this. If I explain to you why I consider goto bad practice then game development is not really changing that
It prompts you to import some assets into your Assets directory if it notices you don't have them installed already.
it's like trying to convince anti-vaxxer that vaccines are actually good
pointless
Oh that's probably me, but consideirng I've been in this channel for four years there's no doubt people who block me because I argue very often
anyway im out of this discussion, have a great friday chaps
wanted to have a friendly discusison about goto but some people got mad af
Note that if these are scripts, then that's not going to work very well : if they aren't present, your code isn't gonna' compile
turned out it was me ๐
No it is me, the post below was blocked ๐
jelaous
i hear righteous indignation being typed out
furious clickety clacks of keyboard keys
they are in fact scripts
334 instances of goto just in dotnet/runtime alone.
The most common use case if for final error handling/final returning logic, anything in the form of:
ReturnType DoStuff(Lots of, Arguments here)
{
if (someCondition)
goto Throw;
DoSomeIntermediateLogic();
if (someOtherCondition)
goto Throw;
DoSomeFinalLogic();
return TheReturnValue;
Throw:
DoSomeCommon;
ThrowingLogicHere;
}
Yes you can absolutely just rewrite it to remove all goto by abstracting away like:
bool TryDoStuff(Lots of, Arguments here, out ReturnType result)
{
if (someCondition)
{
result = default;
return false;
}
DoSomeIntermediateLogic();
if (someOtherCondition)
{
result = default;
return false;
}
DoSomeFinalLogic();
result = TheReturnValue
return true;
}
ReturnType DoStuff(Lots of, Arguments here)
{
if (TryDoStuff(of, here, out var result)
return result;
DoSomeCommon;
ThrowingLogicHere;
}
Yeah look, you got rid of goto cool, but now you have two versions of the same method, repeating the name and arguments and return value twice. Now you may argue "okay maybe just don't throw and always use try pattern" but that's not the point, this is evidently a use case enough that it has over 300 matches in dotnet/runtime alone.
Like I said I don't ever write goto myself, but failing to see the utility of goto and claiming it's always bad is quite the black and white world view you have.
sometimes I regret being right
basically an Input solution that I've extended from a tutorial that depends on the InputSystem
What stuff do you need to customize?
well said
If I need to add more inputs
also, please continue this discussion in a thread if it must continue.
It is monopolizing the chat
(referring to the goto discussion, not you, Babbitt)
I'm well aware
I see goto as inviting the vampire into your house. He canโt hurt you unless you invite him in. Even if he does know a thing or two about wine.
one way to do this, if this is the user experience you want, is to have some config asset which has a type field you can set a type in, then your actual code can get that type at runtime and instantiate it (and call some virtual methods or whatever, assuming you have a base type)
https://github.com/5Babbitt/Babbitts-Custom-Tools/tree/main/Runtime/Input here are the scripts in question that I'd like in the assets folder
you might invoke the "open-closed" principle here
your code should be open for extension and closed for modification
So you shouldn't need to edit the existing scripts.
the user should be creating new code that interacts with your existing classes
yeah i would never expect someone to edit a library for regular use
I only edit a library when there's something actually wrong
yeah, this is a massive violation of the open closed principle
they can extend it, implement its interfaces or pass functions into it
well, or when I really really really want a callback in a specific spot
It shouldn't be the standard way to add stuff to your input system!
your point is made, but does not make me fear it any less
You might look to the new input system for inspiration.
You can add new processors, input controls, etc.
I am using it
As in, look at its code!
we mean to look at how it works
It's very open to extension.
could the user code not extend or implement interfaces you expose, then your system has a init step where there user can pass those implementations back in for it to use
I'm not encouraging anyone to write goto, I don't write any myself. My argument is merely that there is utility in goto which some people seem to fail to grasp.
i am aware of the utility. It has a lot of utility. I fear its usage.
#if UNITY_EDITOR
[UnityEditor.InitializeOnLoad]
#endif
class DeltaTimeScaleProcessor : InputProcessor<Vector2>
{
/// <summary>Compensates for varialble deltaTime</summary>
/// <param name="value"></param>
/// <param name="control"></param>
/// <returns></returns>
public override Vector2 Process(Vector2 value, InputControl control) => value / Time.unscaledDeltaTime;
#if UNITY_EDITOR
static DeltaTimeScaleProcessor() => Initialize();
#endif
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)]
static void Initialize() => InputSystem.RegisterProcessor<DeltaTimeScaleProcessor>();
}
#endif
This adds a new input processor, for example
we dropped the topic on the main thread
(this is taken from Cinemachine)
My bad, I shall stop.
This is the main script, it gets a reference to the generated input class and uses interfaces to receive input callbacks from the action maps, when implemented the interface generates a method for each input and then I add logic to send whatever data I want out as an event
current topic is open closed principle
iโm not sure I understand how this works in a way that provides value tbh
so if we're talking the open closed principle I'd essentially be making a class that inherits all the default logic that I can then add more methods to execute?
you made a middleman, such that I need to go:
input system => my own class => your class => my class that wants to know about specific input events
because i need to feed your class inputs somehow to get it to trigger and interpret events
thatโs right, right?
What's very interesting in these cases is that 99% of these aim at saving a few keypresses by merging a few statements into one, and I would really not consider those a good use case because you're going to end up spending more time reading the logic. Also, a lot of these methods use a goto as they return a value afterwards, like this one. However, I feel like splitting this method into a separate one is way better, as instead potentialHeader is returned and this would improve readability and also get rid of the goto spam the code currently has.
Please make a thread.
to whom do you speak
around there yeah, I uses scriptable objects as a sort of tangibly accessible event and pass the data to that, then on any objects that I need it I use an event listener class to pass that to the script that wants it, it's a little bloated but is still quite clean
Also, you could make a nested method instead in a lot of cases. I would advice against it still it still has the issue of requiring to jump around the code like goto does
This topic has monopolized the chat. Please make a thread.
idk i feel like this is a lot of hoops to jump through, when I could have just written my intermediate input parsing class, and left it at that
best to use the reply feature after an argument because various people have each other blocked and are confused now i think lol
are you like a rules guardian or what
Such a pointless respond, ignore the topic if you're so against it
heโs someone with a vested interest in seeing this place not become a cesspool
i agree
lmao
??? Don't join in on the convo? ๐ค
FusedQyou and Xaxup, the ones having emotional breakdowns over people having different opinions. They should probably see the #๐โcode-of-conduct rules on how to talk to people and stop freaking out and insulting people
he is simply trying to have this channel not flood with a arguement so it can be used to provide support to people with real questions
weโre not your parents. we do not have the time to deal with this shit. Sort it out yourself, or the mods will โsort it outโ for you
just a reminder that 5 minutes ago he was spamming aswell but w/e
Yeah because my response to his message is definitely flooding it. Let's ignore the 5 responses from everyone that come after
not everyone agrees that is life and how the world works get over it
Please stop escalating and let me talk to the guy if you're so against it
https://www.notion.so/Input-Reader-156d5d82f6404cde856dbc00c1897d3d I created documentation on the actual input system here, if you don't mind could you point to any sort of redundancy there
Yes, please stop doing it Fused, seeing as you are one of the two people escalating (along with Xaxup)
It is monopolizing the chat. This is making it difficult for people to seek help. Please make a thread if you want to continue.
i mean in terms of making a middleman for input system, which I think does have value. But this package requires the user to also make a middleman. Which makes it less useful.
I am not seeking to get the last word in an argument. I've said everything I'm going to say with regards to the topic.
I am simply seeking to keep the chat usable.
watching everyone reply to Blocked Message is very gratifying
If Chris Sawyer can make a game like Roller Coaster Tycoon with a bunch of goto and conditional jumps then so can you
just saying that blocking people is most likely because you lack the mentality to continue the discussion in a friendly way or lack of arguments
@deft timber @thin aurora Both of you are already on notice for being argumentative and problem users. Move on, and the next one (including responding to this in any debatable way), is going to be a mute.
ty osteel
ty
To clarify it's basically InputSystem => Input Reader => my class
how does input reader know which inputs from inputsystem to listen to
Using the interfaces generated by the input class InputReader : ScriptableObject, GameInput.IGameplayActions, GameInput.IUIActions
**IGameplayActions **and **IUIActions **will implement an empty method for each input withing those respective action maps
where is GameInput? is it one of your classes with a source generator?
then I add a variable for the event, and send the callbackcontext data using that event in the new methods
it's generated by the inputSystem
i see. This is all kind of abstract at the moment, so youโd need to kind of show the โhow youโd do it normallyโ vs โhow youโd do it with this packageโ comparison
In regards to the package I actually copy the scripts into a folder in the Assets directory then delete the package ones to avoid conflict but that feels dirty
If I add a new input I create the binding in the inputactions asset, the go to my InputReader class and add simple logic on what I want from the input (Vector2, bool, trigger, etc...) then make an event object, connect that to the InputReader and raise the event using the data from the input
I mean you should show what the package does in the specific use case
Just so that I can use it in multiple projects and it automatically updates as I import it from github
I'm new to creating packages so I don't know all the ins and outs yet
the inputreader is just helpful in that it controls which is the current action map, and receives all input callbacks in one place
back to my original question, is there a way to install a package from github and add some of the files to the assets directory instead of the packages directory
you can add all of it to assets, not sure how to go about some though
how would adding all to assets work
just move from the package cache to assets
what just drag and drop?
no, outside of unity
How could I achieve this?
do you know where the package cache is in your project?
not sure about the cache haven't played around with those
look in Library->PackageCache, there you will see all of the source for all of your installed packages
Ok I found it
ok, so move the folder for the package you want into the Assets folder and remove it from Packages->manifest.json
ah ok
that is an option, I was looking for a way to automate the process, though I suppose I could do that with FileUtils
simple .bat file will do
basically want this to happen when I import the asset or like an edit menuy action
doable but you would need to write an AssetPostProcessor
I wouldn't mind looking into it
thanks for that
I am currently building an AR application and I have the problem that my assembly prefab does not appear 0.2 meters to the right of my marker as specified in the code. The assembly prefab appears on the marker... Does anyone know what I can do to make the assembly appear 0.2 meters to the right of the marker? The "Place Prefab Near Marker" Script is giving the positioning of the Assembly prefab. The Code of the "Place Prefab Near Marker" Script is as follows: using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
public class PlacePrefabNearMarker : MonoBehaviour
{
public ARTrackedImageManager trackedImageManager;
public GameObject prefabToPlace;
private const float offsetDistance = 0.2f;
private void OnEnable()
{
if (trackedImageManager != null)
trackedImageManager.trackedImagesChanged += OnImageChanged;
}
private void OnDisable()
{
if (trackedImageManager != null)
trackedImageManager.trackedImagesChanged -= OnImageChanged;
}
private void OnImageChanged(ARTrackedImagesChangedEventArgs eventArgs)
{
foreach (var trackedImage in eventArgs.added)
{
if (trackedImage.referenceImage.name == "MarkerIcons01")
{
Vector3 positionOffset = Vector3.right * offsetDistance; // Offset um 0,2 Meter rechts vom Marker
Quaternion rotation = Quaternion.identity;
Instantiate(prefabToPlace, trackedImage.transform.position + positionOffset, rotation, trackedImage.transform);
}
}
}
}
!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.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
// This class is responsible for placing a prefab object near a detected image marker.
public class PlacePrefabNearMarker : MonoBehaviour
{
public ARTrackedImageManager trackedImageManager; // Manages the tracked images.
public GameObject prefabToPlace; // The prefab to be placed.
private const float offsetDistance = 0.2f; // Distance to offset from the marker.
// Subscribe to the trackedImagesChanged event when the script is enabled.
private void OnEnable()
{
if (trackedImageManager != null)
trackedImageManager.trackedImagesChanged += OnImageChanged;
}
// Unsubscribe from the trackedImagesChanged event when the script is disabled.
private void OnDisable()
{
if (trackedImageManager != null)
trackedImageManager.trackedImagesChanged -= OnImageChanged;
}
// When a tracked image is changed, place a prefab near it if it matches the target marker.
private void OnImageChanged(ARTrackedImagesChangedEventArgs eventArgs)
{
foreach (var trackedImage in eventArgs.added)
{
// Check if the reference image is the target marker.
if (trackedImage.referenceImage.name == "MarkerIcons01")
{
// Offset by 0.2 meters to the right of the marker.
Vector3 positionOffset = Vector3.right * offsetDistance;
// Use the default rotation.
Quaternion rotation = Quaternion.identity;
// Instantiate the prefab at the offset position as a child of the tracked image.
Instantiate(prefabToPlace, trackedImage.transform.position + positionOffset, rotation, trackedImage.transform);
}
}
}
}
ยดยดยด
AI Code
I'm having some issues on how to best determine collisions when using a tilemap in regards to moving vertically (think jumping on platforms) when hitting the sides/underneath of them? I can't seem to wrap my head around on how to tell when I hit the sides of the tiles vs the underside/bottom of them. Any suggestions would be so helpful!
Link to code:
https://hastebin.com/share/ipefupewib.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
two manuscripts posted
please use a paste site for large code blocks: !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.
Sorry for the longer code, I edited to include the paste site instead - thanks for the info!
what are you trying to do with tiles i dont understand
You want to detect the sides and bottom, are you trying to use Platform effector on tilemap or something?
In simplest terms yes I am trying to detect hitting side/bottoms of tiles.
I have two tilemaps, one for background and one for collisions. The one for collisions has a tilemap collider 2d and composite collider 2d. My character has a rigidbody to interact with the tilemap that has the colliders. When I press space, I move my player upwards. If my player is moving upwards and collides with a tile the only checking done is against the players y position. This causes issues when the player is moving upwards and collides with the left or right side of a tile. My code sometimes determines that collision on the side is like hitting the underneath of the tile, because it's based on the players y position.
I would play around with Raycasts and overlaps
for example you can put a ray going up
overlap for checking the overall shape
I'm trying to animate the width of a VisualElement. I thought to just create a .hidden and .visible class, with 0% and 20% width respectively, and this works when I swap around using a Button, however I can't get it to animate on creation (I assume because the class swap happens before the first draw?)
Is there a neat way to get this to work?
https://hastebin.com/share/iziviwisez.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I am currently building an AR application and I have the problem that my assembly prefab does not appear 0.2 meters to the right of my marker as specified in the code. The assembly prefab appears on the marker... Does anyone know what I can do to make the assembly appear 0.2 meters to the right of the marker? The "Place Prefab Near Marker" Script is giving the positioning of the Assembly prefab. The Code of the "Place Prefab Near Marker" Script is as follows:
I hope this ok. For some reason it doesnt work as I want it to work...
HOw about a screenshot of the spawned assembly object being in the wrong place...?
Also you should set your tool handle position to "Pivot" not "Center". It's the thing on the left here:
What on earth am I looking at here lol
You asked me to send you a screenshot of the generated assembly object in the wrong place, didn't you? This is the screenshot; I made the other parts invisible. Only the plane and the start button are visible.
your position offset is in world space, it seems like you'd probably want it relative to the marker position or something like that?
yes, exactly
this is not a screenshot this is a photograph of your laptop?
also I wanted to see you know... the editor ui
with the inspector
etc
it's AR haha, this is a screenshot
showing the position
I see, that explains my confusion
it is confusing to look at
https://docs.unity3d.com/ScriptReference/Transform.TransformVector.html is this what you need?
I have tried it but it doesnt resolve the problem..
I have tried this one too but it but it doesnt resolve the problem..
You tried what? I didn't say anything to try here
change the settings from center to pivot
that isn't going to fix anything, it's going to let you see what's actually going on in the scene window
You will be able to see the actual positions of your objects when they are selected
Ahh, I see. Do you have any suggestions how to resolve the problem ?
is this a good place for ML agents help?
What problem? You still haven't shown a screenshot of the spawned object being in the wrong place.
- Play the game
- select the spawned object
- take a screenshot with the spawned object selected
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class DoubleClickButton : MonoBehaviour, IPointerClickHandler
{
public UnityEvent onDoubleClick;
public Color notSelected = Color.white;
public Color selected = Color.blue;
private float clickTimeThreshold = 0.3f;
private float lastClickTime;
private Image buttonImage;
private RectTransform parentRectTransform;
void Start()
{
lastClickTime = 0f;
buttonImage = GetComponent<Image>();
parentRectTransform = transform.parent.GetComponent<RectTransform>();
}
public void OnPointerClick(PointerEventData eventData)
{
Vector2 localCursor;
RectTransformUtility.ScreenPointToLocalPointInRectangle(parentRectTransform, Input.mousePosition, null, out localCursor);
if (!parentRectTransform.rect.Contains(localCursor))
{
buttonImage.color = notSelected;
lastClickTime = 0;
return;
}
if (Time.time - lastClickTime < clickTimeThreshold)
{
onDoubleClick.Invoke();
buttonImage.color = notSelected;
lastClickTime = 0f;
}
else
{
buttonImage.color = selected;
lastClickTime = Time.time;
}
}
}
i can not get the deselect to work (if !parent transform)
Well OnPointerClick is only going to run if you click on this object
so it doesn't really make sense to detect you clicking outside of this object there...