#archived-code-general

1 messages · Page 340 of 1

dawn nebula
#

Like if the button event is calling a SaveGame function, just call the SaveGame function and not the button event

clever bridge
#

Hey everyone, in my side scrolling 2d platformer it looks like my player character is jerking when moving, but I have the input in Update and the movement method in FixedUpdate, isn't that right? Is there any other cause of the jerking movement?

rigid island
#

show code and other relevant info

clever bridge
#

it's only my player though, the other objects aren't jerky

heady iris
#

this may not align with your framerate

#

Are you using a rigidbody2d?

clever bridge
#

yes

heady iris
#

try turning on interpolation

clever bridge
#

it is set to interpolation

#

how do I have my movement align with my framerate then

heady iris
#

Does your camera follow your player?

clever bridge
#

void Update()
{
hMove = playerControl.Movement.Move.ReadValue<float>();
}

void FixedUpdate()
{
hsp = hMove * speed * Time.fixedUnscaledDeltaTime;
transform.position = new Vector3(transform.position.x + hsp, transform.position.y);
}

#

yes camera follows player

heady iris
clever bridge
#

it's probably adding to x is the problem

heady iris
#

If you're using a rigidbody on your character, you need to set the rigidbody's position

clever bridge
#

so I should be adding to velocity

#

not the x position

heady iris
#

no, you should be setting the rigidbody's position

#

you are not setting the rigidbody's position anywhere in this code

#

you are setting your transform's position

storm wolf
#

Are you using cinemachine?

clever bridge
#

yes

heady iris
clever bridge
#

I've never moved my rigidbody before

heady iris
#

add a Rigidbody2D field, assign a reference to the component in the inspector, and then set its position instead of your transform's position

clever bridge
#

I've always added to velocity or added to transform x

rigid island
#

time to learn

clever bridge
#

so that's the right way to do this?

#

I guess you wouldn't be saying it if it wasn't

heady iris
#

yes, which is why I said to do it --

#

(:

rigid island
#

you want your physics object to be accurate with physics ofc its the right way

heady iris
#

When you set the transform's position directly, you aren't letting the physics system know about the movement

#

it just finds out that it's in a new position (for no apparent reason) in the physics update

clever bridge
#

so like ```rigidbody.transform.x += speed````

#

paraphrasing

heady iris
#

No, it'sj ust rb.position

#

rb.transform.position would be right back where we started

rigid island
heady iris
#

also, you can't add to a single part of the position like that

#

rb.position += speed * Vector2.right; would be more appropriate

clever bridge
#

do I need to do * time.deltaTime

heady iris
#

Correct, actually!

#

I forgot

#

In FixedUpdate, Time.deltaTime will be set to Time.fixedDeltaTime, so you don't have to worry about that distinction

rigid island
heady iris
#

The rule is that if you're changing something over time, you use deltaTime

#

You are gradually changing your position over time, so you use deltaTime

#

with AddForce, that's not the case: you're just saying "push on the rigidbody this hard"

clever bridge
#

i just changed it to my rb and it's still doing the jerking

heady iris
#

Show your new code.

clever bridge
#

void Update()
{
hMove = playerControl.Movement.Move.ReadValue<float>();
}

void FixedUpdate()
{
hsp = hMove * speed * Time.fixedUnscaledDeltaTime;
rb2d.position = new Vector3(rb2d.position.x + hsp, rb2d.position.y);
}

#

rb2d is the rigidbody

heady iris
#

Ah, you actually need rb2d.MovePosition

#

I forgot about that -- setting rb2d.position ignores interpolation

#

at least, that's the case for a Rigidbody. The manual isn't clear about that for Rigidbody2D

clever bridge
#

rb2d.MovePosition(new Vector3(rb2d.position.x + hsp, rb2d.position.y)); ?

#

this doesn't seem right either

#

doing this made it way worse, vertically and horizontally, it was just jerky horizontally, now it's extremely jerky in both dimensions

#

looks like stop motion now

heady iris
#

hm, that's a bit unexpected

clever bridge
#

it may be the camera... the camera doesn't seem jerky

#

and everything else is moving smooth

#

nevermind

heady iris
#

You could make the camera stay still and see how things look

clever bridge
#

when my camera is at one end of the level and fixed the player is still jerky

heady iris
#

I suppose that MovePosition is resetting your velocity to zero

clever bridge
#

it's only jerky horizontally

heady iris
#

Perhaps you can just set the velocity instead?

#

That'll avoid directly setting the rigidbody's position entirely

#
var velocity = rb2d.velocity;
velocity.x = hMove * speed;
rb2d.velocity = velocity;
clever bridge
#

that was it! Thank you so much!

#

in the Update method, is it more expensive to have a local variable or create a variable in a method?

#

meaning is it more consuming to create a variable in the class or in the method, I'm assuming in the method

rigid sleet
#

*Heavily recommend using a character controller for movement if you arent doing anything physics based

chilly surge
clever bridge
#

the reason I'm asking is because I have a 2d 16 bit game and it makes my fan blow hard every time I play it

#

it's probably something else

#

I'm not super great at using the Profiler, I want to lower those spikes

chilly surge
#

With any performance related questions, the first thing you do is to profile it and understand what's eating your performance budget. Randomly guessing what the problem is is not the right way to go.

clever bridge
#

the biggest chunk in profiler says EditorLoop

lean sail
#

a build would show you how your performance actually is, since the editor has a ton going on around

clever bridge
#

I guess that makes sense, maybe it's the editor that's making my fan blow hard, but my computer is pretty good, the editor shouldn't be doing it either

lean sail
#

you can expand the profiler data too and see what specifically is causing issues. Maybe open up task manager just to see if its even unity causing it in the first place

cosmic rain
dusk apex
warm canopy
#

How do I reset something in visual studio 2022 where I stop getting these false errors in the editor:

warm canopy
#

mind you, Unity compiles and plays.

heady iris
#

If you don't have a framerate limit, your game will eat either 100% of your CPU or 100% of your GPU (whichever limit it reaches first)

spring creek
gusty aurora
#

mesh.uv2 = new Vector3[...]

heady iris
#

and why do you expect these changes to persist? are you saving the changes to the asset?

gusty aurora
#

Yup

#

I edit the mesh asset, but unfortunately the changes get cleared (?) when entering play mode

heady iris
#

Show your code.

gusty aurora
#

My understanding is that when entering play mode, all changes to the mesh are removed

#

Can't before tomorrow =X

#

Something like var smoothedUVs = some Vector3[] then mesh.setUVs(1, smoothedUVs) then save asset obviously

heady iris
#

I want to see how you're doing the last bit.

#

notably, you aren't going to be able to rewrite a mesh that comes from an importer

#

It sounds like you want to create an AssetPostprocessor, actually

#

you can use that class to modify an asset after it gets imported

vivid halo
#

I'm trying to code a saving system for my Unity3d project. I searched online and I see recommendations for writing JSON files based on the game state with optional encryption/decryption for anti-tampering. Does this approach sound reasonable?
Addendum: Will scriptable objects auto-save since they are persistent, or are they only persistent within a session?

rigid island
#

encryption/decryption aint worth it though

vivid halo
#

Not really a big value-add?

rigid island
#

sciptable objects for a save is no good, values get reset in new run

rigid island
#

if the game is offline who cares what goes on

#

if the game is online then it has no reason to be storing encryption/decryption code in the client

vivid halo
#

Fair point. I was assuming standard practice without really questioning it

#

Last thing: Add-ons for saving. Are they generally worth it, or is hand-made saving reasonably efficient and feasible?

rigid island
#

depends how complex you're going for and how much you're willing to code yourself, only you can know if they're valuable to your project

#

start simple first if you havent already played around with saving system first

#

adds complexities of first learning their system while learning saving in general

vivid halo
#

My main saving needs are stats, entity position, quest/event data, and related data

#

Okay, makes sense

rigid island
#

yeah You can easily store that in a basic json/bin file

vivid halo
rigid island
#

yes the Unity is limited to what it can serialize

#

properties are one of them that it cant

vivid halo
#

As long as the property has a referenced field, should be fine, right?

rigid island
#

can serialize pretty much unity cant and more.

#

only issue it has is Vector3s

chilly surge
#

You can serialize properties too by serializing the backing field.

vivid halo
#
[SerializeField] private float example;
public float Example => example;
#

How do you serialize a backing field?

#

Or is example the backing field here?

chilly surge
#

[field: SerializeField]

vivid halo
#

Ah, okay

rigid island
#

yeah for Dictionaries you also do it with structs etc

vivid halo
#

Ahh that might be annoying

rigid island
vivid halo
#

I do not mess with structs too often and I have a few dictionaries in use. I imagine I have to convert and unconvert them to keep the mserialized?

rigid island
#

indeed

#

no extra fiddling required

vivid halo
#

Will definitely look into that

chilly surge
#

I've just finished migrating to STJ a few hours ago.

#

I was using JsonUtility, and honestly it's pretty alright. I only migrated because I do not fully control all of the JSON I'm consuming, which is a use case I assume most projects won't run into.

rigid island
#

in unity i think 97% of the time JsonUtility is perfectly fine

#

but yeah like you said, certain APIs i need more control over the de/serializing part

vivid halo
#

Where are JSONs stored? I don't see any docs about a command to store the json in any local directory

chilly surge
#

For sure, and JsonUtility has very good performance, especially comparing to NSJ.

rigid island
#

you have to create a file to store it anywhere

#

Application.persistentDataPath usually

vivid halo
#

Okay, that answers it

#

Thanks!

oblique spoke
chilly surge
#

Oh really.

#

I haven't profiled it myself, but from an article that did the profiling, the number differences are pretty big.

oblique spoke
chilly surge
#

Ah yeah I think those are the articles I remembered.

#

The allocation is especially nice.

fiery spruce
#

whenever i rotate objects flicker for some reason, ive tried messing with clipping planes and that didnt help at all, my only guess is its cause its in update and not fixed update but that doesnt make much sense to me
https://hatebin.com/sfwvjjhqtk

leaden ice
oblique spoke
leaden ice
#

Ah yeah if by "flickering" you actually mean stuttering then yes

#

you should not be rotating your player's transform but rather its Rigidbody

#
transform.Rotate(0f, movement.x * sensitivity, 0f);```
Should become
```cs
playerBody.rotation *= Quaternion.Euler(0f, movement.x * sensitivity, 0f);``` @fiery spruce
fiery spruce
#

weird how that behaves different then playerBody.transform.Rotate(0f, movement.x * sensitivity, 0f);

leaden ice
spring creek
fiery spruce
#

interesting, nice to know

burnt briar
#

Hi, can someone please explain to me why does Unity keep asking me to update UnityWebRequests in 2022.3.26f1 with the Script Updating Consent popup? Did they change something because the documents are still using the same old flow.

burnt briar
iron vortex
#

Does Unity only limit one drawn raycast at a time?

rigid island
iron vortex
#

For some reason this doesn't seem to be working then

Direction = new Vector3(0, -1, 0);

        Ray ray = new Ray(this.transform.position, Direction);
        Debug.DrawRay(ray.origin, Direction * Distance, Color.red);
rigid island
burnt briar
iron vortex
rigid island
rigid island
tawny elkBOT
chilly surge
#

Either way, best to migrate away from obsolete API even if it still technically works.

iron vortex
#

my bad g

dawn nebula
#

So I'm trying to make a custom Timeline track that uses Spline Containers.

#

My clips have a field that allows me to define which spline container it is using.

#

The problem is that once the clip is created, changing the value of the field does nothing.

#

The code is just this.

public class SplineBehaviour : PlayableBehaviour
{
    public SplineContainer splineContainer;
    public AnimationCurve curve;
}
#
[Serializable]
public class SplineClip : PlayableAsset, ITimelineClipAsset
{
    public ExposedReference<SplineContainer> splineContainer;
    public AnimationCurve curve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 1));

    public ClipCaps clipCaps
    {
        get { return ClipCaps.Blending; }
    }

    public override Playable CreatePlayable(PlayableGraph graph, GameObject owner)
    {
        var playable = ScriptPlayable<SplineBehaviour>.Create(graph);
        var behaviour = playable.GetBehaviour();

        behaviour.splineContainer = splineContainer.Resolve(graph.GetResolver());
        behaviour.curve = curve;
        return playable;
    }
}
#

