#archived-code-general

1 messages · Page 54 of 1

plucky inlet
#

Then you have to split it yourself

modest ether
#

That's what I assumed

lethal rivet
#

Just learned a super interesting C# feature, operator overloading
If you have a custom data class (e.g., a vector3) you can overload something like + for your class, so you can do things like VecA + VecB

public static Vector operator +(Vector v1, Vector v2)
{
    return new Vector(v1.X + v2.X, v1.Y + v2.Y, v1.Z + v2.Z);
}```
```cs
Vector v1 = new Vector(1, 2, 3);
Vector v2 = new Vector(4, 5, 6);
Vector sum = v1 + v2; // sum = (5, 7, 9)
glad solstice
#

So im making a mod for a game I have a mavmesh agent on a game object and it follows the target positions fine until it goes through arch ways where the gap is to small even though the game object it self can go through normally
Idk how to fix

I can't add any nav mesh components to the walls or floors
Any solutions by chance?

main shuttle
glad solstice
#

How do I change the agents size?

#

I haven't messed with navmesh much

main shuttle
#

Depends on your version, its either on the gameobject or in windows > AI > navmesh and then agent as far as I can remember.

#

By default its 0.5 unity units wide.

glad solstice
#

I don't have access to scene editor

#

It's all c#

#

I will have a look around for the size though

main shuttle
#

Well, you bake for a specific width, so unless you can rebake the navmesh, I don't see a solution, even if you could change the agents width.

mystic ferry
#

it seems like there are a few "hidden" vector fields given to Transforms. the "forward" vector and the "worldUp" vector being just two listed here. Are there more? what are they and where can I find them? is there a list of them somewhere?

thin aurora
mystic ferry
#

oh nice lol

#

thanks @main shuttle

lethal rivet
main shuttle
mystic ferry
#

seems intuitive

vague slate
#

When I run methods like this, will it early return as soon as one returns true or will it combine bool out of all and then return?

                return TestDirection(cur, tarX) || TestDirection(tarX, tar) || TestDirection(cur, tarY) ||
                       TestDirection(tarY, tar);
mystic ferry
#

|| means or, so why would it only return if they were all true?

#

if you want that, it would be &&

vague slate
#

that's now what I asked

#

I mean

#

how internally will it get compiled

#

will it early return and not run another TestDirection is true was already given or will it run them all and only then return result?

craggy veldt
#

early return yes

mystic ferry
#

well the calls are ran linearly

main shuttle
#

Microsoft says no?

vague slate
#

oh

mystic ferry
#

that's bitwise or, not logical or

vague slate
#

so that's the difference between | and ||

#

or?

main shuttle
#

The conditional logical OR operator || also computes the logical OR of its operands, but doesn't evaluate the right-hand operand if the left-hand operand evaluates to true.

mystic ferry
#

| is used against binary comparisons, not bools

main shuttle
#

So yeah, Slim was right, the logical one returns if the first one is true.

vague slate
#

yeah, early return

#

nice

vague slate
mystic ferry
#

do you know how bitwise operators work?

vague slate
#

sir, I do. But this is also used in booleans as you can see

#

so you can't just say it's only for bit operations

atomic bone
#

what would be the good approaches for accessing all the assets had been loaded from the remote server?
store all of them into dictionary and get them by the actual file name? or?

thick heron
#

my text mesh pro text isn't appearing

#

pls help

craggy veldt
#

tbf he didn't ask for bitwise OR at all 😄

main shuttle
#

Yeah my bad, I was too fast to link the first one...

thick heron
thin aurora
# thick heron Pls help guys

Please don't bump linke this.
Provide more info about your issue and provide the related !code so that we can help.

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

thin aurora
#

With more info we mean any unexpected behaviour or errors

mystic ferry
# thick heron 🤓

"I ask a stupid question and then get triggered when I get called out about it"

#

how are we supposed to help with "my shit don't work. Help now."

thick heron
thin aurora
#

Oh boy

mystic ferry
#

we can tell you're never gonna ship a game

#

unless I'm just biting bait

thin aurora
#

Surprised you spend energy on such a person at all 😄

mystic ferry
#

it's fun imo, because I like to see how sad they are

thick heron
#

💀

vagrant blade
#

@thick heron If you're just going to do silly emojis instead of actually providing details like one would in normal conversation, then refrain from using this discord. It's really not that hard.

#854851968446365696 has a guide to asking questions if you aren't able to formulate one properly.

#

Also, unless it's a code question, UI and such goes in #📲┃ui-ux.

elder zenith
#

How would I go about adding an extension method to Gizmos?

I want to add a Gizmos.DrawLine() variation that takes a (Ray ray) as input instead of (Vector3 from, Vector3 to)

#

I've used extension methods before, just a little lost on how to do this with the whole Gizmos integration

#

Or is it not possible and I just have to create and use my own class?

steep jacinth
#

I made a script that during run time will be added to my player. That script has a SerializeField for a ScriptableObject I created, I then selected the SO for it in the editor. But then when I run the game and add the script, the SerializeField variable with the ScriptableObject is null. Does anyone knows why and if theres a workaround for this?

main shuttle
steep jacinth
main shuttle
ashen vector
#

help i try to change ui text to time but i cant

main shuttle
thin aurora
#

Please explain properly on what the issue is instead of just sending "help"

ashen vector
#

ok

thin aurora
thin aurora
#

You should change it to Debug.Log(timeTake.Value.ToString())

ashen vector
#

ok but ui

thin aurora
#

This way it will display the string equivalent which would be what you want

thin aurora
ashen vector
#

textMesh.text = timetaken.ToString();

thin aurora
#

Same thing

#

You display timeTake.Value.ToString() instead

ashen vector
#

ok

thin aurora
#

Right now you display the networkVariable type

ashen vector
thin aurora
#

Well you're close, but you pretty much call ToString on the wrong thing

dapper schooner
#

Hey, I am setting up some animations and I was wondering what happens if I have an objects animator playing an idle animation and then in a timeline play say a talking animation ? Will it return to playing the idle animation at the end of the timeline?

desert halo
#

This is regarding this video (not trying to debate whether singletons suck or not):
https://www.youtube.com/watch?v=WLDgtRNK2VE

In this context, what would be the issue with using static classes as the event channels instead of scriptable objects? SOs seem like much more to deal with

In this second devlog, we look at how we employed ScriptableObjects to create a flexible and powerful game architecture for "Chop Chop", the first Unity Open Project.

