#archived-code-advanced

1 messages ยท Page 70 of 1

brisk spruce
#

its just kind of not a great API

little sluice
#

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); }

dusty wigeon
brisk spruce
#

you should ideally have a distince interface to distinguish the two

brisk spruce
#

wait is the IEnumerator thing an old way of doing it? is there a better way now?

dusty wigeon
dusty wigeon
brisk spruce
#

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

dusty wigeon
#

More performant ?

little sluice
#

Not comparable imo. Tasks run from a threadpool in .Net while Coroutines are sliced up Update-Calls.

dusty wigeon
#

Coroutine run sequentially.

regal olive
#

I built it and there is no memory leak in the build
sigh

dusty wigeon
brisk spruce
#

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

dusty wigeon
brisk spruce
dusty wigeon
#

Also, you might want to consider the JobSystem if you still working on what you were doing earlier.

brisk spruce
#

yeah the job system was the other thing they tested, and there was a fourth one, forgot its name

dusty wigeon
#

And probably even ECS(DOTS) as how you were speaking you seem like performance was a HUGE factor.

brisk spruce
#

nah, not a big factor, maybe?

#

Ill see if it matters, I am building for mobile so it might actually come up

dusty wigeon
#

I mean, if you need parallelization, the overhead would be pretty small in comparason of the performance gain.

little sluice
brisk spruce
#

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

dusty wigeon
jolly token
dusty wigeon
#

Using Coroutine as Update Function leads most of the time in complicated worflow.

brisk spruce
#

oh thank god, Zenject supports list injection ๐Ÿ™

little sluice
cunning pebble
#

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.

obsidian coyote
#

Anyone know what these types of allocations are, and if they can be avoided with some pattern/workaround?

obsidian coyote
#

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

untold moth
obsidian coyote
#

nothing special

untold moth
#

And MiniContext.WrapScope()?

obsidian coyote
untold moth
obsidian coyote
#

ah rip, oh well, its not a massive problem, guess ill just live with it

untold moth
#

I'd avoid using dynamic. Is there any specific reason you need it? Are you interfacing with a different language there?

obsidian coyote
#

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

untold moth
#

I see. Well, if it works for you, that's fine I guess.

sly grove
obsidian coyote
#

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

cursive fjord
#

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.

novel plinth
#

in 2023.. there's awaitable api it should be comparable to coroutines now in terms of allocation

grim oxide
#

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?

jade coral
novel plinth
jade coral
#

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

dusty wigeon
jade coral
# dusty wigeon Not exactly sure how you would proceed to cut an image directly from a Shader. ...

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

dusty wigeon
#

And, if you truly want to do image cutting in a Web Environment, you should definitely make it on a server.

jade coral
dusty wigeon
limber snow
#

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?

stuck plinth
#

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

limber snow
#

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

stuck plinth
#

oh i misread that part, what exactly is null here? the result of GetCurrentPlayerLoop?

limber snow
upbeat path
#

that would mean that subSystem.subSystemList is null

limber snow
#

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

plucky laurel
#

you will be disabling domain reload in editor on play

#

by default both domain and scene reload are active

#

dont know

limber snow
#

interesting

stuck plinth
#

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

tiny tundra
#

Is there a way to get the OpenGL context via c# or c++?

dusty wigeon
tiny tundra
#

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.

urban warren
#

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! ๐Ÿ˜„

flint sage
#

Nice, glad you figured it out

#

I just rewrote all my expression trees to horrifying reflection

#

(because il2cpp ๐Ÿคฎ )

urban warren
#

Oof, much slower too! At least in editor that doesn't matter.

flint sage
#

Eh, I can still generate delegates and cache them

#

So it's not that much slower but still some

urban warren
#

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?

flint sage
#

Yeah it's il2cpp that kills it

#

(AOT actually but same thing)

urban warren
#

Dang, that's too bad really. They are so cool

flint sage
#

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

urban warren
#

I wish they would. Maybe with/after the CoreCLR thing

