#archived-code-general

1 messages ยท Page 272 of 1

lean sail
#

Sure itd be ever so slightly more efficient, but it would be tedious as well. First it is unnecessary effort. Then you either need to store all the audio sources in a collection or use the Find function to get all of them. Either way, you are doing something I wouldnt consider cheap.

long ridge
#

Okay well is there a way to bake only certain parts or limit the range?

nimble cairn
#

And you're right -- too much of a headache.

mental rover
#

you wouldn't be developing your game around hitting a framerate target without audio to begin with, even if it did help

nimble cairn
#

Of course not :p

modern creek
#

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)

nimble cairn
#

Is it possible to override the AudioSource volume limit of 1?

rigid island
modern creek
#

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

terse surge
nimble cairn
#

@rigid island @modern creek Could I use the AudioMixer component perhaps?

rigid island
modern creek
#

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

rigid island
#

indeed. if you need boost audio, Audacity has a neat Normalize feature to bring all clips to max loudness

quaint rock
#

think normalize only brings the peaks up to max

nimble cairn
#

I like the idea of giving the player the option to turn the sound effects up to 200%.

quaint rock
#

so how loud its perceived will depend on a lot of thigns

long ridge
#

Is there a way to get objects in a radius / is there a way to get navmesh sources by radius?

nimble cairn
#

100% just seems so, typical, lol.

rigid island
long ridge
rigid island
#

but you need colliders

quaint rock
modern creek
long ridge
modern creek
nimble cairn
#

Yeah

spring creek
rigid island
nimble cairn
#

Don't think too deep into it I just want that number

modern creek
#

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

nimble cairn
#

That's exactly the position I am in.

#

Is there an override for the default "100%"

modern creek
#

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?

nimble cairn
#

And I have found that in the Audio Mixer

modern creek
nimble cairn
#

It's just "nice" and I'm putting off more pressing work and this seems a reasonable distraction.

terse surge
# modern creek This... doesn't look like it would compile? Why do you have `internal` as your a...

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.

vivid heart
#

!code

spring creek
modern creek
tawny elkBOT
modern creek
#

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;
terse surge
#

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 ^^

modern creek
#

k, that's helpful.. can there be more than one warning at a time? I suspect yes

terse surge
modern creek
#

it's fine, you're here to learn ๐Ÿ™‚ but it's important to understand the why

terse surge
modern creek
#

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

terse surge
modern creek
#

I don't mean one warning in your compiler, I mean more than one warning monobehaviour

modern creek
#

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:

terse surge
#

also this should fix the 1 to 2 generator

modern creek
#
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;
  }
}
modern creek
# terse surge also this should fix the 1 to 2 generator

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

modern creek
#

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"

mighty flax
#

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 :/

terse surge
modern creek
#

note the lack of () after the name.. so you'd just use it like this:

if (NextBoolean)
{
  // do something 50% of the time
}
terse surge
modern creek
#

changed to .value, sorry

modern creek
#

although I think range() with no parameters is 0,1, but as always, check the docs

quaint rock
#

range of 2 options and a Random.value > 0.5 are both 50 50 chance

modern creek
quaint rock
#

value is nice since you can do percentages of chance easily

modern creek
#

yes and if you really want to get fancy lemme sell you my optimal weighted list generator ๐Ÿ˜‰

quaint rock
#

already got one, have it as a extension method on lists

modern creek
#

(it's not really for sale, I was just teasing)

terse surge
modern creek
#

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)

terse surge
#

dam no gifs

terse surge
#

i kinda alr used it a bunch in my code ๐Ÿ’€

modern creek
#

it's fine, it won't matter until later in your career.. but you may as well get in the habit of avoiding it

terse surge
modern creek
#

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

terse surge
modern creek
#

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

terse surge
#

although originall the games intent was just so i learn how to make a game

modern creek
#

i do have to get back to work a bit so someone else might have to take your ball and run with it

