#archived-code-general

1 messages ยท Page 392 of 1

oblique lagoon
#

it wont work even as plugins

#

unity linker fails as an error

#

it wont compile the unsafe library

#

it has its own burst.unsafe

heady iris
#

I wound up installing System.Runtime.CompilerServices.Unsafe.6.0.0 through NuGet for Unity

#

I no longer depend on that, though.

#

I should probably remove it..

#

Burst should be irrelevant, though.

#

The Burst compiler is only applied to code you've annotated as being burst-compilable

oblique lagoon
#

did it even work

heady iris
#

yes; I was using it to coerce between an int and an enum without any GC alloc

oblique lagoon
#

ohhhh

heady iris
#

well, it was more complex than that -- I'm pretty sure the cast is free

oblique lagoon
#

ok

heady iris
#

It was coercing to a specific enum type, I want to say

#

ugh it was something evil

#

involving a Type object

oblique lagoon
#

well lets me try to download the library then

#

wait let me try

heady iris
#

I was using NuGet for Unity.

#

interestingly, it's still an implicit dependency of another package for me

oblique lagoon
#

last time when i forcefully tried to add a net supported library
i ended up feeding whole .net 7 dlls into unity

#

and still it didnt compile

#

that's why i have very less hopes for it to work and compile

heady iris
#

one of these, i guess

#

I used it back in...Unity 2022 or 2023

#

hey, there's my commit message!

#

Oh yeah, that's what it was

#
public static bool MeetsPref<T>(T en) where T : Enum
{
    T pref = GetPref<T>();
    var val = Unsafe.As<T, int>(ref pref);
    
    T demandedPref = en;
    var demanded = Unsafe.As<T, int>(ref demandedPref);
    
    return val >= demanded;
}
#

it checked if an enum value was greater than another enum value

oblique lagoon
heady iris
#

Terror

oblique lagoon
heady iris
#

I don't believe I could do it with the generic

oblique lagoon
#

ohk

heady iris
oblique lagoon
#

ohhhhhhhh

#

sorry i didnt see that

heady iris
#

It's a surprising behavior!

#

the where T : Enum constraint doesn't guarantee enough, I guess

#

all of this was deeply evil

oblique lagoon
#

let me google a bit

#

and see a better alternative

heady iris
#

anyway, i literally just installed the thing through NuGet For Unity and it worked

oblique lagoon
#

lol

#

you have the option to use bitconverter

#

to convert generic types to value types

heady iris
oblique lagoon
somber nacelle
oblique lagoon
#

you can say how crazy i am by seeing this picture

heady iris
#

i was tilting at windmills to eradicate all GC

heady iris
oblique lagoon
oblique lagoon
#

lol

#

cool aint it

heady iris
#

anayway, it Just Works, even on my ARM macbook

oblique lagoon
somber nacelle
heady iris
#

it might not be easy or safe

#

but it sure is Funny (tm)

oblique lagoon
#

how?

oblique lagoon
#

no need to tamper with it

#

my rules of doing work

#

it workeed

#

i am soo happy

heady iris
#

earlier today, I spent 30 minutes fighting a particle system

oblique lagoon
#

thank you soo much

heady iris
#

i then posted about the problem and solved it in 1 minute

#

classic

#

no prob :p

oblique lagoon
#

love you
your the best
i was stuck on this problem for the last 2 months

#

finally solved it

oblique lagoon
#

fun way of doing work

#

are you all graduates or still studying?

#

i just joined the uni

#

I cant believe my eyes
it finally worked

#

its my lucky day today

#

thanks for the help

#

bye

heady iris
#

oh hey, that's fun

heady iris
#

now I can reinterpret a game object as a string

oblique lagoon
#

what would you achieve by doing so
also isnt a class something you cant convert to value type

#

gameobject is a class in this case

leaden ice
#

Pretty sure it was a joke

oblique lagoon
#

what you should be getting is the pointer to its memory address

oblique lagoon
late lion
heady iris
#

Well now I have to try it

#

This feels like a bad idea

oblique lagoon
heady iris
#

ah yes

#

my game object is a string with a length of 920439632

oblique lagoon
#

its like getting a pointer to an address and reading bytes and converting it to any value to want

#

so its an easy win

heady iris
#

ah

#

there goes unity

#

took a few tries!

#

i don't think i'm going to submit this one

oblique lagoon
#

no way?

heady iris
#

once I asked for .Substring(1), at least

oblique lagoon
#

unity usually crashes on adding libraries that it cannot process

heady iris
#

interestingly, it was okay when I just tried doing something like Debug.Log(notAString)

vagrant blade
#

Not a Unity question. @oblique lagoon

oblique lagoon
oblique lagoon
#

send it i am with you

compact spire
#

I don't see much real time editing of mesh's as a thing unless it's in the context of breaking it into parts. What I am looking for is a bit more complicated in a way. Imagine a model of a submarine, and you play a model of a squarish torpedo launcher in it near the front. I would want to project the hole where the torpedo goes out the front of the submarine model, cutting a hole in the curved front in the process. Does that make sense? How difficult would that even be? In my head I need to add edges/vertices where the tube intersects with the model and then remove some faces. It seems like a non-trivial task...

oblique lagoon
compact spire
#

Wouldn't those features be locked behind the editor portion of Unity?

heady iris
#

Unity doesn't have extensive mesh editing features..

#

I guess there's ProBuilder, which can do some operations

heady iris
#

Actually...you may find this package to be interesting

oblique lagoon
heady iris
oblique lagoon
# heady iris what?

slicing like spliting meshes with a raycast or at the point of intersection

#

i just forgot how to do that
but unity do support it

heady iris
compact spire
#

Hmm Interesting

oblique lagoon
#

yea that as well lol

heady iris
compact spire
#

or when 2 vertices are really close to each other?

#

ugh then you would have to do some dynamic weld of the vertices

heady iris
#

Oh yeah, and you wind up with several separate meshes

#

Which can cause bad seams in lightmaps

#

It looks perfect under realtime light

compact spire
#

I haven't even looked into how I'm going to handle materials for this...

#

I'm ignoring that until I have some basic prototype done

#

proof of concept

#

That asset might give me some idea of how much work it is I guess

lucid brook
#

What do you prefer, assigning your variable in your code with things like .GetComponent or do you mark them as [SerializeField] and assign them in the editor

heady iris
heady iris
#

And even then -- I'll just use GetComponent as a backup to an explicit reference

#
if (!whatever) {
  whatever = GetComponent<Foo>();
}
lucid brook
heady iris
#

And even for the first case, I would still just assign a reference

#

Prefabs mean you don't have to manually assign that reference over and over

rigid island
compact spire
#

@heady iris fortunately it's not a required feature for what I'm trying to make, just a neat one

heady iris
heady iris
#

subtract A from B, join A and B, etc.

latent latch
#

I only ever use GetComponent if the script has a RequiredComponent attribute bound to it

#

but the whole multiple component thing is a problem, and this is why Godot's solution to 1 component per node is a good way to structure stuff

#

too bad GameObjects always need to include tranform values

compact spire
#

@heady iris The asset listed earlier seems to work, but it doesn't seem to have the source with it so that's kind of a bummer

rustic rain
#

how can i check if i'm connected to the internet?

#

in the game

leaden ice
#

Usually - you'll want to test connectivity to your particular game service or whatever internet feature(s) you're trying to make sure are working.

heady iris
#

Yes -- you are connected to the internet if you can reach your game server

#

If the server is down, the entire Internet might as well be out

wheat spruce
#

Ping Google

#

It'll be unlikely that Google would be down

#

You get a response, you're good. No response, it's almost certainly a problem your end

worldly hull
#

i gonna ask a broad question

"in all monobehavior scripts, if this == null , it can only be that object being destroyed"

#