flint sage
#

Doubtful

#

Don't think they'll move away from il2cpp

#

Or do runtime conversion (which likely would be super slow anyways)

urban warren
#

I wonder if it would be possible to add support for it to il2cpp

flint sage
#

Maybe but the toolchain would be too big to add

urban warren
#

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?

flint sage
#

In what context

urban warren
#

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.

flint sage
#

Guessing expressions is the easiest again

#

If they were structs you could I think, assuming the same byte layout, cast the pointer

urban warren
#

Probably, sadly they are classes though

brisk spruce
#

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

urban warren
#

Yeah, there is that, though that sounds kind of expensive

flint sage
#

I think thequestion whether you can do it without reflection ๐Ÿ˜›

brisk spruce
#

its not, its actually technically one of the fastest ways to clone an object if you do it right

flint sage
#

In what way

urban warren
#

Yeah the real question really is without reflection since I know you can use reflection

brisk spruce
#

you also can just write a constructor for B that takes in an A and just manually copies the values

#

Decorator Pattern

flint sage
#

SerializedPropertyBindEvent is internal

brisk spruce
#

Well I mean you have some kind of Foo in your code that derives from it and has values right?

flint sage
#

Nope

brisk spruce
#

Where are you getting the values from

flint sage
#

Reflection

brisk spruce
#

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

scenic forge
#

Source generator mappers would like to say hi.

flint sage
#

The tldr, Mech is subscribing to an internal event that has an internal class as parameter (using reflection and expression trees)

scenic forge
#

Ah.

flint sage
#

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

brisk spruce
#

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

urban warren
#

It feels like there should be a nicer way to do it with expression trees

brisk spruce
#

what do you mean

#

no if you keep all the names the same, reflection will be like 3-4 lines of code

urban warren
#

I mean performance wise

brisk spruce
#

Im not sure what makes you think performance wont be good

urban warren
#

Because reflection is (compared to direct access) very slow

flint sage
#

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?

brisk spruce
#

you have really 2 options

  1. Fetch values with reflection and type cast them manually, set them normally with a constructor or whatever

  2. 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

urban warren
urban warren
urban warren
brisk spruce
flint sage
#

And probably use reflection to iterate over all fields

brisk spruce
#

so at least you are only just doing the Read with reflection, but your Writes are normal

brisk spruce
#

how many values are we talking here

urban warren
urban warren
brisk spruce
#

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

urban warren
brisk spruce
#

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)

scenic forge
#

Btw reflection is only slow on the first access

#

It is cached afterwards, should be pretty close to direct access.

flint sage
#

Source?

#

And for what?

#

Because it's not in net7 so I doubt it's in Unity

urban warren
scenic forge
#

Yeah not sure if it's in Unity.

flint sage
#

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)

glad badger
#

would the symbol UNITY_STANDALONE also include dedicated server builds or can I safely assume this symbol would be client builds only?

jolly token
#

Unity version would be UnsafeUtility.As

urban warren
sly grove
#

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

urban warren
#

That is what I though cool

jolly token
#

Name doesnโ€™t matter, Not including property except backing field

glad badger
upbeat path
glad badger
#

actually I guess I could just do a !UNITY_SERVER constraint to target client only (and exclude editor platform of course)

sweet summit
#

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

urban warren
sweet summit
#

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 ๐Ÿ˜…

austere jewel
hollow moat
#

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 : )

gloomy mica
#

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

real blaze
#

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

supple magnet
#

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.

real blaze
#

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)

supple magnet
#

UNITY_EDITOR and DEVELOPMENT_BUILD

#

But you can assign your own in the project settings.

real blaze
#

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

supple magnet
#

You can

real blaze
#

u mean with a const?

supple magnet
#

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

real blaze
flint sage
#

IIRC that's only for the same file

#

Not project wide

supple magnet
#

You're right

real blaze
#

yes, and that will do for me

#

I doubt a project-wide conditional define exists

flint sage
#

I mean that's csproject defines