🔗 Get the demo used in this video on the Github branch:
https://github.com/UnityTechnologies/open-project-1/tree/devlogs/2-scriptable-objects
(compatible with Unity 2020.2b and la...

▶ Play video
frosty pawn
#

Hi! When I use ScrollRect and then disable gameobject inside scroll rect which was under scroll in scroll start moment then scroll jumps up. How can I fix it?

fleet furnace
ashen vector
#

hi anyone knows how to teleport clients(players) to position in multiplayer game?

pearl swallow
#

How might I be able to do damage over time?

mossy minnow
#

hey everyone. im trying to make a movement controller. rn, i have ApplyMovement(Vector2 dir, float acceleration)
the problem im running into is making the movement relative to the players forward direction.

oblique spoke
pearl swallow
mossy minnow
#

        accelerationMagnitude = UnitInput().magnitude * maxAccel;
        //Mathf.Clamp(acceleration, 0, maxSpeed);
        accelerationMagnitude *= Time.deltaTime * surfaceFriction * speedMult;
        float veer = accelerationMagnitude*(rb.velocity.x  + rb.velocity.y);
        float addSpeed = accelerationMagnitude - veer;
        //Mathf.Clamp(acceleration, 0, addSpeed);

        if(accelerationMagnitude <= 0) accelerationMagnitude *= BrakingDeceleration;

        ApplyMovement(UnitInput(), accelerationMagnitude);
    }

    void ApplyMovement(Vector2 dir, float acceleration){
        Vector3 v3 = new(dir.x * acceleration, 0, dir.y * acceleration);
        rb.velocity += v3;
        rb.velocity = Vector3.ClampMagnitude(rb.velocity, maxAccel);
    }```
#

ive tried following a blog post, but i have trouble understanding it

pearl swallow
#

Is it a 3D or 2D gain?

mossy minnow
#

3D

dapper schooner
pearl swallow
#

And what controls the movement? Mouse, keyboard, console controller?

mossy minnow
#

keyboard rn

pearl swallow
#

And it's just not moving based on the direction the player is supposed to be facing?

mossy minnow
#

its functional, but only moves along the world axes#

pearl swallow
#

Does the character rotate at all?

mossy minnow
#

ah, it doesnt. the camera controls are part of a child

pearl swallow
#
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");
        Vector3 direction = new Vector3(x, 0f, z).normalized;

        if (direction.magnitude >= 0.1f)
        {
            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity,turnSmoothTime);
            transform.rotation = Quaternion.Euler(0f, angle, 0f);

            Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
            controller.Move(moveDirection.normalized * speed * Time.deltaTime);
        }

I see, this is how I have my character work when it comes to where the camera's position is.

pearl swallow
#

It'll automatically rotate and move in the direction of where the camera is facing.

stuck beacon
pearl swallow
#

Do you have a character controller? @mossy minnow?

#

Note that mine is for a third person camera

#

Not for a first person

#

If yours is a third person you should be able to use this.

mossy minnow
#

oh yeah this is for first-person

pearl swallow
#

Well, Vector3.forward controls the direction of where the GameObject is facing.

#

My stuff here should work... I think for what you have.

#

Since I don't think it explicitly says that it is only for third person, jsut the video or where I grabbed was.

#

Just how I configured it might be different because I use cinemachine.

#

You could have the camera rotate on the axis of the mouse, but lock the player's rotation to only move about the Y

#

Just reference the camera's transform when doing the rotation.

#
transform.rotation = Quaternion.Euler(0f, angle, 0f);

This control's the player's rotation.

#

Because your character doesn't rotate, or I assume does not rotate because there's nothing saying it, it is moving "correctly"

#

Your inputs are correct, to me at least, but without the player rotating based on the camera's rotation, it doesn't work.

#

Also

#

Be sure the camera is facing where the camera is facing.

#

Otherwise it you basically have eyes at the back of your head, literally.

crystal holly
#

hey guys, i am using HDRP and i am creating a room geometry procedurally at runtime. i'd like to have a bit more of a realistic lighting. currently everything that is not directly lit but the sun is super grey. some indirect light would be amazing. i don't know much about HDRP and lighting in unity in general but from what i think i picked up is that the whole procedural thing is a bit tricky since most of the lighting magic is prebaked. does anyone have any tips or resources for me?

plucky inlet
crystal holly
idle rose
#

So this is my file heirarchy

#

Lets say I want to grab a reference to ChoppableData asset inside the Script at runtime.
I also want to do this through code, without having to manually connect anything in the Inspector.

Is there any way to do this without using the Resource folder?

fleet furnace
#

What you want is basically ray tracing.
OR compose and light your scene with realtime lights only

plucky inlet
idle rose
crystal holly
plucky inlet
#

Guess you gotta up the shadow quality and also the resolution

crystal holly
#

It's not really about the shadows but the objects not being lit directly appearing all grey

#

Like there is just light and no light

crystal holly
fleet furnace
dapper schooner
#

but thx for the information

rocky jackal
#

why does my function just decide to end early

main shuttle
leaden ice
rocky jackal
#

im not going anywhere with 19 compiler errors

#

its all starting with this

main shuttle
rocky jackal
main shuttle
#

I would follow the manual. But it's still strange that you don't see any error in your IDE.

rocky jackal
#

okay

#

yeah my visual studio instalation is really buggy since i updatet to vsc 2022

clever laurel
#

Can anyone help me understand how one of my FixedUpdate() functions is running before a Awake(), should be impossible?

main shuttle
rocky jackal
#

when i try to acces the joinCode data unity tells me that JoinCodeData doesnt exist in the current context

clever laurel
#

I know it is supposed to be, yet i am getting a null error from a fixed update, before my awake funtion is called, i am debug logging it

rough shuttle
#

How to move array items up?
so I remove an item from index 4, how to shift 5 and 6 up?
also if I remove a few items from different indexes, how to move everything up to fill the empty spaces?

main shuttle
clever laurel
rough shuttle
#

The thing is I'm using an inventory system by asset store @main shuttle
so I can only make an extension of it to overcome this

#

and the whole system uses array not list

clever laurel
#

I am getting a null error in the second code piece, before any dbeug output from the first one.

#

If i move it to onEnable isntead it works

main shuttle
still mica
#

alright so i've been slowly losing my sanity trying to do the single simplest thing on earth which is to literally just change the parent of a gun to an empty gameobject and reset the gun's localposition (with code)

#

but no matter what i try, it's just not working

#

it always keeps the world position

#

no, no other scripts are modifying the gun's transform or anything like that

main shuttle
rough shuttle
#

ok thank you

oak plover
#

How do you use !code again lmao can't figure it out bigsadcat

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

oak plover
#

My smol brain can't understand

leaden ice
upbeat fulcrum
#

Hello, I have a problem since I can not access the play mode by an error, someone could help me thanks. I have come to wait more than 30 minutes and it has not worked for me, any solution?

leaden ice
leaden ice
tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

leaden ice
still mica
#

that's the thing

#

it's supposed to

#

but it's not

still mica
#

should be the case

#

but i tried disabling everything

leaden ice
#

you have to share more details if you want more help

#

you are no doubt missing something

main shuttle
#

If you want the lobby data, go to the next part of the manual

rocky jackal
main shuttle
#

I'm so confused...

rocky jackal
#

the other person who joins the lobby needs to read it so they can connect to the same relay

#

its for multiplayer

wicked night
#

I was trying a new approach for movement code, but the code below is running framerate-dependent meaning the movement speed varies depending on the fps. It... shouldn't be like that, right? I'm multiplying by delta time in the MoveTowards function's maxDelta parameter and am multiplying the overall movement amount at the end by delta time as well.

I've done this kind of thing a thousand times before in dozens of projects and it feels like I'm missing something here. I am incredibly sleep deprived right now, so maybe that's it and I missed something. Any help would be appreciated

vel.x = Mathf.MoveTowards(vel.x,strafeSpeed * Input.GetAxis("Horizontal"),accelStrafe * Time.deltaTime);

vel.z = Mathf.MoveTowards(vel.z,speed,accel * Time.deltaTime);

transform.position += vel * Time.deltaTime;
rocky jackal
# main shuttle I'm so confused...

we have the person who creates the lobby they add the join code for the relay to the lobby so other people who join the same lobby can get said code for the relay and when both are conected to the same relay they should in thorie be able to play together using unity netcode

main shuttle
#

I would assume the manual would explain this

leaden ice
wicked night
# leaden ice this looks... ok I believe... Can you share more code?

Yeah it's so strange. I've removed every single thing in the scene except for this one script, a player object, and a flat "track" to see the movement + a line to print the current speed, and it's still happening. All I have to do is maximize/unmaximize the game tab to see the effect of the framerate dependence.

#

The script is as simple as it gets -

using UnityEngine;

public class Movement : MonoBehaviour
{
  public float speed;
  public float strafeSpeed;
  public float accel;
  public float accelStrafe;

  Vector3 vel;

  void Update()
  {
    vel.x = Mathf.MoveTowards(vel.x,strafeSpeed * Input.GetAxis("Horizontal"),accelStrafe * Time.deltaTime);
    vel.z = Mathf.MoveTowards(vel.z,speed,accel * Time.deltaTime);

    transform.position += vel * Time.deltaTime;

    // Print speed
    print((vel * Time.deltaTime).z);
  }
}
#

I just thought using MoveTowards would be nice to simplify acceleration/deceleration operations, and it works perfectly atm with just 3 lines of code except for the FPS dependence...

main shuttle
vapid grove
#

does anyone know how to set up mediapipe for unity by any chance? i need some help

junior sorrel
#

If key pressed and this function run, it doesnt work?

leaden ice
wicked night
#

It should be correct afaik. MoveTowards linearly moves one float towards another at a fixed rate (my acceleration variables). So need to multiply the acceleration value by delta time in my MoveTowards calls, since I'm doing it every frame. Then, at the end, I'm going to actually move the transform by the resulting velocity I have, so I also need to multiply by delta time there as well. Am I wrong about it? 🤔

main shuttle
#

Or it's the actual camera that's lagging, depending on how you set that one up.

leaden ice
wicked night
main shuttle
leaden ice
#

it's normal and expected for that to be different, since the frame durations are different.

#

what you should print is vel itself

#

or vel.magnitude

#

or vel.z

wicked night
#

oh my god I am too sleep deprived

#

I've just wasted y'alls time

leaden ice
#

get some rest

wicked night
#

thank you and sorry for being super dumb LOL

#

yeah you're 1000% right it's working fine

#

I think the editor frame skipping or whatever was making it look like it was moving faster in the smaller window, and since I was printing the speed the wrong way it was "confirming" my theory

#

never felt more mortified in my life rn

leaden ice
#

If this is the worst, you've lived a blessed life.

main shuttle
civic igloo
#

my rigidbody based player character has different jump heights on different pcs, i'm guessing it's because of the different frame rates, for jumping im setting the players y velocity as the needed jump force

mystic ferry
#

or better yet: use events

civic igloo
#

well i tried putting OnButtonDown in fixedupdate but then it just ignored the input most of the time

mystic ferry
#

it's a good idea to assume when something doesn't work that it's your misunderstanding rather than the engine not working correctly

civic igloo
#

and i just realized it may be an issue of drag changing later

mystic ferry
#

I mean, the reality is that you should never use physics values that change

#

unless there's a direct reason, there's no sense in making your jump force anything other than an int or float

#

SerializeField it, and change it from the inspector

#

for more advanced physics I use things like AnimationCurves, or algebraic functions

civic igloo
#

oh the jumpForce doesnt change, drag changes though

copper matrix
fleet furnace
#

Yeah. So.
Your spawned variable will only ever contain the latest added workout.
I guess what you want to do is on custoum_workout_clicked() you should assingn whatever was clicked as your "spawned" variable. (and rename it to "selected" probably)

twin crystal
#

Anyone know what the best practice is for a complex inventory system using scriptable objects in regards to item stacking? In my list of items would I add another instance of the item scriptable object for each? Or would I store an amount somewhere, for example a static count property on the scriptable object? I am new to inventory systems, so please feel free to correct me if I have anything wrong here

clever laurel
#

Anyone who have experience making Controllers using ScriptableObjects? I played around with it a bit and seems like more problem than benefit

fleet furnace
fleet furnace
clever laurel
fleet furnace
twin crystal
clever laurel
cerulean oak
#

I need to interpolate between points to make a curve, and sample more points to smoth the lines. (In 3d)
I planned on using splines, with tangent control points, but I cant find any tool for unity to create the splines. I found a package, but it seems to be discontinued

#

this is what I want to do

#

what can I use?

#

actually I think its a bezier curve

#

not a spline

#

yes its a bezier

cerulean oak
#

seems to be discontinued or smth

leaden ice
#

it's brand new

#

you have to add it by name

#

com.unity.splines

cerulean oak
#

oh

leaden ice
cerulean oak
#

ty

cerulean oak
#

I cant find how to sample it .-.

#

like, just getting a vector3 at a specific length

cerulean oak
#

oh

#

I was looking in the spline class itself

#

thanks

#

any way to sample between two knots tho?

#

like, 0.5 of the way between knot 1 and knot 2

#

.getCurve() seems to get the individual beziers, but again I cant find the method to sample it

#

im sorry, im usually not this bad at moving through docs and code not my own

leaden ice
#

this package isn't organized in the most user friendly way I'll grant you that

#

I only happen to have a little experience with it

#

I've found that the API is pretty thorough, if complicated.

cerulean oak
#

it seems very complete, has so much stuff, but also pretty confusing

#

thanks again

leaden ice
#

yea

cerulean oak
#

that should be everything I need, hopefully

frail meteor
#

Is it possible to convert an Mp3 into a Wav at runtime?
I'm trying to integrate amazon Polly to get text-to-speech but I can't directly receive a WAV, so far I request,get and save the speech as mp3, now I need to convert it before playing it through the audiosource

#

Seems that unity can't directly do that, I found some suggestions redirecting to something called NAudio but can't find the dll anywhere...

cedar pivot
#

how can i make a football ball dribble system with blend trees

paper stone
#

is there a way to destroy game objects from a list? I am trying to figure how how to make it so the player can instantiate objects, but only a certain amount of them. The instantiation is going fine, but the destruction is not.

leaden ice
#

It doesn't matter if the object is in a list or not

#

note that if you destroy an object in your list, you should probably also remove it from the list, otherwise you have a reference to a destroyed object in there.

paper stone
#

when i try that- i get the error “Destroying assets is not permitted to avoid data loss”

leaden ice
#

don't do that

#

only destroy instances in the scene

paper stone
#

ah yes- how do i destroy the copy

leaden ice
#

Destroy(theCopy)

#

as opposed to Destroy(thePrefab) < this is bad

paper stone
#

fair play

#

thank you

leaden ice
#

is your question "how do I get a reference to the copy"?

paper stone
#

yes

#

yes that is my question

leaden ice
#
var theCopy = Instantiate(thePrefab);```
paper stone
#