im asking this, because the team register events across game objects, but they dont even unsubscribe the events at all, so u can see theres too many

    if (this == null)
    {
      return;
    }``` on the function it registered
somber nacelle
#

the component or entire gameobject has been destroyed in that case, yes

worldly hull
#

im planning to unsubscribe all the events on onDestroy() , and then remove all these ugly null checks

cosmic notch
#

I am trying to take shot of this character and it should fill the render texture in the bottom right ,
These are the requirements
For any outfit combination (including hidden parts), any camera angle, and any action, when the user clicks the "Shoot" button, the animation should pause, and the character image visible in the current camera view should be adjusted so that it fully fits into the "ShootArea" frame. The visible content in the frame should then be captured as a texture and displayed in the "ShootResult" image.

https://pastebin.com/Qnxe3iMc

#

Pressing the shoot should redjust the camera and take teh shot , i dont know how to automatically calculate this

misty drift
#

Hello! Could you tell if you're using DI framework in your projects? And if so which ones?
I'm using zenject-extenject, but I feel comunity is quite dead around it and it's at some point not very easy to use (if need some advanced stuff).

little meadow
#

I always feel DI frameworks are overcomplicated... so I just manually inject the 5-10 things I may need to inject ๐Ÿคทโ€โ™‚๏ธ

thin aurora
#

Except a DI framework is very useful since it allows you to pass dependencies through registering them under a lifecycle. This makes it possible to pass required dependencies between classes without the manual labour and without requiring access to internal classes that would want the dependency

#

Honestly, DI in Unity is silly because it would not solve this issue as much. Manual labour can still very much be omitted without it

cold parrot
eager tundra
cunning aspen
#

Hello, could someone help me with gun orientation for my game? I have a gun on the right bottom side of my camera when I hold right mouse button, the gun is supposed to come in the center and fov of the camera changes. All of this happens but there are two problems : when I am rotating the camera along the x axis, the gun does not move along with it, meaning it is no longer at the corner when not in zoom mode, and when in zoom mode, i can just look up with the gun still pointing in the front

#

I have the gun as a child of the camera but still it is not rotating with the camera

#

what else can I try?

#

also, if it helps, i have created an animation to make the gun go from bottom right to center when aiming

swift falcon
#

How would I check if something is grounded no matter what surface its on?

robust dome
#

really easy to find many sources that explains it

dusky niche
#

is it okay to use a class inside a function directly like this?
I mean I'll be needing this all the time anyways as I'll call the function in update.
Physics.Raycast(groundCheck.position, -transform.up, out var hit, groundMask);

swift falcon
robust dome
#

yeah

swift falcon
#

It is easy to find for a plane and stuff but for any surface not

#

Im using perlin noise to generate a procedural map but it's a lot harder to check if its grounded considering my mesh may float on it so that's why im asking

wheat spruce
#

could you maybe cheat and just check if the object is within some distance of the floor?

#

you ideally want there to be a really clear and obvious rule for what defines a surface as ground, and likewise for having a really simple way to check if your object is grounded. These two things shouldnt be complicated as theyre pretty cut-and-dry things

scarlet talon
#

This avoids hovering on flat or soft angles (since you will be checking for shorter distances)

brazen grove
#

Does UGUI.Rendering.UpdateBatches always mean something is being marked as dirty? I'm using reflection to get a reference to the m_GraphicRebuildQueue of CanvasUpdateRegistry during Canvas.preWillRenderCanvases and it's not got anything in it, but UGUI.Rendering.UpdateBatches is still taking a lot of time every frame

zealous lagoon
#

In the past I could swear you could use InputAction.IsPressed() to see if you are holding down a button in the action (which is sort of confirmed on Unity docs), but I swear either after updating or something its no longer the case. Holding down the key makes IsPressed() be true for one frame and then back to false. Is there some other function for this? I didn't seem to find anything that worked.

#

Although strangely it does work on some input actions, just not all. I haven't changed them at all, so no idea why it'd stop working. Any help is appreciated

heady iris
#

we'll need to see the actions you're using

zealous lagoon
heady iris
#

I need to see exactly what you have set up

#

Something must be different about the action that uses the up and down arrow keys vs. the action that uses the left and right arrow keys

zealous lagoon
#

but just in case:

zealous lagoon
#

up and down are a Button too, set up the same way

heady iris
#

I also want to see if you have anything special on the individual bindings

#

e.g. "Left Arrow"

zealous lagoon
#

here, thanks for helping out by the way

heady iris
#

Do you see exactly the same thing in the bindings for the "Up" action?

#

(also, you have the wrong gamepad binding for Left)

zealous lagoon
zealous lagoon
#

Actually I'll change it to left too and see if holding still works

heady iris
#

That shouldn't matter, but it is the only difference between the actions right now

zealous lagoon
#

yep it works

#

This is how I get input just incase:

    {
        get
        {
            if (LockControls) return false;
            return CurrentMap.Remappable.Left.IsPressed() || CurrentMap.Constant.Left.IsPressed();
        }
    }```
#

LockControls is always false, I print checked

zealous lagoon
#

I think I'll try deleting the key bind and making a new one in the editor.

#

Wow, that fixed it

#

Thanks for trying to help out @heady iris, I appreciate it ๐Ÿ‘
but seems like a random unity bug (or some hidden parameter)

#

ok wait things are very weird now, it works sometimes and sometimes not. If I figure out why I'll post here

heady iris
#

Huh, that's weird.

#

Do you have version control on this project? You could diff the asset to see if anything interesting changed

zealous lagoon
#

ok I have determined a script I made causes the issue, turning it off makes the issue go away. I'm just trying to figure out how I even managed to affect the new input system like that

heady iris
#

What does it do?

#

Is it turning actions on and off?

#

That would mangle the input state

zealous lagoon
#

it only ever reads from the input system, atleast in theory

#

ok its update function causes this, commeting that out fixes it

quick kindle
#

anyone successfully used mapmagic2 on unity 6 macos? i used it a while ago on a windows machine and quite enjoyed it, just getting back into unity after a several-year break, and on my mac its ****ting the bed

zealous lagoon
#

hello

#

after commenting out like every line I found the problem, and it might actually be a unity bug?

when I call a delegate void it causes the problem

heady iris
quick kindle
heady iris
#

That may have been an x86-only DLL

#

I can't use RealtimeCSG because it comes with a binary that doesn't work on this platform

quick kindle
#

yeah that was my worry, that it just doesnt work on mac

heady iris
#

(I have to wonder if I could get Rosetta involved somehow...)

quick kindle
#

i emailed author of mm2 and asked him if its supported

#

seems like i may have been too ambitious in expecting unity to play nicely with mac XD

#

@heady iris have you used any procedural terrain assets on mac? apple silicon

heady iris
#

One major thing is that MonoMod does not work on macOS ARM devices

#

That's used for Evil Editor Patching

knotty sun
#

C# dll's should not be a problem, IL is not hardware dependant. Native code dll's however are another story

quick kindle
#

yeah i think the error message mentioned native code dll

heady iris
quick kindle
#

im correct in assuming tho -- thats a general problem, not just an editor problem? like even if im dev'ing on windows, a build with eg realtime csg wont run on mac (because it needs the native dll?)

knotty sun
#

Native code dll's are OS+Hardware dependant so, yes, you need a specific dll for the target platform

quick kindle
#

yeah k

heady iris
#

But then for something like Steam Audio, which has a runtime component, it'd be no bueno

quick kindle
#

ah yeah. ok for something like mm2, thats a runtime function, so no bueno

zealous lagoon
#

Hello, I spammed a lot about my issue but just here to say I fixed it. A Disable call was sneaked in

heady iris
#

ah, that'll do it

quick kindle
#

vista procedural terrain -- no mac either! XD

#

f it, imma write my own procedural terrain generator XD

bold pawn
#

Does anyone know how to make good race car physics? I followed this tutorial, but my car spins and flips far too easily, and the acceleration and traction are garbage. https://youtu.be/DU-yminXEX0?si=7MeCGavNXYnJWB9P

I will guide you through all the steps needed to make a car controller with a smooth camera. No wasting time, no scripting, and the most simple unity tutorial on car movement out there!

............................

Tired of buying 3D Models? - Blender Tutorials : https://youtube.com/playlist?list=PLUE41oiZre0VCp6WLoURzC1hc7nrgwSsi

Suck at Un...

โ–ถ Play video
rain condor
#

i just made a change in Project Settings to Script Execution Order however, i dont see any files updated/modified/created in my version control system. Ive reviewed my gitignore and nothing is jumping out at me. ive reviewed many files in the ProjectSettings dir and nothing looks like it has these settings. Anyone know where this is? I need this change to persist for all devs on the project.

#

im using Unity 6000.0.30f1

night storm
simple ridge
#

Hi all, I am working on a project where I am generating procedural terrain and rendering it with Graphics.RenderPrimative. This is working well, however it does mean that this terrain has no collision.

I was wondering, what would be the best way to add collision for these meshes? I'd like to avoid having to generate 1000's of gameobjects as that seems like alot of unnecisary overhead. Is their a way to interact with the Physics systems collider data and add shapes to it in the same way as RenderPrimitive?

fossil sedge
#

I am completely fresh to this type of thing so I have no idea what channel to put this in but basically, I am following a tutorial for unity the very basics and I am using Visual Studio and in the vid the guy gets a list after typing "gameObject." and I do not. Is there a simple reason for this? The comments of the vid dont show any concern of this so I am convinced its a me problem.

I have searched the internet for a problem however I have no idea what im meant to search tbh.

tawny elkBOT
fleet gorge
#

your visual studio doesn't know you're working with unity

fleet gorge
#

not sure how you're generating your primitives right now but having a GameObject following the player to serve as the collider works

simple ridge
fleet gorge
#

yep in that case the method I proposed would work

#

change the collider depending on the block

simple ridge
#

Thanks, I assume this would be to have the game object poll the meshes and add them to a list of MeshColliders?

fleet gorge
#

Yep that's one way to go about it

simple ridge
#

I can see this working with an object pooling system, where I can load in the collider data for the player around itself, but what I am unsure on if the performance implications for having enemies do the same. Would this approach be scalable?