terse surge
#

๐Ÿ‘

modern creek
#

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

long ridge
modern creek
#

no, that's fine

long ridge
#

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

long ridge
#

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

rigid island
#

ohh this is runtime ?

long ridge
#

during runtime

rigid island
#

so use a volume and bake that if u want a particular area , no

long ridge
#

hmm I'll check

terse surge
#

anyone knows how to solve this error? how am i gonna give it transform if im still at the part were im instantiating it

long ridge
leaden ice
rigid island
long ridge
#

yes... I don't want to bake the entire map during runtime

#

Navmesh needs to update when a door gets opened/closed

rigid island
#

I need to check again if it bakes for ALL

#

Ok it works

#

define your size here

#

this should only bake a certian area

long ridge
#

ooo

#

that helps a lot!

#

thanks

rigid island
#

proof ๐Ÿ™‚

long ridge
rigid island
#

still mind boggling this function is async but not the BuildNav

long ridge
#

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

rigid island
#

put debug.log

long ridge
#

I know it is cause I get lagspikes when I open the door / close it, I've been using the script for a while

rigid island
#

the lag is normal from BuildNavMesh

#

its a synchronous function

#

why did unity did that, i have 0 idea

long ridge
#

I don't think I got lagspikes when I didn't include UpdateNavMesh

rigid island
#

use both in a coroutine should at least help with freezing

knotty sun
#

I have a mobile game that rebuilds the navmesh frequently, I have never noticed any lag in it

rigid island
heady iris
#

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"

long ridge
#

I do..

knotty sun
#

I use Surface and Children btw

heady iris
#

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)

long ridge
final sphinx
#

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);
}
long ridge
#

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