real blaze
flint sage
#

It's not

#

Maybe you can change them per target but not conditionally like you are doing

supple magnet
#

We use Jenkins to modify the project defines. That way we can do project-wide conditional defines.

real blaze
#

project as in, the whole unity project or the assembly?

supple magnet
#

Whole Unity project

real blaze
#

ah ๐Ÿ‘

#

isn't that a bit overkill? Jenkins itself is a whole lot of work

supple magnet
#

for live ops and full production it's just standard

real blaze
#

ah I see

flint sage
#

Yeah pretty normal to do so

regal olive
#

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

craggy spear
#

How is that an advanced code question? Let alone a code question at all? ๐Ÿคฃ

regal olive
#

Oh, not advanced code but advanced help ๐Ÿ˜…

#

Searching on Google but no result

craggy spear
#

nothing about that is advanced

#

google unity gizmos

regal olive
#

Gizmos hides all, I want to hide only if collider is disabled

craggy spear
#

google harder

#

and post in the correct chan ๐Ÿ˜‰

real blaze
regal olive
# real blaze

I can still see and edit colliders even if they are disabled in my editor, using iMac and unity 2021

hardy sentinel
#

try on windows and unity 2023/LTS

hardy sentinel
# regal olive

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

real blaze
#

generally, so many components of same type on a single game object is dangerous

regal olive
#

Seems it's unity bug

real blaze
coral siren
#

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)?

flint sage
#

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

coral siren
#

okey, thx

upbeat path
regal olive
coral siren
real blaze
# regal olive Oh so bad, no way to hide?

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)

devout coyote
#

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

coral siren
devout coyote
#

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

coral siren
#

it's gonna take long and the overhead will be massive, I am well aware...

devout coyote
#

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!

coral siren
#

thx! yeah, I will take a look at them and see what I can do

errant plinth
#

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.

solar escarp
#

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

vale zenith
#

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

sly palm
#

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?

scenic forge
vale zenith
scenic forge
#

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.

vale zenith
scenic forge
#

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.

vale zenith
sly palm
molten sluice
#

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

somber swift
#

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); }

dusty wigeon
lusty cipher
#

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?

dusty wigeon
#

(If you know programmation and only the clamp is giving you a hard time)

lusty cipher
#

yes

sly palm
cunning pebble
#

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?

fathom locust
#

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?

fathom locust
#

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.

hearty pelican
#

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?

echo dune
#

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!

devout coyote
#

Amplify your signal?

tired fog
#

Is there any performance impact between using a Native Array or an Unsafe List?

tiny pewter
#

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

mellow sail
#

could we turn a dictionary into a Json?

#

in unity

sly grove
#

Newtonsoft JSON can do it

mellow sail
#

is it an inbuild library in unity?

sly grove
#

it's a library you can install from the package manager

mellow sail
#

Okeeyy

#

thank you

real blaze
#

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;
}
kindred tusk
#

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;
real blaze
kindred tusk
real blaze
#

is there even a way to test that?

kindred tusk
#

because it's inferred from the return type

real blaze
#

right. my bad

#

consider that int

kindred tusk
#

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

real blaze
kindred tusk
#

It's possible the same solution coudl apply here, but given the limited example it's hard to say what your issue is.

kindred tusk
#

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

real blaze
#

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...

kindred tusk
#

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?

real blaze
#

I see. thanks for the info mate.
as for my problem, I want a collection of value types

kindred tusk
#

Well that's fairly straight forward

#

List<int>

#

for example

#

List<SomeStruct>

real blaze
#

yeah but generic

kindred tusk
#

How will you know where each index starts and ends?

real blaze
#

like object but only structs

kindred tusk
#

a struct oculd be 1MB

#

or it could be 1 byte

real blaze
kindred tusk
#

Um...