thank you so much

#

that worked

dry dagger
#

Hello. What is the best way for me to switch scenes after an animation has played 5 times?

pseudo moth
#

!learn

tawny elkBOT
#

🧑‍🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

dry dagger
main shuttle
#

Or is the question actually about how to see if an animation is done playing?

dry dagger
#

that, and how to count it.

main shuttle
neon junco
dry dagger
main shuttle
#

It all depends on your setup. You could also start a coroutine that starts the animation and waits for it to finish and then +1. Many ways to Rome on this one.

dry dagger
#

I made an animation where the player digs with a shovel. The whole idea is that once the player shovels 5 or so times, the scene will transition to where the player has a shelter.

#

This is a sequel to a game I made a year ago where a militia soldier is stranded in the Swiss mountains and supposedly froze to death

maiden breach
#

sounds like a cutscene. could just do it all in timeline with a signal at the end to switch scenes

#

or you saying the player has control over the individual shovellings?

dry dagger
#

like this

#

and the shelter would just be a simple hole in the wall of snow, and then a emergency blanket on the door to keep heat in while keeping cold out, and maybe some candles or something

clever laurel
#

I have been stuck on a weird null error for a while now.
Essentially the jump function crashes on null erros if called as a delegate, saying that my Player object (this) has been destroyed, but it works fine if called manually through the script...

leaden ice
clever laurel
# leaden ice sounds like you subscribed it to a delegate somewhere and never unsubscribed whe...

The thing is my Player object is not destroyed, i am 200% sure. Any object i try to log in the function through the delegate is null, while i can log them from anywhere else after and they are not. i put OnDestroy logs on to check to make sure. I fixed the problem but it still makes no sense to me. If i assign the delegate function through another class, with a reference to the class containing the functions, it doesnt work

leaden ice
tardy basin
#

Is there a way to convert a ScriptableObject into a struct?

leaden ice
leaden ice
clever laurel
leaden ice
tardy basin
#

not very helpful tho

leaden ice
#

Tell us what you're actually trying to do

tardy basin
#

I need to store weapon stats as a struct so that they can be synchronized in multiplayer, but I would like to also store them as a ScriptableObject and then read them into that struct, so that they dont get deleted if for example I remove the Component holding the struct from my gun game object

leaden ice
#
[Serializable]
public struct MyData {
  // stuff
}