knotty sun
rigid island
# long ridge but I'll put it in a coroutine

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");
    }```
final sphinx
rigid island
hexed pecan
#

It modifies the struct in place

knotty sun
#

should not do, now you are normalizing which means distance is not a factor

rigid island
#

thats what they want though no?

#

longer distance = faster bullet

hexed pecan
#

Make sure it's zero

rigid island
#

omg new Quaternion(0, 0, 0, 0), null); whyy

knotty sun
rigid island
#

you should not do this @final sphinx

#

use Quaternion.identity

final sphinx
#

i'm a beginneer and didnt know that existed

#

thanks though

hexed pecan
#

Yep, zero quaternion is not valid

rigid island
#

quaternion default is not 0,0,0,0

final sphinx
hexed pecan
final sphinx
#

ill redo what i did earlier gimme a sec

hexed pecan
#

Should set Z to zero after the ScreenToWorldPoint

#

Or you can just set bulletDirection's Z to zero before normalizing it

final sphinx
#

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

forest ravine
#

If a coroutine is awaiting another and externally that other gets stopped by StopCoroutine I believe the first never stops awaiting, can someone confirm?

hexed pecan
#

Good question, maybe test it?

#

Sounds unintuitive if so

long ridge
forest ravine
#

It's the conclusion I'm coming to seeing my "bug"

long ridge
#

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

rigid island
#

since its a synchronous call (it could freeze the code if takes long until done)

lean sail
long ridge
rigid island
#

I think it does additive baking

#

how many navmesh surfaces did put ?

#

hopefully not 1 on each object..

long ridge
#

uh.. well, 1 surface on each door, 1 surface for the game

#

but I am only opening one door

lean sail
long ridge
#

I know I can delete the data but the issue is that it tries to regenerate the map considering the lag

lean sail
#

I didnt see the original issue, but building a navmesh is not too cheap. Relatively speaking

#

Especially if it's a large surface

long ridge
#

Well that's why I want to bake smaller parts where needed

lean sail
#

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.

heady iris
#

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.

long ridge
heady iris
#

no, it's for a thing that gets in your way

#

i.e. an obstacle

hexed pecan
heady iris
#

you should read the documentation before you continue

knotty sun
#

gonna be damn difficult to walk through the door then

heady iris
#

Non-carving obstacles are avoided by agents, I suppose

#

they try to steer around the obstacle

lean sail
#

There is no sense of "dangerous" to your navmesh agents, although in real life itd be pretty dangerous to constantly walk straight into doors

rigid island
#

yes at most you have area cost but thats avoiding a certain area if lower costs are available

hexed pecan
#

Well using an obstacle for something like a temporary fire is ok

heady iris
#

I didn't know it could move around the navmesh

#

interesting

hexed pecan
#

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

heady iris
#

or to make them crowd in front of the player as much as possible

#

ruining their life

hexed pecan
lean sail
hexed pecan
#

Not sure if it carves instantly or in the next frame or at the end of the frame

#

Gotta experiment

lean sail
#

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?)

dense estuary
#

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

Watch "2024-02-15 16-52-59" on Streamable.

โ–ถ Play video
hexed pecan
#

But ideally yeah a zone with a high area cost would be better than just outright carving it out

heady iris
#

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

long ridge
#

How do you exclude objects from the navmesh?

heady iris
#

Although, given that you're going downhill properly, you probably are!

heady iris
#

what is the unexpected behavior?

dense estuary
dense estuary
heady iris
#

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?

dense estuary
#

The acceleration also doesnt seem to be doing anything

heady iris
#

you're changing it in the inspector, right?

#

not in the script

dense estuary
heady iris
#

well, you do expect the player to accelerate really quickly when it's high :p

#

but I'd also expect this...

hexed pecan
heady iris
#
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

dense estuary
heady iris
#

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

dense estuary
#

Its going directly into the normal

heady iris
#

The CharacterController responds to that movement by sliding forward a bit

dense estuary
#

ah

#

that makes sense

#

so I need to set normalVelocity to zero?

heady iris
#

Try doing that first, yeah

#

You'd want to do that if you're grounded and the velocity points into the floor

dense estuary
#

How can I know if the velocity points into the floor?

heady iris
#

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

rapid stump
#

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

dense estuary
heady iris
#

nice (:

#

See if the velocity loss when you hit a slope is tolerable

heady iris
#
Quaternion.FromToRotation(oldNormal, newNormal)

basically

dense estuary
dense estuary
# heady iris if not, this shouldn't be too hard

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

Watch "2024-02-15 17-20-48" on Streamable.

โ–ถ Play video
heady iris
#

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

dense estuary
#

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.

heady iris
#

Reduce, not increase!

#

too eager to say that you're grounded, I mean

#

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

hexed pecan
#

SweepTest is useful if you have multiple colliders on the RB

dense estuary
hexed pecan
#

I know

#

And it's capsule shaped

heady iris
#

Indeed; you'd just have to get the parameters right

#

it'll take a bit of fiddling

hexed pecan
#

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

dense estuary
#

Btw, the randomly floating into the air while on the flat platform was me jumping.

heady iris
#

So you're popping a bit into the air when you come off a ramp

dense estuary
#

yeah

heady iris
#

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

heady iris
#

You'd rotate the velocity vector to follow the ground

dense estuary
#

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?

heady iris
#

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

dense estuary
heady iris
#

It could be done separately, yeah

dense estuary
#

Something like this? ```cs
Vector3 RotateVel(Vector3 vel)
{

if (groundedLastFrame)
{
    var rotation = Quaternion.FromToRotation(oldNormal, newNormal);
    var rotatedVel = rotation * vel;
    return rotatedVel;
}
return vel;

}```

heady iris
#

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

dense estuary
#

Oh wait, RotateVel() is also doing nothing.

heady iris
#

Log to check when it's actually running.

dense estuary
heady iris
#

stick a Debug.Log in the method to check when it's being executed

#

and also log the old and new normals

dense estuary
dense estuary
heady iris
#

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

dense estuary
dark kindle
#

stack unity child game objec

hexed pecan
#

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

midnight skiff
#

Hey y'all question about statemachines. In your opinions is component based or event based better to implement?

quaint rock
#

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

lean sail
quaint rock
#

i would be making much smaller bundles

upbeat hill
#

Hey guys, quick question, how can I access the green axis shown here in code ?

midnight skiff
quaint rock
#

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

lean sail
midnight skiff
#

Fair enough, thanks for the feedback!

upbeat hill
#

Which is super weird I know

quaint rock
#

yes that works because its translate works in local space

#

so (0,1,0) is the direction of that green arrow

upbeat hill
#

ooooh

quaint rock
#

transform.Up gives that local direction in worldspace

leaden ice
#

Especially since you passed in Space.Self explicitly

#

(though that is the default)

upbeat hill
#

Yes but it is default

#

Still super confusing behaviour

quaint rock
#

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

upbeat hill
#

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?

quaint rock
#

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

upbeat hill
#

yes

#

It is as a child of another gameobject

#

This is my issue

#

I use the parent to place the arrow correctly

quaint rock
#

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

upbeat hill
#

can you get rid of all parents?

quaint rock
#

SetParent(null) will do t hat

upbeat hill
#

I'll investigate, thank you so much btw

#

Thank you for your patience

quaint rock
#

though the more common approach is to disable it and create a new arrow in its spot

#

and fire that

half vigil
#

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

rigid island
#

post !code

tawny elkBOT
rigid island
#

with links

#

and explain "doesnt work" mean in this context

#

very doubtful someone will take time to DM

spring creek
#

Only DMs I slide into nowadays are my Wife's

half vigil
#

wops

rigid island
#

nah edit this, put links

#

read bot msg for links

half vigil
#

no errors

rigid island
#

does "links" not mean anything to you ?

half vigil
#

just not doing anything

half vigil
#

thought u were talking to someone else

rigid island
rigid island
#

last msg was 4 hours ago lol

half vigil
rigid island
#

yeah my acoustics act up too, too many concerts ๐Ÿ˜†

half vigil
rigid island
half vigil
#

but it doesnt do anything despite 0 errors

rigid island
half vigil
#

yeah

rigid island
half vigil
#

put in variables and stuff

spring creek
#

have you written any Debug.Logs in the code?

rigid island
spring creek
#

I would definitely start there. Write a debug log BEFORE the raycast, and after it

half vigil
spring creek
#

the one after should log the raycasthit

half vigil
#

will try

rigid island
#

but yeah put some debug.logs and also would , screenshot and show inspector for what ur trying to Grapple on

rigid island
#

ur supposed to look at the logs in the console window

#

and show where you put the logs in code

half vigil
rigid island
#

Inpsector for the Object you want to grapple on

#

not the script

#

wht u tryina swing on?

#

screenshot its inspector

#

fully

half vigil
#

the only parameter needed is the layer

spring creek
half vigil
#

would debug.log(hit) show the name of the object the raycast hit?

half vigil
#

how it be feeling asking for advice on dsicord

rigid island
half vigil
#

alr so for some reason nothing shows uip in the console

#

when doing it on the swing points

rigid island
#

show where u put the debug.log in script

half vigil
rigid island
#

so its not debugging when doing it on Cube(3) ?

half vigil
#

yeah

#

I renamed the ones in the grappleable layer to swingpoint but samething

#

nothing appearing in colsone

#

fuck

#

console

rigid island
spring creek
#

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

half vigil
#

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

dense swan
#

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;
rigid island
dense swan
#

how do I modify it's RectTransform.rect.width and RectTransform.rect.height?

dense swan
#

sizeDelta is... using it's own anchor right and not parent's?
Do I also change the position using anchoredPosition?

rigid island
#

yes

orchid abyss
#

how to modify this so that i can use random.range?

cosmic rain
still depot
#

does Unity not support prepaid subscription in-app-purchase?

dusk apex
#

I could only possibly imagine you'd select a random string name before passing it to the function.

cosmic rain
still depot
cosmic rain
#

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.

orchid abyss
cosmic rain
#

Get a random number in range and use it as an index to get an element from the array.

orchid abyss
#

how to do that in this kind of array tho

rigid island
#

Random.Range can return you the int as a safe index

orchid abyss
#

how to return the index of an array element with its name

still depot
rigid island
orchid abyss
#

i wana do something like this

rigid island
#

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 ?

orchid abyss
rigid island
#

or make another list , where are you getting that range2 int anyway

orchid abyss
#

its an audio manager it has all sounds

rigid island
#

btw cntrl + dot to fix the ambiguity for Random class

cosmic rain
still depot
cosmic rain
#

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.

still depot
#

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

cosmic rain
#

What error?

#

Also, there is a mention of subscription in the documentation

still depot
#

"product isn't found". I'm already have that subscription item in google play console, but the unity API give me that error

still depot
cosmic rain
#

I have a while ago.

still depot
#

especially for subscription product?

orchid abyss
still depot
cosmic rain
#

That doesn't answer my question.

still depot
#

what do you mean by "using code wise"?

deep oyster
#

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

cosmic rain
still depot
#

please read it carefully

mild coyote
#

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

still depot
still depot
west lotus
fervent furnace
#

purple: known
blue:known

#

then you can form a right triangle with
width - r |\ r
|_
red line

cosmic rain
#

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.

mild coyote
mild coyote
deep oyster
#

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)

fervent furnace
#

you just need to find the length of red line

mild coyote
#

connect 1 to 2 with a spring joint
this should be
connect 1 to a sphere or circle collider with a spring joint

deep oyster
#

I think I found something that works

still depot
still depot
cosmic rain
deep oyster
#

well, it's not actually what I was asking, just an alternative solution to the design problem I was trying to solve lol

mild coyote
deep oyster
#

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

cosmic rain
#

With the predicted scaled radius

split crest
#

How do I get players to align on slopes as they run?

orchid abyss
#

how to make sure land sound effect only plays once i land on the ground

lean sail
lean sail
strange gate
#

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?

deft timber
#

how to fix what

#

are you trying to fix your existing code or implement it from scratch

strange gate
#

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

deft timber
#

then show the code

#

we are not wizards

#

how can we figure out what's wrong either

strange gate
#

Also what kind of code do you need? Grenade or the monster

deft timber
#

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

strange gate
#

Bro my code is too big to send in discord

vagrant blade
tawny elkBOT
strange gate
#

Oke

#

which one of code?

deft timber
deft timber
strange gate
#

none of these codes are giving me an error

#

The thing just doesn't work

deft timber
#

then what is the problem

strange gate
#

The thing is that when i throw the grenade and it explodes the monster doesnt die

deft timber
#

then show the code related to the problem

#

jezus

#

!code

tawny elkBOT
deft timber
#

is this chat gpt code

strange gate
#

yeah

deft timber
#

then i wont help you with that

strange gate
#

why not? ๐Ÿ˜„

deft timber
#

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

strange gate
#

Sort of

deft timber
#

that's a terrible way to learn thnigs

strange gate
#

Yeah but I'm trying

#

XD

deft timber
#

also why do you have 2 mono behaviour classes

#

in 1 file

strange gate
#

So im here to ask for help

deft timber
#

delete these comments it's making the code unreadable

#

and dont use chat-gpt

strange gate
#

Sure

deft timber
#

plenty of grenade tutorials online

#

4 foreach loops

strange gate
#

The tutorial is from brackeys

deft timber
#

the code isn't from brackeys

strange gate
#

Grenade is, not code ๐Ÿ˜„

#

Code from chatgpt and the grenade is from brackeys

deft timber
#

then you are watching tutorial but you are ignroing the tutorial and doing codeo n your own

#

right

hard viper
#

comments are good. those comments are useless

deft timber
#

yup never said comments arent good

hard viper
#

just clarifying

deft timber
#
int myInt = 0;

//increasing my int by 1
myInt++;
#

that is a terrible comment

#

for instance

strange gate
#

Im just trying to combine these things in to a normal thing

deft timber
#

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

hard viper
#

you can easily tell chatGPT code from human code because chatGPT regularly adds lots of useless comments.

deft timber
#

in Explode() method

wide dock
strange gate
#

I see

deft timber
#

4 foreach loops + non cached anything

#

anyway, that code has nothing to do with Explosion. It is triggered when grenade object entered the trigger

hard viper
#

but that could be incompetence. No human would go out of their way to type out a ton of comments which are useless

deft timber
#
// Destroy the character GameObject
Destroy(gameObject);
#

so usefull

strange gate
#

Thanks for help

fickle kettle
#

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

#
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

deft timber
fickle kettle
#

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

static matrix
#

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

cosmic rain
static matrix
#

yeah
has worked for me before but I can try an explicit one

cosmic rain
#

So you only one to hit the first 2 layers?

static matrix
#

?
no it hits the third layer (ground)

cosmic rain
#

No, it doesn't. 3 is 1 1 in binary.

#

So layer 0 and 1 are hit.

static matrix
#

it seems to have worked in the past but maybe i'm crazy

cosmic rain
#

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.

static matrix
#

yeah that seemed to work
i think ill just use explicit layer from now on

cosmic rain
#

As for your initial question, maybe replace the magic numbers with an empty transform parented to the character.

cosmic rain
static matrix
#

like using a variable set to the layer mask instead of an int

astral nexus
#

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

cosmic rain
heady iris
#

Yeah, scenes don't have a "disabled" state

hard viper
#

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

kind cipher
#

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.

heady iris
#

Anything showing up in the console?

kind cipher
#

nope. console empty

static matrix
#

everytime I use goto I feel like im channeling a dark art

heady iris
#

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

kind cipher
heady iris
#

Funky

#

you can ask Git to diff the .meta file, assuming you're using that

chilly surge
heady iris
#

goto is great when you need it

latent latch
#

1968 trash talking goto

knotty sun
#

Dijkstra was an idiot

heady iris
#

djikstra considered harmful

knotty sun
#

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

thin aurora
#

If you need to use goto then it's time you refactor your code, because nobody needs that

deft timber
#

if you think about using goto then your code architecture is bad

#

no matter what edge case is it

knotty sun
chilly surge
thick terrace
#

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

thin aurora
deft timber
chilly surge
#

So I guess C# and Microsoft has bad code architecture then.

deft timber
#

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

thick terrace
#

the best use of goto is goto case in switch statements and i swear nobody knows you can even do that

knotty sun
deft timber
#

period

chilly surge
thin aurora
#

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

deft timber
quaint rock
#

in any modern langauge only thing i use labels for is labled breaks in loops

heady iris
#

Clean Code isn't a holy text

thin aurora
#

Lol

#

It's not hard to have consistency like that

#

Goto is a great way to ruin readability

deft timber
#

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

latent latch
#

goto when I can't be bothered to make methods for readability

reef garnet
#

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?

chilly surge
#

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.

deft timber
heady iris
#

so you must be wrong!

thin aurora
#

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

chilly surge
deft timber
#

show me 1 good use case of goto

#

in Unity

#

please

quaint rock
#

so why are you guys having a pointless nerd war over goto when literally 99% of you are on the same side of it

heady iris
#

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

spring creek
heady iris
#

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

quaint rock
heady iris
#

But I think it very clearly expresses the intent of the programmer.

hexed pecan
deft timber
#

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

heady iris
#

"In this situation, go to here"

latent latch
#

I can see it useful for coroutines assuming you don't want to be making methods for them but otherwise eh

reef garnet
quaint rock
deft timber
#

if goto didn't exist in Unity, then I wouldn't even notice

heady iris
#

Glad to hear it.

#

Stop shitting on other people for thinking differently.

hexed pecan
#

And if you say nested loops are bad then you dont do game dev I suppose

deft timber
#

dont be mad

fervent furnace
#

java has this

L0:{
  your code, if fails then break L0;
}
```used this design in some of my java code
hexed pecan
#