real blaze
#
List<StructHolder> Sh;```

to add:
```csharp
void Add<T>(T val) where T : struct {
  Sh.Add(StructHolder<T>(val);
}
kindred tusk
#

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.

sage radish
#

This StructHolder is basically a box with extra steps. It's creating an object to hold a struct.

kindred tusk
#

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?

real blaze
kindred tusk
#

more storage, but you can eliminate the allocations and stuff

kindred tusk
#

You have a class called StructHolder

#

Which is your box

#

Just like I have a class above called Box

#

It's the same shit

real blaze
kindred tusk
#

DOTS isn't even a thing

real blaze
kindred tusk
#

Right here

#
var val = new StructHolder<int>(){ Value = 123; }
#

You're moving 123 from the stack to the heap

real blaze
#

but it was initially a struct, and ended up in a local value

kindred tusk
#

that's exactyl what StructHolder is

#

what was?

kindred tusk
#

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

real blaze
#

isn't boxing just casting struct to object and back?

tiny pewter
#

no

kindred tusk
#

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

tiny pewter
#

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.....

kindred tusk
#

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

real blaze
#

yes that

kindred tusk
#

But it fundamentally doesn't make sense

plucky laurel
#

unions come to mind

#

explicit layout

kindred tusk
#

Because you get the memory address of an array element by doing: array_start + sizeof(T) * index

real blaze
plucky laurel
#

no

mossy pollen
#

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?

plucky laurel
#

boxing occurs when compiler detects that the struct reference will be retained outside of the stack scope

real blaze
plucky laurel
#

yes

kindred tusk
#

The important thing is that it's the same as a box

#

You've just given it a name

real blaze
#

ah, got it!

kindred tusk
#

you still have an instance of class C on the heap

#

which will be collected

real blaze
#

absolutely didn't know that one

plucky laurel
#

var will compile into the actual type

kindred tusk
#

The struct will be stored inline in the class

real blaze
#

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?

plucky laurel
#
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

kindred tusk
#

which may or may not be a problem

plucky laurel
#
int foo = (int)(object)(float)(int)(object)1;
real blaze
plucky laurel
#

this most likely wont box

real blaze
#

compiler magic?

#

that's what I hope happens in my init question too

kindred tusk
real blaze
kindred tusk
#

the above may be an exception

#

Because it's a constant

tiny pewter
#

move stuff from one memory space to another memory space is just copying (and waiting for io), i think boxing is not needed

plucky laurel
#

these things come from intrinsics, jit optimizations in recent versions

real blaze
dusty wigeon
plucky laurel
#

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

real blaze
dusty wigeon
#

You might be interested in Convert.ChangeType

sage radish
#

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.

dusty wigeon
#

Can you just use Unity Profiler to see if there is an allocation ?

real blaze
real blaze
#

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)

dusty wigeon
#

Or something like that.

dusty wigeon
real blaze
dusty wigeon
real blaze
real blaze
dusty wigeon
#

Without using the Convert.ChangeType

real blaze
#

that one's not generic. you have a limited number of methods to choose from

dusty wigeon
#

Limited ?

#

Every ValueType is defined.

real blaze
#

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

tired fog
#

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

tiny pewter
#

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

tired fog
#

Mmm, I know the lenght of the list, it doesn't resize, any benefit with that?

tiny pewter
#

so you have check outputNoise[0],[1].... when the job is finished?

tired fog
#

yeah

#

it's empty

#

the lenght is 0

tiny pewter
#

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

tired fog
#

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?

tiny pewter
#

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

tired fog
bold hound
#

can someone help me with a netcode issue? willing to hop on a call and show them or just via dms

plush hare
#

You should ask questions here.

bold hound
somber swift
rain latch
#

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 ?

tired fog
#

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

sly grove
#

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)

tired fog
#

I see, then I need to look further

sly grove
tired fog
#

Shouldn't i get an error tho once the play mode finishes?

tired fog
sly grove
#

uh... maybe?

#

idk haha

tired fog
#

Mmm, weird, im not getting any ahhaha

sly grove
#

I mean, ideally you would yeah

#

but editor playmode/edit mode domain stuff is weird

#

especially when you have unmanaged memory in the mix

