Sometimes I see code that uses a new allocation to set a Unity Vector2/3 with new values instead of Set(), unless I'm missing some setting of the compiler magically replacing that instruction with something else this is a very unoptimized way of doing so.
@djlink I’ve been using Unity for a couple of years and had no idea that Vector3.Set() existed. It’s always seemed frustratingly inefficient.
@djlink oh, because it might end up creating a vector first and then copying it?
I kind of assumed the compiler could optimise that, but maybe not?
I didn't know that function existed, so thanks for the tip!
@djlink but... Vector3 is a struct, so it should be allocated on the stack and not make a difference because the values are just overweritten anyways?
I'd really try benchmarking those two, I'd bet there's no difference.
@djlink Afaik, Vector is a struct and “new” does not actually reallocate memory. It’s just misleading syntax. Set most likely just returns a new Vector too.
@djlink aahh interesting. I didn't know that one. Next gamedev session will be a optimisation one. Thanks.
@djlink I'm not a Unity user but this Set method triggers a visceral reaction in me. It means either that Vector3 is a class (!!!) or that it is a mutable struct (not as bad but still pretty bad)... If it is the second one, I don't think assigning new values by copy is any different from calling this Set method.
@djlink did not know this! I also recently discovered you should use trygetcomponent rather than getcomponent because it is allocated even if getcomponent is null!
@commonblob the requested component is allocated? Why can it return true then? I gotta research that
@commonblob ok it appears the memory allocation is in editor mode only to provide some log information which causes mem allocations, good to know. Thanks for the info
@djlink ah, didn't realise it was only editor allocation. Even though, handy. And code looks a bit neater anyway.
@commonblob true, changed a couple of my current algorithm just now for that