I understand that what's likely happening is the value of splineContainer is getting passed to the behaviour only on playable creation.

#

Aka a change any point after is meaningless.

#

Is there anyway to have it recreate the playable when I change that field?

#

Or will I need to wrap the SplineContainer in something?

#

@rough scaffold It's referring to these.

rough scaffold
#

oh i see i see

#

thank u so much

#

@dawn nebula and vertical would be w and s essentially>?

dawn nebula
vestal arch
#

looks like an internal error, does the last error give any more details

surreal thorn
surreal thorn
#

No details whatsoever

#

hello

gusty aurora
rigid island
#

What problem do you want to solve ?

heady iris
hasty wave
#

I don't understand why do I get this error? even though I couldn't find any null within the unity nor the script

UnityEditor.Graphs.Edge.WakeUp () (at <0e6f69b30d82405f98d87804eacb548a>:0)
UnityEditor.Graphs.Graph.DoWakeUpEdges (System.Collections.Generic.List`1[T] inEdges, System.Collections.Generic.List`1[T] ok, System.Collections.Generic.List`1[T] error, System.Boolean inEdgesUsedToBeValid) (at <0e6f69b30d82405f98d87804eacb548a>:0)
UnityEditor.Graphs.Graph.WakeUpEdges (System.Boolean clearSlotEdges) (at <0e6f69b30d82405f98d87804eacb548a>:0)
UnityEditor.Graphs.Graph.WakeUp (System.Boolean force) (at <0e6f69b30d82405f98d87804eacb548a>:0)
UnityEditor.Graphs.Graph.WakeUp () (at <0e6f69b30d82405f98d87804eacb548a>:0)
UnityEditor.Graphs.Graph.OnEnable () (at <0e6f69b30d82405f98d87804eacb548a>:0)```

And the game doesn't receive any error at all. And if I exit and rerun the editor it's gone
heady iris
#

Restart the editor.

#

This is a problem with the code that draws a graph window (like the Shader Graph).

#

There is nothing to fix in Arc's code.

heady iris
#

like the Shader Graph editor, as I just said in that message

#

I know what the post says. I've read it before. It is irrelevant here.

#

Unless you're suggesting that Arc should go diagnose and fix an editor bug, it is not at all helpful here.

sacred frost
#

random unity shenanigans most of the time...

heady iris
#

I've seen this error quite a few times

#

(both in questions here, and a couple of times in my editor)

#

Which is why I suggested that immediately, yes.

rigid island
#

thanks!
Sounds like you are trying to refactor it because you're having a hard time time having it be extensible is that right? SOLID is def a good guideline to follow. How about events? Maybe scriptable objects to help decouple some stuff too ? I try to limit also how much I do abstract classes vs just utilizing interfaces when possible.

gusty aurora
#

Is it possible to access the current deltaTime inside Fixed Update ?

heady iris
sleek bough
#

It's identical to fixedDeltaTime

#

If you want to reachout to Update deltaTime, you'll have to choose which one of the overlapping ones you want

vestal arch
crisp minnow
#

So probably a very simple question... I have an object I pick at random that I want to zoom in on, I was planning on setting it to a new parent with a larger scale, but of course this just adjust's the object's local scale down to maintain the exact same size. What's the best way for me to have such an object obey the parent's scale without impacting position and rotation?

heady iris
#

you could just store your local scale before reparenting, then restore it

crisp minnow
#

That's a good point... but I just realized that even if I have my way with this, the object will just suddenly pop to the new scale 😅 I'm gonna have to animate this to grow larger, aren't I? 😆

heady iris
#

Yes, you will.

#

(I'd just "animate" it through code, of course)

#

rather than using an actual animator

leaden ice
crisp minnow
#

Make it bigger 😅

#

So doing that on the parent itself and just set the child to the parent, then fire the zoom in trigger should work since the modification is happening once the child is parented (I might have multiple children to make bigger)

gusty aurora
#

But adding WaitForEndOfFrame(); at the beginning of the Coroutine solves it

heady iris
#

I'd just use yield return null; to wait until the next frame

#

but that'll let you start moving on the same frame that you start the coroutine, i suppose

gusty aurora
#

No that's worse

#

yield return null means I skip a frame

heady iris
#

yeah, that makes sense

gusty aurora
#

print(Time.frameCount);
yield return new WaitForEndOfFrame();
print(Time.frameCount);
=> prints 101 101

print(Time.frameCount);
yield return null;
rint(Time.frameCount);
=> prints 101 102

heady iris
#

There is one very minor issue to worry about here

#

WaitForEndOfFrame() doesn't work if you don't have the game view open

#

(e.g. if you switched to the scene view)

#

Not a problem for the built game, but it could be a nuisance in the editor.

gusty aurora
#

Oh I didn't know about that

#

Actually it feels somewhat counter-intuitive that the first block returns 101 101

gray mural
heady iris
#

Waits until the end of the frame after Unity has rendered every Camera and GUI, just before displaying the frame on screen.

#

Unity is done preparing the frame, but we haven't moved on to the next frame yet

gray mural
#

That was sarcasm awkwardsweat

heady iris
gusty aurora
#

So that means that whatever happens after will not be rendered this frame

gray mural
#

Everything that happens between the yields will happen in the same frame

#

So when waiting for the end of the frame, everything after that will happen in the current frame and stop just before reaching the next yield return

// frame 101
yield return new WaitForEndOfFrame();

// frame 101
transform.position = ...
foreach (...

yield return null;
// frame 102
// ...
gusty aurora
#

Will that transform.position be rendered to the screen in frame 101 ?

heady iris
#

but the point of WaitForEndOfFrame is that it waits until after everything is rendererd

#

this runs after the main camera has already rendered

#

you will not see the new position until frame 102

winged crane
#

How would I go about dynamically creating text at runtime which starts above 2D scene position (x1; y1) and ends above (x2; y2)? I am trying to create something like this:

sacred frost
winged crane
heady iris
#

Looking for some suggestions about namespacing.

I have an abstract class called Anatomy. It has properties for different points of interest on an entity: where its "center" is, where you'd look at to "focus" on it, etc.

I have derived classes like HumanoidAnatomy and ObjectAnatomy.

Which would you prefer?

  • MyGame.Entities.Anatomies.Anatomy
  • MyGame.Entities.Anatomies.HumanoidAnatomy
  • MyGame.Entities.Anatomies.ObjectAnatomy

vs.

  • MyGame.Entities.Anatomy
  • MyGame.Entities.Anatomies.HumanoidAnatomy
  • MyGame.Entities.Anatomies.ObjectAnatomy
#

I only ever reference Anatomy, if that changes anything.

#

I'm using [SerializeReference] so that I can pick a specific child class in the inspector

vestal arch
#

i don't have much experience with the c# ecosystem and how namespaces are usually named, but to me having MyGame.Entity.Anatomy.*Anatomy would be cleanest

#

with the Anatomy class in the same namespace

silent tapir
#

whats good fps for 1.5M tris in unity

warm canopy
# spring creek Sorry, busy with my daughter. That does not look like a false error. Been a whil...

I have made and been making changes to the code despite that VS editor error. Unity plays and runs no problem and unity itself does not detect any error. Originally, this "popped up" after I updated unity and that was 4 minor versions ago, and been living with it since. someone from the DOTS forum told me to delete the VS cache, etc, and though I thought I've done that, I may not have done it correctly and wanted to make sure if someone else might know better. but ultimately, I just want the editor to not see that line as an error.

somber nacelle
#

errors appearing in VS but not the console usually means you just need to regenerate project files. if that doesn't fix it you might need to regenerate the entire Library in the project

warm canopy
#

ahh, how do I "regenerate" the project files? im pretty sure that's a manual process, can you point me to instructions?

somber nacelle
#

in the external tools settings in the editor preferences

spring creek
#

For the library, that just means wholesale deleting the library folder from the root of the project folder while unity is closed. It will take a while to reopen unity because it will regenerate it

warm canopy
#

sorry, where do i find the external tools menu?

somber nacelle
#

in the unity editor you need to open the preferences in Edit > Preferences

swift falcon
#

Is the return function no longer used in Unity?

somber nacelle
#

huh?

heady iris
#

well, the return statement sure still exists

#

the year is 20XX. C# is now 100% continuation passing style

swift falcon
somber nacelle
#

why don't you share the actual error and relevant code instead of making wild assumptions

heady iris
#

Perhaps you are not in a context where return is legal

#

Show what you are trying to do.

warm canopy
heady iris
#

Make sure to close your code editor and reopen it

warm canopy
heady iris
#

Before you delete the library folder, I mean

#

When you do that, close unity, delete the library, and reopen unity

heady iris
vestal arch
#

look at your indentation

#

it is outside the method

warm canopy
heady iris
# swift falcon

Your code editor is doing its best to turn return into a legal statement

heady iris
swift falcon
heady iris
#

well, write your code inside of the method

spring creek
warm canopy
#

Yea, that was a real annoying problem that crept out of nowhere seemingly. I'm glad I don't have to see that anymore 😄

knotty sun
steady moat
slate blaze
#

Am I initializing this component wrong? I created that "PositionChangeTracker" component and every time I initialize it as the variable "pct", pct is null

#

I would rather just initialize the component in the script rather than having it be a public variable that I need to drag and drop yk

vestal arch
heady iris
#

they also make it more clear what object you're using

heady iris
#

also, what component is that script on the left from?

#

you don't get bonus points for showing really tiny crops; please provide more complete information

slate blaze
#

Thanks for the advice brother. No need for hostility, here you go

heady iris
#

A valid reference has been assigned here.

#

Are you having a problem?

vestal arch
#

how are you verifying that pct is null? you aren't checking or using it

slate blaze
#

Right, I would rather it be private than have to drag and drop it. But it won't let me initialize it the same way I can initialize my rb2d. Yes pct is null if it is not dragged into the public variable, I debug.logged it

#

Line 19 is where I have the problem

vestal arch
#

you're grabbing the sibling PositionChangeTracker on the gameobject, overriding the value you set in the editor

#

do you want it public and set in the editor, or a separate component automatically grabbed from the gameobject?

heady iris
slate blaze
#

right right that is what I am trying to do. I want to override it

#

I don't want to set it in the editor I want to set it in my script

heady iris
#

You aren't using it anywhere else in your script, so I don't understand how you know that pct is getting a null reference assigned to it

#

Are you looking in the inspector at runtime?

vestal arch
#

or a property

#

or add the nonserialized (i forget the name) attribute

slate blaze
#

That is the problem. When I make it private and initialize it that way it is null

#

One sec, I will show you

vestal arch
#

...why were you showing working examples before? why didn't you lead with the actual problem? polded

heady iris
#

If you got an error from somewhere else in the script, then I'll need to see that part of the script

#

Nothing in the code you shared uses pct.

#

!code

tawny elkBOT
slate blaze
#

Sorry! I was showing my workaround and trying to explain my problem. 🤦‍♂️

#

@fen. I can show you, but that isn't the problem part

heady iris
#

I bet it really is.

#

unless it's just later in the Update method

#

Either way, I'd like to see the full code that's causing the problem, with no modifications

slate blaze
#

I fixed it 🤦‍♂️

#

I really don't know what the heck it was but when I put the code back the way it was when there was an error it works.

heady iris
#

Perhaps you hadn't saved.

slate blaze
#

Probably something stupid like that. Thanks for yall's input. What does the serialized field do anyway?

vestal arch
#

it lets you set the value in the editor

slate blaze
#

But why not just use public? Just so other scripts can't access it?

heady iris
#

Correct.

#

You want to minimize how much "stuff" is visible from outside of your class

#

That helps you to separate your interface -- how you interact with the class -- from its internals

#

it also tidies up your editor suggestions

#

you don't want to see 100 random variables when you do myClass. in VSCode

#

[SerializeField] tells unity that you want that field to be serialized, which means that it gets saved as part of scene/prefab data

slate blaze
#

Huh, I gotchu. Is that an optimization thing or just a quality of life thing?

heady iris
#

the opposite is [System.NonSerialized], which indicates that a field should not be serialized

#

which is appropriate for public fields that you don't configure in the inspector

heady iris
#

It's particularly important if other people use your code

chilly surge
#

More than just QoL, it's how you build maintainable software.

heady iris
#

"quality of life" is getting stretched a bit here, yes 😛

heady iris
vestal arch
slate blaze
#

I have fallen in love with the unity events system for modularity. It is a godsend

chilly surge
#

It's especially important if you work in a team, if the internals of a class are always exposed and other team members can just publicly alter your internals, then if you ever want to change internals you can't, you have to also start modifying other team member's code which are using your internals.

slate blaze
#

That's really interesting. I have only done solo projects so I haven't had to worry about that lol

chilly surge
#

Yeah a huge part is that you want to maximize team members' ability to work independently and not stepping over each other. If you making one small change to your class means that you need to modify everyone else's code, then no one can be working simultaneously.

heady iris
#

In a solo project, it's still nice to not have to go analyze every single random public field, too

#

All of my old code is 100% public fields (whenever I needed serialization, that is) and I don't like it

chilly surge
#

There's no point in having a 10 person team if only ever 1 person can be working at a time 😄

heady iris
#

fortunately, all of the bad code was written by Past Me, not Present Me

#

clearly not my fault

slate blaze
heady iris
#

you can incrementally make members private

#

check if you have references from outside the type

#

if they exist, see if you can get rid of them without too much work

#

once there are no external references, make it private and add [SerializeField]

slate blaze
#

That's a good idea

heady iris
#

My components often start out as just "bags of data" with a bunch of public fields

#

then I add methods to interact with them and make the fields private

#

(especially for stuff like UI prefabs)

chilly surge
shell scarab
#

aren't collision and trigger calls suppose to be sort of propagated upwards and and call any trigger/collider calls in parents?

chilly surge
#

Fundamentally working on one part of the code base blocking the ability to work on other parts of the code base is just not ideal.

heady iris
#

They do get sent to a parent object with a Rigidbody on it, though

#

Triggers get sent to both the collider's object and the rigidbody's object

#

Collisions only get sent to the rigidbody's object

shell scarab
#

But that makes sense, the rigidbodies in the parents

#

I was like I know i've seen this behavior before

signal lance
#

Anyone here who can help me with object pooling?

heady iris
#

Unity has built-in pool classes

#

for example

#

ObjectPool will use the methods you give it to correctly create and destroy pooled objects

#

the example on that page turns off the particle system when you return one, and turns on the particle system when you take one

slate blaze
shell scarab
#

not ideal, sometimes unavoidable

heady iris
shell scarab
#

yes, I just double checked myself before saying it's wrong, and I've done it before too.

heady iris
#

so you have a Rigidbody component on a parent object

#

and you received an OnCollisionEnter message on the object with the collider?

shell scarab
#

yes

#

I think

jaunty sleet
#

I am trying to write a shader to fade between the color of objects in my scene and the skybox color based on distance from the camera, but my distance calculation method is not working. It is returning all 1, resulting in the objects being invisible because only the skybox color is being shown. Does anyone know how I could fix this? https://paste.ofcode.org/GmNB7J5gQULwRT7aAcpsNq

shell scarab
#

I had a rigid body on an object, which I had collide with a collider that had a script on it logging OnCollisionEnter messages.

stable lintel
#

how does terrain pixel error work

heady iris
#

I'm talking about an object with a parent that has a rigidbody on it.

shell scarab
#

Ah okay, yes that I know. I thought you were talking in general for all those messages you sent.

heady iris
shell scarab
#

I wish the documentation clarified exactly what happens :/

heady iris
#
  • Rigidbody
    • Collider <- trigger

If this hits a collider (trigger or not), both objects receive the message

#
  • Rigidbody
    • Collider <- non-trigger

If this hits a trigger, the Rigidbody's object gets a message

heady iris
#

I'm thinking of making a WebGL project that demonstrates the different behaviors. Might be useful.

shell scarab
#
  • Object (non-rigidbody)
    • Collider <- trigger/non-trigger

And here, only collider receives it.

heady iris
#

Right, that's expected

umbral bolt
#

My code is supposed to add movement on the X and Y as. When I try to run, it gives a compile errors. I cannot seem to find what I did wrong. Could I get some help with this please?

||
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour {
//Movement controlls
public string forwardMovementKey = KeyCode.W;
public string backwardMovementKey = KeyCode.S;
public string leftMovementKey = KeyCode.A;
public string rightMovementKey = KeyCode.D;
//Movement
public float movementSpeed = 5.0f;
private Vector3 movementDirection;

// Update is called once per frame

void Update(){
   movement();
}
void movement(){
    if (Input.GetKey(forwardMovementKey)) {
        movementDirection += transform.forward;
    }       
    if (Input.GetKey(backwardMovementKey)){
        movementDirection -= transform.forward;
    }
    if (Input.GetKey(leftMovementKey)){
        movementDirection -= transform.right;
    }
    if (Input.GetKey(rightMovementKey)) {
        movementDirection += transform.right;
    }
  

    
   // if (Input.GetKey(KeyCode.Space)) {
  //      jump += transform.up;


    // Prevent diagonal movement being faster (optional)
    if (movementDirection.magnitude > 1.0f){
        movementDirection.Normalize();
    }

    // Apply movement
    transform.Translate(movementDirection * Time.deltaTime * movementSpeed);
}

}
||

vestal arch
#

!code

tawny elkBOT
vestal arch
#

if you could say what the errors are too that would help

fleet gorge
#

its how to make funny code blocks
like this

#

backtick, `
not to be confused with apostrophe, '

umbral bolt
#
// using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour {
    //Movement controlls
    public string forwardMovementKey = KeyCode.W;
    public string backwardMovementKey = KeyCode.S;
    public string leftMovementKey = KeyCode.A;
    public string rightMovementKey = KeyCode.D;
    //Movement 
    public float movementSpeed = 5.0f;
    private Vector3 movementDirection;

    // Update is called once per frame

    void Update(){
       movement();
    }
    void movement(){
        if (Input.GetKey(forwardMovementKey)) {
            movementDirection += transform.forward;
        }
        if (Input.GetKey(backwardMovementKey)){
            movementDirection -= transform.forward;
        }
        if (Input.GetKey(leftMovementKey)){
            movementDirection -= transform.right;
        }
        if (Input.GetKey(rightMovementKey)) {
            movementDirection += transform.right;
        }



       // if (Input.GetKey(KeyCode.Space)) {
      //      jump += transform.up;


        // Prevent diagonal movement being faster (optional)
        if (movementDirection.magnitude > 1.0f){
            movementDirection.Normalize();
        }

        // Apply movement
        transform.Translate(movementDirection * Time.deltaTime * movementSpeed);
    }
}
vestal arch
#

ok so what's the issue you're having

umbral bolt
#

It gives a compile error. I have no clue what is wrong and would like to receive help how I can figure out where the error is

fleet gorge
#

erm whats the error

vestal arch
#

ok what's the error though

#

i would rather not roleplay a compiler today

umbral bolt
#

It's a syntax error

vestal arch
#

what's the error

#

what does it say and where is it highlighting

dusk apex
#

Probably cannot convert from key code enum to string implicitly - unless there's an overload.

#

But yeah, you'd actually have to provide the error

vestal arch
#

it's an enum, so maybe

fleet gorge
#

I decided to be nice and execute foreign code on my computer

#

ok so

#

Keycode.W is not a string

vestal arch
#

you didn't execute it, it has a compiler error

#

@umbral bolt so if you're not gonna let us read the error, at least read the error yourself

umbral bolt
fleet gorge
#

thats not the correct error but eh

#

do you know what Keycode.W is

#

or Keycode.S

vestal arch
# umbral bolt

scroll up in the console, and have you set up your ide

umbral bolt
vestal arch
#

!ide

tawny elkBOT
vestal arch
#

that would help you a lot

#

go do so

umbral bolt
fleet gorge
#

do you know what type it is?

#

Keycode.W is not a string

#

what is Keycode.W

vestal arch
#

go set up your ide so your ide can tell you

fleet gorge
#

fun fact of the day: hovering your mouse over a variable can tell you what it is

vestal arch
fleet gorge
#

ive always wondered, doesn't unity install come with visual studio?

rigid island
#

minecraft font UnityChanLOL

fleet gorge
#

ive used it for two years my friends say its unreadable

rigid island
#

lol as long as you can read it all it matters

fleet gorge
#

but i love it

rigid island
#

just thought it was funny

fleet gorge
#

🎊

rigid island
#

i know someone uses calligraphy font so you're safe xD

knotty sun
vestal arch
frosty coral
fleet gorge
#

quick survey react if you use vscode vscode or codeblocks 🧱 for unity

rigid island
vestal arch
#

codeblocks is shit...

fleet gorge
#

i want to see how many vscode users i run into in the wild

dusk apex
fleet gorge
frosty coral
fleet gorge
#

never again

vestal arch
fleet gorge
#

LMAO

vestal arch
# rigid island whats codeblocks?

Code::Blocks is a free C/C++ and Fortran IDE built to meet the most demanding needs of its users. It is designed to be very extensible and fully configurable.

rigid island
#

oh yeah Ill stick to vscode then

#

VS on windows ofc

vestal arch
#

i was in a computer olympiad and the stock computers had vscode, sublime, and codeblocks. literally noone i knew used codeblocks

fleet gorge
vestal arch
#

no clue

fleet gorge
#

i fail to understand

#

esp when theres a whole megacorp behind the top ide for java

vestal arch
#

alphabet 🤗

fleet gorge
#

as much as I hate java intellij is so cool

rigid island
dusk apex
vestal arch
#

i use android studio for non-android java... intellij just doesn't like to work for me for some reason...

fleet gorge
#

isnt android studio a fork of intellij?

frosty coral
vestal arch
#

yes

fleet gorge
#

that is very interesting

vestal arch
#

yeah i have no idea what's up with my situation

fleet gorge
#

for me i was the opposite I used intellij with android for one of my modules

#

simply because I prefer modern intellij UI

vestal arch
#

wasn't even like. static analysis or anything fancy that broke either

fleet gorge
#

I wish I could make UIs like them PomPom_Cry2

vestal arch
#

the whole damn ui broke

#

the layout was right but the background color was the warning color except in the gutter and at the very top

#

so perplexing

chilly surge
#

Every time I open Android Studio, it hogs all the RAM to itself.

vestal arch
#

isn't that all google products though

chilly surge
#

No clue.

#

Maybe they just expect people who use Android Studio to have infinite RAM or something.

vestal arch
#

but with the sponsor of today's video, oper-

rigid island
frosty coral
vestal arch
#

if you don't get a log you can't know if the values are correct or if that check just wasn't reached

rigid island
#

yes I see the else statements are there if component is null but was simple asking to add debug.log inside here

  if (audioSource != null && gunshotSound != null)
        {
            audioSource.PlayOneShot(gunshotSound);
        }```
#

it could be hitting it and maybe their volume is muted or low, thats why we triple check and debug 🙂

vestal arch
#

meanwhile me deleting all the logs after "fixing" it only to have the same issue a few minutes later and have to rewrite all the logs

fleet gorge
#

if you have vs set up for unity you should try pressing the big green button

#

I didn't know about this until 2 years after starting unity

#

fun watch but atrocious font

#

this will help you a lot in your journey rather than spamming Debug.Log everywhere(I still do that)

#

take great care in your art, especially because you prob wont come back to it later

heady iris
#

my philosophy is that you should either:

  • do it as fast as possible as a placeholder
  • do it really well
#

if you spend a while but still need to replace it, then that sucks

fleet gorge
#

plan out the classes you need first.
an inventory has a list Items. an Item has a name, icon, description etc.

public class Inventory {
  List<Item> items = new();
}
public class Item {
  string name, description
}

now you need a system to read from inventory. you also need a prefab to act as an item icon.

public class InventoryDisplay {
  [SerializeField] GameObject p_itemIconl
  void ShowInventory(Inventory inv) {
    // for each item in Inventory.items, show the item icon and count.
  }
}
#

something like this

#

I should make a tutorial on this

glass rover
#

anyone able to help me understand why i cannot get an object to enable and another to disable
this seems so simple

fleet gorge
#

what does this mean

#

show the code you used

rigid island
glass rover
#

Ui -> Button (Text Mesh Pro)

Can get game objects I want when I click a button to enable and hide what I want properly

But using the legit same script to revert it back to the previous enabled/disabled state of the game objects

does not work.

fleet gorge
#

so you
• add a event to the button to set a gameobject active
• add another event to the button to set a gameobject inactive

fleet gorge
#

if you want to toggle it, you need a script rather than depending on those two events

#

We have no idea what your script currently does

rigid island
#

at very least in code channel you should be sharing the !code 🙂

tawny elkBOT
glass rover
#
using UnityEngine;
using System.Collections;

public class PondCloseButtonScript : MonoBehaviour
{
    public GameObject gamePanel;
    public GameObject pondPanel;
    public float switchDelay = 10f; // Time in seconds to switch to the pond panel
    public float revertDelay = 10f; // Time in seconds to switch back to the game panel
    public bool showDebugLogs = true;

    private void Start()
    {
        // Ensure the gamePanel is active and pondPanel is inactive at the start
        if (gamePanel != null)
        {
            gamePanel.SetActive(true);
        }

        if (pondPanel != null)
        {
            pondPanel.SetActive(false);
        }
    }

    // Method to switch from gamePanel to pondPanel
    public void ShowPondPanel()
    {
        if (gamePanel != null && pondPanel != null)
        {
            StartCoroutine(SwitchPanelWithCountdown(gamePanel, pondPanel, switchDelay));
        }
    }

    // Method to switch from pondPanel to gamePanel
    public void ShowGamePanel()
    {
        if (pondPanel != null && gamePanel != null)
        {
            StartCoroutine(SwitchPanelWithCountdown(pondPanel, gamePanel, revertDelay));
        }
    }

    private IEnumerator SwitchPanelWithCountdown(GameObject panelToHide, GameObject panelToShow, float delay)
    {
        float countdown = delay;
        while (countdown > 0)
        {
            if (showDebugLogs)
                Debug.Log($"Switching in {countdown} seconds...");
            yield return new WaitForSeconds(1f);
            countdown--;
        }

        panelToHide.SetActive(false);
        panelToShow.SetActive(true);

        if (panelToShow == pondPanel)
        {
            Debug.Log("Success: Switched to PondPanel.");
        }
        else if (panelToShow == gamePanel)
        {
            Debug.Log("Success: Switched to GamePanel.");
        }
    }
}
#

i do not understand why this does not do what intended

rigid island
#

is your Timescale set to 0 ?

glass rover
#

so i designed this since for whatever reason I already have designed in a much larger web of scripts does not swap me back to begin with. So i copy pasted the button that originally did this and added an empty game object and put this on it to try and auto hide it after 10 seconds and even this doesnt work.

#

so im starting to think its something based on game objects or something i legit have zero unity experience im just making something for fun

#

well no zero, ive made vr chat avatars but with cs i am brand new

rigid island
#

none of this answered my questions but ok 🤷‍♂️

glass rover
#

it doesnt get disabled no

rigid island
#

did you change timescale anywhere

#

put debug.log both inside where you cal StartCoroutine and the Coroutine itself

glass rover
#

i think so but on another script

rigid island
glass rover
#

ahhh

#

okay

fleet gorge
#

the bandage to this is to use WaitForSecondsUnscaled

#

the unscaled one

rigid island
#

Realtime

fleet gorge
#

yea WaitForSecondsRealtime

glass rover
#

bandage was alreayd in place

fleet gorge
#

There's other places in your code that needs it

glass rover
#

hmm lemme go study rq tyty

runic pawn
#

so I have some scripts in my Assets folder that need to use scripts in my Packages folder, and it seems that in order to do that I need to use assembly definitions? So I tried creating an Assembly Definition in the Packages folder that I need to use scripts from but I get the error:
"FolderAsmDef.asmdef has no meta file, but it's in an immutable folder. The asset will be ignored." it seems no meta file is being auto generated for the asmdef...

fleet gorge
#

erm I don't think that's how it works
what package are you using

#

its probably in a namespace

runic pawn
#

its a crypto wallet SDK... i've tried adding the using namespace to the script i want to use it from but that doesnt work

#

well the weird thing is i can use certain parts of that name space but not this one part that i need...

#

//using Solana.Unity.SDK; -- the one i can't use
using Solana.Unity.Wallet;
using Solana.Unity;

fleet gorge
#

what error does it give?

runic pawn
#

but i can do "using Solana.Unity.SDK" in a different script which is in my Assets folder

#

just not this one

fleet gorge
#

could be a .meta file issue, in file explorer go delete the meta file for the script

runic pawn
#

nope, still same problem, it made a new meta file and same thing

fleet gorge
#

close unity first because it has the meta file in ram

#

im not too sure tbh

runic pawn
#

yeah, ok i'll try

#

ok, the problem is till there

#

seems like something to do with compilation order

heady iris
#

Deleting a .meta file will make Unity thing you've deleted the old script and created a completely unrelated script asset with the same name

#

.meta files are not temporary files.

heady iris
heady iris
kindred plume
#

guys i made an active ragdoll but i wanted to make that when he picks a weapon the hands attach to the 2 empty gameobject (leftHandPlacement, rightHandPlacement). But how do i do that? I don't know if i well explained the problem

lean sail
kindred plume
kindred plume
lean sail
# kindred plume can it work with an active ragdoll? I made the active ragdoll using configurable...

Yes but itll slightly take away from the "active" part. Like a joint would be preetty tough to configure so it actually holds the gun up, not an easy task at all. you'll likely just have the gun by itself. In which case you'll need the joints to pretty much always stay firmly on it, or the gun will visibly be floating.
Animation rigging directly takes away from active ragdoll because it controls the transforms directly

#

Stuff like this you'll need to consider what holding a gun even means, or how you want it to play out when the ragdoll gets hit in the arms

kindred plume
#

that's what i wanted to do

runic pawn
heady iris
runic pawn
#

through Packange Manager and github url

heady iris
#

show me the repository

#

You can't modify the contents of Library/PackageCache. They're generated by Unity automatically, and, as the warning told you, they're immutable

lean sail
# kindred plume the gameplay is all ragdoll active. It's like controlling a dead body

Well yea I read that. That doesnt mean much though. If you look at an active ragdoll in popular games it widely varies. Apparently GTA uses one, which I consider a large stretch of the term "active" ragdoll since it's all directly controlled by animations. Then you look at games like human fall flat where clearly you can see it's not controlled by animations

runic pawn
heady iris
#

The package already contains asmdef files. They're also set to be auto-referenced, so they'll be accessible from the default Assembly-CSharp assembly

#

Are you using asmdefs in your own code?

kindred plume
runic pawn
kindred plume
heady iris
#

find out by searching your Assets for t:asmdef in the Project window

#

If your own code is included in an assembly definition, then you need to make that asmdef reference the Solana SDK assembly

lean sail
heady iris
#

The asmdefs in the package are set to be auto-referenced, so code that isn't included in an asmdef will automatically be able to see it

#

But if you create your own assembly definitions, all references must be assigned manually

kindred plume
lean sail
runic pawn
#

well i have several asm def's popup when i search t:asmdef in Assets, i do recall now i had to include something in one of these before

heady iris
runic pawn
#

from the name sorta, but not exactly what the purpose of it is, no

heady iris
#

have a read about them here

runic pawn
#

ty

heady iris
#

You'll need to make your assembly definitions reference the package's assembly definition(s)

#

You won't be modifying the package's contents at all

kindred plume
shadow ridge
#

Hey! I have quite a big problem: no matter what I try I can't know which camera (main camera or scene camera) is rendering. The best I can do is check if the focused view is scene view or game view but that means if I click on another window it doesnt work anymore

lean sail
# kindred plume i can try to solve it by just checking if the box collider is colliding with som...

Sure, if that's the gameplay you want from it where the gun can just kinda stay far away. I'd really consider just having the gun not be a non-kinematic rigidbody though. Unless you really need it to react like the rest of the body, itll likely be better as a child object. Theres a ton of conflicting ideas between an active ragdoll, and being able to firmly grab something or do something in an exact pose. A lot will break

kindred plume
runic pawn
kindred plume
next heath
#

I joined this server to ask for help. For whatever reason, when i move a camera every frame using a script, the camera seems to try to move back to it's original spot right after.
Here is a video of the problem, and the code that seems to be causing the issue.
THE VIDEO CAN POSSIBLY POSE AN EPILEPSY RISK, SO WATCH ON YOUR OWN DISCRETION.

next heath
rigid island
#

you can just use cinemachine

next heath
#

all i want is just a solution to my problem, and i'll be good

rigid island
#

how's a mirror effect relate to positioning

next heath
next heath
#

i'm trying to achieve something like this, if it's not ideal, then i could happily take some feedback

rigid island
next heath
rigid island
#

I'm fully aware what a mirror is

next heath
#

i'm kind of confused, what are you asking again?

rigid island
#

it was half a question and half a suggestion statement.

next heath
#

do you know how to fix my issue though? that's all i need, lol

rigid island
#

if you already have a second camera, output it to a Render Texture, use it on a quad

#

what you're doing with position does not make sense to me, take the advice or don't

next heath
hasty wave
#

Why is unity so buggy when it comes to booleans?

spice frost
# next heath I joined this server to ask for help. For whatever reason, when i move a camera ...

For your approach, The main issue i think thats happening there is that every frame you are applying the same logic, and since you are moving the object that you are also using as a reference it keeps switching, IDK if maybe changing

mainCamDistance = (MirrorCamera.transform.position - mainCamera.position)

to

mainCamDistance = (this.transform.position - mainCamera.position)

, since I assume you want the x value between the mirror and the main camera, not the mirroCamera and the main camera. I might be misunderstanding though

next heath
#

there's that, if it helps

#

(and yes i had it enabled when in play mode)

hasty wave
spice frost
# next heath ok so basically the "MagicMirror" script/component is gonna be in a gameobejct w...

regardless of the setup, i want to point out something: Imagine your case when mirrorcam.x is 3, and mainCam.x is 1 and mirrorCamOrigin is 0

you do the math in one frame and end up with

mirrorcam.x being -2

next frame you have mirrorcam.x being -2, mainCam.x being 1, mirrorCamOrigin being 0

you do the math that frame and end up with

3

so, thats why it keeps going back and forth, as for the whole approach I cant say much about it, been a while since ive played around with render textures /cameras

spice frost
# hasty wave My code stopped function properly entirely all of a sudden, it was functioning p...

You may actually never be hitting the exact value of 95f, you may be jumping from 94.90 to 95.6 in a frame for example, and your check wouldn't work.

Try printing the value in your update and see what the value is when you are expecting it to be 95.

You could try doing (int) HDS.lustValue == 95 to round the value to an integer and compare that, or do another approach at detecting when the threshold is reached. like maybe having a bool "lustReached" that is false and do

if(!lustReached && HDS.lustValue > 95)
{
  Debug.Log("Reached");
  lustReached = true;
}
#

the not-exactly-95 issue is probably caused by this:

Lust.value += 10f * Time.deltaTime;

hasty wave
spice frost
#

you would need to detect somewhere and actually program the cap

if(value > 100) 
{
  value = 100
}

dont have slider behaviour in my head atm so im not sure if the max is set to 100 if it would be able to go above it via code

#

but your line 37 in first script will be improbable to trigger. you would probably need luck to have the exact number be 95

hasty wave
#

it won't go above 100 if you set the max value of the slider to 100.

My if statement was 100f to trigger before but changed it to 95f to debugg somethings... I don't understand why it stopped working altogether because of those booleans

spice frost
#

did you also change your sliders max to 95? if not then your value probably goes from less than 95 to more than 95 without being exactly 95 at any frame thus the check not being true

spice frost
hasty wave
soft shard
#

Im trying to think of a way I could manage different "surface contact" in my game for footsteps, things like walking on metal, grass, wood, etc, rn the best approach that comes to mind is to make a dictionary with a texture/material name as Key and a list of audio files as Value, but this relies on every texture/material in the scene to have a specific name, and I feel that could be difficult to manage - the only other alternative I can think of is to add a script to every surface in the scene with a enum, then the dictionary can be a enum Key instead, but this also means every walkable surface and prop/physics object needs a script with a proper enum assigned for every map, and that sounds like it can be easy to forget when building and changing map designs, any ideas on an alternative approach or is this enum-list key/value script on every surface probably the best for my use case?

timid briar
#

@soft shard hii

iron vortex
#

Anybody know how to do a logical check for the velocity of a Rigidbody? I'd like to do a gate such as "if object.velocity < however you're supposed to represent a Vector3 type"

#

in order to check if the object is moving less than however many units per second in any two or three directions

wraith spear
#

I'm having some trouble with setting a direction for my particle system... Some help would be great.
Current code: https://hatebin.com/qawwlzwilk

I've tried a few things, but nothing seems to work as expected. I seldomly use Quaternions, and always struggle with them.
When testing, my current code sets X to around 4, while it should be 180.

I'm spawning the ParticleSystem on character A, and the PS needs to look at character B.
The current Y and Z rotations are correct, I only need to modify the X.

So let's say character A is standing at (0, 0, 0) and B is at (5, 0, 0), then I would need X to be 270
If character A is at (0, 0, 0) and B is at (-9, -9, 0) X would be 135, etc.
Z is always the same (2D)

All advice would be immensely appreciated!

maiden fractal
wraith spear
#

I think I got it, however, but I still need to do some more testing:

Vector3 direction = (target - particleSystem.transform.position).normalized; Quaternion rotation = Quaternion.LookRotation(direction); float x = rotation.eulerAngles.y; // Not sure why the Y rotation corresponds to the expected X, but it seems to work

gray mural
#

If you're referring to the Vector, which means position, there is no way to simply get the direction out of position without any additional variables

wraith spear
gray mural
#

But it seems that you have 2 positions in the code you've provided, so it's fine

wraith spear
gray mural
#
Quaternion rotation = Quaternion.LookRotation(direction, Vector3.right);
gray mural
# wraith spear I get it! Yeah, that would be difficult. I think it's easier for me if I underst...

There is really nothing hard to understand in what I've just said.
Imagine having a branch on position (1, 1, 1).
Now you're asked what's the direction of this branch.
Well, how would you know its direction if you're only told its position?
If you're now asked what's the direction in which the 1st tip of the branch is facing, which is the difference between the branch's 1st and 2nd tips, you can now surely answer it.

wraith spear
gray mural
#
// Returns the arc-tangent of f - the angle in radians whose tangent is f
Mathf.Atan(offset.y / offset.x);

// Returns the angle in radians whose Tan is y/x
Mathf.Atan2(offset.y, offset.x);
#

Atan2 is just a fancy way to write Atan with 2 parameters

gray mural
wraith spear
woeful leaf
#

Hey does anyone have the specific page for me that involves lambda capturing on this website?https://unity.huh.how/

#

I know it's there but I cannot find it

mellow sigil
#

There's a search field at the top right side, type "lambda" there

woeful leaf
#

ah

woeful leaf
#

Thanks!

hollow moon
#
    {
        if (inputSeed == "")
        {
            SetRunSeed();
        }
        else
        {
            SetRunSeed(inputSeed);
        }
    }

    private void SetRunSeed()
    {
        //Create an 8 digit long seed.
        for (int i = 0; i < 8; i++)
        {
            currentRunSeed += Random.Range(0, 10) * Mathf.RoundToInt(Mathf.Pow(10, i));
        }
        Random.InitState(currentRunSeed);
    }

    private void SetRunSeed(string _inputSeed)
    {
        currentRunSeed = _inputSeed.GetHashCode();
        Random.InitState(currentRunSeed);
    }

How would I go about converting my randomly generated seeds into strings I can display to the player that have the same seed when passed into the hash function?

chilly surge
#

GetHashCode should not be relied upon to give the same result for the same string every time.

hollow moon
#

Would you explain?

chilly surge
#

There's no requirement that it has to return the same value for the same object every time besides in the same run of the application, so it's possible that a string generates one hash code in one run, and you close the game/reopen the game and it generates a different hash code, effectively making your random seed unstable.

hollow moon
#

So unity's hash function is somehow based on the random seed they generate on startup?

chilly surge
#

This has nothing to do with Unity, GetHashCode is a .NET thing, and it's not required to be implemented to be stable across multiple runs.

#

It may be stable, it may not, that's why you shouldn't rely on it.

hollow moon
#

I'm feeling like that clashes with my understanding of the purpose hashcodes/tables but I'm probably misunderstanding something.

#

I guess my question is what would you suggest I do instead to get consistent translation between seeds?

chilly surge
#

Use an algorithm like SHA1/SHA256/murmurhash/MD5/etc, depending if you care about it being cryptographically secure.

chilly surge
hollow moon
# chilly surge `GetHashCode` is used as a preliminary step to speed up comparisons. It's not de...

Thanks for the help. This is the solution I came up with, exited out of unity a few times and everything seems to be working.

    {
        if (inputSeed == "")
        {
            GenerateRandomSeed();
        }
        else
        {
            SetSeedBasedOnInputSeed();
        }
    }

    private void GenerateRandomSeed()
    {
        Hash128 newHash = new Hash128();
        int randomlyGenoratedSeed = 0;
        //Create a random 8 digit long seed.
        for (int i = 0; i < 8; i++)
        {
            randomlyGenoratedSeed += Random.Range(0, 10) * Mathf.RoundToInt(Mathf.Pow(10, i));
        }
        //Add it to our hash, converting to string.
        newHash.Append(randomlyGenoratedSeed.ToString());

        //Set the inputSeed variable to the random number we just generated.
        inputSeed = randomlyGenoratedSeed.ToString();

        //Compute Hash
        currentHashCode = newHash.GetHashCode();
        Random.InitState(currentHashCode);
    }

    private void SetSeedBasedOnInputSeed()
    {
        Hash128 newHash = new Hash128();
        //Add our input string to our hash.
        newHash.Append(inputSeed);

        //Compute Hash
        currentHashCode = newHash.GetHashCode();
        Random.InitState(currentHashCode);
    }
chilly surge
#

That still does not guarantee to work, please just forget about GetHashCode existing at all.

hollow moon
#

It's from a different class. It's the implimentation within Hash128

chilly surge
#

Once you have the hash, extract whatever amount of information you care about and then use that as the seed directly, do not pass that through GetHashCode again.

#

This piece of code is not guarantee to work correctly:

currentHashCode = newHash.GetHashCode();
Random.InitState(currentHashCode);
heady iris
#

It looks like this particular struct does have a deterministic GetHashCode implementation

#
    public override int GetHashCode()
    {
        return u64_0.GetHashCode() ^ u64_1.GetHashCode();
    }
chilly surge
#

Even if it does, that's just not something you should be relying on. It's not required to have this exact implementation everywhere.

vocal raptor
#

Why can I not change my playersVelocity with this?

        Vector3 playerRotationAngle = playerRigidBody.transform.rotation.eulerAngles;
        playerRigidBody.linearVelocity = Quaternion.Euler(0f, playerRotationAngle.y, 0f) * playerRigidBody.linearVelocity;```
I want him to keep his velocity/momentum, but it just spins him in circles
heady iris
#

I don't see any other way to extract the result from Hash128, other than turning it into a string and then truncating it

heady iris
chilly surge
#

Maybe use something else that allows you to directly extract an int out of it then. The point is that it's just a misuse of what GetHashCode is meant to do, even if it just happens to work for this case.

heady iris
late lion
#

They're implementing a string based seed, but UnityEngine.Random expects an integer.

hollow moon
heady iris
#

Are strings allowed to be completely arbitray strings?

#

Your code generates a random 8-digit number

hollow moon
#

Yes. Only because I was unsure how else to handle generating a random string.

#

You can see that the input will take whatever string you provide it. It's just that the system will only randomly generate 8 digit numbers as seeds if one is not provided.

chilly surge
#

You can simply:

  • For the case of completely random, randomize an int and pass that to the Random.InitState.
  • For the case of user inputting a string, use a deterministic digest algorithm (not GetHashCode) and extract an int amount of data out of it, and pass that to the Random.InitState.
#

GetHashCode is not meant to be used in this way, even if it just happens to work.

heady iris
#

here's what I would do:

string input = "asdfjadsfklafjds";
var bytes = Encoding.UTF8.GetBytes(input);
var hashFunction = SHA256.Create();
var hashed = hashFunction.ComputeHash(bytes);
int result = BitConverter.ToInt32(hashed.AsSpan(0, 4));
#

Run the string through a hash function and truncate the result to 4 bytes

chilly surge
#

I've seen software which gives different result when run on different operating system, because they used GetHashCode for the wrong purpose.

heady iris
#

You now have a completely random integer

#

This will work for any string, no matter how long it is

#

including 0-length strings and strings with emojis in them

#

today's random seed is 💯 👻

heady iris
chilly surge
#

Yep same as I said, digest the input, grab an int amount of data and use it as seed.

late lion
heady iris
#

You can plug whatever hash function you want in there

rose stream
#

Hello

#

needed to know if this is possible

#

suppose i have a binary reader

#

in a specific class

#

that reads a specific file format i created

gray mural
#

ScriptableObject proper event subscription & unsubscription

rose stream
#

now suppose i am using a file explorer and loaded 3 files and used that custom binary reader class i wrote for reading the file format i created

#

i loop through 3 files

#

and load all their data

vestal arch
#

could you just send a single message to explain your problem

rose stream
#

but is there a way to do this asynchronously
like when one file is loaded
it tells back

#

the other file is loaded

#

it returns the name of the file

#

more like a loading bar that completes when all the files are loaded
rather than the whole game pausing till the code is not finished loading all those files

#

in my case
I am loading more than 200 files
so i need a way to create a loading bar

rose stream
chilly surge
#

Depends on if your loading is IO bound or CPU bound.

rose stream
chilly surge
#

Then profile it to figure out.

rose stream
#

and i am loading mostly everything in memory and after getting the information
i release all the unused memory as well

#

Also what is IO?

chilly surge
#

Reading the files from disk, in your example.

#

If it's IO bound, it's very easy to just change only the IO to async and keep everything else in main thread. If it's CPU bound then you'd need to move things to a separate thread to do your deserialization.

fervent furnace
#

input/output
the input/output between your cpu and peripheral eg your disk

rose stream
#

how to profile it?

#

i never used it before!!

hollow moon
#
    public void InitializeRun()
    {
        if (inputSeed == "")
        {
            GenerateRandomSeed();
        }
        else
        {
            SetSeedBasedOnInputSeed();
        }
    }

    private void GenerateRandomSeed()
    {
        string generatedSeed = "";
        for (int i = 0; i < generatedSeedLength; i++)
        {
            generatedSeed += possibleSeedCharacters[UnityEngine.Random.Range(0, possibleSeedCharacters.Length)];
        }
        inputSeed = generatedSeed;


        var bytes = Encoding.UTF8.GetBytes(generatedSeed);
        var hashFunction = SHA256.Create();
        var hashed = hashFunction.ComputeHash(bytes);
        int result = BitConverter.ToInt32(hashed.AsSpan(0, 4));

        outputSeed = result;
        UnityEngine.Random.InitState(result);
    }

    private void SetSeedBasedOnInputSeed()
    {
        var bytes = Encoding.UTF8.GetBytes(inputSeed);
        var hashFunction = SHA256.Create();
        var hashed = hashFunction.ComputeHash(bytes);
        int result = BitConverter.ToInt32(hashed.AsSpan(0, 4));

        outputSeed = result;
        UnityEngine.Random.InitState(result);
    }

Alright. We good with this?

#
    const int generatedSeedLength = 10;
    const string possibleSeedCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
chilly surge
#

Your GenerateRandomSeed can just be replaced with generating the seed directly, rather than generating a random input string and have it go through the same digesting process to get out a seed.

rose stream
#

does this seem ok?

heady iris
#

(But it doesn't do that, so...)

vestal arch
hollow moon
heady iris
#

ah, it goes into inputSeed

#

I missed that this was a field

chilly surge
#

Okay then that makes sense. You can abstract away the repetitive code.

hollow moon
heady iris
#

yeah, only the float version is inclusive

#

(which is kind of weird, too)

vestal arch
#

oh wtf

chilly surge
# rose stream does this seem ok?

The thing you are profiling for is that you need to be able to answer:

  • How long (in milliseconds or whatever unit) does the entire loading process take?
  • What % of that is in IO vs deserialization?
    Then you can decide the strategy afterwards.
vestal arch
#

this is cursed then lmao

heady iris
#

yeah, that's for floats

vestal arch
#

i guess that does make more sense though

rose stream
#

if you meant by file stream

#

some files which are not packed are IO bound and are read through file stream

#

but some files are packed and then are unpacked and then read through memory stream

i dont know what the solution would be

chilly surge
#

Well, it doesn't seem like you have numbers to answer those two questions yet.

chilly surge
#

Whenever comes to a performance related question, the first thing is always to profile it, so you have concrete numbers to analyze. Guessing what the problem might be and throwing random solutions at the wall is never the way to go.

rose stream
#

CPU usage while loading one file

#

28.978 ms

#

is it enough or need some more info?

chilly surge
#

You need to figure out how much time is spent reading the files vs decoding.

heady iris
#

None, as far as I know

#

I didn't know about the Mouse keycodes until yesterday 😛

heady iris
#

So it's halfway there :p

south thunder
#

Hi frens
My coworker is producing code like the following, and I'm curious as to the general consensus.
I'm not crazy about the syntax or string comparison, but I could be convinced it's fine. My real concern might just be that in context, I just see it as hacky workaround used to perform logic based on the name of the game object instead more robust solution.

How could I phrase the theoretical "programmatical" solution in contrast to this solution based in string checking. imo, the script where the name checking switch statements should just be configured with the proper references, maybe with dependency injection. I would prefer just a chain bunch of if-else with string comparison over this strange use of the when keyword in a switch, but maybe that's just me being a curmudgeon.

Opinions?

switch (caseSwitch)
{
    case string s when s.Contains("someValue"):
        // ...
        break;
    // ...
}
heady iris
#

when itself is not strange. This is just pattern matching.

#

However, basing your game logic off of the names of game objects is weird.

vestal arch
heady iris
#

What is this code supposed to do?

#

I need some more context.

steady moat
# vestal arch instead of the gameobject name, maybe use tags?

If this is a simple case, it might be best to actually keep it as a switch-case/if-else. To make it better you can wrap it in a function.

If this is case is more complicated, you might want to use Reflection, Dictionary or any design pattern that can be adapted to the situation. But, given the information you gave us, it is hard to know what could be better.

chrome berry
#

And if tags aren't enough - because Unity tags are limited to one tag per object - you can make your own interface for a custom tag system, and then any class can implement it

south thunder
#

Sometimes the switch's case's would be all the possible names of the game objects that might be spawned instead of creating a variable to selection functionality.

heady iris
south thunder
woeful spire
#

Tags are horrible, that’s my input.

(Please do educate me if I’m wrong, sometimes I think I know stuff when I don’t)

heady iris
#

indeed!

#

very fragile

chrome berry
heady iris
#

Are you unable to share the full script?

south thunder
#

I can't/shouldn't share the whole thing. He's used the pattern a few times, but I just had never seen the use of "when" in a switch like that before.

#

both the syntax and the use threw me off

heady iris
#

when is fine, but the entire concept is bogus

chrome berry
south thunder
#

For a while I was using tags in OnCollision methods to check if the object was in the right ballpark before calling getcomponent, but I did some research and it's not usually worth it. unless you're dealing with a lot of collisions that don't carry the comonent you're looking for

chrome berry
# south thunder I can't/shouldn't share the whole thing. He's used the pattern a few times, but ...

I use when sometimes when I want a switch statement that operates on Vector2/3 or its Int versions. If I know I am dealing with a variable that will be equal to Vector2Int.Up or Vector2Int.Down, I can check for them. Otherwise you can't use Vector2/3/Int in a switch statement

Well, to be specific, you can't check if a case is equal to Vector2.Left (for example) because that isn't a compiler constant

woeful spire
heady iris
#

I don't think I use tags at all in my game, other than for MainCamera

#

bceause if I want to be able to put something in Group A, I also might want it to be in Group B

#

You can only have one tag

woeful spire
chrome berry
#

So if I want to denote a creature is undead, incorporeal, a member of a certain faction, and other minor traits, I could use a custom tag system

heady iris
#

well, you're going to implement that with a component, aren't ya

chrome berry
heady iris
#

an interface implemented by what?

#

Ah, you're saying you don't want extra empty components on top of your existing ones

#

That is reasonable, especially if the "tags" can only be meaningfully attached to something with that existing component

chrome berry
#

Yeah, any monobehaviour can implement it. Like my base Character class, or Trap class, or Item class, etc.

heady iris
#

in fact, it's more than reasonable in that case

#

it would be wrong to have a component that denotes an "Undead"

#

because you could slap it onto something that isn't even a character

#

that would be semantically wrong

south thunder
#

interfaces are underrepresented in unity dev

heady iris
#

my game is all-in on composition, so I don't really have "tags"

#

an Entity is a "foo" if it has the component that allows it to be a "foo"

chrome berry
#

Interfaces can be over or misused, but they're an excellent tool to break out of OOP overinheritance issues

south thunder
#

You can use GetComponent with an Interface type, its so good.

chilly surge
#

Tags are also fragile because they are just magic strings.

chrome berry
#

Yeah, unity tags are. I usually don't use those

#

An alternative to scriptableobjects as tags in a custom system would be a flags enum (though then you're limited to 32), or a list of enums.

knotty sun
shell scarab
#

Is there any way to add assembly references? I'd like to use Span2D from Microsoft.Toolkit.HighPerformance.dll since I cannot use System.Span2D since that is a later version of c#.

rigid island
#

will it do what you want in unity 🤷‍♂️

shell scarab
#

it is compatible with .NETStandard 2.1 and .NETStandard 2.0, but I cannot figure out how to add the reference...

#

I just want it for the 2D span, since it was in this assembly before it was added to C# in the System namespace.

somber nacelle
#

put the dll in your project and reference it in your asmdef

shell scarab
#

oh so I don't add it through the regular way ok

somber nacelle
#

the "regular way" would be using nuget which unity does not support yet

primal wind
#

Can i kindly point towards NugetForUnity

heady iris
#

I use that, yeah

#

It mostly works!

primal wind
heady iris
#

I have a mysterious asmdef used for nothing in my project that i'm afraid to delete

primal wind
#

It works with all the libs i currently need so there's that

#

Even my own multiplayer lib works there

heady iris
#

I use it for a couple of libraries. It has behaved well.

primal wind
#

I guess as long as they support netstandard 2.1 it's fine

chilly surge
#

I tend to just extract the package and drop the dlls in, unless the transitive dependencies are getting too deep and it's too much manual work.

shell scarab
shell scarab
heady iris
somber nacelle
#

however that doesn't mean that my statement about unity not supporting nuget was wrong though. and it's kind of silly to install one of those for just a single dll they need

white dirge
#

Hello, I hope im in the right section. Sometimes when I close a project all the level layout disappears but only the game objects, but the scripts and the assets are still there. Anybody has any idea why this happens?

heady iris
#

this is not a code problem. it sounds like you have the wrong scene open

somber nacelle
#

if your library is being regenerated for whatever reason then you will need to open your scene again

weak venture
#

Certain things will have it switch to a new untitled scene by default on start so you just need to find your main scene in your assets and open it back up

white dirge
heady iris
#

You can still have a new, un-saved scene open

#

it would be called Untitled

white dirge
#

look, this is all i have. It doesn't seem like I have any new scene

somber nacelle
#

where did you save your scene to

white dirge
#

Well, I just ctrl+s and than close the project. The scene must be saved manual every time?

rigid island
#

you have to be mindful of looking at that

heady iris
#

Create a cube. Save the scene. Close and reopen the editor.

#

The cube should still be there.

iron vortex
gusty aurora
#

For UI, what's the difference between Image, Raw Image and Panel ?

gray mural
weak venture
#

I'm seeing framerate spikes only when profiler is recording on remote machine. I suspect the spikes are due to profiling over network. Is there anything i can do to get an even clearer picture? Can I profile to like a dump file that I then check? Would a direct ethernet connection between game host and profiler help? Or should I just ignore the spikes that seem to only hit when profiler running and just look at the other frames

shut zealot
#

!collab

tawny elkBOT
swift falcon
#

i have a class with a list of Stats, i want to populate the list with all Stats in my database of Stats
so in the default constructor i call this populate function, however it doesn't work when not in runtime since my database is a singleton mono with a list of scriptable objects (i'm simplifying, the scriptable object is a separate class with info to construct the Stat class)
if this a a good way to go about this, what's a fix to this to make it work in runtime or another approach to this?

wintry heart
#

Hey there everyone, so I'm currently working on a Friday Night Funkin Sandbox game in Unity 2D and I have made some progress, now the original game uses a different game engine which didn't agree with my laptop. I have created what's necessary for the game but I'm not capable of making a score/misses system so if anyone would like to help or volunteer that would be great, feel free to reach out to me!

eager fulcrum
#

Hey, I have a public float x = 2f; in a scriptable object, but it is set to 0 in inspector, any ideas why?

#

okay i added another temp field and then x refreshed

#

whats happenin

lean sail
# eager fulcrum whats happenin

you probably didnt recompile after adding the =2f part. values serialized in inspector dont magically change when you assign a default value to anything, that'd break a lot of logic

eager fulcrum
#

it should happen automatically after i save script and go back to unity right?

lean sail
#

you can, by default i believe its whenever you change code and go back to unity. theres an option to change so you have to trigger it manually

eager fulcrum
#

i have it set to trigger automatically

#

like im 99% sure

lean sail
# eager fulcrum like im 99% sure

why guess, just check it. also still doesnt affect what i wrote, i just suggested a possible reason why your value was 0. In that it was probably set to 0 before you added that =2f part

eager fulcrum
#

why guess how can i check it?

somber nacelle
#

in preferences, there's a setting for "Auto-Refresh". if that is disabled then it will not automatically recompile when you save because the assets are not being refreshed automatically

#

there's also some assets that mess with the compilation process like Hot Reload. though theoretically that should be triggering more compilations, however I have seen issues where it was somehow preventing a compilation 🤷‍♂️

eager fulcrum
#

I will just call it a bug and move on

lean sail
#

call what a bug? if you create a new asset does it still set the default values to 0?

eager fulcrum
leaden ice
lean sail
#

hm yea i guess thats a bug. unless you renamed the variable from x to something else

eager fulcrum
#

dunno, maybe Praetor is right and I just did something by mistake

#

we will never know what exactly happened

elder citrus
heady iris
#

It's very very very hard to say anything without seeing the code

astral relic
#

can someone please tell me the bind-pose of a bone of a skinned mesh, its relative to what? is it the world matrix or some matrix relative to root node or what

heady iris
#

i'd expect it to be in the local space of the root bone

#

because that's the space that the local bounds are computed in

heady iris
#

!code

tawny elkBOT
heady iris
#

Your local X and Y axes change as you rotate

elder citrus
#

one thing is missing but what

#

okay i solved

#

i sepereted x and y and made y related to self

unborn sphinx
#

Am I guessing right, that something like this cannot be invoked without a corresponding wrapper method?

somber nacelle
unborn sphinx
cosmic rain
cosmic rain
#

If you just make a wrapper to call it, then it's not an event at all. You might as well remove the event keyword

unborn sphinx
#

I just wanted to keep them in a one event class, but I now took them apart and put them in their respective parent

#

I wanted to be able to call them from one space, like a relay station and evryone would subscribe there (so i don't need to remember which event was where)

#

but yeah... just an idea, not good style

somber nacelle
#

if you search that up you could see many different ways to implement that pattern

unborn sphinx
#

yeah, but I could also leave it now as it is

#

have move it twice now

silent tapir
#

What's the best approach for a spatial inventory system from games like Tarkov and Arma: Reforged?

iron vortex
#

what you suggested works but I'm just curious

iron vortex
#

oh it's a property of Vector3

#

I was thinking it was supposed to be a Rigidbody property

#

or some kind of sub property of its velocity idk

#

thanks though

somber nacelle
#

no, they accessed the magnitude property of the velocity which is a Vector3

iron vortex
#

There any way I might be able to check for specific axes of the vector, like say just X and Z and exclude Y?

somber nacelle
#

just access those properties on the Vector3. or do you mean get the magnitude of the vector without the Y axis

iron vortex
#

the latter yes

#

I think the Y vector might be throwing off a logical gate I made

somber nacelle
#

copy the vector3 into a local variable, assign 0 to the Y axis then access that object's magnitude

iron vortex
#

for context I'm using it to find a threshold for how fast the object is moving to determine whether it's stationary or not

#

and I'm doing that by comping the magnitude

iron vortex
somber nacelle
#

that's the best way to do it without actually affecting the velocity on the rb

#

one day when unity finally finishes upgrading to the CoreCLR we can use the with keyword to make that even easier. it could be var velocity = rigidbody.velocity with { Y = 0 };

iron vortex
#

That will be nice but I'll probably forget about it completely

silent tapir
#

What's the best approach for a spatial inventory system from games like Tarkov and Arma: Reforged?

somber nacelle
#

stop reposting the same question over and over in multiple channels

#

try doing some actual research

iron vortex
#

Chances are if somebody knows how to help with your problem they'll see it in due time somewhere and will respond, and if it's something as general as an inventory scheme you're probably going to have to do as the above person said and figure most of it out yourself because that shit is almost always complicated and case-specific** **

quaint rock
#

best to just give it a go and then come with the smaller problems you encounter

soft shard
quaint rock
#

also best to decribe it, i am assuming it is just the kinda where objects take up x amount of cells and can be rotated and what not to fit

silent tapir
silent tapir
#

I am not sure what approach I should take is it

quaint rock
#

would first get a inventory grid working

#

then after that when you drag things its just a matter of having each item define a shape, and checking for all cells within the shape if they are occupied or not

somber nacelle
silent tapir
soft shard
silent tapir
cosmic rain