trim shard
#

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?

sly grove
trim shard
sly grove
#

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)
brisk spruce
#

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

pseudo onyx
#

Can lines like Animator.SetIKPositionWeight work if the armature this is being used on does not have any ik bones?

weary scroll
#

Can Someone help me please with Lightning, Even if you have small Knowledge (Lighting Text Room) - its a emergency

brisk spruce
#

An emergency? O_0

flint sage
#

He's being held hostage

rotund stump
#

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).

gentle moth
sage radish
real blaze
#

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

tiny pewter
#

why your dictionary contains only one key......

orchid marsh
#

Acquiring of keys is slow.

orchid marsh
#

Maybe don't call it often or optimize elsewhere

dusty wigeon
tiny pewter
#

if the dictionary just for containing one key. then try not to use dictionary

#

dictionary is sparse

dusty wigeon
#

How is it sparse ?

orchid marsh
#

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.

orchid marsh
dusty wigeon
#

Accessing at a value

#

from a key

tiny pewter
#

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

sage radish
#

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.

real blaze
tiny pewter
#

it is better to give more info

sage radish
dusty wigeon
#

Humm, I though the Dictionnary was not a HashTable.

#

I guess it is just a wraper of a HashTable.

tiny pewter
#

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#....

sly grove
gentle moth
sly grove
#

you said "I have a problem with limiting drag distance" but didn't explain what the problem is

#

you said that already...

gentle moth
#

i know

gentle moth
real blaze
sly grove
real blaze
orchid marsh
#

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.

gentle moth
tiny pewter
#

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

orchid marsh
#

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.

real blaze
scenic forge
#

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.

sage radish
#

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.

scenic forge
#

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.

scenic forge
real blaze
real blaze
scenic forge
#

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.

proven vault
#

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? ๐Ÿ™‚

proven vault
flint sage
#

Otherwise the backing field is generated as readonly

#

And thus not srializable

sage radish
proven vault
sly grove
proven vault
#

Just very confusing to noobs...

sly grove
#

most noobs don't even know what a C# property is!

proven vault
#

Very confusing to intermediate programmers*

#

I feel like even "SerializedData" would be better, or something...

flint sage
#

There's 15 years of tech debt, this is the least of their problems

proven vault
#

Just talking outloud, not trying to imply it was too high priority or making some kind official request, my bad, maybe Unity 2030 ๐Ÿ™‚?

sly grove
#

if you want a quaternion for a direction vector that would be Quaternion.LookRotation

#

Quaternion.Euler is for euler angles

trim rock
#

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.

sly grove
#

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

trim rock
austere jewel
trim rock
obsidian coyote
#

The removal of dynamic also net me another 60 fps, so now my test is running at 250 fps

sly grove
#

Also potentially lets you use IL2CPP?

obsidian coyote
#

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

sly grove
#

sounds like progress

#

now jobify it and cut it to 1000fps ๐Ÿ˜‰

obsidian coyote
#

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

potent shoal
#

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.

#

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.

spare axle
#

i am very unexperienced but are the gun things atached to the ship

gaunt swan
#

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

ember temple
honest grotto
#

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

honest grotto
# potent shoal this is my current code: ```csharp private float GetRotationAxis(float turretRot...

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
        }
vernal sparrow
#

Hello guys

#

I need a developer for a quest game

untold moth
vernal sparrow
#

Thanks

grave raft
#

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;
ember temple
grave raft
#

needs to be calculated before launched

ember temple
# grave raft yeah?

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?

gentle moth
#

Please im stuck on this problem ages

tiny pewter
#

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

gentle moth
#

please

ember temple
# grave raft yes 0, 100, 400

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));
tiny pewter
#

You end up with two equcations and three variables if i am correct, you may want to fix either T or Vy or Vxz

grave raft
tiny pewter
#

Actually target and launcher may not be the same horizontal level so the float time=something is wrong

grave raft
tiny pewter
#

It maybe some y plus dy

ember temple
grave raft
#

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