fossil sedge
fresh hazel
#

Hey,
I have some UI I spawn that way:

for (int i = 0; i < _equipementManagementContainer.childCount; i++) Destroy(_equipementManagementContainer.GetChild(i).gameObject);

foreach (var eq in ship.Equipements.SelectMany(x => x.Info.CanHold).Distinct())
{
    var emp = Instantiate(_equipementManagementPrefab, _equipementManagementContainer);
    var amd = emp.GetComponent<AmmoManagementData>();
    amd.Init(ship, eq, updateAmmoData);
    ammoMData.Add(amd);
}

Which contains this code

public class AmmoManagementData : MonoBehaviour
{
    [SerializeField]
    private Button _add, _remove;

    // [...]

    public void Init(Ship ship, AmmoType ammo, Action updateAmmoData)
    {
        // Initialising some other things

        UpdateUIButtons();
    }

    public void UpdateUIButtons()
    {
        _add.interactable = /* Condition for add */;
        _remove.interactable = /* Condition for remove */;
    }
}

The first time I instantiate it, everything is fine, but when it get deleted and instantiated again, clicking on buttons give me this error:

MissingReferenceException: The object of type 'UnityEngine.UI.Button' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.

However all references seems to be still good inside the Unity editor (the SerializeField is still well assigned for example)

Would anyone please know what the issue could be?

plucky inlet
#

and as you are not showing the entire code, we wont know ๐Ÿ˜„ // [...]

fresh hazel
#

Hmm but the button I'm clicking is the new one, why would it fire event from the one deleted?

#

I'm spawning a prefab that indeed contains a button inside

plucky inlet
#

And what line is giving you the error?

fresh hazel
#

Buttons are "minus" and "plus" and reference the object i'm spawning

#

The ".interactable" one

plucky inlet
#

And those are still there when you destory everything inside _equipementManagementContainer?

fresh hazel
#

oh wait no sorry i'm stupid

#

I referenced that from elsewhere

#

Thanks a lot ๐Ÿ™

plucky inlet
#

there you go ๐Ÿ˜„

slim trail
#

hello

#

how do I can changhe ParticleSystem.shape.scale via code because when I try to set to it my vector compiler says that is read only variable

#

Is there any way to do that?

#

If no what should I do to change that while player is in game

knotty sun
#

you first need to make a local variable for shape, then you can change scale.
unlike other properties you do not need to set shape back to particleSystem.
Refer to the docs if in doubt

forest vigil
#

Guys I need help, I'm making a moving platform and I need my player to attach to it. I tried making my player's velocity and the platform's velocity to be equal if the player is standing on it, but it started jittering. I tried then making the player become the platform's child, but it started inheriting its transform scale which is a problem because the scale is an important feature for both the platform and the player. What can I do?

using System.Collections.Generic;
using UnityEngine;

public class PlatformMover : MonoBehaviour
{
    public float platformSpeed = 5f;

    private void Update()
    {
        transform.Translate(Vector3.right * platformSpeed * Time.deltaTime);
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Player"))
        {
            collision.transform.SetParent(transform);
        }
    }

    private void OnCollisionExit2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Player"))
        {
            collision.transform.SetParent(null);
        }
    }
}```
vestal arch
#

probably the former, then fix the jittering issue, rather than the parent/child thing

forest vigil
#

how can I do that without making my player a child?

vestal arch
#

what code did you have with the former solution?

#

let's start there

forest vigil
#

The one above

vestal arch
#

that seems to be the latter solution

#

where's the code where you were

making my player's velocity and the platform's velocity to be equal if the player is standing on it

wraith cobalt
fossil sedge
#

Hey I am very new and don't understand what this means, its most likely really simple but I have no idea.

vestal arch
fossil sedge
#

Ahhh so I need to remove the "s"

knotty sun
#

you are trying to get a component from an array rather than an element of the array

fossil sedge
#

It works now, thanks alot guys. Now i'll know for next time ๐Ÿ™

robust dome
#

he is assigning an array to an object does that really work

vestal arch
robust dome
#

doesnt GetComponents return an array

vestal arch
#

it does, but they aren't using it there

leaden ice
vestal arch
#

they're trying to use GetComponent on an array, which isn't a thing

#

it's invalid from the method call, the assignment can't be checked since there's no valid type there to check

robust dome
#

wait what

#

because he said it is working now , that is why i am asking

leaden ice
#

that is what's being assigned to the variable

#

which itself is of type Logic
there are no arrays involved.

vestal arch
robust dome
#

oh lol i missread that i thought someon told him to use GetComponents instead.

#

i did not read that line never mind

sleek crypt
#

I tried using the VR Multiplayer template to build my game, but the Vivox connection doesn't seem to be working. When I run the game in the editor, I connect okay, but when I try to connect in a build on my Quest, I get stuck permanently trying to connect. I have permissions for microphone, sound and internet set up, and I've tried delinking and linking Unity services. Anyone have any advice?

half vale
#

void Reloader()
{
if (Input.GetKey(KeyCode.R) && m_LastTimeShot + AmmoReloadDelay < Time.time && m_CurrentAmmo < MaxAmmo){
// reloads weapon

           GetComponent<Animator>().SetTrigger("Reload");
            IsReloading = true;
            m_CurrentAmmo = MaxAmmo;    
            GetComponent<Animator>().SetTrigger("ReloadDone");
            IsReloading = false;

        }
                     else {
                     
                           }


    }
#

so basically it only will reload when the reload delay time elapses

#

is there a way for you to press the r key then the time passes then it does it

#

because now i have to keep ,ashing the key until the time elapses

cosmic rain
hardy tartan
#

When a coroutine starts and then play mode exits, the coroutine still runs and if it instantiates some objects then those will now remain in the editor. The expected behavior is that an object created from a coroutine at play time will be destroyed when exiting.

cosmic rain
#

Unity doesn't know that the coroutine was started during play mode and that every API in it needs to behave the same way as in play mode, despite being in editor mode.

hardy tartan
cosmic rain
hardy tartan
#

Well it would keep my scene from having changes in it when I didn't make any changes.

cosmic rain
#

This a very specific case and it's the developer responsibility to handle it.

#

That being said, any running coroutines should stop normally, since the scene is usually reloaded on switching between play mode and editor. Do you have scene reload disabled or something?

hardy tartan
#

I don't see why. If I clone an object while in play mode and then exit play mode, it goes away. Why does it know about my changes but not a coroutine started during play time?

cosmic rain
hardy tartan
#

Ah I see so the reload happens, then the coroutine is still running and then the objects get created. That makes a lot more sense. Thanks!

cosmic rain
#

No, if reload happens, your coroutine should stop, as the object that runs it would be destroyed.

#

It seems like in your case the object that runs the coroutine is not destroyed. Which is likely due to reload not happening. Perhaps you have it disabled in the settings.

hardy tartan
#

Oh it's not a coroutine, it's an async task if that makes any difference. I forgot I refactored this code to use async/await.

#

I'm not sure what you mean by settings. I don't have it set to DontDestroyOnLoad if that's what you mean.

somber nacelle
#

that definitely makes a difference. if you're on unity 2022+ just use the monobehaviour's destroyCancellationToken. otherwise you need to manage your own cancellation token(s) and cancel them when exiting play mode (or destroying the object)

chilly surge
#

An alternative option would be to use UniTask, which stops pending tasks when exiting play mode.

hardy tartan
#

Thank you!

cosmic rain
#

In fact, you will run into far more serious problems with async if you're not handling it correctly.

worn star
#

if anyone knows HLSL help , why is the vertexInput and out put a float 4 , the object has so many vertices shouldnt it be a an array of float4s ?

#

i am super beginner

#

๐Ÿ™

mellow sigil
blissful carbon
#

Excuse me, has anyone used Tesseract with Unity?
I've tried many methods, but it seems to keep showing this error.

cosmic rain
zenith valley
blissful carbon
#

Also, there aren't many tutorial resources of this type, and I spent a long time searching for them myself.

mossy snow
#

if I saw it in a PR, instant rejection because it won't build. It does too much based on thisGameStatus. Looks like you mashed the logic of multiple things into one super script

thin aurora
#

We generally don't do code reviews

stiff wasp
#

ok

thin aurora
#

If you want that, make a thread

stiff wasp
#

Code Review

neon yarrow
#

Running into issues with Unity Version Control.

Changes to Scriptable Objects are not recognized by VC unless you either manually check out OR on editor shut down. This issue persists whether the change was made in the Inspector or programmatically with a set dirty flag. Manually refreshing assets also does not help. These changes are also undetected in the PlasticSCM desktop app.

Now surely I am doing something wrong as it would be unthinkable that after 2 years of development Unity would once again release a "stable" version with a bug which could cause massive amount of lost work.

Latest LTS, latest PlasticSCM.

#
Unity is an AWESOME game engine, but for nearly a decade they have been INFURIATINGLY bad about calling fflush() to write changed asset data to disk. 
neon yarrow
#

It was in fact the issue, the solution is to write your own editor extension which upon detecting an SO is marked dirty, to create a visual effect to indicate the object needs to be manually written to disk.

misty drift
#

Hello! Could you please suggest to me some good guides on architecure for gamedev?
I do know about different patterns and aproaches(MV patterns, layers, events, solid etc.), but when I try to mix those I have some issues. May be there is a good channel or site where I can find good examples on architecture?

For example It's easy for me to do mvp pattern for my enemy, but then I need manager to manage it, spawner etc. And it's becomes harder to integrate those parts.

young tapir
#

I'm trying to set up a basic scene class to manage physics material based audio, is there a way I can access scene wide collisions? I'm aware that basic MonoBehaviors have an OnCollision/Colliding event but that doesn't really suit my needs since I can't parent everything under the Scene gameObject.

Any advice would be great, this is pretty much my only hurdle ๐Ÿ˜

misty drift
#

Could you clarify what you mean by "scene whide collisions"?

young tapir
#

Any collision, anywhere in the current scene

misty drift
#

And what you want to do for all those collisions?

young tapir
#

Check if the physic material matches that of the AudioLinker, and play a random sound from the list based on velocity

misty drift
#

Why you can't attach script to handle this logic on the object which will handle collisions?

young tapir
#

For every collider? Or every parent?

That seems very time consuming and inefficient compared to one central script managing the basic collisions lol

#

Scene is a manager class for the whole scene. I intend to manage the basic things like collision audio & effects so I don't have to spam a component

misty drift
#

Hm.. in this case I'm not sure. As far as I understand if you need to handle collision you still will need some script.
You can use singleton pattern to get your scene script so it's still one class to manage them all, but as far as I understand you will need to have some code to get OnCollision. Though may be there is better option...

young tapir
#

I am planning on having a singleton that just grabs the only active component, ya.
It seems a bit weird that there's no static event for Physics.OnCollision, or something similar :/

misty drift
#

Well you need to have some sort of object to actually collide as far as I understand. That's why static OnCollision doesn't make much sence.

#

I assume you have player moving on those materials, so may be you can have this script on player once, and then call your singleton manager there.

young tapir
#

Hm.. I could add a script to every collider that just invokes Scene.local.onSceneWideCollisionEvent ๐Ÿค”

#

Or just.. The main parent lol

misty drift
#

oh okay

weak snow
#

Just imported starter asset character controller 1.1.0 for Unity 6
-cinemachine installed
even using Cinemachine or using Unity.Cinemachine doesnt work
Assets\Starter Assets\Editor\StarterAssetsDeployMenu.cs(6,13): error CS0234: The type or namespace name 'Cinemachine' does not exist in the namespace 'Unity' (are you missing an assembly reference?)
Any idea ?
The wierdest is i have another script runnin just fine with this
#if UNITY_2023_2_OR_NEWER
using Unity.Cinemachine;
#else
using Cinemachine;
#endif

leaden ice
#

It's now Unity.Cinemachine IIRC

leaden ice
weak snow
#

Because it's not working using Unity.Cinemachine, please read more carefully

#

Ok it's fixed, here's how to

trim schooner
#

is it in an asmdef?

#

oh there we go

zenith zealot
#

So i have a question. I want to check if an object that is bouncing is no longer moving (or at least very close to) but I am unsure of how for a few reasons

I of course check its absolute value for the velocity to account for it moving up and down, but its still going to periodically cross '0' when it changes directions. So then I thought what if I use some sort of time delay to see if its still in that value range after a certain amount of time, but I realized through bad luck it could be switching directions at the exact moment that is checked. so that wont work.

How can I check to be sure it is staying within a very small velocity range over the course of a couple seconds that way I know its done moving, or pretty much done moving

vestal arch
#

is it moving both horizontally and vertically?

zenith zealot
#

yes

#

also love the peko pfp AshLove sorry just had to mention it

#

i guess i could use some sort of loop that will keep going for a certain amount of time, that seems kinda yucky though

deep stirrup
#

Is there a way to serialize to JSON a Dictionary<> using JsonUtility? Everytime I try it just returns {}

#

And what about custom classes? No matter what I do, it return the same empty thing ๐Ÿ˜ฆ

deep stirrup
#

๐Ÿฅน

rigid island
#

you could probably use structs or something, but it will probably be hella messy

deep stirrup
#

yeah, I'll try this, thank you!

rigid island
#

unity doesnt serialize them by default

deep stirrup
#

oh, good to know!

deep stirrup
weak snow
#

it is just my first attempt in 1 minut so probably better ways, need improvments but i guess it will work

rigid island
#
  1. use proper code formatting.
  2. the code kinda sucks
zenith zealot
#

couldnt that still have annoying edge cases where the velocities coincidentally end up in spots that will false flag it as not moving

weak snow
zenith zealot
#

what im thinking would be best is to have some sort of loop that keeps checking the velocity constantly for lets say... 2 seconds and if at any time during those 2 seconds it leaves the range, the loop breaks. if it doesnt then the object is considered to be close enough to not moving

#

maybe?

rigid island
hexed pecan
#

And resets when not

zenith zealot
#

YES!

rigid island
young tapir
# young tapir Hm.. I could add a script to every collider that just invokes `Scene.local.onSce...