public class MySO : ScriptableObject {
  public MyData data;
}```
tardy basin
#

okay, thanks, I didnt think about that

pure dragon
leaden ice
#

make a tree structure of commands

pure dragon
leaden ice
#

quick and dirty example is something like:

public class Command {
  public Dictionary<string, Command> childCommands;
  public Func<CommandResponse> execution;
}```
Then you build it like:
```cs
Dictionary<string, Command> tree = new() {
  { "debug" : new { 
     childCommands = new () {
       "devsight": new {
         childCommands = new() {
           "disable" : new { execution = () => return new CommandResponse("Devsight Disabled.");}
           "enable" : new { execution = () => return new CommandResponse("Devsight Enabled.");
         }
       }
     }
}```
Then just do a loop over your arguments list and traverse down the tree until you find the one to execute
pure dragon
#

interesting approach. I will definitely look into that, thanks.

swift falcon
#

I'm trying to Tile.SetColor but it seems like Tiles have the LockColor flag enabled by default, preventing that. I disable it in the code through a mask, but it doesn't kick in until I reload, and only lasts so long as I don't quit Unity. How can I set LockColor to false once and for all?

E: fixed, solution was to use RemoveTileFlags

heavy lynx
#

is it possible for a script to access the properties and attributes of a child object of the object it is attached to

tall fog
#

Hello, how can I transform a cubemap shape from Cube to Sphere?

swift falcon
#

say, would someone with rigidbody collision forces experience know if/what to do if I want to find the force being exerted on another object? like, if I want to find the velocity being imparted on a rigidbody from the collision of the two.
Reason being I want to be able to include that in jump forces to impart some of that momentum into a jump, but I need to be able to set the jump force directly because I don't want to factor in current player y velocity since I'm changing gravity directions

charred root
#

does any1 know how i can change the input this object gets with a different one in my assets?

latent latch
#

Rather, a different variation of card

charred root
#

i have like different presets for it

#

i just wanna know how to change the object to something random from my assets folder

dusk apex
#

Are there particular assets you're wanting to switch to?

latent latch
#

Right, so you have a prefab called Card, but you're setting the SO initially on the inspector. If you want different values on this prefab, you'll have to pass that information in when you init the prefab.

charred root
golden vessel
charred root
#

its just the swapping it to an alr created present

#

so would i make the list by adding each card to the script

#

and swapping

#

cuz i thought of doing it

dusk apex
#
[SerializeField] Card[] cards;
public Card card;```
charred root
#

yeah

golden vessel
#

^

neon junco
#

Don't use a list just use a array. Lists can't be modified

charred root
#

okok lemme try that thanks guys

golden vessel
dusk apex
#

Either should be fine.

golden vessel
#

Yeah, lists is better imo just cos if you go through it you won't have a null at some point

#

But probably irrelevant for that problem

charred root
#

sorry for another question but how would I change this object with one from the list

charred root
#

i meant with code

golden vessel
#

card = cards[something]

swift falcon
#

to better clarify my question: I'm attempting to get a vector as a result of a collision between two rigidbodies. I know they generate contact points, and I'm looking at the documentation on that, but I'm not sure what returns information I'm looking for.
It's not the velocity of the object, it's the velocity projected from the surface normal of the contact point that I'm looking for
I've found things like ContactPoint2D.normalImpulse, but that's a result of the momentum of objects colliding I believe, and not a static force (meaning if I ram one object into another this number fluctuates based on the initially collision speed) and I'm looking for a force exerted by the object simply based on that point's movement vector,

#

head hurts

golden vessel
#

card = cards[random.Range(0, cards.Length)] should give you a random prefab out of those you put in the list

neon junco
charred root
golden vessel
charred root
#

then i want to change this object to one from the list

#

im just unsure of the code and cant find anything

#

I tried firstCard.Card = card;

#

after i set card

golden vessel
#

So you can fill it in editor

neon junco
golden vessel
neon junco
golden vessel
soft shard
charred root
#

im really bad at explaining what im trying to do

neon junco
# golden vessel They have their use for specific problems tho, I use them for equipments or spel...

In my game i had to sort a certain plant price and health of the plant by the int as i collected them and I maybe spent 2/3 days trying to make it work but never could until i was told i was using a array and arrays can't do any of what i wanted to do. So from then on I only use lists because in my mind lists are almost the same with arrays just no cap unless you program it cap like remove 1 off when it gets to a certain count

golden vessel
soft shard
charred root
#

my code takes in the upgrade cards objects here

#

i just need a way to say hey firstcard.card = card;

leaden ice
#

not three variables

charred root
#

this is so hard to explain over text

#

i have an array here

half oyster
#

this is probably rlly simple so im sending it here (ik i switched channels thats cause im not rlly a beginner but im not like the best)

i have these sprites inside my player prefab, which can be changed in the avatar editor. when you hit save, the player becomes a "dont destroy on load" but once you go back to the avatar scene theres another player still there, how do i delete the original player and swap its place with the edited one?

charred root
#

cards are the list of the different upgrades

#

the firstCard secondCard etc are the display

#

which change once their object card changes

golden vessel
# charred root

card probably doesn't need to be public or serialized. You don't want to see it in editor, since you'll only use it through code

neon junco
leaden ice
#

Or just store the data about the player somewhere and have the actual player object just read that data at scene load

golden vessel
#

Then make a list/array of cards that you do serialize, and fill it by dragging your prefabs in it in the editor

leaden ice
#

rather than the player itself being DDOL

half oyster
charred root
#

ima screen record an explanation and send it if thats alright

leaden ice
cursive knot
#

I have a question regarding rotations if anyone is able to help. I'm trying to rotate a cube as I move it but the rotation is getting messed up for different configurations. It works when moving in only the x direction, or only the z direction, but when I use both the y rotation starts changing, cant figure it out, my code should be simple: https://paste.ofcode.org/jq7muVBw4nFgVsTv6ZnjgA

neon junco
charred root
#

here if sm1 can watch that and kinda understand what im trying to do

#

bc idk how else to explain it

neon junco
# charred root https://streamable.com/4o9s35

I know what ur trying to do but don't think ur understanding us.

You want to create a box that you open and when it opens 3 cards will appear but you want the cards to be random from the list of cards you have already made. Correct?

cursive knot
#

The desired result is that the cube will be oriented based on direction of movement. It's a die, so if I move it right, if the number 1 is on top, it is rotated so now one is pointed right, move right again it is on the bottom etc. This works when the rotation of either x or z is zero, can move it any times in z direction and it rotates properly, or any direction x and its great, but if I move it one time in the x, and one time in the z, the rotation no longer works properly, instead of rotating the number on top will stay the same and rotate around the y axis

leaden ice
charred root
#

yes i have all of that done but swapping the object to a new card

golden vessel
#

Should I use WaitForSecondsRealTime when dealing with audio?

neon junco
leaden ice
cursive knot
#

exactly

leaden ice
neon junco
golden vessel
#

The axis of rotation should change according to previous rolls, is that what you mean?

charred root
charred root
#

do u see how in the Card Display script it takes in a card

charred root
#

i even

#

call first card

#

OKOK wait

#

lemme show an example bc i do it using textmeshpro

neon junco
charred root
#

here

#

do u see how i take in nameText

#

and change the value

#

im trying to do that

#

but with a different object thats not textmeshpro

#

if u watch the full video

#

i show everyhting

#

the button alr works

#

the list alr works

#

its just setting the current card to a different one

#

like the object

golden vessel
neon junco
#

Do the same thing with random range ? you can put ints in for numbers and make ints stand for strings or objects etc

golden vessel
#

You're still doing the same thing, like rotate again in the x axis, when the x axis is not the same one. Doe s that makes sense?

#

It's the same one for the die, but not from your perspective

cursive knot
#

The first two directions I move die its fine, rotation of x and z work perfectly, but when I move once in the z direction then move to the x it breaks, I don't mind changing from euler angles, but using other rotation methods weren't working, this was as close as I could get what I wanted

#

ahhh video didnt post correctly sorry

golden vessel
#

I think the easiest way to solve it is to deal with it in a absolute way, store the value of each rotation to the corresponding face of the die, and change rotation from the last rotation (that you stored) to the new one

#

Dunno if all I'm saying makes sense ^^

golden vessel
soft shard
golden vessel
charred root
#

i found another way to do it

cursive knot
#

Yes, I understand its rotating around the Y-axis after moving once then in a different direction after, I'm just seeing how I can fix it

charred root
#

however im now having trouble calling a method from another script

soft shard
charred root
#
    public void setCard(Card input)
    {
        card = input;
    }
#

this should be fine right

#

its just in a different script

dusk apex
charred root
#

the script im trying to call a method from is on this game object

golden vessel
charred root
#

and i call it by using firstCard.setCard(card);

soft shard
dusk apex
#

Just set the field? firstcard.card = card.

#

Assuming it's public

charred root
#

this is first card

half oyster
#

why wont this work- i want it to make its parent anything with the tag "List" on awake but it stays on DDOL

soft shard
# charred root i have firstCard as GameObject

A GameObject wont have access to your public function, youll have to access it with either GetComponent, or make your firstCard the same type as the class that has your public function your trying to access

charred root
swift falcon
#

Rigidbody2D.GetPointVelocity (declaration: (public Vector2 GetPointVelocity(Vector2 point)) with "point" being the global space point to calc velocity for)
I already am getting a collection of contact points when colliding with objects to do ground check stuff... If I want to examine those contacts and then getpointvelocity information from them, does anyone know what I should do?

dusk apex
soft shard
dusk apex
#

Just have it referenced as the correct type to begin with.

half oyster
dusk apex
#
if player doesn't exist
    set instance
    set exit
    set parent
    parent set DDOL
else
    destroy gameObject```The parent has to be a DDOL object as well.