tiny pewter
#

There should be two possible values of T in Uy(T)=dy

grave raft
ember temple
ember temple
#

Or does it just move in a straight line

grave raft
#

0,-9.81,0

#

i can give it wind by doing this
1,-9.81,0

tiny pewter
#

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

grave raft
#

yeah, i need time, and to get time i need final veolocety

tiny pewter
#

Final v=Vy+Vxz

grave raft
#

so Vxz is projectileSpeed

#

what avout Vy

tiny pewter
#

Xz component of velocity

#

The gravity only affect y component then just separate them

grave raft
#

like?

tiny pewter
#

You can split a velocity (x,y) to two velocity (x,0)+velocity(0,y)

#

Velocity vector

grave raft
#

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?

tiny pewter
#

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

grave raft
#

im doing in 3d

tiny pewter
#

Then x y z, and g=(0,10,0)

grave raft
dusty wigeon
#

For wind, I would consider using an added velocity instead of a force. This would simplify the formula.

grave raft
dusty wigeon
grave raft
#

but im not adding any aditional force

dusty wigeon
#

For side wind, using a force would make the formula way more complicated.

dusty wigeon
#

Increasing only the Y component is fine.

grave raft
#

the y is problem in my code, everything else works

dusty wigeon
#

However, if you modify the X or Z component then you cannot use most formula for uniformly accelerated rectilinear motion

grave raft
#

the only thing i have problem is gtting the final veolocety

#

when that is done everything else will work fine

dusty wigeon
#

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();
        }
    }
}
grave raft
#

what is a

dusty wigeon
#

Nothing

grave raft
#

b?

dusty wigeon
#

Nothing

#

It is a whole forumal

#

Just divided for readability

grave raft
#

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?

dusty wigeon
#

Given an angle

#

yes

grave raft
#

i dont have an angle

dusty wigeon
#

I mean, initial

#

Then you gotta do the same

#

But isolate for final

grave raft
#

initial, at the start veolocety?

dusty wigeon
#

Start Velocity = Initial Velocity

grave raft
#

but i am searching for final

dusty wigeon
#

Then, redo the same for final

grave raft
#

?

dusty wigeon
#

What parameters do you know ?

#

Do you know the inital velocity ?

grave raft
#

targetDistance

#

yes

#

200m/s

#

fixed

#

constant

dusty wigeon
#

The angle ?

grave raft
#

non

#

that is at the end

#

aimDirection is the end

dusty wigeon
#

You gotta know the angle

#

So you want to find the angle ?

grave raft
#

no, i want to find final veolocety

dusty wigeon
#

To get to the target ?

#

What are you trying to do...

#

With the final velocity

grave raft
#

to get final veolocety so the time is connect

dusty wigeon
#

So, you want your projectile to take exactly X sec to get to the target.

grave raft
#

yes

#

to get that, i need final veolocety

dusty wigeon
#

Find the velocity required to travel to the target

#

The find the angle required

#

With the remaing velocity

grave raft
#

i know their positions, their accelerations, their velocity's, their distance, rigidbodies, and coeffs

dusty wigeon
#

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

grave raft
#

here, let my simplify it

#