Hello, I'm working on the collision method I mentioned earlier. My process is:

Loop through every collider and give them a collision handler. Each collision invokes a scene collision event, for effects etc. This part works perfectly. Getting the audio to play properly is where my issue arose.

I have a scriptableObject that uses a physicMaterial reference, along with some basic lists and Vector2s for audio. OnSceneWideCollisionEnter checks against a full list of all the MaterialLinks and compares materials. Which is always returning false. I've also tried comparing the material.name but flag is always false.

     public virtual void OnSceneWideCollisionEnter(Collision collision)
        {
            foreach (PhysicsMaterialAudioLinker audioLinker in physicsMaterialAudioLinkers)
            {
                bool flag = collision.collider.material == audioLinker.material;
                if (flag)
                {
                    if (sceneSettings.useCollisionDebug) Debug.Log("Hit material: " + collision.collider.material + "Matches current: " + flag);
                    if (collision.relativeVelocity.magnitude >= audioLinker.minMaxLowVelocity.x && collision.relativeVelocity.magnitude <= audioLinker.minMaxHighVelocity.y) InstantiateAudio(AudioImpactIntensity.Low, audioLinker, collision);
                    else if (collision.relativeVelocity.magnitude >= audioLinker.minMaxMediumVelocity.x && collision.relativeVelocity.magnitude <= audioLinker.minMaxMediumVelocity.y) InstantiateAudio(AudioImpactIntensity.Medium, audioLinker, collision);
                    else if (collision.relativeVelocity.magnitude >= audioLinker.minMaxHighVelocity.x && collision.relativeVelocity.magnitude <= audioLinker.minMaxHighVelocity.y) InstantiateAudio(AudioImpactIntensity.High, audioLinker, collision);
                }
            }
        }```

Has anyone got any idea as to why this'd be happening? Everything has been going pretty well thus far so some help would be appretiated ๐Ÿ˜

https://pastebin.com/g4W8LCta Scene Script
https://pastebin.com/hcrVxym2 Collision Handler Script
https://pastebin.com/HkzFpKqE Audio Link Script
zenith zealot
#

a timer would be perfect!

young tapir
#

Sorry, I think I may have interrupted ๐Ÿ˜…

rigid island
zenith zealot
#

i think at least

young tapir
rigid island
young tapir
#

Tldr; Comparing a physic material reference in a scriptable object vs one referenced in a collider is always returning false, I understand that PhysicMaterial references are Types but even comparing name doesn't work.

rigid island
young tapir
#

Ya, exactly.

rigid island
#

I wonder if its counting it as an Instance of the material so if its checking that rather than the type

young tapir
#

I did notice the physicMaterial reference in the collider is set to (instance) as soon as OnSceneWideCollision triggers

rigid island
#

goodluck running timer++ on different framerates

young tapir
rigid island
zenith zealot
#

tbh framerate isnt really an issue at the end of the day since exact time doesnt matter, just a general one

rigid island
#

lol okay

zenith zealot
#

since all i need to do is know if it hasnt been moving past a certain speed for a couple seconds. being off by, hell even a whole half second is fine

rigid island
#

making timers without using framerate independent functions defeats the point of a timer

zenith zealot
#

tho i probably wont use a timer

#

im thinking of just using a while loop that checks delta time? or is that an awful idea

weak snow
rigid island
zenith zealot
#

man, i havent touched unity in 2 years

#

would it just be time then?

rigid island
#

its justs saying "multiply this by the time between each frame" so it becomes framerate independent

#

so IF you wanted to make a timer you would need time += Time.deltaTime

weak snow
#

you can check time at first then compare to time yes

young tapir
thin aurora
#

I suggest you take navarone's advice since so far they have been one of the only ones giving some actual usable advice

zenith zealot
#

basically in pseduco code

while(time < time + variable)
{
do this
}

rigid island
#

Maybe not relying so much on physics material but some type of flag you set? I still don't know what the usecase is

rigid island
young tapir
#

Collision audio based on the physic material, for instance a glass physic material would play glass sound effects at different intensities based on velocity.

rigid island
weak snow
rigid island
#

I suppose you can use Time.FixedDelta in fixedupdate timer, but its probably not even needed if you're just checking the rb.velocity

thin aurora
# zenith zealot So i have a question. I want to check if an object that is bouncing is no longer...

How can I check to be sure it is staying within a very small velocity range over the course of a couple seconds that way I know its done moving, or pretty much done moving
Maybe I misunderstand the question here, but if you want to check over a period if the velocity has been low to none, then I suggest you do two things:

  • In FixedUpdate check if velocity is low to none. If this is the case, store Time.time in a variable.
  • In Update, periodically check the variable passes a timestamp. For example, if you want to check if the ball has been with low velocity for 5 seconds, you compare Time.time against the variable plus 5 seconds.
  • In the event the ball does increase velocity and you check this in FixedUpdate, you reset the variable back, for example to null to indicate there's nothing to check..
#

Simple check takes just a single variable and no coroutines

young tapir
weak snow
#

not velocity, magnitude

young tapir
#

The name has (instance) in it lmao. I am sad I missed that

rigid island
thin aurora
#

JFC, the wiki of Time.time has an example that uses timestamps exactly like I mean

rigid island
zenith zealot
#

Man I'm sorry if I'm being dumb. I maye have majored in game development but, the market is shit so I'm rusty. Thsts why I'm trying to get my act together and do my own stuff owoSob

rigid island
#

its fine you have many ways to go about this, ultimately you should pick whatever seems easier to you

hexed pecan
zenith zealot
#

plus the wisconsin college system is a joke that doesn't teach crap

rigid island
young tapir
zenith zealot
young tapir
#

But hey, it works perfectly. Just gotta go download a bunch of audio clips now lol

zenith zealot
#

just as an example

#

dozens of other examples exist

rigid island
hexed pecan
weak snow
#

I just learned C# and Unity by myself and got certificated, but i did exactly what you want in like 5 projects. I just don't have the code here.
FusedQyou solution is close to mine. And i agree to avoid coroutines + it will be on a lot of objects it can be very confusing (and if you set timescale somewhere here goes the headache)

thin aurora
#

You don't learn by listening, or watching

rigid island
thin aurora
#

You have to make stuff. Make stupid stuff. Make broken stuff

#

As long as you make stuff and it's yours

zenith zealot
#

yep, in college i did a bit of game dev on my own time. I've just gotten rusty since like, i gotta also balance a job due to my major not getting me shit, its hard to find that time

#

adulting hard

rigid island
#

it gets harder once you have gray hair on your ๐Ÿฅœ

hexed pecan
#

@young tapir Btw do you need to instantiate the physics materials?
Because using the material property automatically instantiates it when accessed. If you don't need that, use sharedMaterial
(It's similiar to how Renderer.material/sharedMaterial works)

rigid island
#

Ahhh that makes sense why it was creating an instance..

young tapir
hexed pecan
#

Collider.sharedMaterial gives the one on that collider

rigid island
#

^ the asset not an instance

hexed pecan
#

The main question is - are you modifying the physics materials or no?

young tapir
hexed pecan
#

Yep go with sharedMaterial 100% then

rigid island
#

oh unity..forget they have material vs sharedMaterial

hexed pecan
#

Can also get rid of the name.Contains check too and just use comparison

young tapir
#

Well that was a huge oversight on my end haha, thank you for pointing that out

rigid island
#

same lol I forgot even just accessing the property changes to instance, I thought only modifying did.
the more you know ๐Ÿ’ซ

#

๐Ÿค– code

zenith zealot
#

i'm making my own spaghetti code right now, i think i got it

#

like its probably awful code

#

but it should work

hexed pecan
#

Sick commentcs // Get the Rigidbody component rb = GetComponent<Rigidbody>();

weak snow
zenith zealot
#

i always feel gross when i have a lot of ifs nested

tulip spruce
#

so I have three scrips, one where after a selection if health is 0 then I save the survival time since aplication start. Then another script for enemies, so when enemies health goes to 0 I increase the count with one to KilledenemyCount. Now I this third script I want to calculate a score based of these two paramaters and then pass it into the highscore table. But I am unsure how to do this the best way.

zenith zealot
#

and by a lot i mean 3 or more

rigid island
#

helps with the nesting

#

if(unwantedIstrue) return
// more code etc.

weak snow
hexed pecan
#

We all know it's AI generated lol

rigid island
#

sure the code generated makes a timer, but it isn't practical to use for OPs problem

#

if you want to get better, dont use AI to generate any code. Simple enough

weak snow
hexed pecan
#

It does look like it should work ๐Ÿคทโ€โ™‚๏ธ

rigid island
weak snow
fresh cosmos
#

Hey so quick question. If i load 2 scenes with async, and one scene is priority 1 and the other 0. Will the scene with priority 0 not load until scene 1 has been enabled?

Because from what i can tell this is the case. Scene 0 is at 0 progress until i enable the first scene and then both finish loading

thin aurora
#

Can you not?

tulip spruce
#

is it possibl to get the return value from these when they are called from another script?
public float GetSurvivalTime(float time)
{
Debug.Log($"survial time from scoreCaluclator script {time}");
return time;
}

public int IncrementKilledEnemies()
{


    count = count + 1;
    Debug.Log($"current count is {count}");
    return count;
}
public void ScoreCalculator()
{

}
rigid island
weak snow
thin aurora
#

Both the spoonfeeding and the useless AI code is not helping

hardy tartan
#

Can we spare the philosophy of programming banter?

zenith zealot
#

alright

hexed pecan
zenith zealot
#
    {

        if (character.getFired()) //if character has been fired
        {
            //if the character is moving under a certain speed after being fired it is counted as no longer moving
            if (Mathf.Abs(character.getXVelocity()) <= velVar && Mathf.Abs(character.getXVelocity()) <= velVar && timerTest == false) //these numbers are place holders
            {
                timerTest = true;
                testTimeEnd = Time.time + timeVar;
            }
        }


        if (timerTest == true)
        {
            if(Time.time < testTimeEnd)
            {
               if (Mathf.Abs(character.getXVelocity()) > velVar && Mathf.Abs(character.getXVelocity()) > velVar)
                {
                    timerTest = false;
                    Debug.Log("still moving");
                }
            }
            else
            {
                Debug.Log("moving has ended");
            }
        }
    }```