half oyster
#

took me a while but i finally got it!

#

thank you!

half oyster
swift falcon
#

How do I serialize a field in a component such that said field is clamped between the values of 0.0 and 100.0 and utilizes a visible slider?

swift falcon
#

Ooh... 🤔

zinc parrot
#

Is there any other way? cant really export that as a package for the asset store

swift falcon
golden vessel
#

Hey, I'm trying to change music on the next beat after an event.
Does that look right? It's hard for me to check, I suck at rhythm. (bpm is 100)
float timeToWait = (float)(AudioSettings.dspTime - MusicManager.instance.startBossMusicTime) % (60f / 100f);

#

I guess there's missing info, that's the time I want to wait between the event and the next beat

#

MusicManager.instance.startBossMusicTime is the time when the music was first started

leaden ice
#

then I suppose:

float timeRemainingUntilEvent = eventTime- AudioSettings.dspTime;``` assuming dspTime is the current playback time of the song
golden vessel
leaden ice
#

what is "the switch"

golden vessel
leaden ice
#

Are you saying you want to know what time the next beat is, given the current time?

golden vessel
#

Or I guess in audio

leaden ice
#
int mostRecentBeat = Mathf.FloorToInt(currentSongTime / beatInterval);
int nextBeat = mostRecentBeat + 1;
float nextBeatTime = nextBeat * beatInterval;```
golden vessel
#

I agree with what you said tho, I think I sacrifice readability for number of code lines too often ^^

leaden ice
#

This is how I do all my complex calculations

#

I like it to be so stupid simple a toddler can read it

#

not literally I guess but

golden vessel
#

Putting in raw numbers is meh overall ^^

#

Alright, thanks a lot for the advice 🙂

swift falcon
#

Is there a way I can make certain serialized elements in a component enabled/disabled pending the value of a certain boolean?

leaden ice
#

It will make your life easier

swift falcon
#

I'll look into that.

#

Is it in the Unity Store?

latent latch
#

Github

half oyster
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ClickToMove : MonoBehaviour
{
    [SerializeField]
    [Range(2, 12)]   //slider

    //MAKE SURE U TURN OFF GRAVITY OR IT WONT WORK
    
    
    
    private float speed = 4f;

    public Animator animator;



    private Vector3 targetPosition;
    private bool isMoving = false;
    
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            SetTargetPosition();
        }

        if (isMoving)
        {
            Move();
        }
    }

    void SetTargetPosition()
    {
        targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        targetPosition.z = transform.position.z;

        isMoving = true;
    }

    void Move()
    {
        transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);

        if (transform.position == targetPosition)
        {
            isMoving = false;
        }

    }

    
    void OnCollisionEnter2D(Collision2D collision)
    {
        //Check for a match with the specific tag on any GameObject that collides with your GameObject
        if (collision.gameObject.tag == "StopPLR")
        {
            //If the GameObject has the same tag as specified, output this message in the console
            speed = 0f;
        }

        if (collision.gameObject.tag == "StartPLR")
        {
            //If the GameObject has the same tag as specified, output this message in the console
            speed = 4f;
        }
    }
}

this is my characters walking script, a click to walk type thing, and i have a question, how come the animations playing disables the player from being able to move

leaden ice
#

Either make it only animate a child object or turn on Root motion

half oyster
#

oh ok tysm!!

half oyster
leaden ice
half oyster
neon junco
#

putting in under a parent object?

oak plover
#

hey so im trying to do animations for hurt and death how would i go about taking damage and dying i cant figure it out any ideas?

maiden breach
winged sphinx
#

hey is there a generally accepted standard character for separating strings for splitting?

maiden breach
#

It all depends on what youre trying to split. No standard.

half oyster
#

my script wont enable my walk anim

#

shouldnt this work

animator.SetBool("Walking", true);```
#

nvm i did it!!

winged sphinx
maiden breach
#

\n?

#

Semicolon is a common one too

#

Why are you creating the string you have to split though? Why not just store it in structured data from the get-go?

winged sphinx
#

I'm saving a deck recipe with playerprefs. probably not what I should be doing but it's how I know how to do it and it's fine if it's temporary.

oak plover
#

how do you declare a trigger thats in your animator to you player script lmao

#

i might be having a stroke or not rn

swift falcon
#

Is there a way to create projection matrix for a given field of view, without creating a camera?

half oyster
#

why will my scenes not switch in a build 🗿

void fog
#
using Microsoft.VisualBasic.FileIO;

        public static IEnumerable<string> SplitCSV(this string source)
        {
            using (
                var parser = new TextFieldParser(new StringReader(source))
                {
                    HasFieldsEnclosedInQuotes = true,
                    TextFieldType = FieldType.Delimited,
                    Delimiters = new[] {","},
                    TrimWhiteSpace = true
                })
            {
                parser.SetDelimiters(",");

                while (!parser.EndOfData)
                {
                    var fields = parser.ReadFields();

                    if (fields == null || !fields.Any())
                        continue;

                    foreach (var field in fields)
                        yield return field;
                }

                parser.Close();
            }
        }```
#

this textfieldparser is super slow though

hollow karma
#

hey guys

#

I have this 2d character controller

winged sphinx
hollow karma
#

and I was adding walljumps

void fog
#

tab delimeted files are also very very common

hollow karma
#

instead of walljumping

#

sometimes it will do a regular jump

#

this is because my ground check triggers with the wall

#

even though it shouldn't

#

my theory is that the player goes through the wall for a split second because its moving too fast

#

so the ground check gets triggered

#

i know that the groundcheck is triggered by the wall, and thats what im basing my guess off of

winged sphinx
#

it sounds like your groundcheck is overshooting your character horizontally.

hollow karma
#

i thought it might

#

but its not

#

i think

#

here ill send a screenshot

#

oop

#

no you are right

#

LOL

#

look at this

#

wait nevermind

#

it dosent overshoot

#

i have a rounded hitbox

#

sorry i though the inner square was my collider for a second

buoyant crane
hollow karma
#

sure

#

this bug happens even without interpolation

#

i have continuous col detection, which I'm pretty sure is as good as it gets

#

if you want ill share my code as well

buoyant crane
hollow karma
#

ill remove all the comments of my code and send it so it is easy to read

hollow karma
#

here you go