Fen is a Ten

deft timber
#

i see

heady iris
#

This kind of "X considered harmful" argument makes you sounds like you've gotten all of your opinions from hot takes on Reddit

reef garnet
#

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?

hexed pecan
heady iris
thin aurora
deft timber
thin aurora
#

Also please share your examples of use cases because I still haven't seen one

deft timber
#

and passive-aggresive with cringe jokes

knotty sun
hexed pecan
#

The label is right after the goto which is readable

thin aurora
#

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"

thin aurora
heady iris
fervent furnace
#

making method is physical goto, make your eye and cursor goto line A to B

knotty sun
latent latch
hard viper
#

goto ๐Ÿคฎ

heady iris
thin aurora
#

If you really care about those nanoseconds use that

deft timber
heady iris
#

But banging this "goto considered harmful" drum isn't useful

hard viper
#

GOTO ๐Ÿคฎ๐Ÿคฎ๐Ÿคฎ๐Ÿคฎ๐Ÿคฎ๐Ÿคฎ

thin aurora
#

Never thought I'd see a worse argument than when people defend #region

spring creek
#

<@&502884371011731486>

hexed pecan
thin aurora
#

No

heady iris
#

This is completely out of control. Good day.

hard viper
#

i already blocked that guy a while back

heady iris
deft timber
thin aurora
#

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