how bad is my spagehtti code?
thin aurora
tulip spruce
zenith zealot
#

i should probably test if it does lmao

rigid island
#

as long as it works its fine, just make it legible
(check out the early return pattern I suggested)

thin aurora
zenith zealot
#

ya know, might be helpful if i didnt check the x velocity only lmfao

hexed pecan
hexed pecan
zenith zealot
#

seems to work, tho ill have to find a way to test edge cases

#

thanks so much! AshLove

tulip spruce
weak snow
tulip spruce
#

like this currently

hexed pecan
#

Or maybe you want both

tulip spruce
rigid island
zenith zealot
#

i lied, but ill have to check later what i did wrong

hexed pecan
#

@tulip spruce You can do cs public float GetSurvivalTime() => time; public void SetSurvivalTime(float newTime) => time = newTime;
Or just use public properties (or fields if you want).

#

And time would be a private variable in that class I suppose (maybe rename to survivalTime)

tulip spruce
#

okay, not sure if I explained corretly. But maybe this will work

#

when this is called in antoher script: scoreCalculator.SetSurvivalTime(survivalTime);
I want to obtain the reurn value that SetSurvivalTime gives in another script? I do not know if this is possible

zenith zealot
#

I'm dumb. The issue is that while I am making sure both x and y velocity are below a threshold to start checking if movement stopped, I'm also checking to be sure BOTH are above it to stop checking. It should check if either is

Tho, do i even need to check them individually? I could probably just check velocity itself right?

weak snow
# thin aurora Can you not?

