#archived-code-advanced
1 messages ยท Page 70 of 1
Thanks! That was great advice. It works now.
And just in case someone else searches for "update asset" or "overwrite asset"...
var path = "Assets/CortiWinsTool/MyQuad.asset"; var loadedAssetMesh = UnityEditor.AssetDatabase.LoadMainAssetAtPath(path) as Mesh; if (loadedAssetMesh != null) { createdMesh.name = loadedAssetMesh.name; UnityEditor.EditorUtility.CopySerialized(createdMesh, loadedAssetMesh); UnityEditor.EditorUtility.SetDirty(loadedAssetMesh); } else { UnityEditor.AssetDatabase.CreateAsset(createdMesh, path); }
This is why they upgraded it.
you should ideally have a distince interface to distinguish the two
oh?
wait is the IEnumerator thing an old way of doing it? is there a better way now?
Maybe you will be interested in https://gamedevbeginner.com/async-in-unity/
Yes, that would be consider the "old" way.
my understanding is coroutines are less flexible as tasks / valuetasks, but they are more performant
benchmarks I have seen usually have coroutines coming out a bit ahead of tasks
Tasks biggest upside is they have a return, so you can distinguish a Task<int> from a Task from a Task<string>
unless coroutines do have the ability to have a return type? I havent seen documentation on that yet though but I wouldnt be surprised if it exists
More performant ?
Not comparable imo. Tasks run from a threadpool in .Net while Coroutines are sliced up Update-Calls.
Coroutine run sequentially.
I built it and there is no memory leak in the build

