#archived-code-general
1 messages ยท Page 392 of 1
unity linker fails as an error
it wont compile the unsafe library
it has its own burst.unsafe
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
did it even work
yes; I was using it to coerce between an int and an enum without any GC alloc
ohhhh
well, it was more complex than that -- I'm pretty sure the cast is free
ok
It was coercing to a specific enum type, I want to say
ugh it was something evil
involving a Type object
I was using NuGet for Unity.
interestingly, it's still an implicit dependency of another package for me
which one?
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
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

Terror
wait wait
couldnt you do that by type casting
as enums are just uint
I don't believe I could do it with the generic
ohk
yeah
It's a surprising behavior!
the where T : Enum constraint doesn't guarantee enough, I guess
all of this was deeply evil
might be
let me google a bit
and see a better alternative
anyway, i literally just installed the thing through NuGet For Unity and it worked
lol
you have the option to use bitconverter
to convert generic types to value types
and my project still compiles if I use it
well i need unsafe for memory stuff
but if the point was to avoid allocations then this isn't a great idea anyway. if they didn't care about allocations they could have just done (int)(object)val
you can say how crazy i am by seeing this picture
bingo
i was tilting at windmills to eradicate all GC
what in god's name did you do to unity
the library i am gonna use is using the unsafe library for some native libraries
that's why i need it anyways
a tons of shit
lol
cool aint it
anayway, it Just Works, even on my ARM macbook
thanks for the advise
you made my day mate
sure, but that's not really related to what you suggested. BitConverter probably could have done the job, but fen was avoiding allocating memory to do the conversion which means they had to use Unsafe.As for it instead of using some of the much easier/safer ways
ok sir
how?
(this thing)
if it works it works
no need to tamper with it
my rules of doing work

it workeed

i am soo happy
earlier today, I spent 30 minutes fighting a particle system
thank you soo much
love you
your the best
i was stuck on this problem for the last 2 months
finally solved it


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
@oblique lagoon Unity's own UnsafeUtility also has a As method that works the same way.
https://docs.unity3d.com/ScriptReference/Unity.Collections.LowLevel.Unsafe.UnsafeUtility.As.html
oh hey, that's fun

now I can reinterpret a game object as a string

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
Pretty sure it was a joke
what you should be getting is the pointer to its memory address
i think so
string is also a class, so you would just be reinterpreting the pointer. I assume .NET will spot the mismatching types as soon as you try to call any of its methods.
now it makes more sense
well i dont think so
its like getting a pointer to an address and reading bytes and converting it to any value to want
so its an easy win
once I asked for .Substring(1), at least
unity usually crashes on adding libraries that it cannot process
interestingly, it was okay when I just tried doing something like Debug.Log(notAString)
Not a Unity question. @oblique lagoon
sorry my bad
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...
i think unity has these features already as its a game engine and it support destruction as well
you dont need to write it from scratch
Wouldn't those features be locked behind the editor portion of Unity?
not at all
Unity doesn't have extensive mesh editing features..
I guess there's ProBuilder, which can do some operations
Boolean mesh operations are fun
Actually...you may find this package to be interesting
editor only but slicing is something unity supports for runtime
so you dont need to worry at all
what?
This lets you combine multiple inside-out meshes together into one large space
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
Yes. I am not aware of this being something that's easy to do without using third-party packages
Hmm Interesting
yea that as well lol
It has some hiccups -- you can run into problems with floating-point precision when two objects barely touch each other
or when 2 vertices are really close to each other?
ugh then you would have to do some dynamic weld of the vertices
Oh yeah, and you wind up with several separate meshes
Which can cause bad seams in lightmaps
It looks perfect under realtime light
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
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
haha, it's complicated :p
I prefer serialized references unless there is absolutely no way that GetComponent will ever fail or give me the wrong object
And even then -- I'll just use GetComponent as a backup to an explicit reference
if (!whatever) {
whatever = GetComponent<Foo>();
}
So with things like a rigidbody on the same object you just do get component but if it's outside of that you use a serialized references?
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
imagine you had 5 more components on the same object you want to grab, if you put them all in Awake/Start you now are building up your hang time for initializing your object .
Inspector reference is usually the best