hard viper
heady iris
deft timber
#

pointless

thin aurora
# deft timber which one

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

deft timber
#

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

heady iris
deft timber
thin aurora
deft timber
#

jelaous

hard viper
#

i hear righteous indignation being typed out

#

furious clickety clacks of keyboard keys

chilly surge
#

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.

hard viper
reef garnet
#

basically an Input solution that I've extended from a tutorial that depends on the InputSystem

heady iris
reef garnet
#

If I need to add more inputs

heady iris
#

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)

reef garnet
hard viper
#

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.

thick terrace
# reef garnet they are in fact scripts

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)

reef garnet
heady iris
#

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

quaint rock
#

yeah i would never expect someone to edit a library for regular use

heady iris
#

I only edit a library when there's something actually wrong

hard viper
#

yeah, this is a massive violation of the open closed principle

quaint rock
#

they can extend it, implement its interfaces or pass functions into it

heady iris
#

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!

hard viper
heady iris
#

You might look to the new input system for inspiration.

#

You can add new processors, input controls, etc.

reef garnet
heady iris
#

As in, look at its code!

hard viper
heady iris
#

It's very open to extension.

quaint rock
# reef garnet I am using it

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

chilly surge
hard viper
#

i am aware of the utility. It has a lot of utility. I fear its usage.