#

i removed all comments

#

im gonna try using a boxy hitbox

#

and see if that changes anything

#

actually i figured it out

#

so im pretty sure my ground check needs to be behind the inner squre of my rounded hitbox

#

because if i decrease the edge radius back to boxy

#

now the ground chekc overshoots

#

is it bad to have the ground check be too tiny though?

elfin vessel
#

Has anyone figured out a good way to have an inline editor for a scriptable object? (I have Odin but InlineEditor does nothing)

hollow karma
buoyant crane
hollow karma
#

yes

#

because i had a debug log

#

that sent out what object the ground check was colidinig with

#

and when the bug happened it sent out one saying it collided with the wall

#

so im positive that its that

buoyant crane
# hollow karma yes

ok, you could try moving your ground check code into FixedUpdate(), or try shrinking the horizontal size of the ground check

hollow karma
#

like lets say the player is making a big jump

#

and lands like right on the edge

#

i mean once they fully get on the platform the ground chekc will trigger

#

but like for that little bit of time it isn't

#

is that ok?

hollow karma
buoyant crane
#

it might not be if it’s extremely noticeable. but try seeing if moving the ground check to FixedUpdate fixes it

hollow karma
#

i dont call groundcheck in fixed update

#

here lemme send a snippet of code

#

this is on my groundcheck trigger object

#

sorry for the screenshot its just a rly small amount of code

#

so i think these events already run in fixed update

#

if im not mistaken

#

i think the bug is fixed though

#

i will report back if it isn't

#

thanks!

half oyster
#