Maybe this would help you https://docs.unity3d.com/2023.2/Documentation/Manual/AwaitSupport.html
you can largely speaking translate pretty much anything between coroutines and tasks, one just has more boilerplate than the other if you actually need a Task<T> instead of plain ole Task
As per the documentation:
In most cases, Awaitable should be slightly more efficient than iterator-based coroutines, especially for cases where the iterator would return non-null values (such as WaitForFixedUpdate etc).
yeah I would expect tasks to perform better but I was checking some blogs out where they did test cases for a few ways to approach async ops in unity, and the coroutines were edging out ahead of the Task stuff
Also, you might want to consider the JobSystem if you still working on what you were doing earlier.
yeah the job system was the other thing they tested, and there was a fourth one, forgot its name
And probably even ECS(DOTS) as how you were speaking you seem like performance was a HUGE factor.
nah, not a big factor, maybe?
Ill see if it matters, I am building for mobile so it might actually come up
If they were measuring the overhead, maybe, however it would not really matter for you won't it ?
I mean, if you need parallelization, the overhead would be pretty small in comparason of the performance gain.
That is a risky statement imo. In coroutines you can safely use all Unity functions because it is called from the mainThread, while in Tasks you need to be much more careful.
Its starting to look like I do indeed wanna use coroutines, not tasks for this, because I need to "watch" for a state on my monobehaviors (wait for them to not be busy), and tasks might be an issue with that, Ill have to test and see if it actually works or if it breaks
Let's me suggest the usage of your own dispatcher then. Instead of relaying on the incertitude and complexity of coroutine, you can simply use a function call on a given object of your choice and manipulate its lifetime.
Tasks run from main thread in Unity synchronization context
Using Coroutine as Update Function leads most of the time in complicated worflow.
oh thank god, Zenject supports list injection ๐
Good to know, thanks!
Is anyone here good at c++? I'm working on a dll plugin to open a thread that runs alongside my game and exposes some information from rawinput to the c# scripts. It almost works, but for some reason my calls to "bool GetDeviceKeyHeld(int deviceId, int keyId)" always return false, even though I can step through the debugger and see them getting set in the way I expect. I think I messed something up with the way the getters are called. I'm gonna struggle to describe the problem, so I'll save the details for if anyone thinks they can help.
Anyone know what these types of allocations are, and if they can be avoided with some pattern/workaround?
Where are they called from?
All over the place
while they aren't individually very high in mem alloc, some code paths can be pretty hot that they are in resulting in a decent amount of memory
What's in that MiniTankScript.DistAtAnhle() method? Is that your code?
nothing special
And MiniContext.WrapScope()?
It's probably the use of dynamic that causes the allocation.
ah rip, oh well, its not a massive problem, guess ill just live with it
I'd avoid using dynamic. Is there any specific reason you need it? Are you interfacing with a different language there?
yeah, i wrote a scripting language that can be changed/etc at runtime
basically the script gets compiled into a set of nested closures, and needs to be able to work with various return types, so dynamic seemed like the perfect fit, still getting like 200 fps so not game breaking w/ the allocations, but oh well
I see. Well, if it works for you, that's fine I guess.
Just so you're aware dynamic will not work with IL2CPP so you'll be locked to Mono.
Yeah, I was aware of that. Not a problem in my case just making this game to pit the programmers at my work against eachother with scriptable tanks so I don't have to worry about Playstation or Switch, etc where you need il2cpp
I'll see if there is a reasonable way to avoide the use of dynamic, but since the scripting language is similar to javascript it seemed like a good fit
Hi, I would like to make something like nanite but for Unity, as long as I know nanite it's just like some kind of autoLOD, so if someone could help me with this I would be grateful.
both tasks and valuetasks are not more performant than coroutines. As a matter of fact it will allocate more than coroutines unless you do your own custom struct-based AsyncMethodBuilder
in 2023.. there's awaitable api it should be comparable to coroutines now in terms of allocation
I have an editor script editing Environment lighting settings via RenderSettings static class.
It works great except when I change these settings in editor, I have to mouseover the unity GUI for the scene view to reflect these changes.
Is there some function I can call to reproduce this behavior without having to manually move the mouse out of the scene view?
maybe you calling OnInspectorGUI, you can also use OnEditorGUI
dymamic uses Reflection.emit under the hood, so yeah, you cant
guys i am building an image editor, but cutting images in single thread is slow (i probably didn't optimize too well but i don't have much time). Multithread is out of question because of webGL requirements. You think it's good to send all infos to a shader and do the cutting there, and reading back from the shader using a renderTexture? You know of some way to optimize image cutting?
Compute Shader out of question too for the same webGL requirements
Not exactly sure how you would proceed to cut an image directly from a Shader.
Personally, I think you should do it single threaded and spread on multiple frame. Ideally, you would use a server to process the image instead of doing it client side.
Spreading calculations in multiple frames won't take less time to compute ๐ฆ
I was thinking if sending a StructuredBuffer containing the points in UV space and sampling every pixel like that might help, because every pixel can be computed parallel on gpu. Point in polygon algorythm should run a lot faster, even if there will be some conversion to do. There are also probably some calculations i can skip
If somebody that works in image processing has some nice resources for image cutting, it will be much appreciated
It sure won't however, the user can wait if you do not simply freeze the application.
And, if you truly want to do image cutting in a Web Environment, you should definitely make it on a server.
This is true, but server costs and client loves money! Thanks for advice mister!
The cost of server is actual super low. Also, you can use your own OnPremise server.
hi there, i have a bug and i wonder why it happen in my android device, because i think it was only something for testing in unity, if a check reload scene here
then my class Game call playerloop utility and get a null
so it crashes in line list<playerloopsystem> , i can understand this bug in unity editor because i check only reload scene, but why i get also a null on my android device?
any chance your Game class is just getting stripped out of the android build? if there's no other references to it maybe it needs adding to link.xml
but also it crashes in unity edito
also i make an empty scene and this game.cs still making crashes, if i modify the code works, like the cache or something is reloaded, but when i press again play crashes because get a null from playerloop
right now is fixed if i uncheck reload scene, but i wonder why i must learn this
oh i misread that part, what exactly is null here? the result of GetCurrentPlayerLoop?
yes, if i check reload only scene, then is like the loopsystem is empty
that would mean that subSystem.subSystemList is null
im close to code newbie but i think this should be posted here, in google i cant find more info or i dont know how to search this
if you just "check reload scene" there from the state of the screenshot you posted
you will be disabling domain reload in editor on play
by default both domain and scene reload are active
dont know
interesting
i don't know this API too well but maybe you should just be skipping the subsystems where subSystem.subSystemList is null since you appear to be searching for a specific system? and those obviously won't match
Is there a way to get the OpenGL context via c# or c++?
Not exactly sure what you want, but maybe this could be useful to you: https://docs.unity3d.com/ScriptReference/GL.html
So I'm trying to use an API called Triton which is an advanced ocean renderer. It draws the ocean in its code, but it wants the OpenGL context so it can draw directly to it.
I got it working. Indeed had to use expression trees. It really wasn't that hard at all, as you said. Just needed to brush up on a few of the specifics and actually got it working first try. For unregistering I just keep a copy of the callback the user passes and the delegate that the expression tree makes. And on unregister I fined the matching callback and then unregister the paired delegate.
Still can't believe it worked first try. Makes me think I did something wrong haha. Well thanks for your help, you too @dusty wigeon! ๐
Nice, glad you figured it out
I just rewrote all my expression trees to horrifying reflection
(because il2cpp ๐คฎ )
Oof, much slower too! At least in editor that doesn't matter.
Eh, I can still generate delegates and cache them
So it's not that much slower but still some
I remember that expression trees didn't work on some Apple platforms (AOT platforms?). Do you know if that is still the case by chance?
Dang, that's too bad really. They are so cool
But it's really only ios that (used to?) ban it
Apple did loosen some restrictions but Unity doesn't really want to support it
I wish they would. Maybe with/after the CoreCLR thing
Doubtful
Don't think they'll move away from il2cpp
Or do runtime conversion (which likely would be super slow anyways)
I wonder if it would be possible to add support for it to il2cpp
Maybe but the toolchain would be too big to add
Yeah that is what I was thinking
Question, do you know if it is possible to copy the data from one class to another if they are exact mirrors?
In what context
There is the SerializedPropertyBindEvent internal event, and I was thinking it would be nice to just make my own MySerializedPropertyBindEvent and 'convert' from the internal one to mine.
That way you still have like .target and .currentTarget etc.
with reflection, yeh
Guessing expressions is the easiest again
If they were structs you could I think, assuming the same byte layout, cast the pointer
Probably, sadly they are classes though
for just cloning class A to class B, you just use reflection to iterate over all properties/variables an Get em, then Set em on the other
Yeah, there is that, though that sounds kind of expensive
I think thequestion whether you can do it without reflection ๐
its not, its actually technically one of the fastest ways to clone an object if you do it right
In what way
Yeah the real question really is without reflection since I know you can use reflection
you also can just write a constructor for B that takes in an A and just manually copies the values
Decorator Pattern
SerializedPropertyBindEvent is internal
Well I mean you have some kind of Foo in your code that derives from it and has values right?
Nope
Where are you getting the values from
Reflection
Reflection of what though
whats the method(s) at play here, so I can first go take a look at their documentation real quick so I have context
Source generator mappers would like to say hi.
Again internal
The tldr, Mech is subscribing to an internal event that has an internal class as parameter (using reflection and expression trees)
Ah.
That internal class is cast to an object (or discarded, I forgot) using expression trees
So the question is how to convert that object to his internal class
oh yeah you 100% need to use reflection to get the values still yes
if its internal event with internal prop on it and internal class and etc etc
It feels like there should be a nicer way to do it with expression trees
what do you mean
no if you keep all the names the same, reflection will be like 3-4 lines of code
I mean performance wise
Im not sure what makes you think performance wont be good
Because reflection is (compared to direct access) very slow
I mean if it's just a few props and it doesn't happen often it's fast enough
But expression trees should be easy too no?
you have really 2 options
-
Fetch values with reflection and type cast them manually, set them normally with a constructor or whatever
-
Fetch values with reflection and set with reflection
Shouldnt be hard to benchmark the two options and figure out which is faster
actually maybe you can have a clever shortcut by injecting into constructor with uh... object.create or whatever? But you have to keep in mind that if you re-arrange or modify the things constructor it'll explode if you dont update the creation code too
Looks to be 20 or so. And Unity likes to call bind events... places...
How would ya do it with Expression Trees. What method(s)?
What do you mean about 1 about type cast them manually?
like get each value individually (which will be an object from reflection), then cast em to the specific Type you know them to be, and now you have all your strongly typed props, and then call constructor of your CustomClassB(...) passing in all your strongly typed variables
And probably use reflection to iterate over all fields
so at least you are only just doing the Read with reflection, but your Writes are normal
Ah right!
how many values are we talking here
ohh got it. yeah that seems like a massive pain especially since some Properties are private set
huh?
Quick glance it looks like about 20
Yeah so if you really care about performance, manually pulling each value individually by name with reflection will be fastest (avoids logic branching) I expect, but then you gotta maintain each of the names if they ever change
Actually hmmm
I wonder if you can quickly compose an expression tree... using your other class though
Yeah, I the UITK (where the event is) codebase is to volatile for me to want to do that. But that is a good point. Appreciate the suggestion
like first build an Expression<Func<ClassB,T>>
then use a bit of expression tree reflection magic to actually turn it into Expression<Func<SerializedPropertyBindEvent,T>>
which I think is just a matter of making a new instance of the uh, root class, and passing the rest of the tree into it for the selector
lemme double check some code I got
In other news, my new approach to my engine where I pre-calc all my entities multiple rounds of movements first, then actually queue them all to do those moves, is working pretty good.
I think I need some kind of data returned from each entitiy as the round queues for a "duration" they need, and then everyone also needs to wait and ensure that time is up as well (thus if you have 10 units that take 1s to move, but 1 unit takes 3s to move, everyone else will pause for 2s)
Btw reflection is only slow on the first access
It is cached afterwards, should be pretty close to direct access.
Possibly for getting the info type.GetProperty(..) (don't think so though). But not for propertyInfo.GetValue(). Unless something has changed that I missed
Well, there's at least a very noticeable different between CreateDelegate and InvokeMethod
Could be generic related but it's not all optimized (and thus manual optimization is still very much worth it)
would the symbol UNITY_STANDALONE also include dedicated server builds or can I safely assume this symbol would be client builds only?
Unsafe.As given that both class has exactly same layout ๐
Unity version would be UnsafeUtility.As
Oooh... I will give that a try! Thank you! Does it include properties, or just fields? And same names?
properties are functions
they don't hold any state
only fields and events do
though at the memory level events are just delegate fields I would assume
That is what I though cool
Name doesnโt matter, Not including property except backing field
I have an assembly that I want to make sure is only included in client builds and never the editor or server builds.
you can set the platform in the inspector of the assembly
actually I guess I could just do a !UNITY_SERVER constraint to target client only (and exclude editor platform of course)
Any good resources on using advanced Mesh api?
I'm trying to generate custom meshes based on voxel data and already have it working decently with SetTriangles/SetVertices but want to optimize things further
Yeah, this series from Catlike Coding is top tier
https://catlikecoding.com/unity/tutorials/procedural-meshes/creating-a-mesh/
And a repo showing examples of how to use the API from a Unity developer
https://github.com/Unity-Technologies/MeshApiExamples
Thanks, ill look into it! was already familiarizing with Burst
I thought this would be as simple as throwing all my logic in a coroutine but thats not how they work ๐
See #archived-code-general for other docs, resources, and roadmap.
See #1062393052863414313 for questions relating to the Data-Oriented Technology Stack.
๐ Resources
C# Discord
i have an issue that i think is in my script but i posted it in animation and dont want to get banned for cross posting so can someone dm me who can help
nvm i fixed it : )
is there anyway to reset Cinemachine Framing Transposer position, that let the follow target at the center of deadzone ?
the gameplay sometimes reset player position to world origin (0,0,0), I want player at the canter of deadzone as well
hi. there any preprocessor for debug builds?
I want to use them for compile-time branching
there's a DEBUG but Rider can't take me back to it's source so I don't know what it's for
Edit -> Project Settings -> Player -> Other Settings -> Scripting Define Symbols
Click the + button and add an entry for DEBUG. It should recompile the scripts and Rider should pick it up automatically.
If you want to build without it, remove it from the list.
thanks, but that's not what I'm looking for. I'm looking for a preprocessor that Unity already has for debug times (editor and dev builds)
UNITY_EDITOR and DEVELOPMENT_BUILD
But you can assign your own in the project settings.
seems the two should work with a DEBUG (https://forum.unity.com/threads/solved-is-unity-debug-preprocessor-always-defined-yes-by-design.400542. ) but DEBUG is a little buggy? the post was from a good 7 years back tho, I have to test it with 2022 myself it seems
multiple preprocessors seem too much code. if Debug works, it'd be nice
if only we could do bool operators in #define like #define ANY_DEBUG = UNITY_EDITOR || DEVELOPMENT_BUILD || DEBUG
You can
u mean with a const?
I just tried this
#if UNITY_EDITOR || DEVELOPMENT_BUILD
#define FULL_LOGGING
#endif
maybe have an undef in the else branch or maybe it isnt needed
hmm yeah that's a good trick! thanks mate
You're right
I mean that's csproject defines
that's conditional? I'm not familiar with that
It's not
Maybe you can change them per target but not conditionally like you are doing
We use Jenkins to modify the project defines. That way we can do project-wide conditional defines.
project as in, the whole unity project or the assembly?
Whole Unity project
for live ops and full production it's just standard
ah I see
Yeah pretty normal to do so
How to hide colliders if it's disabled in scene view? Because when I disable collider, I can still see them but I don't want to see , Version 2021.3.14
How is that an advanced code question? Let alone a code question at all? ๐คฃ
Gizmos hides all, I want to hide only if collider is disabled
I can still see and edit colliders even if they are disabled in my editor, using iMac and unity 2021
try on windows and unity 2023/LTS
the issue is that CharacterController inherits from Collider
and how collider gizmos are designed to work is: as long as there's an enabled collider, render all colliders
what is a character collider doing on an object with so many colliders anyway? should be deleted imo
generally, so many components of same type on a single game object is dangerous
Removed character controller, disabled all colliders but still showing, not hidden
Seems it's unity bug
told you they don't hide, they just fade
hello ๐ I am planning to procedurally generate levels in my game using evolutionary algorithms. I would love to create AI that plays the levels and scores them according to its runs. Is it possible to run/simulate the game from within the game itself (so that the levels can be played and scored by the AI)?
I think the new input system lets you fake inputs through code
But really it is on you to add support to your game to simulate it
okey, thx
sounds like you need to look at the Unity ML package
Oh so bad, no way to hide?
I don't think so, it might make it better, but I am going through evolutionary algos for academic purposes. Great to know it exists though, ty!
you'll need to disable the gameobject. that'd work if your colliders were on separate gameobjects.
either disbale the gameobject or remove the component altogether
if you're keeping them in a single gameobject for performance, you can write a script that separates them into separated children for editting, then back to a single gameobject once done
& of course that'd break any connections from the colliders you if had any (that's fixable too, but too complex for a quick script)
Be careful, evaluation can be quite difficult and time-costly if you intend to do it inside of unity, as you'd have the play the entire level - afaik it isnt super easy to speed up simulation (ive never worked with unity ml agents, but this might be a solution for you)
you should really spend some time thinking about the overall architecture of your project in order to make it feasible, you said you are doing it for academic purposes and I am assuming it is for a course project then, tight deadlines and stuff
well I hope it being time costly shouldn't be a problem when used as a design time procedural generation, but I'll see and potential give the ML agents a go as well, if evolutionary agents are not feasible
Well if you need to evaluate the level, and I assume you mean by letting an agent play through it, that can be quite costly
ideally you'd run your environment as fast as possible, like many of the gym environments - in an effort to speed up evaluation
And if you want to train an agent for every newly generated level, thats some extra overhead aswell
I am not sure yet, it may also be just using the unity physics to compute some thingies around the generated level
it's gonna take long and the overhead will be massive, I am well aware...
might be better from a research perspective to use DOTS for this instead
unity physics isn't deterministic iirc
And its also fairly trivial to up your simulation speed for Entities.Physics
But take a look at ml agents first!
thx! yeah, I will take a look at them and see what I can do
Consider adding in some procedural generation layers.
An acquaintance of mine got good results by first procedurally generating a structure which then was fed into his generative ai system.
For my script, I'm trying to make it so that once the player steps on a "SafeZone" a place where they can change their character, it updates a Ui sprite showing what character they are. The variable currentCharacter doesn't seem to be updating even when the "Player" is colliding with the "SafeZone". Here is the code.
https://paste.ofcode.org/63uE92nHJKKHYcxgmn6SwV
part of it might be that I'm using GameObject.Find and gameObject.CompareTag, the reason this is here is becuase my player objects are all prefabs and can not be referenced through the inspector window, another issue might be that referencing a collision of two seperate gameobjects unrelated to the UI Sprite might be causing an issue, or at least that's as far as I can understand it
Does anyone know if it's possible to run an accurate stopwatch/timer between OnAudioFilterRead and Update/FixedUpdate ? I want to know the delta so I can offset stuff accordingly on the main thread.
I tried SystemDiagnostics.Stopwatch but it didn't work as I hoped
So I've been trying to implement MQTT and WebGL in Unity using MQTTNet. As usual, everything works fine in the Editor. I connect to test.mosquitto.org:8080 using WebSockets and TLS. But as soon as I create a WebGL build, nothing happens. It gets stuck at connecting to the broker.
Anyone know a solution to this?
Why do you need it, are you doing some sort of precise audio syncing?
Yes, trying to make a sequencer
You don't time it
Instead you should establish a sync point (x in Time.realTimeSinceStartup corresponds to yth sample in the audio data) and then you can freely convert between timelines.
not 100% sure i'm interpereting you correctly, but my reasoning for trying to do this is to account for any samples processed between the previous OAFR and the current Update.
here is a post i made yesterday with more context: https://forum.unity.com/threads/any-reliable-way-to-get-time-passed-between-onaudiofilterread-and-fixedupdate-is-that-even-useful.1462103/
Yeah you don't do it like that
If you want your beats to play at 120 BPM, then they should be 0.5s apart
If the first beat starts at 12.345 DSP time, you already know the next beat should play at 12.845 DSP time
You can just schedule it ahead of time, without needing to know anything on the audio side.
Good point... i thought there was some reason i needed this, but i may have lost sight of the basics along the way lol
I added a timeout, but it also ignores the timeout. So there is something entirely broken.
does anyone know how i can make an object jump to a another plane regardless of its position i tried making it move to the plane but i don't know how i can make it jump to the object
When I was searching through the unitys soure code, I found this bit of code which to me looks like a bad idea performance-wise because they are calling the min (same for max obviously) property three times where one would do the job. If the Vector3 addition is really done 3 times and each time only the relevant component is used, it sounds really wasteful (I know we are talking about really small performance gains but I imagine unity is trying to squeeze every bit of performance possible in their code). So is there some specific reason why this isn't bad? Is the compiler smart enough to optimize this anyway or does it have something to do with the aggressive inlining?cs public Vector3 min { [MethodImpl(MethodImplOptionsEx.AggressiveInlining)] get { return center - extents; } [MethodImpl(MethodImplOptionsEx.AggressiveInlining)] set { SetMinMax(value, max); } } [MethodImpl(MethodImplOptionsEx.AggressiveInlining)] public bool Intersects(Bounds bounds) { return (min.x <= bounds.max.x) && (max.x >= bounds.min.x) && (min.y <= bounds.max.y) && (max.y >= bounds.min.y) && (min.z <= bounds.max.z) && (max.z >= bounds.min.z); }
Pretty sure you would want to cache the min/max value. However, as you said, the difference should be minimal. Also, if you cache the value, you might have worst performance in some case (where the first condition fail).
i have a rotation clamp problem i cant solve, is this the right place to ask for help?
or is it considered beginner code problems?
(If you know programmation and only the clamp is giving you a hard time)
yes
Wireshark shows absolutely no outgoing traffic to the MQTT broker. So the WebGL app simply doesn't do anything.
I'm working with a custom dll plugin and I need to do a lot of deleting and replacing it in the editor. Problem is that whenever I run it, hooks are made which prevent me from deleting it without restarting the editor. Big pain. I'm having a tough time finding info on this on the web. Anyone here know how to make sure all hooks are cleaned up on exiting playmode?
I'm making a custom playable track, and I need the clips to have direct references to other clips on the same track. I'm making a property drawer and trying to get a list of sibling tracks; what is the best way to go about this?
Figured it out, I had to feed the references into the custom PlayableAsset script via the custom TrackAsset script, and then rely on that in the drawer.
Hi everyone,
Does anyone know how set the game window pixel size depending on computer display rez?
I have a windowed game that i want to set the rez to 1200x1200 for 2k monitors and 950x950 on 1k monitors etc. any ideas?
Hey actually this may be more advanced but If I'm getting live input from the microphone in Unity to visualize a block moving up if louder, how do i increase the sensitivity so for even the slightest sound the block moves up more if that makes sense. Any help is greatly appreciated!
Amplify your signal?
Is there any performance impact between using a Native Array or an Unsafe List?
They can be burst compiled so maybe better than managed version
Though if your algorithm has a terrible time complexity they cannot help you much
sure, just not with JsonUtility
Newtonsoft JSON can do it
is it an inbuild library in unity?
it's a library you can install from the package manager
hi. is the Value boxed/unboxed when the project builds for release?
public class StructHolder<T> where T : struct {
public T Value;
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public object BoxAndGetValue() => Value;
}
or will it get inlined and bypass the cast?
lets say we use it like
int val = new StructHolder<int>(){ Value = 123; }
.BoxAndGetValue();
if it does indeed inline and avoid boxing, then my next question is: will it still be inlined were the method overridden from a parent class?
public abstract class StructHolder {
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public abstract object BoxAndGetValue();
}
public class StructHolder<T> : StructHolder where T : struct {
public T Value;
public override object BoxAndGetValue() => Value;
}
It will be boxed.
Because it is cast to object, which is a reference type.
If you want to avoid boxing, you must use it in a generic context.
Inlining doesn't actually change the behaviour of your code, the difference is just that there will be no actual call to BoxAndGetValue()
Meaning your example would be inlined to:
var val = (object) new StructHolder<int>(){ Value = 123; }.Value;
more like
int val = (int)(object) new StructHolder<int>(){ Value = 123 }.Value;```
and so I was wondering if the compiler will be smart enough to remove that extra useless casts
well your example has var which is of type object
is there even a way to test that?
because it's inferred from the return type
It's possible to examine the generated IL, but I've never done it.
However, I would say that no, it can't, because it would be breaking your API which returns object
if you want to assign the int without boxing you can do:
int val = 123;
๐
btw I had to solve a problem like this myself for an event system
does compiler even care about API in inlined release code though?
It's possible the same solution coudl apply here, but given the limited example it's hard to say what your issue is.
AFAIK inlining shouldnt' change the behaviour of your program, it just eliminates the stack frame
Since returning object si a cast to object, it's totally possible that boxing was your intention
Just because the cast is implicit doesn't mean it's not the intended behaviour of the program
yeah that's what worries me. that it might think I actually had a reason for that object and wanted to make sure it's casted
and can't easily test the damn thing either...
You're in a dead end here
While there may be a solution to your problem--this is not it.
What is the problem anyway?
I see. thanks for the info mate.
as for my problem, I want a collection of value types
yeah but generic
How will you know where each index starts and ends?
like object but only structs
the list is not that low level. I had that wrapper class above to store the elements in the list
Um...
List<StructHolder> Sh;```
to add:
```csharp
void Add<T>(T val) where T : struct {
Sh.Add(StructHolder<T>(val);
}
Do you want to store the values inline?
Or do you want to box them?
Because you can just do:
List<object> myStructs;
which obviously boxes them
But that's really the only way to do it without sometinhg absoultely bonkers
Or, the normal way of approaching this, is to have multiple lists, one for each type.
This StructHolder is basically a box with extra steps. It's creating an object to hold a struct.
Yep, I actually have this same thing:
namespace EffortStar {
public class Box<T> where T : struct {
public T Value;
public Box(T value) {
Value = value;
}
}
public static class Box {
public static Box<T> Create<T>(T value) where T : struct => new(value);
}
}
for... reasons
@real blaze it sounds like you might be looking for an ECS or something.
Have you considered that?
it won't be boxed, for it's not casting to anything. it's just holding a pointer to a struct. I'm on phone so it'll take some time, I'll write the wrapper list class
more storage, but you can eliminate the allocations and stuff
The box is an anoymous class
You have a class called StructHolder
Which is your box
Just like I have a class above called Box
It's the same shit
I love ECS, but that's off limits for this case. it's a library code for any Unity project and not just DOTS
so many ECS options out there
DOTS isn't even a thing
but nothing moves from heap to stack. how will it still be considered boxing?
No, it moves from stack to heap
Right here
var val = new StructHolder<int>(){ Value = 123; }
You're moving 123 from the stack to the heap
but it was initially a struct, and ended up in a local value
edited
I think you might have a fundamental misunderstanding around how structs and classes work
Adn as such I can't follow what you're saying
isn't boxing just casting struct to object and back?
no
Boxing is putting a value type on the heap
Which can be done implicitly when you assign a value type to a reference type
unboxing is bringing it back
i dont get the point why you cast a struct to object at first, you can experience both disadvantages of class (slow allocation time) and struct (slow copying time)
if you want some pointer to struct you can simply declare struct* but it can only point to unmanaged heap.....
they explained above, I was trying to get back to the point that it's not possible to achieve it.
Basically wanting to somehow store different struct types in a single array
yes that
But it fundamentally doesn't make sense
Because you get the memory address of an array element by doing: array_start + sizeof(T) * index
so, when I have a class that has a struct field, if I get that field and pass it to a local variable, it'll be boxed?
class C { public int V; }
...
class Other{
C c;
...
var v = c.V; // boxing?
}```
no
question so i'm using an action to handle multiple functions being played when the character is attacking (for example movement is disabled and can't jump mid attack), but the action it self is a static variable.
If i were to switch characters I know those actions would still be tied to the original character who subscribed their functions to the action.
What would happen if i were to try and unsubscribe functions from one instance of a class and resubscribe with another instance of a class?
boxing occurs when compiler detects that the struct reference will be retained outside of the stack scope
to me?
yes
It won't be boxed, but it will be copied from the heap to the stack
The important thing is that it's the same as a box
You've just given it a name
ah, got it!
absolutely didn't know that one
var will compile into the actual type
The struct will be stored inline in the class
so, since we have to move stuff from heap to stack at some point anyway, then I guess it makes sense to box it as well?
class Foo
{
object boxedInt;
void Foo()
{
boxedInt = 1;
}
}
object cant hold an int, thus it is boxed, a class is generated, object allocated, stored on the heap, reference returned
well, if you have to, sure. Just obviously beware that there will be GC
which may or may not be a problem
int foo = (int)(object)(float)(int)(object)1;
we were considering both values were struct. no objects anywhere
this most likely wont box
no it won't
๐๐๐โ
move stuff from one memory space to another memory space is just copying (and waiting for io), i think boxing is not needed
this is most likely unavailable to unitys .net
these things come from intrinsics, jit optimizations in recent versions
about the boxing... the code were to be inlined at compile time to int val = (int)(object)someClassInstance.intField. copying is clearly inevitable since we're duplicating a struct field anyways. but important thing is whether or not compiler will remove the extra useless casts to avoid boxing. so it's more about compiler optimization
Why do you need to box in this case ?
how do i delete this image
whether or not compiler will remove the extra useless casts to avoid boxing
most likely not
you can check IL
build, check IL for box unbox
no need, but inevitable. more details here: #archived-code-advanced message
You might be interested in Convert.ChangeType
In IL, no, but the JIT compiler seems to optimize it.
Here's what it looks like in JIT when there is boxing
But this is just for JIT, and probably CoreCLR JIT. Mono might handle it differently, IL2CPP might handle it differently.
Can you just use Unity Profiler to see if there is an allocation ?
oh good point. and thanks for the compiled examples
seems it either won't inline the function, or it does but fails to optimize extra casts away
(this is in release mode inside Editor. I'll test windows build in a bit)
In your case can you not do:
class StructHolder<T> {
T Value;
U GetValue<U>() {
return Convert.ChangeType(Value, typeof(U));
}
}
Or something like that.
test 4 is this. seems it allocates extra
I guess it does return an object. Boxing it anyway.
and twice at that, for whatever reason. test 2 allocs 32,768 but this one 65,536
I guess you would need to manually call the appropriate Convert.To[...] function manually.
wrote it as public T GetValue() => (T)Convert.ChangeType(Value, typeof(T));
same results in mono release build
I'm sure it does allocate. It returns an object.
You could try to manually use the Convert.To[...]
Without using the Convert.ChangeType
that one's not generic. you have a limited number of methods to choose from
the whole point was being generic. to use any T that's a struct
did some build tests. mono at least optimized (int)(object)intValue away. il2cpp didn't even do that. and neither optimized the function at #archived-code-advanced message . did with and without incremental GC settings, same results. il2cpp was at master with minimal stripping, both .Net framework and standard resulted the same. Unity 2021
how can I use an unsafe list on a job?
[ReadOnly] NativeArray<Vertex4> vertices;
[WriteOnly] UnsafeList<float4> outputNoise;
[ReadOnly] NoiseSettings outputNoiseSettings;
[ReadOnly] SampledAnimationCurve outputAnimationCurve;
float2 offset;
int seed;
public void Execute (int i) {
Vertex4 v = vertices[i];
float4x3 pt = transpose(float3x4(
v.v0.position, v.v1.position, v.v2.position, v.v3.position
));
pt.c0 += offset.x;
pt.c2 += offset.y;
float4 noiseValue = GetFractalNoise<N>(pt,seed, outputNoiseSettings.persistence, outputNoiseSettings, outputAnimationCurve);
outputNoise.Add(noiseValue);
}`
the array is not being filled
you need to use pointer so that the unsafelist inside the job can be synchronized outside the job since the list can be dynamic resized (ie realloc may happen in job)
i think you likely get a seg fault or heap use after free but you dont, you probably just read the length
Mmm, I know the lenght of the list, it doesn't resize, any benefit with that?
so you have check outputNoise[0],[1].... when the job is finished?
you just check the length....if you sure than the list doesnt got resized in job, then access it content (ie memory space pointed by Ptr) directly, but pretty dangerous if you are not sure
since you copy the struct into job but the struct "outside" the job (in method or class property) is not updated after the job is finished so the length is 0
i see
okay im changing some things then
InvalidOperationException: The previously scheduled job DisplaceFlattened`1 writes to the Unity.Collections.NativeArray`1[Unity.Mathematics.float4] DisplaceFlattened`1.outputNoise. You are trying to schedule a new job DisplaceFlattened`1, which writes to the same Unity.Collections.NativeArray`1[Unity.Mathematics.float4] (via DisplaceFlattened`1.outputNoise). To guarantee safety, you must include DisplaceFlattened`1 as a dependency of the newly scheduled job.
I know for sure that Im not writing to the same indices, how can I disable the error?
set the length of unsafelist to its capacity first then in job:
*(outputNoise.Ptr+i) =noiseValue;
look like you are trying to read/write before job is finish but i am not sure why there is such safety checking on unsafe list
No no I changed that, forget about it, I flattened all my unsafe lists to one single array
that was it
Perfect
can someone help me with a netcode issue? willing to hop on a call and show them or just via dms
Nobodies going to personally tutor you. Nor have you said which network engine you're using
You should ask questions here.
sry look in #archived-networking i gave more info there
Thats what I thought but im just wondering why unity did that then. Other places they are avoiding their own vector operations and do things using separate floats for each axis to gain every possible bit of performance. I was wondering whether inlining would actually make the compiler realize that only one of the 3 values is used and remove the code for those redundant ones
Hello ๐
I tried to switch bodies on my player, but I have a problem
The body remains invisible despite the properties of Skinned Mesh Renderer component being identical to the original model
The only way I found to make that working, is manually copy / paste the entire component values (Skinned Mesh Renderer component) and the problem is I canโt do that by code
Maybe do you have a tips or some informations that can help me ?
Yo, maybe someone can help me out
If I declare my native arrays as temp job i get this warning
Internal: deleting an allocation that is older than its permitted lifetime of 4 frames (age = 5)
UnityEngine.StackTraceUtility:ExtractStackTrace ()
Unity.Collections.NativeArrayDispose:Dispose ()
Unity.Collections.NativeArrayDisposeJob:Execute ()
Unity.Jobs.IJobExtensions/JobStruct`1<Unity.Collections.NativeArrayDisposeJob>:Execute (Unity.Collections.NativeArrayDisposeJob&,intptr,intptr,Unity.Jobs.LowLevel.Unsafe.JobRanges&,int)
But the memory profiler stays low
if I instead mark them as Persistent, there's no errors, no warnings, but the memory profiler keeps increasing to infinity (opr my pc crashes)
i'm disposing of them, and I thought disposing them should clear the memory
TempJob allocations are automatically deallocated after 4 frames
so it sounds like you're actually not disposing your allocations properly
and TempJob just happens to dispose them for you
(along with giving you a warning)
I see, then I need to look further
Note that this won't actually happen in a production build - so you will probably still get your memory leak in a build with TempJob
Shouldn't i get an error tho once the play mode finishes?
if using persistent
Mmm, weird, im not getting any ahhaha
I mean, ideally you would yeah
but editor playmode/edit mode domain stuff is weird
especially when you have unmanaged memory in the mix
guys, is it possible for me to call an API request not allowing the user to access that request but without having a multiplayer server?
What does "not allowing the user to access that request" mean?
because it is a match request, if some user hack the game it is dangerous to keep this request out of security because he can use the request outside the game and call it as many times as he wants.
There is nothing you can do to stop nefarious users from calling your API and from intercepting and copying/duplicating requests your game client makes in the normal course of things
the way to handle that is to have:
- proper user authentication and authorization in your API (proper identification of users aka accounts/logins and logic code that makes sure the user is authorized to access the things they are authorizing)
- rate limiting in your API (n requests per second/minute/hour per user/device/ip)
- Proper server side validation of requests (e.g. user can only do X if they have Y)
Aside from that, even triple A games struggle with DDoS handling, and even when you fortify against that it's usually not at the API level, but at the server / load balancer level
Can lines like Animator.SetIKPositionWeight work if the armature this is being used on does not have any ik bones?
Can Someone help me please with Lightning, Even if you have small Knowledge (Lighting Text Room) - its a emergency
An emergency? O_0
He's being held hostage
Hey All, is there anyone who know how to opitimize il2cpp generated code? I have to do a lot of cast, I'm sure cast are valid, I don't need any validation or safety for it, but generated code uses il2cpp::vm::Object::IsInst instead of some other c++ cast (I think reinterpret_cast would be the best).
This is a coding channel #๐โfind-a-channel
Hi! I have a problem with limiting drag distance in my darg and snap script made to work for multiplayer. here is the script: https://pastebin.com/MKaeEzeD
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.
This problem is talked about here, but the solution they give is just to avoid casting in performance critical code
https://www.jacksondunstan.com/articles/4533
JacksonDunstan.com covers game programming
hey. I have a Dictionary<T,U>, it had only one key. What's the fastest way to retrieve that key?
the First() from LINQ seems like a compile-time-added code and I can't see how it's implemented. so I don't know how well dic.Keys.First() would perform
why your dictionary contains only one key......
Acquiring of keys is slow.
Why is it important ?
Maybe don't call it often or optimize elsewhere
It depends on the data structure. What make a Dictionnary slow in acquiring keys ? Genuine Question.
if the dictionary just for containing one key. then try not to use dictionary
dictionary is sparse
How is it sparse ?
The collection is at optimum performance when using keys to acquire values O(1). Not knowing the keys would require accessing the keys which can be acquired using the Keys property or First - which likely does something similar to the Keys property in that the Keys collection is to be copied converted before acquiring the element.
Isnt O(logn) ?
For what? Finding values?
i believe you have studied data structure, it needed to be sparse
dictionary is not designed for random access nor iteration
and it is hard to define what is "first" since dictionary is unordered
Accessing the key collection does not have to be expensive. It's not fetching all the keys at once, it only returns a count and an enumerator. Calling First() on a KeyCollection will only enumerate over the first element.
well clearly I have simplified my problem to this question
it is better to give more info
The KeyCollection Enumerator is very simple, basically just as quick as a for loop and array access:
https://github.com/microsoft/referencesource/blob/51cf7850defa8a17d815b4700b67116e3fa283c2/mscorlib/system/collections/generic/dictionary.cs#L939
Dictionary stores all the keys in an internal entries array, so it's easy to enumerate.
Humm, I though the Dictionnary was not a HashTable.
I guess it is just a wraper of a HashTable.
it is hashtable (an abstract data type....) because the Dictionary<TKey,TValue> class is implemented as a hash table. from docu
but the name hashtable is already used in c#....
Can anyone help me
what's the problem
Hi! I have a problem with limiting drag distance in my darg and snap script. The script is not limiting the drag distance but placeing the object to the player with the distance of maxDistance also it's made to work for multiplayer. here is the script: https://pastebin.com/MKaeEzeD
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.
you said "I have a problem with limiting drag distance" but didn't explain what the problem is
you said that already...
i know
The problem is that it's not limiting the distance but it's spawning the object i want to drag to the player with distance of the maxDistance
for the Keys.First() I checked the source, it wasn't really straightforward and I lost it at some point trying to find the Enumerator implementation for Collection (which KeyCollection inherits from) code in Github. I doubt it'll be a pretty O(1) code... so I'll try another thing. thanks
it seems like the if / else on lines 38/43 are doing two completely different things. SO it's unclear what you're actually trying to do there
why overcomplicate a simple question though? I don't follow the reason here really. thanks for trying to help btw
Interesting. Strangely though, I've tested the performance a few times in the past and Enumerable First isn't on par with array index accessing from what I could tell at the time. There may have been other factors though.
It's trying to get the closest player and count the distance from the object to the player and if the distance is more than maxDistance than not allow the player to drag the object (im pretty lost in my spaghetti code)
i dont understand why you need a dictionary just for storing one key, i would just store the "key" instead, maybe you are using some api
Here's someone's limited comparison of the two https://stackoverflow.com/a/33544511 @sage radish
The casting operation source as IList<TSource> or creating an Enumerator object is very likely the reason why First() is considerably slower.
Seems very good though or good enough.
interesting; knew it'd be slower, but not that much slower. guess it's officially out of option then. thanks.
Are you grabbing the key of this dictionary million of times in a hot path? Have you profiled it to know that it is indeed the performance bottleneck? It sounds very much like premature optimization.
If you want to avoid the allocation, you can avoid LINQ and use the KeyCollection.Enumerator directly, which is a struct
You just need to call Keys.GetEnumerator, enumerate it once by calling MoveNext, then access the key in the Current property.
You can also do:
foreach (var key in dict.Keys)
return key;
return default;
Instead of:
using var enumerator = dict.Keys.GetEnumerator();
enumerator.MoveNext();
return enumerator.Current;
They both generate basically the same lowered C# code, but former is easier to understand and handle error imo.
Granted, this and that you have a dictionary with just one entry are the bigger issues.
it is indeed a low level optimization. turned out it's impossible to get a O(1) from it so I ended up changing the structure so it won't need that anyway.
agreed, GetEnumerator will need disposing too
An optimization being low level or high level is orthogonal to whether it's premature or not.
But yeah a different data structure sounds like what you need instead.
Is this still the correct way to serialize auto-implemented properties in Custom Editors? https://forum.unity.com/threads/c-7-3-field-serializefield-support.573988/#post-6731440
More specifically, I am trying to do
SerializedProperty userConfigProperty = serializedObject.FindProperty("<UserConfig>k__BackingField");
Where the auto-implemented property whose backing field I'm trying to access is
[field: SerializeField] public UserConfig UserConfig { get; }
(note that UserConfig is a class with [Serializable] attribute, so this should be fine). But, later when I try to access userConfigProperty, I get null reference exceptions.
Also, I will say it is immensely confusing to new devs that these are called SerializedProperty, when 'C# Properties' themselves can't be serialized... so serializedObject.FindProperty("NameOfProperty") doesn't actually work for 'C# Properties'. It would be great if it were renamed to SerializeField and the method was renamed toFindField instead, but maybe there's a a good technical reason I'm missing for having this confusing naming. Maybe this will be fixed in Unity 2024? ๐
Welp, it works if I add a private setter.
[field: SerializeField] public UserConfig UserConfig { get; private set; }
SerializedProperty isn't just for serializable C# fields. It also exposes serialized data on the native side, and those don't necessarily have to be fields. Property is a more generic term, and since it's unused in C++ where this API is implemented, it's a good term to use.
I figured something like that was going on.
It will never be "fixed". Also note that when that was developed unity supported three scripting languages (Boo, UnityScript, C#)
Just very confusing to noobs...
most noobs don't even know what a C# property is!
Very confusing to intermediate programmers*
I feel like even "SerializedData" would be better, or something...
There's 15 years of tech debt, this is the least of their problems
Just talking outloud, not trying to imply it was too high priority or making some kind official request, my bad, maybe Unity 2030 ๐?
if you want a quaternion for a direction vector that would be Quaternion.LookRotation
Quaternion.Euler is for euler angles
Oh, you are right, thank you on that!
Do you have any idea on the
Gizmos.DrawWireCube(castStartingPoint + castDirection * hitInfo.distance, _boxSizeCast);
The first argument is the "cube centre", the second one is the "cube size", I'm trying to specify the position as well as the "forward" direction of the cube.
But it's not working as I was expecting.
Here's a little trick about Gizmos
if you want to be able to rotate the gizmo you can use
So you can for example do:
var mat = Matrix4x4.TRS(castStartingPoint + castDirection * hitInfo.distance, Quaternion.LookRotation(castDirection), _boxSizeCast);
Gizmos.matrix = mat;
Gizmos.DrawWireCube(Vector3.zero, Vector3.one);```
now all the position/rotation/scale is done in the matrix
just watch out because it will affect ALL subsequent calls to GIzmos
That's extremely interesting, wow, I had zero notion about that possibility. Thank you!!!
The physics debugger can draw casts already if your version supports it. I also have a package which has all the functions for drawing casts https://unity.huh.how/programming/debugging/draw-functions
Thank you for the suggestion, that will come extremely handy on the future!
You were right, i rewrote my scripting language compiler to not use dynamic anywhere, got rid of the last 150~kb of allocations ๐
The removal of dynamic also net me another 60 fps, so now my test is running at 250 fps
Also potentially lets you use IL2CPP?
yeah it should as well
lol, when i started the project and got the first working version of the benchmark it was using 600kb-1.1mb memory per fram, and running at roughly 90 fps. Now it uses 0kb per frame and runs at 250 fps per frame lol
nah can't the remaining fps is due to the user script being inefficient, best i can do is make each script run in its own thread
the idea was that you can paste in a string of code and the game parses and executes it at runtime, so if that user submitted code is inefficient, then you're sorta limited on the frametimes
all the frametime is being consumed by the benchmark script ive got piloting my tanks
Nice.๐
Greetings,
I have an object that needs to face the mouse position. However, instead of just facing the mouse position I want to determine whether or not the object must decrease or increase. In other words, I need an axis for what rotation should be necessary to face the mouse.
All my attempts so far have resulted in very poor results.
I want to make my object give me a value of 1, 0 or -1 depending on whether or not it's facing the mouse.
this is my current code:
private float GetRotationAxis(float turretRotation)
{
var axis = 0;
var target = GetMousePosition();
var currentAngle = turretRotation;
var targetAngle = Math.Atan2(target.y - transform.position.z, target.x - transform.position.x) * 57.29578f;
var angleDiff = currentAngle - targetAngle;
if (angleDiff > 180)
angleDiff -= 360;
else if (angleDiff < -180)
angleDiff += 360;
if (angleDiff > 5)
axis = -1;
else if (angleDiff < -5)
axis = 1;
return axis;
}
private Vector3 GetMousePosition()
{
Plane p = new Plane(Vector3.up, transform.position);
Ray r = Camera.main.ScreenPointToRay(Input.mousePosition);
p.Raycast(r, out float enter);
Vector3 mouseWorldPosition = r.GetPoint(enter);
return mouseWorldPosition;
}```
As soon as I rotate my player, this stops working.
Here is the issue I am having.
As you can see, every 90 degrees the turret inverts it's facing axis.
I want the turret to always give the correct input axis back, instead of inverting after 90 degrees as shown in the video.
i am very unexperienced but are the gun things atached to the ship
Hi !
It have been 3 days i have been fighting with a bug, so i came looking for help.
I making a game with interact with the OS, the character lived inside your destock like clippy ๐
I manage to have app transparency on Mac and Window and i recently add System Tray option.
On window it's working completly fine but on mac, once i use a sysTray command, unity can't receive the keyboard input.
I read it must be due to MacOS not considering Unity as the main app and refusing to send it input. But event if after a systray method i call this methods :
[NSApp activateIgnoringOtherApps:YES];
[[NSRunningApplication currentApplication] activateWithOptions:NSApplicationActivateIgnoringOtherApps];
[window makeKeyAndOrderFront:self];
but it don't solve it and i don't have any other idea
Shouldnโt that transform.position.z inside the target.y - transform.position.z be a transform.position.y instead? This seems like a 2d top down game so the z axis would be pretty much unchanging. Iโve got to go soon but if that didnโt fix it, Ill take a look at it again once I get back
Hello mates !
I'm struggling with an issue about concurrency call in my game :
I have several weapons on a spaceship that are shooting automatically enemies. When a projectil hit (by colliders) it trigger a CalculateDamageFunction which is checking every passiv effects etc, and next calling the ApplyDamage method to the enemy that is hitted.
The issue is the projectile should be destroy if it hit the enemy but sometimes i'm loosing lot of projectile because the total of damage of all the projectiles that hit are superior than the enemy current health point.
So do you know how to manage parallel damage to an enemy without this side effect please ? ๐
I'm thinking about a buffer on the enemy that contain the damage that he should apply on himself but i'm afraid that the projectil don't receive the information that it hit the target (and so should be destroyed) before long time if the buffer is too full
About the GetMousePosition i'm using it for a similar case :
Vector3 MousePos;
Plane plane = new Plane(Vector3.up, Vector3.up * 1); // ground plane
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float distance; // the distance from the ray origin to the ray intersection of the plane
if (plane.Raycast(ray, out distance))
{
MousePos = ray.GetPoint(distance); // distance along the ray
}
Try Upwork or some other freelancing platform.
Thanks
hello, i am kinda stuck on something that i simply cant solve for past 7 hours
the projectile veolocety needs to be the final veolocety instead of the starting veolocety, i dont really know how to apply gravity to that veolocety
float timeToTarget = targetDistance / (mainRigidbody.velocity + gameObject.transform.forward * projectileSpeed).magnitude;
Is this projectile motion?
The only thing you need is to calculate the time it takes for the object to touch the ground. Do you know the target position?
yes
0, 100, 400
Can anyone help me please
Please im stuck on this problem ages
Horizontal distance traverse=dxz=int Vxz dt and Vxz is probably a constant if no air resistance
Vertical =dy=int Vy dt and Vy=Uy+Gt
Given dxz and dy find T,Uy and Uxz=Vxz since UxzT=dxz so you can directly get T=dxz/Uxz=some contant/Uxz and some Uy(T)=dy
please
what?
Itโs more so the distance from the start to the target. Itโs a bit long.
// calculate the time it takes to reach 0 from initial y velocity
float time = -velocity.y / gravity;
// calculate the distance traveled during that time
float height = velocity.y * time + .5f * gravity * time * time;
// then calculate the time it takes to fall from that height to the ground
float distanceToGround = end.y - (start.y + height);
time += Mathf.sqrt(distanceToGround /(.5f * gravity));
You end up with two equcations and three variables if i am correct, you may want to fix either T or Vy or Vxz
um, im kinda working with non of them fixed due wind
Actually target and launcher may not be the same horizontal level so the float time=something is wrong
that is the thing i want to fix
It maybe some y plus dy
My brain is tired so I definitely couldโve messed up somewhere ๐ . The distanceToGround should account for that right?
this is without gravity counted in time, the thing i need to add
the shooter is at 0,0,0
the thing i need to change is projectileSpeed
due that also needs gravity
There should be two possible values of T in Uy(T)=dy
i dont need time, i need the final velocity when bullet reaches the tartget
Wait actually, I mightโve misunderstood your original question. Is your bullet affected by gravity?
yes
Or does it just move in a straight line
The xz component shouldnt be changed so only the y component is changed, you definitely need time, but the calculations is much simpler
T=dxz/Uxz then Vy=Uy+GT
Ofc no air resistance
yeah, i need time, and to get time i need final veolocety
Final v=Vy+Vxz
Xz component of velocity
The gravity only affect y component then just separate them
like?
v^2 = u^2 + 2 * g * s
v = final velocity
u = initial velocity
g = acceleration due to gravity
s = distance to the target
like this?
Eg the final v=(x,y)+(0,10)t you will found that x component donest get changed so you can do calculation on x and y separately
im doing in 3d
Then x y z, and g=(0,10,0)
formula?
@grave raft Not exactly sure what you want, but I did this at some point for an other user. It might help you: #archived-code-advanced message
For wind, I would consider using an added velocity instead of a force. This would simplify the formula.
not doing a force, i just change the gravity it self
Gravity is a force.
but im not adding any aditional force
For side wind, using a force would make the formula way more complicated.
If you modify Gravity, you are effectively adding force.
Increasing only the Y component is fine.
the y is problem in my code, everything else works
However, if you modify the X or Z component then you cannot use most formula for uniformly accelerated rectilinear motion
the only thing i have problem is gtting the final veolocety
when that is done everything else will work fine
The link I sent is literaly that.
Finding the inital velocity
public class Shoot : MonoBehaviour
{
[SerializeField] private Transform target;
[SerializeField] private Rigidbody rigidbody;
[SerializeField] private float angle;
[SerializeField] private float maxDistance;
public void Execute()
{
//x = v * t
//x = v * cos(a) * t
//h = v * sin(a) * t + 1 / 2 * g * t ^ 2
//t = x / (cos(a) * v)
//h = v * sin(a) * (x / (cos(a) * v)) + 1 / 2 * g * (x / (cos(a) * v)) ^ 2
//h = v * sin(a) * (x / (cos(a) * v)) + 1 / 2 * g * (x / (cos(a) * v)) * (x / (cos(a) * v))
//h = v * sin(a) * (x / (cos(a) * v)) + 1 / 2 * g * x ^ 2 / (cos(a) ^ 2 * v ^ 2)
//h = sin(a) * (x / cos(a)) + 1 / 2 * g * x ^ 2 / (cos(a) ^ 2 * v ^ 2)
//h - sin(a) * (x / cos(a)) = 1 / 2 * g * x ^ 2 / (cos(a) ^ 2 * v ^ 2)
//1 / 2 * g * x ^ 2 / (h - sin(a) * (x / cos(a))) = cos(a) ^ 2 * v ^ 2
//1 / 2 * g * x ^ 2 / (h - sin(a) * (x / cos(a))) / cos(a) ^ 2 = v ^ 2
Vector3 delta = target.position - transform.position;
float distance = Mathf.Min(Mathf.Sqrt(delta.x * delta.x + delta.z * delta.z), maxDistance);
float height = delta.y;
float a = 0.5f * Physics.gravity.y * distance * distance;
float b = height - Mathf.Sin(Mathf.Deg2Rad * angle) * (distance / Mathf.Cos(Mathf.Deg2Rad * angle));
float c = a / b / Mathf.Pow(Mathf.Cos(Mathf.Deg2Rad * angle), 2);
Vector2 planeDirection = new Vector3(Mathf.Cos(Mathf.Deg2Rad * angle), Mathf.Sin(Mathf.Deg2Rad * angle));
Vector3 direction = new Vector3(delta.x, 0, delta.z).normalized * planeDirection.x + Vector3.up * planeDirection.y;
rigidbody.velocity = direction * Mathf.Sqrt(c);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Execute();
}
}
}
what is a
Nothing
b?
so this
Vector2 planeDirection = new Vector3(Mathf.Cos(Mathf.Deg2Rad * angle), Mathf.Sin(Mathf.Deg2Rad * angle));
Vector3 direction = new Vector3(delta.x, 0, delta.z).normalized * planeDirection.x + Vector3.up * planeDirection.y;
rigidbody.velocity = direction * Mathf.Sqrt(c);
is final veolocety?
i dont have an angle
initial, at the start veolocety?
Start Velocity = Initial Velocity
but i am searching for final
Then, redo the same for final
?
The angle ?
no, i want to find final veolocety
to get final veolocety so the time is connect
So, you want your projectile to take exactly X sec to get to the target.
Find the velocity required to travel to the target
The find the angle required
With the remaing velocity
i know their positions, their accelerations, their velocity's, their distance, rigidbodies, and coeffs
Use that to know what velocity is required to take you to the target in X seconds
Then use the remaing velocity to find the angle
here, let my simplify it
float timeToTarget = targetDistance / (mainRigidbody.velocity + gameObject.transform.forward * """"""""""""v""""""""""").magnitude;
V, is final veolocety
everything else its done
wow some real effort there ๐ Sorry to ask, but did you write this manually or auto-generated?
Manually
I've done worst.
But, I use youtube tutorial and sometimes Symbolab
@grave raft sorry, was all the time I had for the moment
ok
I'm here to replace Sim, what do you need @grave raft?
final veolocety
after X seconds?
without using time due time is fed without that
time is a component of velocity's formula, there's no way you get what you want without it
you can get the time if you first calculate the path, and then use x (position) to determine it
thats the thing, i dont have time, nor the path
so, you have the initial velocity and the angle, and the forces that apply (gravity), so you can calculate the path it'll take
it goes from distance, to veolocety, to time, to path, to angle, shoot
i can get the angle of shooter and target without gravity
tldr:
- you need to get the time if you want to get the velocity
- you need to get the path to calculate the time it takes to traverse from x0 to x1 -- and you need the x1
- you need to know g, ฮธ, and x0 to calculate the path, as well as the initial velocity
but i'm 99% sure you're overcomplicating it.. xy issue -- what's the actual outcome you want?
there is no xyz issue, there is problem of getting incorrect time due i dont have final veolocety
given an initial velocity vector, launcher position and target position, found final velocity vector
but actually you can miss the target
it will not miss the target if it knows the final vector
this can be solved much easier..
void Shoot(Vector3 velocity) => rb.velocity = velocity;
void FixedUpdate() {
rb.velocity.y += Time.fixedDeltaTime * Physics.gravity;
Debug.Log($"Current velocity is {rb.velocity}");
}
so, at any given frame, you get the 'current velocity' -- which is the 'final velocity' at that frame
rb.velocity.y??
that is always 0, that never moves
but the final velocity vector is affected by initial velocity vector and T=Sxz/Uxz so you have to restrict initial velocity vector
otherwise, if you need to know the velocity at any given point of the path, you need to do this, starting with 3
Are you sure? You said gravity is affecting thisโฆ
yes, it does, it affects bullets
the only info i have about bullets, the only things i can get is their gravity direction, and their starting speed(curently)
xy issue, not xyz issue: https://xyproblem.info/
Asking about your attempted solution rather than your actual problem
@ember templeI'm using X and Z for position, I am using Y for depth. But yes it is a top down game.
who are you now ๐
previous conversation ๐
its an xzy(3D) issue, non of the aiming will work if time is incorrect, due final veolocety is incorrect
@grave raft Are you sure this wonโt work?
you're being really hard to help right now. you've neither tried my solution, read the links I posted, or asked questions about the solution
yes, it wont, it contains time
It solves for time
I thought that was what you were looking for
float timeToTarget = targetDistance / (mainRigidbody.velocity + gameObject.transform.forward * projectileSpeed).magnitude;
Your goal was time?
@grave raft People are using their time to try to help you. At least have the courtesy of reading what they send. I'll report you if you keep this up
we sent tons of solutions, all of which can work to calculate the velocity at a given point before shooting a projectile, you're just being an ass
yes, to get time i need to get final veolocety(projectileSpeed)
๐ซ
NO
time can be simply calculated by Sxz/Uxz
?
the xz and y component of velocity vector are independent since your gravity only affect y component of velocity
that's true
Then it should probably be target.z - transform.position.z
oh forgot, different convo ๐
I mostly assumed you had a target in mind. It calculates the time it takes to reach the apex of the motion and then the time it takes to reach the end of the motion and adds the 2 of them together.
if you dont believe me you can test in unity, having a two velocity which (x,0,z) and (x,y,z)+gt and see the time they travel the same horizontal distance
@ember templeYes, that was an oversight for sure. I corrected that. It unfortunately has not provided any different results.
how about this
void CalculateAimDirection()
{
// Get the current position, velocity and acceleration of the target
Rigidbody targetRigidbody = target.GetComponent<Rigidbody>();
Rigidbody mainRigidbody = gameObject.GetComponent<Rigidbody>();
Vector3 targetPosition = target.transform.position;
Vector3 targetVelocity = targetRigidbody.velocity;
Vector3 targetAcceleration = (targetRigidbody.velocity - previousTargetVelocity) / Time.deltaTime;
// Calculate the smallest positive solution to the equation
float[] coeffs = findQuarticCoeffs(projectileSpeed, transform.position, targetPosition, playerVelocity, targetVelocity, playerAcceleration, targetAcceleration);
//float timeToTarget = PolynomialRootFinder.FindSmallestPositiveRealRoot(coeffs);
float targetDistance = Vector3.Distance(gameObject.transform.position, target.transform.position);
float timeToTarget = targetDistance / (mainRigidbody.velocity + gameObject.transform.forward * projectileSpeed).magnitude;
// Calculate the predicted target position
Vector3 predictedTargetPosition = targetPosition + (targetVelocity - mainRigidbody.velocity) * timeToTarget + 0.5f * targetAcceleration * timeToTarget * timeToTarget;
// Calculate the aim direction
aimDirection = (1f/timeToTarget * (predictedTargetPosition - transform.position) - 0.5f * projectileAcceleration * timeToTarget).normalized;
if(debug)
{
debugObj.transform.position = predictedTargetPosition;
Debug.Log("timeToTarget = " + timeToTarget);
Debug.Log("targetVelocity: " + targetVelocity + ", previous: " + previousTargetVelocity + "\n" + "Calculated targetAcceleration: " + targetAcceleration);
Debug.Log("targetPosition: " + targetPosition + ", predicted: " + predictedTargetPosition);
Debug.Log("aimDirection: " + aimDirection);
}
}
read it
it could be a lot easyer solution if you just read the code
Spaceship
https://hastebin.skyra.pw/ucakorebog.java I recommend using distance only once and this makes it a little more readable.
now it doesnt aim at all
UI element`s world space position doesn't work properly when add Grid Layout Group Component. Also world rect corners has same issue. Does this component manipulate coordinate system incorrectly ?
Hey all, I was directed out of #๐ปโcode-beginner for this question. I am having trouble getting a tensorflow model which I have converted to ONNX to work in Unity with the Barracude package and would love some help.
Basically this line is causing an AssertionException: Assertion Failure. Value was False. Error.
Code starts with image 1, which resizes the image in image 2
Lmao, that's definitely not code-beginner territory
that said, AssertionException sounds like a unit test - there's more to the story than what you've shown here. I'd love to see the failed unit test
and ideally, the exact line that broke the code - not just a function call
It is not necessary a Unit Test.
https://docs.unity3d.com/ScriptReference/Assertions.Assert.html
my bad
still, that's clearly not the exact line that called the error
Thanks for the tips! I wouldn't consider myself a particularly advanced programmer which is why I asked there first. Hopefully I can keep up ๐
This is the line that seems to be causing the issue in the Tensor.cs file
Notably, Tensor is not a type that I programmed, but rather one from the barracuda library
This is the line in my code that seems to break things
The assert is a sanity check
in other words, you need to know why srcData.length != length
Maybe you have to update a buffer or something
Good point, I'll print both of those and see what they are
I see a lot of debug.logs
Have you tried debugging with breakpoints? Put a breakpoint on that line, attach your editor to the unity editor, and hit play in Unity. It'll pause at the breakpoint and you can hover over values to see what they actually are at that point. It's VERY helpful and imo a lot easier to deal with than endless logs
https://docs.unity3d.com/Manual/ManagedCodeDebugging.html
It's a lot more intimidating than it is difficult haha
You should definitely look into the debugger if you do not know. (That being said, using logs to find out at what moment something is printing an other log may be easier than using a debugger)
True. They both absolutely have their place.
Hey gang just for y'all's interest I re-wrote things using data types I understand a bit better and got it working ๐ I think it was some weird thing where the dimensions of the Tensor weren't happy with the images I passed in. I really appreciate everyone's help!!
I have implemented a nav mesh agent for my voxel game. It is similar to nav mesh agent unity. Now, I want to recalculate path for agents when the world changes.
In my view, it should be handled inside nav agent class itself.
public class NavAgent:MonoBehaviour{
private IWorldChangedHandler _worldChangedHandler;
private INavigationSystem _navigationSystem; // find path
private void Start(){
_worldChangedHandler.Changed+=OnWorldChanged;
}
public bool SetDestination(int3 targetPoint){/**/}
public void SetPath(IEnumerable<int3> path){/**/}
public void ResetPath(){}
public void Pause(){}
public void Resume(){}
//...
private void OnWorldChanged(){
// check current path and if there is an aobstacle on the current path, call set destination method (recalculate path)
}
}
What is your opinion?
In Unity, path recalculation (if it is auto) is handled in NavMeshAgent class itself?
Hey, i just found out that MonoBehaviour derriving classes can be casted to bollean (example below) and I can't find any resources about it other than "
bool Does the object exist?" on docs. Can anyone tell me if it's better or worese than using null comparison or SafeUnityNull or something neat that's build in.
Transform rg = GetComponent<Transform>();
if ((bool)rg)
Debug.Log("We got it!");
else
Debug.Log("Nada!");
the cast is implicit, you don't need to (bool)
it's the same, except imo it's harder to understand intention and easier to make mistakes
Yes, but rider hates not having it and as you mentioned it's easier to understand when it's written.
But even unity exaples are not using it. Is it safe to use, or should be avoided?
Rider doesn't mind for me ๐คท
Thinking about it, I am using 2017 with old project and i might not have package, whoops.
Ok, I just found out that's a simple operator.
I don't get it why nobody uses/knows about it, it's brilliant to have
Because it's confusing and imo illogical
and its existence means you can create some logical mistakes that wouldn't happen otherwise
I suppose that would be best checked, for me at first glance it looks as good unless negation is used.
Thanks for help, have a nice day.
One of the many examples of this doing things you might think are unexpected, and only Rider's inspections really make it clear what's going on
I'm a bit confused on when singletons should be avoided, and why they make debugging difficult. Not sure if this is "advanced" enough to go here haha
In my game, each player has one target player, the only player they can kill. If they kill their target player, their target player's target becomes their new target, so the targets go in a circle, like the classic game of assassins. I'm using FishNet as a network solution-- should my targeting mechanics script be a singleton?
its not the debugging they make difficult, they impede the changes in codebase
they force to make hard coupled classes that are coupled on concrete type name
swapping one class for another if its a singleton leads to massive refactor
if you need a singleton to access things, make a singleton service locator
so that everything else is not
Networking with singletons is actually super useful since you can design them around each client's character, meaning you can pretty much just make a PlayerManager a singleton
So it makes high level modules depend on low level modules?
I think I'm mostly following
instead of like interfaces
it makes you write code like
StaticClass.instance.DoStuff();
or
StaticClass.DoStuff();
where
public static void DoStuff()
{
instance.DoStuff();
}
which is even worse
aha
ew lol
Fishnet codebase is heavily structured with singletons if you want to dig into all of that
var playerTargeting = ServiceLocator.Get<IPlayerTargeting>();
playerTargeting.DoStuff();
does that mean it's better suited for singletons?
now the class that requested it, doesnt care what the type is, which version it is, etc
the thing is if you had a 100% knowledge of what is going to be in your code base and you were sure there would not be any changes to the api or systems, you could straight up convert everything to singletons
I am not clairvoyant haha
but its not realistic in a developing project, yes
not necessarily better, but much of what client side scripts would do make sense to be singletons
documentation goes over it a bit
there is no reason to use singletons over even a rudimentary service locator
What does that imply exactly? A static instance to access those specific scripts?
is that just a different way of accessing global instances?
pardon my ignorance
yes its a layer that separates user from the target system, so that you dont need to hard couple to specific types
Should I use that for my Target Controller class? I was considering a singleton because I was thinking there should only ever be one instance of this script to prevent conflicting information
multiplayer is pretty confusing ngl
yes you should in general use a middle man, like service locator, or any other pattern that decouples
It comes down to, do you have a single character? Does your enemy use this targeting controller class? Ect
The class basically keeps track of everyone's targets (which is in a circle), and as players are killed it shrinks the circle
if that makes sense
each player's kill script will have to interact with it
Ah, ok so this would be like a game manager script, which accumulates all player kills? So there's a single instance that runs on the server
Yep!
Right, so the server, or client host should be tracking what is killed. You'd have a game manager script that would keeping tracking of the general state of the game.
So I put this script not on my player object but on an empty in the scene, right?
public void RegisterPlayer(PlayerController player)
{
if (player != null && !players.Contains(player))
{
players.Add(player);
AssignTargets();
}
}
private void AssignTargets()
{
for (int i = 0; i < players.Count; i++)
{
players[i].targetPlayer = players[(i + 1) % players.Count];
}
}
public void PlayerKilled(PlayerController killedPlayer)
{
// The killer takes over the target of the killed player.
PlayerController killer = killedPlayer.targetPlayer;
killer.targetPlayer = killer.targetPlayer.targetPlayer;
// Remove the killed player from the list.
players.Remove(killedPlayer);
// Reassign targets.
AssignTargets();
}
My main logic rn looks something like this
Yeah, some empty game object you'll have that lives in the scene with these instance specific scripts
Sounds good, thanks for the help!
and thank you too! I'll look into service locators
Yep I'm on it already
FGG is cool
I'm kind of surprised people say fishnet is an easy solution because so far it's been fairly involved for me
lol, I don't feel like anything network related has been easy
I've got some of it down, but have been stuck with syncing issues, mostly related to object pooling
Yeah i'm not looking forward to optimizing
Hellu
So this method is obsolete
https://docs.unity3d.com/ScriptReference/Graphics.DrawMeshInstanced.html
And I should use this one
https://docs.unity3d.com/ScriptReference/Graphics.RenderMeshInstanced.html
However, If im using a command buffer I can still use this one?
https://docs.unity3d.com/2020.3/Documentation/ScriptReference/Rendering.CommandBuffer.DrawMeshInstancedIndirect.html
Also, what does it mean being obsolete, is it also slower?
DrawMeshInstanced and RenderMeshInstanced is basically the same thing with more available options for the latter. Those have same performance. *Indirect version is a different thing. By this call instanced parameters can be prepared in GPU, and should be passed as ComputeBuffer
I see, thank you, i've notices a slight performance drop using RenderMeshInstanced instead of the commandbuffer version of drawmesh
Is there a way to cast and recive shadows when using the CommandBuffer option of DrawMeshInstanced?
Hello!
I am in the process of making a cardgame on Unity. in this game, every card can have from 0, to 4 abilities; the abilities themselves generally affect more, than one value, which I solved by making sub-ability classes (all derived from a base class), that when combined would construct one single ability (say, lower your score and increase your stats - that would be 2 sub-abilities forming the ability).
Instead of prefabs for every card, I wanted to be able to create the cards from a List that would contain all the data of each individual card- adding number and string values works, my issue is with adding the abilities/sub-abilities. I wasn't able to find a way, how to do this (basically, "new Card(... ,<LIST OF SUB-ABILITIES FORMING THE MAIN ABILITY>, ...)" doesn't work like this). I'm unsure how, or if it is possible to add a class declaration with parameters into a List like this...
Does somebody know, or does anyone have a link to a tutorial/instructions, how one would solve this issue? I would really appreciate it!
P.S.: In the future, I would like to store the information of all cards in a database, from which the card would be "built", so that's why I store all their information in a List for the time being- as a way to "load" a card from its parameters.
According to documentation you canโt cast or receive shadows with CommandBuffer methods. You should use corresponding functions from Graphics
that sucks
because I need the command buffer to schedule the call after the depth buffer
Can I do somehow that with the graphics?
Can you describe your task?
I have a texture generated from the depth buffer with mip levels, that gets generated after the depth buffer is created via a command buffer. I then, schedule the call to draw grass. Between the depth and the draw call, I dispatch a compute shader that gets that new depth texture, and performs occlusion culling to the grass via Hi-z. Via command buffer the order makes sense. Via graphics.Render(...) the texture used for the dispatch is the previous frame depth, and not the current, making the occlusion culling lag one frame
You gotta use ScriptableObject for the card definition.
public class Card : ScriptableObject {
[SerializeReference] private List<Effect> effects = new List<Effect>();
}
[Serializable]
public abstract class Effect {
...
}
[Serializable]
public class DamageOverTime : Effect {
}
.
.
Can you leave depth pyramid generation and HI-Z culling to be in command buffer, but grass rendering to be excuted via Graphics.Render method?
Do you mean something like this?
https://pastebin.com/nqLCFZk9
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.
Hey, thank you for the quick reply!
About the code example code you've made, would it be possible to make your Card class abstract to use it as a parent for derived classes?
Yes, however, I do not really see the point of doing it.
Hello, thank you for the reply!
Your example is damn near spot on, with the major thing being different there is making the instance of the card - I would need to add it more in a way close to cardList.Add(new Card (new Ability (new List <SubAbility> {new SubAbility ("Ability1"), new SubAbility ("Ability2")}));), if that is possible
The cardgame I'm making has two types of cards, that share a nice deal of values (one among those being having Abilities)
If you do not know what a scriptable object is, I suggest you read more about. It might be closer to what you need than what you think.
I can, but the the data recived from depth texture to the graphics rendere is lagged one frame
I have a question, i am working on ship movement, but im trying to add force up so that my ship will not rotate instantly when i hit something with a bit of speed.
I have this code but im stuck. What happens now is when i start the game, the ship instantly starts rolling on its side... How can i achieve that theres a force being pushed UP so it always stays up?
[SerializeField]
private Rigidbody rb;
[SerializeField]
private float moveSpeed = 500;
[SerializeField]
private float rotationSpeed = 500;
private float horizontalInput;
private float verticalInput;
public float maxCollisionForceThreshold = 500f; // Adjust this value as needed
public float maxAngularVelocity = 10f;
public float torqueAmount = 100f;
[SerializeField] private GameObject explosionPrefab;
private void Update()
{
horizontalInput = Input.GetAxis("Horizontal");
verticalInput = Input.GetAxis("Vertical");
}
private void FixedUpdate()
{
// Calculate the dot products of the forward and right axes with the desired directions
float dotForward = Vector3.Dot(transform.forward, Vector3.up);
float dotRight = Vector3.Dot(transform.right, Vector3.up);
// Apply torque around the forward and right axes based on the dot products
rb.AddTorque(-Vector3.forward * torqueAmount * dotForward);
rb.AddTorque(-Vector3.up * torqueAmount * dotRight);
// Rotate the ship left and right
transform.Rotate(Vector3.up * horizontalInput * rotationSpeed * Time.deltaTime);
// Move the ship forward and backward based on its local forward direction
Vector3 forwardMovement = transform.forward * verticalInput * moveSpeed * Time.deltaTime;
// Limit the speed to the moveSpeed variable
Vector3 limitedVelocity = rb.velocity + forwardMovement;
if (limitedVelocity.magnitude > moveSpeed)
{
limitedVelocity = limitedVelocity.normalized * moveSpeed;
}
rb.velocity = limitedVelocity;
}
It should be this part, but im not in any luck fixing it ๐ฆ
// Calculate the dot products of the forward and right axes with the desired directions
float dotForward = Vector3.Dot(transform.forward, Vector3.up);
float dotRight = Vector3.Dot(transform.right, Vector3.up);
// Apply torque around the forward and right axes based on the dot products
rb.AddTorque(-Vector3.forward * torqueAmount * dotForward);
rb.AddTorque(-Vector3.up * torqueAmount * dotRight);
Thanks!
You're mixing adding torque with transform.Rotate
Not a good mix
Anyone familiar with Unity's IObjectPool<T> class and can tell me why it spawns upwards of 100 objects with my script? All I require is 15 - 25, nothing more
Nvm, I don't think this is a particularly good implementation if you just want a specific enemy count as it doesn't provide a way to track the actual spawned count :/
you don't seem to be using the pool at all
you re just calling Instantiate
also the pool is not going to limit the number of objects for you. That's not what it does
It's a thing that lets you reuse objects instead of frequently destroying/respawning them
i havent use the object pool provided by unity but the createEnemy func is invoked in init the pool but not in get() most of the time
Some pooling systems use a limit to keep the number of pooled objects in some range. If the limit has been exceeded, instead of enabling disabled object those reuse already enabled object. This is neat for independent objects that don't affect the gameplay, such as destruction decals.
It's not a necessary feature, but it can be useful.
Object pooling is an optimization technique though, it should not affect your business logic.
!mute 980625836875063348 1d spam ignoring warnings
issamiyad#0 was muted.
Lol
Can anyone suggest me an approach that would be the best to recreate the icecream creation where the ropelike thingy drops off the dispenser and smoothly gets placed into the cone ๐ ?
public void AddComponent<T>(T component) where T : struct {
}```
Can I change this method's signature in a way which will let me call it without specifying the generic type?
you mean to infer the type?
Yep
Could you type it for me?
where should I put the out T?
Ah I followed a tutorial for it, maybe it was innacurate. I figured a much simpler way to implement a full system. I can't find a use case for the Unity built way over writing it myself
- I would make the icecream cone independant of the thingy drops
- I would create a script that enable the creation of a mesh around a spline
- I would preplace the spline on the cone and fill them just at the right moment when the thingy drops hit.
- I would reuse the script that I created to do the thingy drops.
(to be noted its different of lobbies which work already but useless on this project)
Anyone use UniTask?
It seems to create performance issue for us.
How can I do something like this?
var type = component.GetType();
var pool = spawnWorld.GetPool<type>();```
You cannot. You must use spawnWorld.GetPool(type).
You could use Reflection in theory, not something I recommend*
Make a Dictionary<Type, ObjectPool>
They are created in the method GetPool<T>
The method looks somehow like this
public EcsPool<T> GetPool<T> () where T : struct {
var poolType = typeof (T);
if (_poolHashes.TryGetValue (poolType, out var rawPool)) {
return (EcsPool<T>) rawPool;
}
var pool = new EcsPool<T> (this, _poolsCount, _poolDenseSize, GetWorldSize (), _poolRecycledSize);
_poolHashes[poolType] = pool;
_pools[_poolsCount++] = pool;
return pool;
}```
Why can you not use ?
public IEcsPool GetPool (Type poolType) {
if (_poolHashes.TryGetValue (poolType, out var rawPool)) {
return (IEcsPool) rawPool;
}
var pool = Activator.CreateInstance(poolType, ...);
_poolHashes[poolType] = pool;
_pools[_poolsCount++] = pool;
return pool;
}
Combined with:
public EcsPool<T> GetPool<T> () where T : struct {
return (EcsPool<T>)GetPool(typeof(T));
}```
I do use it in my game, haven't seen any performance issue myself. What problem are you having?
And what would the activator be?
The way to instantiate a class knowing its type only at runtime
It's a built in class used for reflection in case you are not aware https://learn.microsoft.com/en-us/dotnet/api/system.activator?view=netstandard-2.1
that would be a bad plan for Unity types though, so don't do that
???
Sorry if this is pretty basic, but how much do you all avoid singletons?
In my game, each player has one target player, the only player they can kill. If a player kills their target player, their target player's target becomes their new target, so the targets go in a circle, like the classic game of assassins. My game has a class which keeps track of everyone's targets (which is in a circle), and as players are killed it shrinks the circle.
I think this script should act kind of like a manager on an empty gameobject in the scene, existing server side and not creating a separate instance for each player.
Would a singleton be a good way to accomplish this? Or should I look into things like service locators? Thanks for the help!
Oh, and I'm using Fish-Net
Players reporting game hanging after I migrated to Unitask and I suspect it is a performance issue. On a very low end desktop, me myself also experience game pauses.
but I took a look at the profiler though, I see rendering is taking up a lot but pretty sure this was the case previously too. and previously player don't experience pause/hanging
Can't say with only that much information but I doubt it though, unless you are spamming UniTask in a hot loop or something.
lemme get you the profiler info?
What were you using prior to UniTask?
normal C# task
I have a lot of fire-and-forget pattern though
C# task will just swallow the error if you fire-and-forget, so i switchedd to unitask
we are mainly using unitask to load addressables
Yeah fire and forget should be fine, I use them quite a lot in my UI code, and UniTask has UniTaskVoid which is even more optimized for it.
yes Iam using UniTaskVoid a lot
It's certainly odd, UniTask has basically equivalent API surface as C# task, so it should just be a drop in replacement in your code; I was about to suggest something else if you were migrating from coroutines to UniTask but that's not the case.
Are you sure UniTask is the cause of the performance issue? Perhaps it's some other change in the same update? I'd suggest find a way to reproduce the hang/frame skip and see what profiler says, before going down a wild goose chase.