heady iris
#
#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

quaint rock
heady iris
#

(this is taken from Cinemachine)

chilly surge
#

My bad, I shall stop.

reef garnet
#

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

hard viper
#

current topic is open closed principle

#

iโ€™m not sure I understand how this works in a way that provides value tbh

reef garnet
#

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?

hard viper
#

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?

thin aurora
# chilly surge [334 instances of `goto` just in `dotnet/runtime` alone.](<https://github.com/se...

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.

GitHub

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps. - dotnet/runtime

heady iris
#

Please make a thread.

hard viper
#

to whom do you speak

reef garnet
# hard viper thatโ€™s right, right?

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

thin aurora
heady iris
hard viper
thick terrace
deft timber
thin aurora
hard viper
heady iris
#

<@&502884371011731486>

#

this has gone on long enough.

hard viper
#

i agree

deft timber
#

lmao

thin aurora
#

??? Don't join in on the convo? ๐Ÿค”

spring creek
quaint rock
#

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

hard viper
#

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

deft timber
thin aurora
#

Yeah because my response to his message is definitely flooding it. Let's ignore the 5 responses from everyone that come after

quaint rock
#

not everyone agrees that is life and how the world works get over it

thin aurora
#

Please stop escalating and let me talk to the guy if you're so against it

reef garnet
spring creek
heady iris
hard viper
#

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.