photon seems rlly outdated for my unity, what do i do:(

soft shard
cosmic rain
south gorge
#

im trying to get my gun to shoot in the direction of my mouse

#

it only goes in one direction when I click the mouse

#

im pretty sure it is having a problem finding the location of the mouse

void fog
#

how are you updating the aim in correlation to the mouse?

#

are you detecting mouse position each tick and moving/rotating?

south gorge
#

i believe so but I am not 100% sure

#

i think its only when I click

void fog
#

you're seting shoot direction to 4 different values

#

the input position, you zero the Z, then you set it to a camera position based on the shoot direction

#

im not really sure what that is all doing

#

i assume Z is the same direction as your flat plane

#

eg. shoot along the plane

#

what is transform.position?

south gorge
#

thats the guns location

#

i think

void fog
#

what happens if you take out those shootDirection things and just have one?

#

see what different effects that gives?

#

eg. just have that first one and remove the other 3 (comment them)

#

id have the first two if the mouse position gives you a strange vertical value

south gorge
#

the bullets act different

#

I got it to update

#

the direction I didnt know how to check to see if it was working

#

but now it updates the values in unity when I move my cursor on screen

#

but when I click it just comes out the same side

#

and goes in 1 direction anyway

#

hmm it only updates 2 values

neon junco
#

Does the bullets fire from the gun end or just appear in middle of screen?

south gorge
#

from the end of the cube

#

there is a cube floating above my blue ball

#

i was trying to keep it simple for learning

#

looks like this

#

I just want to create objects on what ever side I click really

neon junco
#

Why don't you move the cube to the front of the ball and have the bullets fire from the cubes location and move the character with your mouse movement

south gorge
#

its a mobile game

#

I have a stick

neon junco
#

finger is same as a mouse input

south gorge
#

yes

#

the ball is suppose to roll around and the top part should shoot in the direction

#

its like a tank

#

the ball moves already

neon junco
#

have the box fixed on its axis so it wont move with the ball?

south gorge
#

i just have the cube locked at the moment because the ball rolls with the sphere so it keeps hitting the floor every time I roll

neon junco
#

i mean roll

south gorge
#

im just messing around for the sake of practice

#

but its a cool mechanic that i want to learn

neon junco
#

So works now?

south gorge
#

no

neon junco
#

Whats not working then

south gorge
#

here is a how the objects move

#

north

#

no matter where I click

#

1 sec

neon junco
#

Like i said move the box in front of the ball and have the bullets fire from the cubes location or a game object

south gorge
#

thats what a clip looks like

#

thats not what I want to do though hah xD

#

hmm

#

what if I can make a ring around the sphere

neon junco
#

U want it to fire from where the ball is facing?

south gorge
#

noooo

#

just where the the cursor clicks

#

the cube does not move at the moment

neon junco
#

have a ring around ur character and have the cube rotate to where mouse is

south gorge
#

rotate

#

yes let me try that

swift falcon
#

Has anyone here ever made an extension method for MonoBehaviour? This function compiles itself, but I can't use it anywhere
public static bool GetComponent<T>(this MonoBehaviour behaviour, out T component) where T : MonoBehaviour
{
component = behaviour.GetComponent<T>();
return component != null;
}

neon junco
south gorge
#

its so close

#

i almost got it

neon junco
south gorge
#

ty

tulip sparrow
#

does anyone know how to make a particles in a particle system go in specific rotations based on the direction they are going? I'm trying to make my attack look better

neon junco
swift falcon
#

So I’ve been looking though System.IO special files/folders

I have found that you have Access to the windows folder, like the main system windows folder. Doesn’t that mean you can literally easily delete that folder thought the program?? Or will it just not let it do that. I wanna try it on a virtual machine

neon junco
#

Okay but why?

swift falcon
neon junco
swift falcon
#

I’m not saying I’m gonna make a game that’s randomly going to delete your windows lol, I’m just curious if it’s that easy to just delete important folders thought a simple script

swift falcon
#

You die you get random ass files deleted form your pc

Personally sounds like a good concept to me

ashen vector
#

i added third person camera from starter assets and my project broke

glossy granite
#

Hello I disabled autorefresh to be able to use hot reload, but unity is still refreshing
Any idea how to solve it ? thank you

thin aurora
#

Might have been an error that happens once

cosmic rain
quartz folio
glossy granite
swift falcon
glossy granite
#

Autorefresh not working

elder zenith
#

RaycastHit[] raycastHits = Physics.BoxCastAll(refCollider.bounds.center, refCollider.bounds.extents, transform.forward, Quaternion.identity, raycastLength, 0, QueryTriggerInteraction.Collide);

raycastHits = raycastHits.Concat(Physics.RaycastAll(ray, raycastLength, 0, QueryTriggerInteraction.Collide)).ToArray();```

My `Physics.BoxCastAll` and `Physics.RaycastAll` are not returning anything. Where am I going wrong? At first I suspected it was bc all the cars use trigger colliders, but I placed a default cube in the scene and the array length is still at 0. (Used concat just to see if either one is working)
#

the "refCollider" is the one you see in front of the car

elder zenith
#

..god damn it

quartz folio
cosmic rain
#

If you want a layer mask that targets all layers ~0 might work

elder zenith
#

~0? with the tilde?

cosmic rain
#

Yes

#

Actually maybe not.

#

You need a bitwise invert

quartz folio
#

Physics.AllLayers is much more reasonable

elder zenith
#

oh, lemme see if that works

#

Sure does! Big thanks

quartz folio
#

Physics.DefaultRaycastLayers takes the ignore layer into account

orchid bane
#

How do I utilize A* pathfinding in a way which would base calculations on count of travelled roads instead of distance between nodes in such a graph?

cosmic rain
orchid bane
cosmic rain
#

What are you using for A*?

orchid bane
cosmic rain
orchid bane
#

For now it's

        private static float HCost(Node curNode, Node goalNode) {
            return Vector3.Distance(curNode.transform.position, goalNode.transform.position);
        }```
Which doesn't suit my needs
tepid river
#

Just return 1

#

Thats 1 cost per step

#

The algorithm doesnt care about the physical layout

cosmic rain
#

That and Map.FindValidPath should calculate the path distance based on the number of jumps.

sudden meadow
#

Is there a good alternative for [Header("Textures")] that will properly group together a group from a parent class with the same group in a class that inherits it?

#

in the inspector

cosmic rain
#

A custom inspector/editor!😬

sudden meadow
#

Was what I expected tbh

oak plover
#

can someone help me im so confused lmao

#

im doing animations and i tried to set up a death animations and im going down a rabbit hole

plucky inlet
oak plover
#

code related

plucky inlet
#

So whats the issue then?

oak plover
#

ok

cosmic rain
#

@oak plover did you manage to solve the animation event issue?

oak plover
plucky inlet
#

Oh the issue was already known, sorry to ask then. If you got a thread, feel free to invite 🙂

iron basalt
#

how do i make a Func delegate take any type of parameter? (edit: this is a general c# question)

Func<AnyType, SomeType> function;

vague slate
#

How do I extract only Y axis rotation from quaternion?

#

I remember there's a way to do projection on plane

#

but I don't remember specifics

hexed pecan
vague slate
#

I have two direction vectors and I rotate object between them on Y axis.
How can I know in which direction rotation would be faster?

As of now I do rotation using const offset and to make a turn left, object makes a turn to right until it reaches left 😅

#

For now it's just like this

                var rotationOffset = quaternion.RotateY(cs.rotationSpeed * deltaTime);
                transform.rotation = math.mul(transform.rotation, rotationOffset);
cosmic ermine
#

just need to save a function to something inside a struct, and to be able to call it later, what type should i use?

cosmic rain
cosmic ermine
cosmic rain
#

If you need explicit help, share your code

cosmic ermine
cosmic rain
vague slate
cosmic rain
#

Either lerp or rotate towards based on your explanation.

vague slate
#

I can't use lerp, because rotation logic is stateless

cosmic rain
#

Then rotate towards

vague slate
cosmic rain
vague slate
#

quaternion and math types

#

and it's quaternion doesn't have such methods

hexed pecan
cosmic rain
#

Aah

hexed pecan
#

Simply checking Quaternion.Angle can work too but its around any axis

cosmic ermine
hexed pecan
vague slate
#

cross product did the trick

mossy minnow
#

hey everyone, if i were to do rb.AddForce(dir * force);, how would i make the dir go from Axis space (like x = 1, y = 0 for forward, etc) into the actual direction that the object is facing?

hexed pecan
#

AddRelativeForce

mossy minnow
#

right now, it doesnt factor in the rotation of the object

#

ah that sounds like what i need

hexed pecan
#

Or multiply the force with a rotation

cosmic ermine
# cosmic rain Share your code

boiled down code, because my code is a mess: ```cs
struct SomeStruct
{
public delegate void SomeMethod(); //crashes visual studio's CSharpWrappingCodeRefactoringProvider upon typing
}

public void Nonsense()
{
//does something
}

public void Chaos()
{
SomeStruct Something = new();
Something.SomeMethod = Nonsense;

Something.SomeMethod() // cannot be used like a method

}

mossy minnow
#

how would i calculate how much force it takes to just overcome the friction so it stays the same velocity?

#

when in a non-accelerating or decelerating state

sleek bough
#

Not sure why it crashes for you though

cosmic ermine
#

ah ok thanks, so should i have a delegate void for each of the function fields i want to have on the struct, or is sharing 1 between multiple ok?

sleek bough
#

I prefer using Actions though, avoid whole declaration thing

cosmic ermine
#

Actions sound familiar, I'll look into them quickly then, thanks

sleek bough
cosmic ermine
#

thanks

#

ah ok now the struct works, now I just have to see if it is possible to get a list or array of the struct! (probably won't be possible due to the fact that structs in lists have to be non-nullable value types, but I can try, and if it isn't possible then I can just redo my code to not need a list of it)

craggy veldt
#

mutable structs are bad, use class instead

sleek bough
#

And you can also subscribe multiple actions to one...

cosmic ermine
craggy veldt
#

structs in lists... really, just use class

cosmic ermine
sleek bough
#

Yea, if you are trying to store a bunch of methods just keep list of actions

#

or if you need to trigger all of them, subscribe them

cosmic ermine
#

just tryna clean up my code to be more readable, cause this is for ui, and each menu has a setup function and an every frame update function, and having them sprawled out everywhere is a nightmare, and having a nice simple WhateverMenu.SetupFunction, and stuff like that should make it more readable, thanks

sleek bough
#

myAction += myAction1;
myAction += myAction2;
myAction.Invoke();

cosmic ermine
#

btw is there anyway to force the struct to be non-nullable and a value type or am i going to have to get rid of the list and redesign some stuff?

cosmic rain
#

value types are non nullable by default

cosmic ermine
cosmic rain
#

structs are value type

cosmic ermine
#

then why can't i have my struct in a list?

cosmic rain
#

Who said that you can't?

cosmic ermine
#

visual studio, also i probably should have specified that it was a native list, cause there might be differences between regular lists and native lists that i don't know, sorry

cosmic rain
#

That's a native list. You kinda forgot to mention the important part.

#

are you doing DOTS?

cosmic ermine
#

sorry, I often forget that native containers ain't the default... and yes I'm using dots

cosmic rain
#

Well, then you should also know that you can't use any reference types in DOTS(you can on the main thread, but seeing how you use a native collection you probably want to use it in a job?)

#

delegates are reference types btw

#

I think

#

Yeah, it is.

cosmic ermine
cosmic rain
#

As long as they're not used in a job, it's fine.

cosmic ermine
cosmic ermine
cosmic rain
#

Yep, a regular list is fine.

#

But then why not use a class as well?

cosmic ermine
#

ok thanks, sorry for my foolishness lol, and i have no clue what the difference is between making it a class vs a struct, but sure I'll use a class lol, can't do more harm than i have already

cosmic rain
cosmic ermine
craggy veldt
#

when you store it somewhere it makes copy...

cosmic ermine
craggy veldt
#

not quite sure about that, but carry on!

ashen vector
elder zenith
#

if I cast e.g. 3.5f as (int), does it round down, up, or just discard the decimal part?

elder zenith
#

Ah fair enough

half oyster
#

this is even when i import pun 2

#

i got it working!!

#
using Photon.Pun;
using Photon.Realtime;
swift falcon
#

Love you unity debugger

#

everytime

#

misses breakpoints too

iron basalt
#

(VISUAL STUDIO 2022 QUESTION)

how do i make it so that VS displays all params docs? (you currently have to fill everything slowly to see it)

#

not very important cuz you can just click it in VS to see full doc, but just curious

half oyster
#

why is this happening-

quaint sierra
#

trying to get my character to do a backflip but this code makes the character go crazy and fall out of the level. What am I doing wrong?

mental rover
#

depending on what you're aiming for here, I'd consider separating the visual backflip from any physics/movement controller. Make it an animation instead

teal jetty
#

hi

#
  public GameObject videoPlayerObject;

    private void Start()
    {
  
      Debug.Log("videoPlayerObject"); //WORK
       _socket.On("receiveVideoURL", (response) =>{
             Debug.Log("videoPlayerObject"); //NOT WORKING WHY
            var url = response.GetValue<string>();
            Debug.Log($"Received video URL: {url}");

            console.log(videoPlayerObject)

        });

#

so i can't .play() video

#

idk why

cosmic rain
teal jetty
#

It's not just the debugging, it's really everything that can't be called,

#

i send you a past

cosmic rain
#

Unity API

teal jetty
#

so how i can do it ?

cosmic rain
#

Many ways.
Raise a flag and consume it on the main thread for example.

teal jetty
#

Can you give me an example?

cosmic rain
teal jetty
#

Yeah, andthere are a lot of libs that don't work anymore, this is the only one I even looked at examples but I don't see

#

let seee maybe wrong doc

cosmic rain
#

Why not use unity transport btw?

teal jetty
#

UnityThread.executeInUpdate(() => {

teal jetty
cosmic rain
#

Hmm

#

Pretty sure unity transport should work as well.

#

It has it's own sockets implementation.

#

But maybe I'm wrong.

tall fog
#

Hello, quick question, how can I convert a cubemap into an sphere from code?

teal jetty
tepid jewel
#

Hey! I need some help with meshes. I am currently migrating a project from three js to unity and I have a geojson with latlngs that I am using to make a three.Shape (https://threejs.org/docs/#api/en/extras/core/Shape) The shape has something called holes and this is very useful as I just give it a path for the outer bounds of the polygon that I have reformated from the latlng with mercator projection and then I give it the holes inside of this polygon (in the same format) and it calulcates everything for me, but I can't seam to find a good way to do this in unity. Can anyone help me out? I have multiple ideas, either to make multiple meshes and somehow "cut" one out from the other (like boolean in blender, this is they way I want to avoid) or in c# somehow calulate and triangulate it with the holes, but how do I do that?

rocky jackal
#

so i have made a build and send it to a friend to test multiplayer and i would like to see his log files but i cant find them anywhere and everything on the internet says something about a folder that i cant see

worn gulch
#

hey guys

foggy granite
#

ok wtf i just got chatgpt to write a first person character controller script for me wtf

wraith cobalt
foggy granite
#

true kek

hot torrent
#

I have severe crash issues, just managed to catch one crash while profiling, what could be causing that?

hexed pecan
#

Looks like theres a lot of garbo collection going on 🤔

#

Also look at your crash logs to see if you find any clues

hot torrent
hexed pecan
#

What did you mean with crash issues then?

#

You mean it crashes while profiling?

hot torrent
#

Well... it`s not a "crash"

hot torrent
#

it's hard to explain!

#

So, Sometimes, while the game is running (on my quest 2) it hangs itself up, it doesn`t render any new frames and is just stuck on one while sound is still playing, then if i put the headset on standby and back on, there is a terrifying visual glitch happening, as seen here:

#

At the end of the video you can see how it's supposed to look.

#

As you can see, the meshes get messed up aswell

normal arch
#

I have a question, how does the unity layer system work? I want to create my own similar to it because the way I want to do it won't work with unity's own layer system. Basically I want to make a 2d game that includes jumping and platforming, I haven't made the code yet but the basics of it are there is a jump button that increase the player's sprite renderer y value and a float called height level, when this jump is over gravity is set to 1, and when the height level is equal to the floor level (another float) the gravity = 0. When the player gets on a platform their floor is set to another value with an on trigger enter and exit 2d function, and that's it. I want certain colliders to be non interactable for certain entities based on that entity's height level. Is there any way I can do this?

viral seal
#

guys i have 2 errors im trying to implement unity ads and im using a template that already has unity ads. when i clicked the on button to monitize these errors popped up. any fixes?

swift falcon
#

anyone can help me?

teal jetty
fervent furnace
#

i see someone talk about a* above
are there any guys know what is the stopping condition of bidirectional a*?
i read some python codes,
one is just frontier of forward search==frontier of backward search,
some of them is max(top of two heaps) <= minimum predict value (i read a pdf on is similar to this but <= minimum predict value + certain value),
i wrote my a* based on second one but i am not quite sure

tepid river
#

wdym stop condition?
either you have reached all nodes or your stop early when you found what you were searching

#

ah nevermind, bidirectional

#

for dijkstra, the current node is always the best path so far, so with bidirectional you just stop when you meet.
a* uses a heuristic on top of that, sacrificing perfection for speed, so you can also stop when you meet and accept that it might not be 100% ideal path

#

if you want a perfect path, you shouldnt use a* anyways

fervent furnace
#

a* is complete if h is not overestimate ofc my h may not be perfect

tepid river
#

yes if you would let it finish. but im not sure about that if it meets inbetween

fervent furnace
#

i have considerd implement bidirectional bfs but it is quite slow compared with a*

#

although it guarantees return a shortest path

tepid river
#

bellman forde is worse than dikjstra and a*, only useful if you must have negative edge values

#

dont know your use case, but you can jsut scale back the weight of the heurisitic. the closer it gets to zero, the more A* turns into dijkstra. just try out and use what feels right

fervent furnace
#

it should independent from use case, the beauty of math and algorithm but i am poor in discrete math so i cant enjoy it

tepid river
#

you have to put restrictions in anyways. bellman forde has them too

#

it will crash on negative cycles iirc

fervent furnace
#

some paper on NBA* but i cant fully understand it...

worthy brook
#

I'm having some trouble getting Netcode for GameObjects to work, I managed to create a manager and run a host and have a client connect to it, and I added Client Network Transform and Network Object components, but the clients who connect to the host still can't move. Anyone know what the issue might be?

I'm following this tutorial for NGO btw: https://www.youtube.com/watch?v=3yuBOB3VrCk

latent latch
#

Try this one instead. Tarodev usually has the repo in the description available.

worthy brook
#

thanks! I'll take a look

median folio
#

Hello, I'm trying to wrap my head around some logic. I have about 10 cubes that moves from point A to B. I also have a separate manager class to control the logic of the level.

I was thinking about firing an event when each cube finishes moving from A to B and then my level manager can listen to this. The problem is that I would need a reference to each of those 10 cubes in my manager?

I'm trying to find a way to dev this that I can use that cube logic in any level without hardcoding too much. Any suggestions on how to go about this?

civic fern
# median folio Hello, I'm trying to wrap my head around some logic. I have about 10 cubes that...

One way to approach this is to use a script that can be attached to any game object that needs to move from point A to B this script can have its own event that is fired when the game object reaches point B your level manager can then listen to this event without needing a direct reference to each game object instead it can simply search for all game objects in the scene that have the moving script attached and subscribe to their events

bronze rampart
#

Should I be using scriptable objects for anything I intend to spawn in and out at a high frequency? Or for use cases that don't need to store more than a few variables should I continue to use pooled GameObjects with monobehaviours?

civic fern
median folio
civic fern
#

goodluck, keep us updated :D

#

if u need more help just ask

bronze rampart
# civic fern for objects that need to be spawned and destroyed frequently, like bullets, part...

Im spawning a bunch of projectiles that are affected by various forces non of wich I would like to get the rigidbody component for at runtime and before I start storing things other than gameobjects in my pooler I want to make sure im not going about it wrong. Its just a rigidbody for now but I use this pooler to pool everything that spawns at runtime more or less and would prefer it to be very lightweight and simple

civic fern
# bronze rampart Im spawning a bunch of projectiles that are affected by various forces non of wi...

If you don't want to get the Rigidbody component at runtime, you could consider adding it to the prefab for the projectile, so that it's already attached when you instantiate the object this will be more performant than trying to add the Rigidbody component at runtime if you're concerned about the memory usage of storing other components in your pooler, you could consider using a lightweight alternative like structs or simple data classes to store the necessary information however keep in mind that this may make your code less flexible and harder to maintain in the long run ultimately it's up to you to decide what approach makes the most sense for your specific use case and performance requirements. If you're unsure, it's always a good idea to test and benchmark different approaches to see which one performs best in your game

bronze rampart
civic fern
#

Yes, if you want to use the Projectile class for your projectiles, you will still need to get the Rigidbody component from each spawned projectile.
However, you can minimize the performance impact of this by caching the Rigidbody component after getting it once and then reusing the cached reference for subsequent updates. For example, you could add a private Rigidbody rb; field to your Projectile class and then cache the reference in the Start or Awake method

#

then in your update or fixedUpdate method, you can use the cached refrence instead of calling getComp everytime

bronze rampart
#

ok cool. That was more or less the plan I just wasnt sure of this was the intended use case for scriptable objects since ive avoided learning about them them like the plague

polar marten
polar marten
bronze rampart
#

Instance objects --> get components --> set active as normal now all that is at start but what's 300 getcomponents all at once? lol

#

or whatever my pool size is

#

much preferred to at runtime though

polar marten
#

scriptable objects make sense as data containers of string, float, int, struct fields. if they reference rendering data like textures and sprites, you are usually better off with a prefab. if they reference prefabs, you are making a design error.

#

if you are adding code to a scriptable object class, you are making a design error

worthy brook
bronze rampart
#

TYVM! @civic fern @polar marten

civic fern
#

💟

#

goodluck

polar marten
polar marten
#

what version of unity are you using?