understood! lol
thank you!!
@heady iris fortunately it's not a required feature for what I'm trying to make, just a neat one
And god help you if you have two of the same component!
If you want to dig around for other packages, the term you're looking for would be "boolean mesh operations"
subtract A from B, join A and B, etc.
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
@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
make a test request to a website or web service
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.
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
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
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
the component or entire gameobject has been destroyed in that case, yes
im planning to unsubscribe all the events on onDestroy() , and then remove all these ugly null checks
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.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pressing the shoot should redjust the camera and take teh shot , i dont know how to automatically calculate this
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).
I always feel DI frameworks are overcomplicated... so I just manually inject the 5-10 things I may need to inject ๐คทโโ๏ธ
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
The elimination of manual Labour is what makes people use it as a glorified singleton to inject everything without thinking about logic flow. I find idiomatic use of a DI container, with proper messaging up/down the hierarchy to be no less tedious than manual injection. And any kind of direct referencing between branches is absurdly difficult to maintain
I'm using VContainer, fully recommend it ๐
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
How would I check if something is grounded no matter what surface its on?
really easy to find many sources that explains it
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);
Are u answering me or
yeah
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
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
You need to check the hit's distance and its angle. Define what distance is appropriate for a flat surface, and as the steepness increases, so should the distance threshold of the hit
This avoids hovering on flat or soft angles (since you will be checking for shorter distances)
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
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
we'll need to see the actions you're using
Like the Mappings file? It's simply left arrow key and right arrow key. Up and down work when holding, not these two.
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
but just in case:
its so weird, it worked before. I haven't worked on my title screen for a while, and I go back and it's broken like this. No idea how.
up and down are a Button too, set up the same way
I also want to see if you have anything special on the individual bindings
e.g. "Left Arrow"
here, thanks for helping out by the way
Do you see exactly the same thing in the bindings for the "Up" action?
(also, you have the wrong gamepad binding for Left)
oh yeah, thanks ๐
yes, except it says Up Arrow.
Actually I'll change it to left too and see if holding still works
That shouldn't matter, but it is the only difference between the actions right now
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
inserting a print here reveals its true for exactly one frame, then goes back to false.
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
Huh, that's weird.
Do you have version control on this project? You could diff the asset to see if anything interesting changed
sadly not, I really should though. Anyway making a constant print it seems like how it behaves depends on which UI element I have selected? Seems very weird, I'm testing right now.
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
What does it do?
Is it turning actions on and off?
That would mangle the input state
no... its a custom slider component I made cause I didnt like the built in one
it only ever reads from the input system, atleast in theory
ok its update function causes this, commeting that out fixes it
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
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
What problem are you having? I'm using an ARM macbook and a few packages don't work for me because they provide an x86-only binary blob
eh i already deleted it from my project -- it looked like it was trying to use some noise dll and didnt have it? totally smelled like a mac bug
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
yeah that was my worry, that it just doesnt work on mac
(I have to wonder if I could get Rosetta involved somehow...)
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
I've had a pretty good experience, save for third party packages that ship with x86-only DLLs
One major thing is that MonoMod does not work on macOS ARM devices
That's used for Evil Editor Patching
C# dll's should not be a problem, IL is not hardware dependant. Native code dll's however are another story
yeah i think the error message mentioned native code dll
Yeah, native code.
It's a shame, because RealtimeCSG is fantastic
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?)
Native code dll's are OS+Hardware dependant so, yes, you need a specific dll for the target platform
yeah k
Well, in that case, it'd be fine -- that code is only used in the editor
But then for something like Steam Audio, which has a runtime component, it'd be no bueno
ah yeah. ok for something like mm2, thats a runtime function, so no bueno
Hello, I spammed a lot about my issue but just here to say I fixed it. A Disable call was sneaked in
ah, that'll do it
vista procedural terrain -- no mac either! XD
f it, imma write my own procedural terrain generator XD
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...
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
i think the best ones are on the asset store and cost money
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?
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.
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข
Visual Studio (Installed via Unity Hub)
โข
Visual Studio (Installed manually)
โข
VS Code
โข
JetBrains Rider
โข :question: Other/None
your visual studio doesn't know you're working with unity
is this grid based or mesh based?
not sure how you're generating your primitives right now but having a GameObject following the player to serve as the collider works
Yes, a 3D grid. Though the collison volumes arn't hard set as cubes. They can be any shape that fits inside the cells volume
yep in that case the method I proposed would work
change the collider depending on the block
Thanks, I assume this would be to have the game object poll the meshes and add them to a list of MeshColliders?
Yep that's one way to go about it
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?
Thanks alot ๐
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?
I bet, you are assigning the buttons some clickevent or similar, and that is still trying to be fired even when you deleted the previous object
and as you are not showing the entire code, we wont know ๐ // [...]
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
And what line is giving you the error?
Buttons are "minus" and "plus" and reference the object i'm spawning
The ".interactable" one
And those are still there when you destory everything inside _equipementManagementContainer?
there you go ๐
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
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
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);
}
}
}```
probably the former, then fix the jittering issue, rather than the parent/child thing
how can I do that without making my player a child?
The one above
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
Why are you matching the velocity instead of just adding it to the player?
Hey I am very new and don't understand what this means, its most likely really simple but I have no idea.
FindGameObject__s__WithTag gets multiple gameobjects, an array of them. you can't GetComponent on an array
Ahhh so I need to remove the "s"
you are trying to get a component from an array rather than an element of the array
You put an extra s in there
It works now, thanks alot guys. Now i'll know for next time ๐
he is assigning an array to an object does that really work
he's not assigning an array to anything
doesnt GetComponents return an array
it does, but they aren't using it there
and where do you see them "assigning it to an object"?
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
GetComponent<Logic> returns a Logic
that is what's being assigned to the variable
which itself is of type Logic
there are no arrays involved.
he changed the FindGameObjectsWithTag to FindGameObjectWithTag so now there's no array at all
oh lol i missread that i thought someon told him to use GetComponents instead.
i did not read that line never mind
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?
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
This is really a question for #๐ปโcode-beginner
You can implement some kind of input queue. In the simplest form, just set some reloadQueued bool to true if you press the button during a cool down and when the cool down is done, check the bool, reset it and start the reload again.
thank you
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.
Stop the coroutine when exciting play mode.
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.
"Unity doesn't know that the coroutine was started during play mode" Why not?
Because it doesn't keep track of that information. It doesn't have any need to.
Well it would keep my scene from having changes in it when I didn't make any changes.
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?
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?
It doesn't revert the object. It reloads the whole scene. Unity doesn't keep track of whether your individual changes were made at play mode or outside of it.
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!
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.
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.
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)
An alternative option would be to use UniTask, which stops pending tasks when exiting play mode.
Thank you!
That makes a huge difference
In fact, you will run into far more serious problems with async if you're not handling it correctly.
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
๐
Excuse me, has anyone used Tesseract with Unity?
I've tried many methods, but it seems to keep showing this error.
Ask in the appropriate channel next time( #archived-shaders ).
Shaders run many times for each data primitive(vertex or pixel), so each time it runs it only processes one vertex.
perhaps you're missing a package? (i might be wrong)
Emm... I'm not really sure either, since this is my first time working on something related to OCR.
Also, there aren't many tutorial resources of this type, and I spent a long time searching for them myself.
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
We generally don't do code reviews
ok
If you want that, make a thread
Code Review
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.
Surely, this is not the issue in question: https://discussions.unity.com/t/scriptableobjects-are-not-updating-when-changed-on-the-filesystem-via-git/777923?page=2
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.
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.
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.
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 ๐
Could you clarify what you mean by "scene whide collisions"?
Any collision, anywhere in the current scene
And what you want to do for all those collisions?
Check if the physic material matches that of the AudioLinker, and play a random sound from the list based on velocity
Why you can't attach script to handle this logic on the object which will handle collisions?
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
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...
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 :/
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.
Hm.. I could add a script to every collider that just invokes Scene.local.onSceneWideCollisionEvent ๐ค
Or just.. The main parent lol
oh okay
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
They changed the namespace
It's now Unity.Cinemachine IIRC
Why is that last part weird? It's showing you exactly what's changed lol
Because it's not working using Unity.Cinemachine, please read more carefully
Ok it's fixed, here's how to
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
is it moving both horizontally and vertically?
yes
also love the peko pfp
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
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 ๐ฆ
nah just use newtonsoft
๐ฅน
yeah, I'll try this, thank you!
just regular classes/struct require to be [System.Serializable]
unity doesnt serialize them by default
oh, good to know!
Yeah, that works, you saved some painfull hours of my time!
it is just my first attempt in 1 minut so probably better ways, need improvments but i guess it will work
- use proper code formatting.
- the code kinda sucks
couldnt that still have annoying edge cases where the velocities coincidentally end up in spots that will false flag it as not moving
Thanks for your help, i already love you.
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?
its ok save face and blame it as "AI code"
Sounds like you just want a timer that counts when your velocity.magnitude is below a certain threshold
And resets when not
YES!
Start a coroutine when you plan on checking the magnitude
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
a timer would be perfect!
Sorry, I think I may have interrupted ๐
use links for code
i think at least
Ah, let me change that quickly..
what is the TLDR version of your issue.
Whats happening vs what you expect happening?
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.
so you want to check if both have the same physics material or something?
Ya, exactly.
I wonder if its counting it as an Instance of the material so if its checking that rather than the type
I did notice the physicMaterial reference in the collider is set to (instance) as soon as OnSceneWideCollision triggers
goodluck running timer++ on different framerates
I'd say I could just set the AudioLink material to the instance in the collider but, there's no way of knowing whether they're the same without already doing that :/
oh yeah that might be creating its own instance of it
tbh framerate isnt really an issue at the end of the day since exact time doesnt matter, just a general one
lol okay
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
making timers without using framerate independent functions defeats the point of a timer
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
just add in fixedupdate for timer
deltaTime isn't something you check. its a number you use for calculations
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
you can check time at first then compare to time yes
Is there a way to convert it to a generic type of the original material? I'm a bit confused on how that'd be rectified ๐
I suggest you take navarone's advice since so far they have been one of the only ones giving some actual usable advice
basically in pseduco code
while(time < time + variable)
{
do this
}
I'm trying to think if its a better way to do this
Maybe not relying so much on physics material but some type of flag you set? I still don't know what the usecase is
to make things easier I would suggest using a Coroutine
but you can easily use the Update loop too with a proper Timer using DeltaTime or Time.time
Collision audio based on the physic material, for instance a glass physic material would play glass sound effects at different intensities based on velocity.
its dirty as hell but maybe take the name of the material to use in a lookup like Dictionary ?
Why not using fixedUpdate instead ? Isn't it more reliable because we are talking about rb magnitude so physics needs update ?
sure checking the velocity magnitude might make more sense in FixedUpdate, I just wouldn't put a timer there because it will be based on the PhysicsLoop not an actual timer
I suppose you can use Time.FixedDelta in fixedupdate timer, but its probably not even needed if you're just checking the rb.velocity
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
FixedUpdatecheck if velocity is low to none. If this is the case, storeTime.timein 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 compareTime.timeagainst 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 tonullto indicate there's nothing to check..
Simple check takes just a single variable and no coroutines
That gave me an idea, bool flag = collision.collider.material.name.Contains(audioLinker.material.name);, which worked!
not velocity, magnitude
The name has (instance) in it lmao. I am sad I missed that
nice! dirty but hey it works lol
yeah had no idea they were instantiated, iirc that happens on material if you modify something on it but no idea it did that by default on physic material
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 
its fine you have many ways to go about this, ultimately you should pick whatever seems easier to you
Weird that the direct comparison of PhysicMaterials didn't work though... You aren't making instances of them or anything are you?
I would print the names and instance ID's of the compared physicsmaterials in an else when if(flag) fails
plus the wisconsin college system is a joke that doesn't teach crap
most colleges teach you crap thats either outdated or not useful in the real world
Collisions turn them into an instance. 
I'm assuming my material link is no different, so they're both instances and thus, different. Even at a direct comparison
its more that like, things get brushed over so fast you don't even learn them. I think in the 5 years i was there, 1 lecture talked about pointers. Thats it. Subject never came up again lol
But hey, it works perfectly. Just gotta go download a bunch of audio clips now lol
yeah they have to throw so much material at you thinking you will use them all. Its good stuff to learn, just not in a school context. Mostly you can learn this stuff on your own when you encounter it imo
Yeah if they are instances then it explains why it didn't work before
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)
If you want to learn, you really have to take time and make things
You don't learn by listening, or watching
yeah pointers ARE important to know of course, especially low level. Butin C# for example you're not really dealing with pointers by default (its managed for you)
You have to make stuff. Make stupid stuff. Make broken stuff
As long as you make stuff and it's yours
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
it gets harder once you have gray hair on your ๐ฅ
@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)
Ahhh that makes sense why it was creating an instance..
I'm not sure how sharedMaterial would work actually ๐ค
Is it every material on that gameObject instead of just one specific collider's material?
Collider.sharedMaterial gives the one on that collider
^ the asset not an instance
The main question is - are you modifying the physics materials or no?
I am not, that seems better then 
Yep go with sharedMaterial 100% then
oh unity..forget they have material vs sharedMaterial
Can also get rid of the name.Contains check too and just use comparison
Well that was a huge oversight on my end haha, thank you for pointing that out
same lol I forgot even just accessing the property changes to instance, I thought only modifying did.
the more you know ๐ซ
๐ค code
i'm making my own spaghetti code right now, i think i got it
like its probably awful code
but it should work
Sick commentcs // Get the Rigidbody component rb = GetComponent<Rigidbody>();
Doing your own stuff is the best way yes, i took it as a little exercise for my pause. Now i go ๐
we can change it to Bots now
i always feel gross when i have a lot of ifs nested
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.
and by a lot i mean 3 or more
use the Early return pattern
helps with the nesting
if(unwantedIstrue) return
// more code etc.
dude it's AI generated i just prompted the logic and read the general workaround. Lot of negative people here i'm pretty disappointed... I know programmers are lacking social skills but hey, instead of being like this can't you help me to get better or help the one calling for help ?
We all know it's AI generated lol
getting better is not replying to someone problem using generated code that doesn't make much sense
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
I'm sorry but no, it does and it works because i tested it. So tell me why it isnt practical i'm still open to llearn
It does look like it should work ๐คทโโ๏ธ
I'm talking about the originals before you did the fixups
I did thousand of lines since 2017 thank you, but for a simple problem i can make a simple prompt. You didnt throw any code, i did my best
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
Can you not?
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()
{
}
spoonfeeding code sometimes isn't the answer. Explaining / walking through the problem with OP will be more benificial in the long run but hey you do you.
If you post on a public forum you have to be open to any critisim, i have no issue if someone corrects me. I don't take it as some offense or something lol
Of course there will always need fix, but to fix properly i need some discussion. I didnt know what she really wanted first
Both the spoonfeeding and the useless AI code is not helping
Can we spare the philosophy of programming banter?
alright
Yes, they are public. What did you try?
{
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?
Does it work? Then it's not bad
#archived-code-general message this is my goal, and this is what I tried to do.
i should probably test if it does lmao
as long as it works its fine, just make it legible
(check out the early return pattern I suggested)
Probably better than just posting the code ๐
ya know, might be helpful if i didnt check the x velocity only lmfao
If you are asking how to access a return variable, you just do cs float survivalTime = otherObject.GetSurvivalTime();Or whatever
Why does GetSurvivalTime just return the value you pass in though?
I want it to save the time I pass into a variable I can use in the scorecalculator script which I pasted above. And this GetSurvivalTime is called and passing the survivaltime in the playerHealth script currently. (idk if this is a good way)
Correcting me doesnt offend me. But you didnt, just saying bad code and format, that's why i got taunt. But ok, if you think i "spoonfed" maybe i did, i just got 500+ students but it was years ago, now i'm more kind and helpful.
if (health <= 0)
{
survivalTime = Time.time;
Debug.Log($"survivaltime from playerHealth {survivalTime}");
scoreCalculator.GetSurvivalTime(survivalTime);
enemySpawner.DisableSpawning();
SceneManager.LoadSceneAsync(0);
Destroy(gameObject);
}
like this currently
Sounds like it should be SetSurvivalTime, not Get?
Or maybe you want both
right, I should. Bad naming of me
no worries. we tryina help.
I mean I still thought the code was bad but I knew it was generated, no foul no harm though.
have a good day ๐
i lied, but ill have to check later what i did wrong
@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)
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
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?
How can i not ? (you're talking about the code taking too much screen space ? How can i help with code then ?)
Show me how Get/SetSurvivalTime works.
The code you posted last doesn't make sense
magnitude for example is both X and Y combined.
even though you should use the sqrMagnitude version as its more efficient
Dude i told you to read about magnitude
And i did all the code for you, read it
Oh yeah i eared about that, but i don't "really" get why
it saves you doing a square root operation which can be arguably "expensive" to do every time
instead you just multiply it by itself and you're good
so
var sqMag = rb.velocity.sqrMagnitude
if(sqMag * sqMag > someThreshold)```
Your code was ai no? No offense but I ignore ai stuff like that. The kind that takes away from human work. because I am strongly against it
Ah yes, thanks
Ai art, coding, music, etc
the important part about coding isn't to generate code, its to learn how to reason and logic your way thorough
That too
thats why AI suck, they just regurgitate stuff on the internet, you aren't learning how to problem solve
It was AI generated, then a human, me, read it, corected it, and tried to help you. Being against it won't change your problem, it's a tool. Then i told you to READ about the importance of magnitude instead of checking velocity and you just ignored it.
I'm sure you know well enough that these lazy AI answers are not going to help somebody in the slightest
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
https://docs.unity3d.com/Manual/scripting-vectors.html @zenith zealot this will be handy . bookmark it
will do ty
well it's sad, i learned a lot with AI. I does so much mistakes i learned a lot debugging it. But it does throw a base. An imperfect base to work on.
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
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.
I do understand your point, i have a lot of teachers and artist as friends. Don't abhor it, tame it, or the financial issue will get bigger (i hope not, but im pragmatic)
now the real question is, would this even be more efficient by any noticeable amount
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...
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
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.
There is a massive difference between a machine learning it and a person
If you say so.
a person learns, a machine just takes a ton of assets and regurgitates something from that
Think about any improvment is a kind of steal of the past system. It's all political to fix some global rules, but this will never happen. We just need to work with it, or get f**** by it :/
oh boy, could we possibly not have this discussion here
What it even means to "understand" something is an open problem in philosophy.
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
beginner... i have a degree ๐ญ
โข 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
Yeah that went to far sorry, just being taunt for using it to help someone. I won't make this mistake here again because it's clearly unproductive, but hey it works in my company and we need less programmer time for simple questions.
like i said, my bad for getting into the argument. thats entirely on me
you aren't the only person here, though.
lurkers can also benefit or be harmed from content here
Well, just in general. Some people are absolutely oblivious when it comes to debugging, and we have had plenty of people that come here and wonder why their AI generated garbage is not working
no i know, im just making a joke
deleting my posts is the only thing to do, sorry that it goes like this, i'm quitting this ๐
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
small things add up lol not something you should worry too much in the beginning . most people don't care about it but I see it as if you can optimize it so simply , why not
Thankfully this AI talk is a recurring issue so I'll see you all in the next meeting
It is just a form of bike shedding.
Well i did that with very young students, throwing something imperfect to their face (AI stuff is good for that) and i let them questionning what is done and why. But here it's just a trigger so delete, even my solution because yes, people need to stop to be lazy. I'm not, i'm just struggling with time.
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.
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
That is a typical BS response from someone who has no clue what they are talking about
That's not a productive comment so I will not be engaging with it.
You think it's a good idea to "throw" "imperfect" code to people who are looking for genuine help without any indication that there's an issue with it? Or is this bad wording?
I do this like a little exercise, finding a little solution to a little problem is my way to have small entertainment on my breaks. I just have no idea how it will trigger professionals (because im not, i make C# for fun).
Let me clarify for you. Programming something makes what you have done available to millions, pen and paper does not. you cannot equate the two. Programming is not intinsicly lazy
they're confusing automation with programming
Yes there are differences between writing with pencil and paper, and programming. I'm glad you spotted that. The problem with your observation is... I never stated otherwise.
No it's not bad wording (although my english isnt that good) it's a method of teaching. Then i throw the good answer and the sources but everything went to AI discussion instead of a discussion about the initial topic.
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
(im pretty sure they're a troll at this point)
No you're just making strawmen and getting angry about them.
angry
yeah definitely a troll
I tend to explain the process to them and link articles from https://unity.huh.how/ when applicable instead of spoonfeeding the answer, for example.
Calling my statements BS sounds angry...
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
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...
right, exactly, i didn't say BS, that was steve
Dude, when i post the clean code they tell its spoonfedding, when i suggest some reading it's ignored, when i post imperfect code it's hoops... I earned my life teaching with these methods.
So why take up his mantle?
well, if you aren't, then no need to continue that line of discussion.
This is not a "teaching" channel though, this is a help channel. Feel free to "teach" the correct way, but don't spoonfeed and/or post intentionally bad code
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
It's almost like people can have different opinions and personalities and that's okay.
What happened here?
its actually funny how many students in uni fully rely on chatgpt (but also kinda sad
)
we can probably just like move on from this yes? keep it Unity coding questions
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.
I can't say anything I didn't read it. Isnt this a coding help channel?
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.
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.
yes, if you need help feel free to ask
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.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I'll also add the scene & Material link:
https://pastebin.com/0abGJCxa
https://pastebin.com/xze3qH5Y
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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
Context?
none
this is an equation of motion
^ yeah
yeah
So what does it have to do with Rigidbodies
I don't know why it divides the velocity by the amount of time that has passed, though
Change gravity in what way? Do you want it so objects can get inverted gravity?
Rigidbody doesn't have a convenient "gravity scale" property
However, you can just apply your own force
Rigidbody2D does
and im not working in 2D
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
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
The formula you actually want (assuming you're talking about simulating planets or orbits or something) is this: https://en.wikipedia.org/wiki/Newton's_law_of_universal_gravitation
To calculate the current gravity force
wouldnt it accelerate the rigidbody for a few seconds before it reaches the customGravity force?
What does that question even mean?
how do you "reach" a force?
a force is not a velocity
You might be confusing "force" with "speed" or something
gravity is a force/acceleration
probably
force is just acceleration over mass / acceleration is force per mass
so it just extends to infinity?
Step 1 is probably to achieve a basic understanding of newtonian physics - especially the relationship between forces, masses, velocity, and position
what is "it"
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
Typically you hit the ground well before infinity
so i just use addforce(downwardforce*int, forcemode.acceleration) and i shouldnt worry about anything?

What do you mean by "not worrying about anything"?
If you want to just get a multiple of normal gravity, you can use Physics.gravity * whatever
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.
not doing anything else than this piece of code
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
Then there's no point in doing this at all.
What are you trying to actually achieve
it's not clear
well, nothing else beyond this code to get custom gravity for this object
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)
If you want this particular object to have different gravity than the other objects, sure it makes sense
void FixedUpdate() {
rb.AddForce(Physics.gravity, ForceMode.Acceleration);
}
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.
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
i think i got into some controversial topic 
Nah you just... asked a question that you didn't realize you were asking
And weren't clear about your intentions
no lmao, we're just super confused on what you actually want to get
so we're trying to sort out what you actually want
just as always lol
We're concerned because this formula would only be relevant if you were trying to compute the exact velocity and position of the object
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
yes
oh nah, dont worry. I think its just crossed wires, its not a insult but it does seem like youve misunderstood aspects of how rigidbodes work, so your questions are worded a little strangely as a result
just as ol' Cave Johnson intended
throw peas at the wall and see what happens
im pretty sure it was something about making orange juice
the oranges explode or catch on fire or something like that
Basically instead of this question, it would have caused less confusion and led to faster help for you if you just asked "How do I get one object in the scene to have different gravity than the rest of the scene"?
(although I'm still not sure if that's what you want)
why does life give me lemons? take the lemons away from me! what am i supposed to do with these?
more like (downward) acceleration of gravity not some static unity gravity type of thing
(downward) acceleration of gravity
Yeah no idea what that means
gravity is a thing that causes downward acceleration of objects
you can always accelerate the gravity upwards i think
wait no
it would happen with negative gravity
my bad
no, upwards gravity just means you're redefinining "down" or where the gravity points
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"?
technically acceleration of gravity is already negative by convention since up is typically positive
idk
i made 9.81 force in the unity's physics settings window or something like this
anyways, what is it that you're actually trying to do
that's the default.
And what issue is there with that?
in high-level terms, not with this physics jargon
i dont get the physics now
my head is now a bunch of unsorted info
-# just as it shall be
Well at some point you could write a simple sentence in english explaining what you're trying to do.
im Polish so my english is not perfect yet๐
This does not make any sense
Perhaps you can show an example of a game that does what you want to do?
i saw some dev guy on yt shorts talk about gravity in 2D games(he did it by hand, he did not set it in rb2D)
some game about a blue haired ninja or smth
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
now while were talking about gravity, its really weird thing
one thing pushes you and other thing keeps you at the surface
the normal force, yes
i hate floaty jumps
especially when the gravity is the same as you descend
your decent gravity should be heavier than your ascend if you want it to feel nicer
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
Well it's unclear sort of because one of them you have TWO lines on for some reason
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
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
that sounds like the opposite of what those blue lines are
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?
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)
ok so that sounds like two different problems:
- Identify all cover that is hidden from the enemy
- filter out to only covers that are further away from the enemy than the player is
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?
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
The brute force solution here is to basically have every "Cover" in a list, along with their normal vectors.
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
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?
lets say you define the normals as those blue lines in your diagram. Then to see if the cover is valid you would do:
float dot = Vector3.Dot(blueArrow, redArrow);
bool coverIsSafe = dot > 0;```
the dot product will return negative values when the two directions are "oppositish" and positive when they are "sameish"
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
I see, that would be good
ah ok, useful stuff
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
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
gdl.space broke, so use another site
ok sorry
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)
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
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Wrap the code in three backticks, like this:
```cs
void Whatever() {
}
```
Adding the "cs" to the first line gives it nice colors
okay wait
but you can just use cinemachine here tbh.
idk what is this but thx
its easy to look it up , its so you don't have to reinvent the wheel
https://unity.com/features/cinemachine
doe smoothing and all that for you , no need to manually lerp or anything
okay idk how to use it but thx very much
its very simple, you just add a new virtual camera and set the follow target. The link i sent has tutorials on each component / follow mode you can use
okay , i didnt see anything but thx
nah im just stupid
i didnt click the link
but is this a ''addon'' or is this on unity by default?
nah i found
its a package you download from unity package manager
yeah i saw my bad
one last question , how do i make that the cam doesnt have lag and is center to the player ?
couldnt find it
in the manual
wdym lag? probably you mean the Damping ?
and its usually centered to the pivot, so whereever your pivot is
idk what is damping but like its follow behind the player , with latency
lower the damping values
wut is damping ?
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
Just temporarily change your object's layer while you do the raycast
then set it back
what about particles and stuff though
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
for raycast that would work but how could i have particles and stuff ignore just the player collider
oO i didnt know that function thank you
you are an absolute mad lad, I made a prototype (using the example you gave) to find the normal's that are safe which works well https://hatebin.com/qpfuvpcugf. thanks for guiding me in the right direction
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.
ho okay thanks
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
I'm struggling to understand the benefit of the S in SOLID (SRP), does anyone have some good examples/resources on this?
The benefit is that when you want to change something, there is one and only one place to make the change
It reduces programming errors and mental load.
I get that, but stuff like splitting a Die() method from a script that handles taking damage, or splitting health from taking damage seems super counter-intuitive for me
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
In that case you would be using interfaces ( IDie ) etc and inheritance right?
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
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
But if that's not the case, then it belongs somewhere else
Sure but if the whole point of SOLID is the what if... then... what if in the future you wanted a target dummy that can't take damage?
from my experience i use a health script in itself, which simply offloads logic through UnityEvents, and passing a hit struct thgrough that event
at least that's how I'm understanding it currently
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
that's an interesting way of going about it - I haven't gotten to play around with UnityEvents yet but I should probably look into those
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...
for this case you could have the same effect of hitting a target dummy with health, but having a 0x multiplier would make it not take damage
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
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?
what is dependency injection
the D in SOLID
from my understanding a method/class not caring about the specific thing passed into it
oh yeah
like when you have a Enemy class, and Skeleton and Zombie inheriting from it
and functions acting on enemies can work for ALL enemies ay
or maybe that isnt it idk this whole SOLID thing is making me feel dumb
yes i think at least thats what DIP was
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)
also like your profile picture and name it makes me look insane XD
hahaha
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)
oh yes inversion my bad, we learned about dependency injection recently and i got them mixed up
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
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
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)
I know but my biggest module at uni revolves around SOLID this year so there has to be something objective.... right?
though a lot of times you'll see it more relying on interfaces rather than other object types
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
this is called "composition" and is a way to loosely couple your objects over inheritance which is more tightly coupled
interfaces = composition and inheritance = inheritance right?
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
i know its a bit deeper than that
interfaces are inheritance too but unity as a whole is kinda built around composition, so i find myself rarely using interfaces
interfaces are one way to implement composition, yes. but you don't have to use interfaces for composition. think of a gameobject. it is composed of multiple different components
ive maybe used an interface less than 10 times in my time with unity
interfaces are not inheritance. though a lot of people (wrongly) treat them that way, they should not be used to inherit behavior. they should be used to ensure objects implement specific ways to interact with them, but not guarantee specific behavior
yeah ye tru
its just cos it is same syntax as inheriting a class lol, they inherit the framework but no default behaviour
I wish you could do something like
public IFoo, IBar doesBoth;
give me typeclasses, dammit
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?
well, roughly? sometimes it's pretty clear that a class is doing more than it should, but not always
I think a good thought exercise would be to think about a Car implementation in a single class, then break it into reasonable parts
so for instance, if you change the brake system, it wouldn't affect the fuel system or something like that
I use almost zero interfaces in my game. It's just a bunch of composition.
but there will never one "true" answer saying that you divided the parts correctly
i would suggest damagable should use a seperate script because there is usualy common / default behaviour with damageable objects
yes but in that case, if you split the functionality into methods rather than classes, don't you end up with the same result?
not really because then you most likely are going to violate the other SOLID principles
I would question the logic of having IRangedAttack and IMeleeAttack in the first place
once you've got it split up into different methods you can then split those methods off into more related classes. single responsibility principle doesn't refer to just classes. your methods should also have a single responsibility
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)
it shouldn't?
yeah the functionality should be split into different components that are then attached to a Zombie gameobject
why is Zombie so special that it's a unique kind of object?
will it ever make sense to operate only on zombies?
and that is pretty much the basis of composition
exactly what i was saying
That's a good question to ask yourself
a zombie should be the gameobject composed of generic scripts that make up a zombie
Does it make sense to specifically care about this thing?
holy moly ok now youve got me reconsidering what ive been learning as a whole
My game is just Entity. That's it. You're an Entity.
because skeleton and zombie classes are like the most basic inheritance example we were given
Player? Entity. Monster? Entity. Door? Entity. Spectator? Entity
brothr i dont even do that lool
Entity includes some basic requirements, like having a name
it really boils down to composition vs inheritance. and especially with unity you'll really end up better off with composition because that is what the components are for
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
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
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
yeah, almost every "animal -> dog" example is a godawful use-case for inheritance
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.
I still use abstract classes quite a bit, but i rarely ever go beyond a single layer of inheritance deeper than that
bingo
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 ^
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
yeah its important to compose the definitive object from generic components
That's kind of my brain situation. PlayerHumanoidBrain only makes sense with HumanoidLocomotion, and PlayerSpectatorBrain only makes sense with SpectatorLocomotion.
eg you take generic / reusable behaviours a b c and d, put em together to form a "skeleton" gameobject
in that case wouldn't you couple them again? but then you break SRP
Not if A+B+C forms a single coherent job
you can always cut a class in half