heady iris
#

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.

hard viper
#

watching everyone reply to Blocked Message is very gratifying

latent latch
#

If Chris Sawyer can make a game like Roller Coaster Tycoon with a bunch of goto and conditional jumps then so can you

deft timber
#

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

vagrant blade
#

@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.

hard viper
#

ty osteel

deft timber
#

ty

reef garnet
hard viper
#

how does input reader know which inputs from inputsystem to listen to

reef garnet
#

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

hard viper
#

where is GameInput? is it one of your classes with a source generator?

reef garnet
#

then I add a variable for the event, and send the callbackcontext data using that event in the new methods

reef garnet
hard viper
#

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

reef garnet
#

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

hard viper
#

I mean you should show what the package does in the specific use case

reef garnet
#

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

knotty sun
reef garnet
#

how would adding all to assets work

knotty sun
#

just move from the package cache to assets

reef garnet
#

what just drag and drop?

knotty sun
#

no, outside of unity

reef garnet
knotty sun
reef garnet
#

not sure about the cache haven't played around with those

knotty sun
#

look in Library->PackageCache, there you will see all of the source for all of your installed packages

reef garnet
#

Ok I found it

knotty sun
#

ok, so move the folder for the package you want into the Assets folder and remove it from Packages->manifest.json

reef garnet
#

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