float timeToTarget = targetDistance / (mainRigidbody.velocity + gameObject.transform.forward * """"""""""""v""""""""""").magnitude;

#

V, is final veolocety

#

everything else its done

hardy sentinel
dusty wigeon
#

I've done worst.

#

But, I use youtube tutorial and sometimes Symbolab

#

@grave raft sorry, was all the time I had for the moment

grave raft
#

ok

hardy sentinel
#

I'm here to replace Sim, what do you need @grave raft?

dusty wigeon
#

If it can help those are the most important formula

hardy sentinel
#

after X seconds?

grave raft
#

without using time due time is fed without that

hardy sentinel
#

time is a component of velocity's formula, there's no way you get what you want without it

grave raft
#

there is

#

i know there is

hardy sentinel
#

you can get the time if you first calculate the path, and then use x (position) to determine it

grave raft
hardy sentinel
#

so, you have the initial velocity and the angle, and the forces that apply (gravity), so you can calculate the path it'll take

grave raft
#

it goes from distance, to veolocety, to time, to path, to angle, shoot

#

i can get the angle of shooter and target without gravity

hardy sentinel
#

tldr:

  1. you need to get the time if you want to get the velocity
  2. you need to get the path to calculate the time it takes to traverse from x0 to x1 -- and you need the x1
  3. 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?

grave raft
tiny pewter
#

given an initial velocity vector, launcher position and target position, found final velocity vector
but actually you can miss the target

grave raft
hardy sentinel
#

so, at any given frame, you get the 'current velocity' -- which is the 'final velocity' at that frame

grave raft
#

rb.velocity.y??

that is always 0, that never moves

tiny pewter
#

but the final velocity vector is affected by initial velocity vector and T=Sxz/Uxz so you have to restrict initial velocity vector

hardy sentinel
ember temple
grave raft
#

the only info i have about bullets, the only things i can get is their gravity direction, and their starting speed(curently)

hardy sentinel
potent shoal
#

@ember templeI'm using X and Z for position, I am using Y for depth. But yes it is a top down game.

ember temple
grave raft
ember temple
hardy sentinel
#

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

grave raft
ember temple
#

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?

hardy sentinel
#

@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

grave raft
ember temple
#

๐Ÿซ 

tiny pewter
#

NO
time can be simply calculated by Sxz/Uxz

grave raft
#

?

tiny pewter
#

the xz and y component of velocity vector are independent since your gravity only affect y component of velocity

hardy sentinel
#

that's true

ember temple
hardy sentinel
#

oh forgot, different convo ๐Ÿ˜…

ember temple
tiny pewter
#

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

potent shoal
#

@ember templeYes, that was an oversight for sure. I corrected that. It unfortunately has not provided any different results.

grave raft
#

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

ember temple
#

Spaceship

potent shoal
ancient slate
#

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 ?

topaz marsh
#

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

turbid tinsel
#

and ideally, the exact line that broke the code - not just a function call

turbid tinsel
#

still, that's clearly not the exact line that called the error

dusty wigeon
#

To show the error stack you can try to set:

#

In Player Settings

topaz marsh
#

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

dusty wigeon
#

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

topaz marsh
#

Good point, I'll print both of those and see what they are

half swan
#

It's a lot more intimidating than it is difficult haha

dusty wigeon
#

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)

half swan
#

True. They both absolutely have their place.

topaz marsh
#

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!!

timber flame
#

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?

raw locust
#

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!");
austere jewel
#

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

raw locust
#

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?

austere jewel
#

Rider doesn't mind for me ๐Ÿคท

raw locust
#

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

austere jewel
#

Because it's confusing and imo illogical

#

and its existence means you can create some logical mistakes that wouldn't happen otherwise

raw locust
#

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.

austere jewel
raw locust
#

That would be actually good example.

#

I think I'll throw it into obfuscator bin then.

wide anvil
#

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?

plucky laurel
#

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

regal lava
#

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

wide anvil
#

I think I'm mostly following

#

instead of like interfaces

plucky laurel
#

it makes you write code like

StaticClass.instance.DoStuff();
or
StaticClass.DoStuff();
where 
public static void DoStuff()
{
    instance.DoStuff();
}
which is even worse
regal lava
#

Fishnet codebase is heavily structured with singletons if you want to dig into all of that

plucky laurel
#
var playerTargeting = ServiceLocator.Get<IPlayerTargeting>();
playerTargeting.DoStuff();
wide anvil
plucky laurel
#

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

plucky laurel
#

but its not realistic in a developing project, yes

regal lava
#

documentation goes over it a bit

plucky laurel
#

there is no reason to use singletons over even a rudimentary service locator

regal lava
#

What does that imply exactly? A static instance to access those specific scripts?

wide anvil
#

pardon my ignorance

plucky laurel
#

yes its a layer that separates user from the target system, so that you dont need to hard couple to specific types

wide anvil
#

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

plucky laurel
#

yes you should in general use a middle man, like service locator, or any other pattern that decouples

regal lava
#

It comes down to, do you have a single character? Does your enemy use this targeting controller class? Ect

wide anvil
#

if that makes sense

#

each player's kill script will have to interact with it

regal lava
#

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

regal lava
#

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.

wide anvil
#
    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

regal lava
#

Yeah, some empty game object you'll have that lives in the scene with these instance specific scripts

wide anvil
wide anvil
regal lava
#

There's a fishnet discord too for more network specific help

#

devs are pretty helpful

wide anvil
#

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

regal lava
#

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

wide anvil
tired fog
#

Hellu

#

Also, what does it mean being obsolete, is it also slower?

brave cairn
# tired fog Hellu

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

tired fog
#

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?

marsh laurel
#

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.

brave cairn
#

According to documentation you canโ€™t cast or receive shadows with CommandBuffer methods. You should use corresponding functions from Graphics

tired fog
#

because I need the command buffer to schedule the call after the depth buffer

#

Can I do somehow that with the graphics?

brave cairn
tired fog
#

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

dusty wigeon
#
public class Card : ScriptableObject {
  [SerializeReference] private List<Effect> effects = new List<Effect>();
}

[Serializable]
public abstract class Effect {
  ...
}

[Serializable]
public class DamageOverTime : Effect {

}
tired fog
brave cairn
# tired fog .

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?

tropic vigil
marsh laurel
dusty wigeon
marsh laurel
# tropic vigil Do you mean something like this? https://pastebin.com/nqLCFZk9

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

marsh laurel
dusty wigeon
tired fog
unreal bobcat
#

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!

sly grove
#

Not a good mix

unreal bobcat
#

ouch

#

๐Ÿ˜…

hybrid belfry
#

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 :/

sly grove
#

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

tiny pewter
#

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

tropic vigil
scenic forge
#

Object pooling is an optimization technique though, it should not affect your business logic.

torpid birch
#

please i need help

#

NOOOOOOWW

#

now

#

HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH

#

<:(

frozen imp
#

!mute 980625836875063348 1d spam ignoring warnings

thorn flintBOT
#

dynoSuccess issamiyad#0 was muted.

regal olive
#

Lol

dull mica
#

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 ๐Ÿ˜„ ?

flint geyser
#
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?
plucky laurel
#

you mean to infer the type?

flint geyser
#

Yep

plucky laurel
#

ref/out

#

but it requires you to pass a reference

flint geyser
#

Could you type it for me?

plucky laurel
#

ref T component

#

out T component

#

well actually it should infer it as is i think

flint geyser
#

where should I put the out T?

plucky laurel
#

it works as is

#

no need for ref/out

hybrid belfry
dusty wigeon
wraith eagle
#

(to be noted its different of lobbies which work already but useless on this project)

north marsh
#

Anyone use UniTask?

It seems to create performance issue for us.

flint geyser
#

How can I do something like this?

var type = component.GetType();
                    var pool = spawnWorld.GetPool<type>();```
dusty wigeon
#

You could use Reflection in theory, not something I recommend*

sly grove
flint geyser
#

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;
        }```
dusty wigeon
sly grove
#

Combined with:

public EcsPool<T> GetPool<T> () where T : struct {
  return (EcsPool<T>)GetPool(typeof(T));
}```
scenic forge
flint geyser
dusty wigeon
scenic forge
long ivy
#

that would be a bad plan for Unity types though, so don't do that

flint geyser
#

???

wide anvil
#

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

north marsh
scenic forge
#

Can't say with only that much information but I doubt it though, unless you are spamming UniTask in a hot loop or something.

north marsh
scenic forge
#

What were you using prior to UniTask?

north marsh
#

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

scenic forge
#

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.

north marsh
#

yes Iam using UniTaskVoid a lot

scenic forge
#

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.