How can i not ? (you're talking about the code taking too much screen space ? How can i help with code then ?)

hexed pecan
#

Show me how Get/SetSurvivalTime works.
The code you posted last doesn't make sense

rigid island
#

even though you should use the sqrMagnitude version as its more efficient

weak snow
#

And i did all the code for you, read it

weak snow
rigid island
#

instead you just multiply it by itself and you're good
so

var sqMag = rb.velocity.sqrMagnitude
if(sqMag * sqMag > someThreshold)```
zenith zealot
zenith zealot
#

Ai art, coding, music, etc

rigid island
#

the important part about coding isn't to generate code, its to learn how to reason and logic your way thorough

zenith zealot
#

That too

rigid island
#

thats why AI suck, they just regurgitate stuff on the internet, you aren't learning how to problem solve

weak snow
thin aurora
zenith zealot
#

Like i said I mean no offense, maybe you had useful info in there. But the second I see that something had ai involved i just block it out completely

rigid island
zenith zealot
#

will do ty

weak snow
zenith zealot
#

you are entitled to your opinions, and if it worked for you, thats great. But i abhor it

#

especially as someone who has been financially affected by ai

thin aurora
#

It's also just horrible advice. I already posted my 2 cents an hour ago but the idea of suggesting AI to somebody is just going to cause more harm than good.

weak snow
zenith zealot
weak snow
# thin aurora It's also just horrible advice. I already posted my 2 cents an hour ago but the ...

well, "lazy AI" was if i didnt prompted well and not corrected anything. Does the code i posted work exactly like Ashley demanded ? Yes it does.
Thank you for this instructive discussion, i'm feeling kinda old those days and i feared being outdated, but i see that a lot of people are sensitive about tech improvement (and yes, AI is an improvment).
Ai is a powerful tool, and as any powerful tool it has to be used with care.
Now i know why my company had so much bad talks with professionnal programmers/artist about AI...

zenith zealot
#

i don't see ai as a tool because it flat out steals, no matter how you look at it. Unless every last bit of it is trained solely on things owned by the company that made the ai, its stealing

hardy tartan
#

You're trained on other people's code and art etc. You didn't invent language. We all steal. That's why AI steals. Because it is like us.

zenith zealot
#

There is a massive difference between a machine learning it and a person

hardy tartan
#

If you say so.

zenith zealot
#

a person learns, a machine just takes a ton of assets and regurgitates something from that

weak snow
vestal arch
#

oh boy, could we possibly not have this discussion here

hardy tartan
#

What it even means to "understand" something is an open problem in philosophy.

zenith zealot
#

yeah lets not tbh, sorry for even getting into it

#

thats on me

thin aurora
#

AI is definitely useful, but we don't need somebody posting spoonfed and lazy AI answers here. Nor do we need somebody telling others to use AI to fix their code because that is going to seriously harm beginners and their ability to both code and debug

#

And yes, please stop this discussion. Just don't post AI here if you're going to contribute with help

zenith zealot
#

beginner... i have a degree ๐Ÿ˜ญ

vestal arch
#

โ€ข Donโ€™t post unverified AI-generated responses in questions or answers; check for accuracy, and state whatโ€™s AI-generated.
#๐Ÿ“–โ”ƒcode-of-conduct - that's the stance the server takes.

the spoonfeeding aspect is also not great.

can we skip the lengthy discussion

weak snow
zenith zealot
#

like i said, my bad for getting into the argument. thats entirely on me

vestal arch
thin aurora
zenith zealot
#

no i know, im just making a joke

weak snow
vestal arch
# weak snow Yeah that went to far sorry, just being taunt for using it to help someone. I wo...

fyi: the general stance in most help servers/communities is to not use AI-generated stuff as answers, and that AI-generated stuff can be a base/starting point, but never a complete solution, but it's not a good starting point/recommendation for beginners since a beginner wouldn't know how to make it complete/correct

while it might work in your company with experienced professionals (to each their own), it kinda breaks down for a general audience

rigid island
thin aurora
#

Thankfully this AI talk is a recurring issue so I'll see you all in the next meeting

hardy tartan
#

It is just a form of bike shedding.

weak snow
hardy tartan
#

Everyone is lazy. Why would you be a programmer if you weren't lazy? Just do it all by hand with pencil and paper like a true artisan.

vestal arch
#

support is a time-intensive process, if you're short on time you might just want to avoid starting convos/discussions that you don't have time to continue, especially here where it's pretty active
then you can go have fun with the newfound free time lol

knotty sun
hardy tartan
thin aurora
weak snow
knotty sun
rigid island
#

they're confusing automation with programming

hardy tartan
weak snow
thin aurora
#

People really don't need somebody that forces them to go through hoops with intentionally bad code

#

Just help them, and help then without posting AI to save time

vestal arch
hardy tartan
#

No you're just making strawmen and getting angry about them.

vestal arch
#

angry
yeah definitely a troll

thin aurora
hardy tartan
#

Calling my statements BS sounds angry...

vestal arch
#

sorry but; you haven't really said anything of substance here

#

getting argumentative over nothing is pretty reminiscent of troll behavior, so if you aren't one, maybe consider that

hardy tartan
#

Okay but now you're changing topics. First you said he wasn't angry and I said using the word BS sounds angry and then you just ignored that and kept on going to the next topic.

#

It takes two to argue...

vestal arch
#

right, exactly, i didn't say BS, that was steve

weak snow
hardy tartan
#

So why take up his mantle?

vestal arch
#

i didn't

#

i wasn't even talking to you wtf

hardy tartan
#

Okay.. then what are we talking about here?

#

You're calling me a troll...

vestal arch
#

well, if you aren't, then no need to continue that line of discussion.

thin aurora
#

In case you didn't notice, there are far better approaches to getting somebody to learn a process (like I said, linking documentation, pushing in the right direction with tips)

#

And I very much doubt your AI code was supposed to be some learning excercise

#

Also happy 2 hours since the inception of their question which sparked this discussion

hardy tartan
#

It's almost like people can have different opinions and personalities and that's okay.

sonic venture
#

What happened here?

royal parrot
#

its actually funny how many students in uni fully rely on chatgpt (but also kinda sad sadok )

rigid island
#

we can probably just like move on from this yes? keep it Unity coding questions

weak snow
# sonic venture What happened here?

I tried to help fast with AI generated code, now i'm trying to avoid the bullets. Even after deleting all i posted. But this discussion need to stop, yes.

sonic venture
#

I can't say anything I didn't read it. Isnt this a coding help channel?

thin aurora
#

Just to clarify, there's no dodging bullets here. Feel free to end the discussion but if you respond in a way that makes it seem like you don't understand the point then I'm just responding back, which is to not post generated code as an answer and/or sugegst the use of ChatGPT for their answer. Not sure how else I could form this.

weak snow
#

Yes it is, and i won't come back here because it felt bad. Good day anyway, and sorry for being misunderstood, i really tried to help and i'll never do it here.

vestal arch
young tapir
# young tapir Well that was a huge oversight on my end haha, thank you for pointing that out

Hello, I managed to get the collision audio from my previous messages here working perfectly. Even swapped to different audio based on the material hit, relative to the current material.

I do have one, pretty glaring issue though, when two things collide, both play audio ๐Ÿ˜…
Each collider gets a CollisionHandler in Awake, which means that both CollisionHandler scripts invoke the scene collision, which plays them both. Here's the code: https://pastebin.com/xZVd8Fab

My question is, is there an easy way to compare the velocity of two gameObjects without a rigidbody? I tried something that checks distance between the gameObjects last position to see how fast it's moving but did not end up working.

soft escarp
#

should i use this formule

Vโฐ x โˆ†t + ((โˆ†V / โˆ†t) x โˆ†tยฒ) / 2
for the dynamic gravity? i just want to make the gravity change over time for a rigidbody object

soft escarp
heady iris
#

this is an equation of motion

leaden ice
#

^ yeah

soft escarp
leaden ice
#

So what does it have to do with Rigidbodies

heady iris
#

I don't know why it divides the velocity by the amount of time that has passed, though

wheat spruce
#

Change gravity in what way? Do you want it so objects can get inverted gravity?

heady iris
#

Rigidbody doesn't have a convenient "gravity scale" property

#

However, you can just apply your own force

leaden ice
#

Rigidbody2D does

soft escarp
leaden ice
#

but for Rigidbody you can use

FixedUpdate() => rb.AddForce(customGravity, ForceMode.Acceleration);``` to do your own custom gravity
#

(and turn off normal gravity)

#

That formula wouldn't be useful though

wheat spruce
#

yeah, theres nothing special about gravity itself, its literally just a constant force that moves an object down

#

replace that gravity force with your own, and now you control which way gravity is

leaden ice
#

To calculate the current gravity force

soft escarp
leaden ice
heady iris
#

a force is not a velocity

leaden ice
#

You might be confusing "force" with "speed" or something

vestal arch
#

gravity is a force/acceleration

vestal arch
#

force is just acceleration over mass / acceleration is force per mass

soft escarp
leaden ice
# soft escarp probably

Step 1 is probably to achieve a basic understanding of newtonian physics - especially the relationship between forces, masses, velocity, and position

vestal arch
#

what is "it"

heady iris
#

things tend to fall faster and faster over time, yes

#

The only reason you don't accelerate forever is that drag starts slowing you down

leaden ice
heady iris
#

well, and that

#

kersplat

soft escarp
heady iris
leaden ice
heady iris
#

If you want to just get a multiple of normal gravity, you can use Physics.gravity * whatever

leaden ice
#

Basically the point of that code is that you would be calculating the customGravity vector elsewhere

#

and then you can modify it however you please.

soft escarp
vestal arch
#

acceleration is velocity over time
if you have constant net acceleration and infinite time then velocity will also be infinite
net acceleration would be gravity minus air resistance/drag, which is proportional to velocity squared, so drag will eventually catch up to gravity, and the point at which they cancel each other out is terminal velocity

leaden ice
#

What are you trying to actually achieve

#

it's not clear

heady iris
#

which is true

#

(just make sure you turn off gravity on the rigidbody, so that you don't get both normal gravity AND your own forces)

leaden ice
#

If you want this particular object to have different gravity than the other objects, sure it makes sense

heady iris
#
void FixedUpdate() {
  rb.AddForce(Physics.gravity, ForceMode.Acceleration);
}
leaden ice
#

if you want the gravity to "change over time" as you said before, it doesn't make sence.

#

But I'm not sure you understand the difference between gravity and velocity now.

heady iris
#

This recreates standard gravity for a rigidbody.

#

If I do some crazy thing to the force vector, then we no longer have normal gravity

#
void FixedUpdate() {
  rb.AddForce(Physics.gravity * Mathf.Sin(Time.time), ForceMode.Acceleration);
}
#

this would make gravity oscillate up and down

soft escarp
#

i think i got into some controversial topic awkwardsweat

leaden ice
#

Nah you just... asked a question that you didn't realize you were asking

#

And weren't clear about your intentions

vestal arch
#

no lmao, we're just super confused on what you actually want to get

leaden ice
#

so we're trying to sort out what you actually want

soft escarp
heady iris
#

You don't need to do that, though. That's why we have a physics system.

#

You just shove it with forces and stuff happens

wheat spruce
soft escarp
#

just as ol' Cave Johnson intended
throw peas at the wall and see what happens

wheat spruce
#

im pretty sure it was something about making orange juice

#

the oranges explode or catch on fire or something like that

leaden ice
#

(although I'm still not sure if that's what you want)

soft escarp
soft escarp
leaden ice
#

gravity is a thing that causes downward acceleration of objects

soft escarp
#

wait no

#

it would happen with negative gravity

#

my bad

vestal arch
#

no, upwards gravity just means you're redefinining "down" or where the gravity points

leaden ice
#

Since it's a vector, the vector itself can't really be "negative" (although individual xy or z components can be), it would just be a vector pointing in the opposite direction

#

(in the sense that vectors cannot have negative magnitude)

#

Anyway still don't know what you're asking lol

#

are you saying "I want gravity to get stronger or weaker over time"?

vestal arch
#

technically acceleration of gravity is already negative by convention since up is typically positive

soft escarp
vestal arch
#

anyways, what is it that you're actually trying to do

leaden ice
#

And what issue is there with that?

vestal arch
#

in high-level terms, not with this physics jargon

soft escarp
#

i dont get the physics now
my head is now a bunch of unsorted infomacos
-# just as it shall be

leaden ice
#

Well at some point you could write a simple sentence in english explaining what you're trying to do.

soft escarp
leaden ice
#

write it in polish?

#

See how Google Translate handles it lol

heady iris
#

Perhaps you can show an example of a game that does what you want to do?

soft escarp
vestal arch
#

gravity is just a specific acceleration

#

usually down

heady iris
#

Some games will have gravity that changes over time to produce a different "feeling"

#

like a jump that's floatier than it ought to be

soft escarp
#

now while were talking about gravity, its really weird thing
one thing pushes you and other thing keeps you at the surface

vestal arch
#

the normal force, yes

soft escarp
rigid island
spare dome
#

How can I find the sides/faces on given objects that face match the closest (that are facing away) to the current direction given?

#

sorry if this is kind of confusing

leaden ice
#

you want the face that looks the most away from the object?

#

or you want all faces that are looking a certain amount away from it?

#

In either case you'd probably just iterate over all the normal vectors of the faces and check the angle between that normal and the direction towards the yellow dot

#

ANd depending on what your heuristic is, you include the face or not

spare dome
#

I want all of the faces that face the to the closest direction compared to the current Direction which in this case being the red line

leaden ice
#

waait what is the red line?

#

I thought the red arrow was just pointing out the player.

#

If the red arrow means something, how is the player position relevant then?

#

Maybe you could explain what you're trying to achieve with this?

spare dome
#

The red line is the current direction, I'm trying to make a dynamic cover finder by getting the direction from an enemy to the player (which being the red line) then making vector3's with an offset from the player in the direction of the current direction then shooting raycast's from them to the closest object then getting all of the normal's on them that match the closest direction compared to the current direction (the red line).

#

then pathfinding the current "player" to one of the normal's by a random decision (I will make another position/vector3 from the selected normal)

leaden ice
#

I would say focus on only one of those at a time

#

Are all the squares always lined up perfectly in terms of rotation like this?

spare dome
#

currently my level has squares with no rotation but I would like some custom shapes if possible, I'm just trying to make this as simple as possible to implement so I can change things if needed

#

to find all of the cover hidden from the enemy I would need to find a way to get all of the normals of an object then iterate through them

leaden ice
#

Then you just loop through all the Covers and check which ones have normal vectors aligned with the red arrow (using the dot product)

#

If they're just squares, the normals are trivial to calculate

spare dome
#

for simplicity could I just keep them as squares then just calculate the angle between their normal's direction to the direction of the vector then just see if they fall under a certain threshold?

leaden ice
#

the dot product will return negative values when the two directions are "oppositish" and positive when they are "sameish"

heady iris
#

Make sure the vectors are both normalized for optimal results

#

It doesn't matter in this specific case, since you're comparing to zero

#

if both input vectors have a magnitude of 2, the result will be -4 to 4

#

The dot product is super useful for any situation where you need to know how "lined up" things rae

#

see also: Vector3.Angle or Vector3.SignedAngle

spare dome
heady iris
#

The latter takes an axis that the angle is figured relative to

#

which allows it to be positive or negative

#

Vector3.Angle is just Mathf.Acos(Vector3.Dot(a.normalized, b.normalized))

#

(the dot product is the cosine of the angle times the magnitudes of the two vectors!)

#

please don't send us a video of your code

#

you can share the script with !Code

tawny elkBOT
heady iris
#

gdl.space broke, so use another site

leaden shoal
heady iris
#

Also, if you want to get nice recordings of your game, there's a Recorder package for that (:

#

it's very handy

#

(can look at that later)

leaden shoal
#

okay

#

so i was saying

#

im trying to make a player cam follow script but it wont work , and if i changed the off set Y to 2 the player just fly :

#
using UnityEngine;

public class CameraFollow : MonoBehaviour
{
    public Transform player;  // Rรฉfรฉrence au joueur
    public float smoothSpeed = 0.125f;  // Vitesse de transition de la camรฉra
    public Vector3 offset;  // Dรฉcalage de la camรฉra par rapport au joueur

    void LateUpdate()
    {
        // Calculer la position souhaitรฉe
        Vector3 desiredPosition = player.position + offset;

        // Smooth dรฉplacer la camรฉra vers la position souhaitรฉe
        Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);

        // Appliquer la nouvelle position ร  la camรฉra
        transform.position = new Vector3(smoothedPosition.x, smoothedPosition.y, transform.position.z);
    }
}
#

fuck idk how to make it darker

#

ping me if respond

rigid island
tawny elkBOT
heady iris
#

Wrap the code in three backticks, like this:

```cs
void Whatever() {

}
```

#

Adding the "cs" to the first line gives it nice colors

leaden shoal
#

okay wait

rigid island
#

but you can just use cinemachine here tbh.

leaden shoal
rigid island
#

doe smoothing and all that for you , no need to manually lerp or anything

leaden shoal
#

okay idk how to use it but thx very much

rigid island
leaden shoal
#

nah im just stupid

#

i didnt click the link

leaden shoal
#

nah i found

rigid island
leaden shoal
#

yeah i saw my bad

leaden shoal
#

couldnt find it

#

in the manual

rigid island
#

and its usually centered to the pivot, so whereever your pivot is

leaden shoal
rigid island
leaden shoal
sonic warren
#

does anyone know solutions to this common issue

i have some physics objects and queries based from my player, and i want to basically have them only ignore the player collider but none else

specifically it is some physics2d-enabled particlesystems, and ray cast 2d

i wanna avoid having a different layer for just the player's character and not the other players' characters

#

would like to see other peoples approaches to this

leaden ice
#

then set it back

sonic warren
#

what about particles and stuff though

leaden ice
#

what about them

#

that has nothing to do with the raycast question

sonic warren
#

i have at the moment just put the particles clear of the player but it would be good to have them coming more from the player instead without a gap

#

the particles use physics to bounce of the environment and other players

leaden ice
#

Again what does this have to do with the raycast part

#

focus on one thing at a time

sonic warren
#

for raycast that would work but how could i have particles and stuff ignore just the player collider

sonic warren
#

oO i didnt know that function thank you

spare dome
rigid island
# leaden shoal wut is damping ?

from the docs for example
X Damping How responsively the camera tries to maintain the offset in the x-axis. Small numbers make the camera more responsive. Larger numbers make the camera respond more slowly.

leaden shoal
#

ho okay thanks

sonic warren
#

ok the ignoreCollision doesnt exactly support particle generated colliders, but i decided to just have the effects ignore players and only work with the environment

#

so i can still get the thruster particles splaying out over objects like the asteroids but they just pass over other ships

still lagoon
#

I'm struggling to understand the benefit of the S in SOLID (SRP), does anyone have some good examples/resources on this?

heady iris
#

The single responsibility principle prevents unnecessary coupling

#

hang on

#

cat

leaden ice
#

It reduces programming errors and mental load.

still lagoon
heady iris
#

well, I wouldn't necessarily decouple those -- but let's think about that example

#

What if I want to implement a target dummy?

#

It shouldn't be able to die, but it should be able to take damage

#

I guess you can just give it 99999999999999 hp or something like that

still lagoon
#

In that case you would be using interfaces ( IDie ) etc and inheritance right?

heady iris
#

My own ideal is to avoid having code that only some instances of the class will ever actually use.

If every entity in my game can take damage, then taking damage belongs on the entity class

somber nacelle
#

I'd argue that you should separate the responsibility of death from the health. the health could do something like raise an event when something would die, but shouldn't be handling the death itself

heady iris
#

But if that's not the case, then it belongs somewhere else

still lagoon
sonic warren
#

from my experience i use a health script in itself, which simply offloads logic through UnityEvents, and passing a hit struct thgrough that event

still lagoon
#

at least that's how I'm understanding it currently

sonic warren
#

eg OnDie, OnHit, OnHeal

#

when you die the logic is attached from other scripts to that event

#

that way its nice and reusable even though things die in different ways, like a player might have death animation, a wood crate may spawn some physics debri

#

but all can use same script

still lagoon
sonic warren
#

my health hit info (passed when attacking a instance of health) passes a damage type and health can have multipliers per type or overall, so...

sonic warren
#

i am no authority ive never made a game, i just play around with unity for fun over the last 5 years, but heres a recent character i did for a school project which i think (smart people tell me if im wrong) demonstrates Single Responsibility:

#

the lower ones are a bit of a mess added last minute from aanother dev but the top ones are my scripts made to be generic

#

heres that health script inspector if u wanna see

still lagoon
#

I'm struggling to see the benefit of these being independent classes. I get dependency injection... but that seems to me where that ends? Like once you follow dependency injection does it matter if you change any part of the code?

sonic warren
#

what is dependency injection

still lagoon
#

the D in SOLID

sonic warren
#

oO

#

i dont remember by names but i probably know what it is if u explain it

still lagoon
#

from my understanding a method/class not caring about the specific thing passed into it

sonic warren
#

oh yeah

still lagoon
#

like when you have a Enemy class, and Skeleton and Zombie inheriting from it

sonic warren
#

and functions acting on enemies can work for ALL enemies ay

still lagoon
#

or maybe that isnt it idk this whole SOLID thing is making me feel dumb

still lagoon
sonic warren
#

like this i have my 'mortals' on one layer, anything mortal can work for all mortals, eg the sword can damage anything (assuming its on the different team)

still lagoon
#

also like your profile picture and name it makes me look insane XD

sonic warren
#

hahaha

somber nacelle
# still lagoon the D in SOLID

the D in solid is dependency inversion not dependency injection. they are quite different. dependency injection is just the practice of passing dependencies to objects instead of constructing them in the object. dependency inversion is to rely on abstractions rather than concrete implementations (so your dependency would be on something like an interface instead of a specific class)

still lagoon
eager tundra
#

I would say not to overthink it, after all it's not even an objective concept
but it is useful to decouple your classes so that you can reduce the impact of changes

still lagoon
#

would it still work with my inheritance example?

#

as in Enemy parent class being passed in instead of Skeleton or Zombie

#

or would it only be considered dependency inversion for interfaces

somber nacelle
#

yes, that is precisely what it is for. you rely on the abstraction (like the abstract Enemy class) instead of a concrete implementation (Skeleton or Zombie)

still lagoon
somber nacelle
#

though a lot of times you'll see it more relying on interfaces rather than other object types

sonic warren
#

i dont know if this is an official "coding standard" like SOLID but i prefer in alot of cases to follow a decentralized model of composition, so like i dont just have a 'enemy script' but a series of scripts that compose the 'enemy' as a gameobject

#

but in this case if its like the AI of different enemies, then if they have common AI it would make sense to inherit

#

like what do you think a 'Skeleton' script instance actually does to the gameobject

somber nacelle
still lagoon
#

interfaces = composition and inheritance = inheritance right?

sonic warren
#

you can still 'compose' with a centralized topology, like having a script that is the 'enemy' which then operates other scripts

like Skeleton.cs which handles / drives other scripts

but yeah i tend to prefer de-centralized composition

still lagoon
#

i know its a bit deeper than that

sonic warren
#

interfaces are inheritance too but unity as a whole is kinda built around composition, so i find myself rarely using interfaces

somber nacelle
sonic warren
#

ive maybe used an interface less than 10 times in my time with unity

somber nacelle
sonic warren
#

yeah ye tru

#

its just cos it is same syntax as inheriting a class lol, they inherit the framework but no default behaviour

heady iris
#

I wish you could do something like

public IFoo, IBar doesBoth;
#

give me typeclasses, dammit

still lagoon
#

would you say its fine to implement interfaces WITH inheritance? as in, Enemy base class that has IDamageable, and then Skeleton has IRangedAttack and Zombie has IMeleeAttack for example?

eager tundra
heady iris
#

I use almost zero interfaces in my game. It's just a bunch of composition.

eager tundra
#

but there will never one "true" answer saying that you divided the parts correctly

sonic warren
#

i would suggest damagable should use a seperate script because there is usualy common / default behaviour with damageable objects

still lagoon
eager tundra
#

not really because then you most likely are going to violate the other SOLID principles

heady iris
#

I would question the logic of having IRangedAttack and IMeleeAttack in the first place

somber nacelle
heady iris
#

It doesn't make sense for Zombie to implement IMeleeAttack

#

the zombie isn't a melee attack

#

(Zombie shouldn't even be a class, though)

still lagoon
#

it shouldn't?

somber nacelle
#

yeah the functionality should be split into different components that are then attached to a Zombie gameobject

heady iris
#

why is Zombie so special that it's a unique kind of object?

#

will it ever make sense to operate only on zombies?

somber nacelle
#

and that is pretty much the basis of composition

heady iris
#

That's a good question to ask yourself

sonic warren
#

a zombie should be the gameobject composed of generic scripts that make up a zombie

heady iris
#

Does it make sense to specifically care about this thing?

still lagoon
#

holy moly ok now youve got me reconsidering what ive been learning as a whole

heady iris
#

My game is just Entity. That's it. You're an Entity.

still lagoon
#

because skeleton and zombie classes are like the most basic inheritance example we were given

heady iris
#

Player? Entity. Monster? Entity. Door? Entity. Spectator? Entity

sonic warren
#

brothr i dont even do that lool

heady iris
#

Entity includes some basic requirements, like having a name

somber nacelle
sonic warren
#

nothing on my player says its a entity or a player or anything lol its just a thing that takes input talking to a thing that gets it running around, and another script that allows combat, and then a script that lets it be damaged

somber nacelle
#

while those make a decent example of how inheritance works, in practice it's not a great actual use case for inheritance since composition would make it more open to change

heady iris
#

and an Entity has these two things:

  • Brain, which makes decisions
  • Locomotion, which controls the entity's position

I determined that these are worth making "special", because they have such unique roles in my game.

Everything else is a Module

heady iris
#

they instantly explode when you think about more than like

#

3 kinds of animal

#

It's a useful metaphor

#

You know, come to think of it: I use almost no inheritance, either

#

beyond inheriting from abstract classes and maybe subclassing those concrete classes

#

but even then -- I'm actively working to get rid of those

#

I have a unique kind of player brain for each locomotion mode. I don't like that. I have to know to switch brains out if the player's locomotion mode changes.

somber nacelle
#

I still use abstract classes quite a bit, but i rarely ever go beyond a single layer of inheritance deeper than that

heady iris
#

bingo

sonic warren
#

that top one could be considered the "brain", in this case commanding the other behaviours (like locomotion and combat) by taking user input, but could just as well replace it with some AI script to command the other behaviours

#

@heady iris ^

heady iris
#

If you go too far down the composition rabbit hole, you start having problems with what I'd call "fake composition"

#

A only makes sense with B and C

sonic warren
#

yeah its important to compose the definitive object from generic components

heady iris
#

That's kind of my brain situation. PlayerHumanoidBrain only makes sense with HumanoidLocomotion, and PlayerSpectatorBrain only makes sense with SpectatorLocomotion.

sonic warren
#

eg you take generic / reusable behaviours a b c and d, put em together to form a "skeleton" gameobject

still lagoon
heady iris
#

you can always cut a class in half