knotty sun
#

simple .bat file will do

reef garnet
#

basically want this to happen when I import the asset or like an edit menuy action

knotty sun
#

doable but you would need to write an AssetPostProcessor

reef garnet
#

I wouldn't mind looking into it

white coyote
#

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);
        }
    }
}

}

tawny elkBOT
white coyote
#

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);
            }
        }
    }
}
ยดยดยด
knotty sun
#

AI Code

sudden bobcat
#

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

rigid island
#

two manuscripts posted

heady iris
#

please use a paste site for large code blocks: !code

tawny elkBOT
sudden bobcat
#

Sorry for the longer code, I edited to include the paste site instead - thanks for the info!

rigid island
#

You want to detect the sides and bottom, are you trying to use Platform effector on tilemap or something?

sudden bobcat
# rigid island what are you trying to do with tiles i dont understand

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.

rigid island
#

for example you can put a ray going up

#

overlap for checking the overall shape

steady marsh
#

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

white coyote
#

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...

leaden ice
#

Also you should set your tool handle position to "Pivot" not "Center". It's the thing on the left here:

leaden ice
#

What on earth am I looking at here lol

white coyote
# leaden ice 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.

thick terrace
leaden ice
#

also I wanted to see you know... the editor ui

#

with the inspector

#

etc

thick terrace
#

it's AR haha, this is a screenshot

leaden ice
#

showing the position

leaden ice
thick terrace
#

it is confusing to look at

leaden ice
#

Anyway it's probably offset just fine

#

easier to see by looking in the scene view

white coyote
white coyote
leaden ice
white coyote
leaden ice
#

You will be able to see the actual positions of your objects when they are selected

white coyote
zinc forge
#

is this a good place for ML agents help?

leaden ice
#
  1. Play the game
  2. select the spawned object
  3. take a screenshot with the spawned object selected
tender arch
#
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)

leaden ice
#

so it doesn't really make sense to detect you clicking outside of this object there...

tender arch
#

oh

#

so how do i fix that