#archived-code-advanced
1 messages ยท Page 164 of 1
My plan would be to move these client queues into a server based redis cache that is cleared when connections are closed, lost or the instance is finished. Then keep a smaller queue on the client and poll the server queue when its empty
if it's tracking sensor data, or maybe some cinema application? something like that
I would look into what game networking does to compress data like this
i think you need an intermediary application that aggregates your position tracks or whatever they are
it's hard for me to understand where the 10 minutes comes from
I mean yea I could move it into a byte array or something
you're not going to have 2GB of 10m polled tracks
so it would help a lot if you just... said what it is
Oh that's interesting. Keeping all the history on the server instance and not even tracking it in client, just polling and rendering
usually someone who doesn't describe verbatim what they're trying to do
is way over their head
i'm pretty sure i've been in this forum for years
and have seen that to be true, pretty much every time
Haha its just proprietary man. Nothing personal. Its not my info to share
They might not be at liberty to talk freely about this
You should remember that NDAs exist, and breaching them is not a joke
So much wisdom for a cow ๐ฎ
yes, but someone who's not good enough of an engineer to describe in useful terms what they're doing, or to come up with a valuable analogy
you know, they're doomed
they are definitely biting off more than they can chew
i wish i could have a scorecard for that
especially coming to a free forum for free advice
there's nothing proprietary about... data visualization either
You've made my day honestly @undone coral . This conversation was fantastic
I really do need to go be productive tho. Best of luck to you all and thanks for the advice/convo
i'm just trying to help you
when this thing... doesn't work in 6 months
you know, roll with it
hmmm... probably a visualization of where people are located
that's conceivable
the conversation has ended
โ 10m polling โ ill conceived need to put that data on a 3d map or something
well sometimes stuff is proprietary because... who would want to help someone working for some giant company
for free, to make something that helps track people
can you merge the collision meshes?
i think you can meld vertexes and produce a single continuous mesh for the collider and it will fix your problem
or maybe set all the normals on the collision mesh to point up
How would that work with Textures and UVs won't they get messed up?
you would use a different mesh for the collider than the rendering
this is a really good thread
this helped me understand the issue
Ahh that makes sense. Thanks for the help/advice
before trying to meld the meshes
there are assets that do this at runtime
i suggest Poseidon CSG
you can use a lot of different "CSG" assets but this one definitely works at runtime and produces correct output
and is fully open source (paid asset tho)
Awesome!! I will definitely look into all of this
if that isn't on the table i would consider making the normals of the vertices of logically connected edges all point the same direction
or fake the ball. make it a sliding cube and animate a rolling ball? i don't know. that's not something i've tried
the reason you never see this with character controller
is because it's sliding, it never rolls
and the "contact" is the angular momentum of a face of the ball interacting with a new edge
i assume it's a sphere collider
when i was working on a super monkey ball style game
which was built out of tiles
i never observed this either
there's a nonzero chance that, despite everything that people say in this thread, the underlying problem is weird collision meshes. if you use a conventional box collider and it's correctly positioned, i think you may not see this issue
The player is actually a ball, so I don't think I could get away faking it with a cube and sliding it.
I actually recentlly watched Sebastian Lague's land mass generation tutorial, and in one of the videos, he recalculates normals for the vertices that touch adjacent meshes. I'm guessing the same thing needs to be done for the physics meshes in this case.
okay that's really reassuring
because i totally made that up based on what on read in the thread
try poseidon CSG first before you do this because i think it will fix up this stuff for you automatically already
there's also mudbun
there are a ton of great assets ๐
I also tried with box colliders and the same issue happens.
okay
then it's probably the normals
when you meld i'm pretty sure it's the average of the vertices
which, logically, for two adjacent edges of boxes
would be a normal pointing straight up
for example
if it was the top of two boxes
Yeah exactly
Yes thanks for talking through this with me, really appreciated.
So i need to do an export function, that exports applied textures to a skin in one image (texture2d) in a minecraft like texture image. The problem is, when i apply pixels from one texture to another, the texture isn't stretched like here, it justs stays at the same width and height it was before. How can i pixels of a stretched sprite/texture like this?
in other words - how can i extract a stretched texture pixels instead of the original one
Hey, I'm trying to add a function that would force my player character to go to a certain point, but I can't really debug it since Unity instantly crash as I test it T_T.
{
while (forcePlayerPosTo.ForcePlayerPos(posDialogue))
{
forcePlayerPosTo.ForcePlayerPos(posDialogue);
}
DialogueManager.instance.dialoguePartObject = dialoguePartObject;
StartCoroutine(DialogueManager.instance.StartDialogue());
}```^
^ that's probably the problematic part
``` public bool ForcePlayerPos(Transform pos)
{
movementIsOverriden = true;
float step = moveSpeed * Time.deltaTime;
if (Vector2.Distance(transform.position, pos.position) < step)
{
movementIsOverriden = false;
return false;
}
else
{
movement = Vector2.MoveTowards(transform.position, pos.position, step);
return true;
}
}
^ here is the function I'm calling.
You've written an infinite loop
Is there a reason this needs to be in a while loop at all?
I figured x]
I think you just want an if statement, not a loop
Well it's basically, while the distance is superior to one step, the player goes toward the point
Hard to say from this little context
Yeah sure but a loop happens all in one frame. You want that movement to happen over multiple frames
So you should be using Update or a coroutine
Hmmm I see
I was trying to avoid that, but it makes sense
Well I need to put more work into it then, thanks I wasn't understanding my mistake
So I guess I should call ForcePlayerPos directly in the update method, makes sense thanks
I'm using Rigidbody.AddTorque to make a ferris wheel spin. But I want it to only apply torque if it's under a certain speed. How can I do this? I've looked at Rigidbody.MaxAngularVelocity but i'm not sure how to apply that
nvm, found Rigidbody.AngularVelocity.SquareMagnitude!
Hey guys, im tryna fix my code. So im trying to sort my inventory. The way im doing it atm is: Create a Temp list with the stuff in my bag, then loop through the different item type databases to find if its in there, then readd to the list.
iterative loops everywhere as u can see. Problem: Stops after the first one and I end up filling my bag with only the First Item.
Image 1 (Diagram of what I mean), Image 2 (The Code)
Specifically running the Equipment atm, with 3 items in bag. the first fits the loop, the 2nd doesnt so it returns null then it coding breaks from there
You could use the List<>. Sort method built into C#. Sorts the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements. So implement IComparable in your BaseItem class
how do you do that?
Can you sort By more than 2 variables? or like 1 then the other?
For my inventory, im trying to sort by ItemType, then ItemID
so it should be smth like Weapons 1-5, then Armour 1-5
They have overlapping IDs tho, like both Types have IDs 0-4
You'll have to use LINQ for that. Something like theList.OrderBy(i => i.ItemType).ThenBy(i => i.ItemID)
Hello. I've made a scriptable object script and the associated object, and put some materials references on them, but can't seem to get the fields to expose so i can attach actual materials. i've tried serialized, public, private etc. nothing seems to make a difference. any idea what the problem would be?
(in the inspector)
by materials references i mean i have them in the script
anyone?
#๐ปโcode-beginner
Either:
- you have compile errors
- your fields are not serializable due to their type not being serializable by Unity or due to inappropriate access modifier or lack of [SerializeField]
which one is it - a memory leak or a stack overflow?
idk
Maybe start with the error or problem you're seeing
Also don't crosspost
Stick to one channel please
it might be a memory leak but it also said stackoverflow
i only crossposted because they told me to go here
alright i just reverted to older code and it seems to have gone away
Probably not a memory leak because you don't seem to know what that means
Assuming that the "it" that says stack overflow is an error message, the stack trace tells where the error is
Could anyone point me in the right direction? I am trying to make a function (scans a folder for files, then import those files during runtime) asynchronous to keep the game from completely freezing as I want to display a loading indicator during the progress and allow the player to interact with the game during the process (assuming that is how it works).
what kind of files?
PNGs that it then creates into Texture2Ds then into Sprites. As well as JSONs that the game deserializes.
the PNGs are best loaded via UnityWebRequestTexture it uses internal threads to create and upload the texture: https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequestTexture.GetTexture.html
you can load the json files in a separate thread via regular async/await, you just have to schedule a callback on the main thread to handle further processing that requires the unity api
Ah, alrighty! I'll look into those.
@proud iris unitask has a very useful UniTask.SwitchToMainThread(); to make it easy to author stuff like this for unity
UniTask.Void(async () => {
foreach (var file in walk("/path/**/*.png")) {
using (var req = UnityWebRequestTexture.GetTexture(file)) {
await req.SendWebRequest();
var texture = DownloadHandlerTexture.GetContent(req);
...
await UniTask.SwitchToMainThread();
uiImage.GetComponent<Image>().sprite = Sprite.Create( ... , texture);
}
}
});
Hi all, do you know if there's a way to enable all my scriptable objects in the project? I'm relying on SOs for events and centralized managers, but I just discovered that unless an SO is referenced by some object in the managed part of the code in memory (objects in the scene), it's not deserialized, created and enabled. Therefore my project doesn't work when it's in a fresh state (such as in a build).
I have SOs that are not referenced by any objects in the scenes because I have a layer of indirection with other SOs as events. These ones are referenced (and thus work), but the SOs that are not referenced don't.
Unfortunately I think the workaround here is to just have some dummy object that references those SOs
Or put them in Resources or an Addressable asset bundle or something
yeah, that's what I was thinking... I thought there was a more elegant solution. I was quite surprised to discover this lazy deserialization behavior. I was expecting all SOs in my project to become objects in memory to be honest.
I'm not familiar with these terms. Do you have any link regarding those?
you can place them in the resources folder, then instantiate them in a [RuntimeInitializeOnLoad] static method
or, put them in resources, then instantiate inside an instance property no them
thanks I just read now. I solved by putting them in Resources and having a dummy object in the very first scene that calls Resource.LoadAll("path/to/my/scriptableobjects")
I'm pretty sure it's a dirty solution, but I needed something quickly
Someone please help
Im trying to access Weight from the ItemData struct in another script. Im trying to count all the weight numbers together to get a total for a crate system. Someone help?
I have a non-Unity bot streaming System.Numerics.Vector3s into my Unity client at a steady rate (roughly 60 fps). What is the most efficient way to convert it to UnityEngine.Vector3 once it hits the client? Currently constructing a new UnityEngine.Vector3(packetโs System.Numerics.Vector3.x, y,z) upon receiving the packet in the Unity client, but I am wondering if there is a more efficient way, since Iโm doing this so often
your "ItemData" on line 18 has a capital I, it should be lowercase
and you can't do a foreach on an integer ("Weight")
you would do for (int i = 0; i < itemData.Weight; i++)
tried that and didnt work, i used a different method and got it thanks
Well 60fps is not that fast but technically using the constructor is slower than just taking a default Vector3 and populating it
Thanks, that makes sense
I'm putting this in the particles channel and this one because I don't know which one it belongs in, and I have been googling this and cannot find it. What is the correct syntax of changing the particle main color in C#? I keep looking at google solutions and I keep getting some sort of error
its all described here: https://docs.unity3d.com/Packages/com.unity.visualeffectgraph@11.0/manual/ComponentAPI.html
I guess I mistyped what I was asking, I guess I should just say how do you change the start color of a particle system in C#
I don't see where in that document where it says how to change the start color
Definitely a question for #โจโvfx-and-particles or #๐ปโcode-beginner but https://docs.unity3d.com/ScriptReference/ParticleSystem.MainModule-startColor.html @rich storm
anyone played around with making their own player loop?
my custom playerloop seems to be runnign twice
show code
my only guess is that you are appending yours instead of replacing
check UniTask implementation
I got it to work lmao.
I was adding the same playerloop twice.
Does anyone know which is cheaper/faster(computationally) to get the center point between 2 Vector2s?
Example A): center = (Vector2a + Vector2b) / 2.0f
Example B): center = Vector2.Lerp(Vector2a , Vector2b, 0.5f)
Thanks
The code for Lerp:
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public static Vector2 Lerp(Vector2 a, Vector2 b, float t)
{
t = Mathf.Clamp01(t);
return new Vector2(
a.x + (b.x - a.x) * t,
a.y + (b.y - a.y) * t
);
}
Note the attribute, the code in this method will be inlined, so there will be no real method call in IL when you call the Lerp in C#.
Plus, division is more expensive computationally than multiplication.
So the second one.
Rewrite the first one to *.5f and it's the same
Interesting!
JIT might even do it for you
IIRC division is not always slower nowadays due to JIT optiimzations
e.g. The jitter can also change integer divisions and multiplications like x / 2 or x * 2 into x >> 1 or x << 1.
Also that clamp introduces branching which might be slower
So you know, lots of variables
Looking through the assembly it actually never does a division. It always combines arithmetic shifts and sometimes multiplication to do its thing
Latest runtime or mono runtime?
Latest
Wouldn't surprise me if there are differences in this between latest and mono
Anyways, the only reason you should care about this if you're doing some uber high performance thing (which you probably don't want to use Unity for) or shaders (maybe)
Yeah, that is micro optimization stuff here
I appreciate all the input, especially the stuff on JIT optimizations. I learned something new.
hi guys i need some help
hi sirs, i am sending this here because i think its abit advanced error, but im not advanced, So i just want to know how can I refer variables from canvas when the scene loads, the canvas is on DDOL so it is being destroyed(to prevent duplication) and when i go back the variables are "missing" and null reference error occur.
I'm trying to make a login system using an API and a MySQL database, everytime I echo something and try to get it with the www the www.text comes back blank and I don't know why, I've done the register and it works 100% so idk what's wrong here
maybe try sending the values to an "notDestructible" game object before destroying the canvas
wdym
as ddol ?
hold on @golden gulch was using my acc, he is gonna help u now
idk what a ddol is, im trying to say for you to create a and empty game object with just a script with those variables and before destroying the canvas u send the values to there, aka u set the variables with the same value as the canvas vars, make the game object not destructible and the when you need those values go get them there
that way the vars wont go missing bcs they dont get destroyed
and i dont think it would affect general performance
I don't see a math channel, so I hope you guys don't mind me asking this here.
It's a math related question, best asked with a picture.
I also have the info of what weight is at the 3 points of the triangle. Forgot to put that in the "info I have" part
Looks like homework
Nope, lol it's work related. Haven't been in school in many years
But that's encouraging to hear, cuz there must be an answer to it then, if people do this for homework
I'd be happy with a topic I can search for on my own. I just don't know what I'm looking for.
I mean it could be homework but it looks like a paint drawing, I hope your schools make better assignments than that ๐
Ya, I did it in MS paint
ANd like I said, I'm not in school
I never took trig or calc in college
Self taught, one thing at a time, when it becomes relevant to my work.
Couldn't you use the distances to each corner?
(no idea if it works for all triangle types)
That's something I've thought of, I can get the distances, but what to do after that. ..
Well, if all distances are equal, that'll be the center
So you can work out proportions
Ya, I can get the centroid, but that doesn't tell me the weight at the red point
distances are usually not gonna be equal
Well, if ya don't have the answer, then I don't want to make you do my work for me. I'll brainstorm it out, and figure it out
I appreciate your time.
Have a look at barycentric coordinates
Ohh, that looks promising at first glance! Thank you!
guys can someone help me ive been searching for this for 4 days now:
i made an api using php and im using the www class to make a login system, the problem is i can register an user using www but i cant get the info that i need from the site , it comes empty and idk why, on yt all the things i tried to do work but not for me
WWW is deprecated now, use UnityWebRequest. You'll also need to show some code.
i tried with that but nothing changed it keep on coming blank
You are not sharing information that would enable anyone to help you
also make 110% sure the problem isnโt in the PHP code
Neither, use a paste site
i used postman and it comes back with the info so the php works
What does the JSON look like?
if the username and the password match to anything it comes like this:
[[{"ID":"18","UserName":"joaofixe","Image":"","Money":"0","Reputation":"0","UserCarIDSelected":"0"}]]
JsonUtility cannot parse that. Maybe use newtonsoft.
Also you have a nested array you donโt want
but if the WWW was getting the text it would show it up in the debug right? bcs it doenst
whats that?
I'm not even sure it's valid JSON to have an array inside of another without a key or object separating them
The [] denotes an array, and you have [[ ]]
An array directly in another
oh you're right
thanks
ill fix that but that wont fix my problem for now
ok thats fixed B)
Well, nested arrays are valid, I've put it into a validator and it passed. Still not what you want here though. Also if you only expect one player returned when you authenticate (no multiple accounts per username), there shouldn't be any arrays in the returned JSON, just
{"ID":"18","UserName":"joaofixe","Image":"","Money":"0","Reputation":"0","UserCarIDSelected":"0"}
And that object can actually be parsed by JsonUtility, unlike the top-level array one, which is unsupported.
I would still recommend switching to Newtonsoft as it has better capabilities
thank you ill look into newtonsoft
so, im trying to get into A* pathfinding, and i think i understand it, but it seems like for physics objects, A* only works if the grid size is as big as the object trying to pathfind, else it will see being right against a wall as a valid position right? Is there a good work-around for this?
Don't make nodes next to the wall?
Or give them a different score
You can also do something like a navmesh
navmesh?
that seems a lot more convenient
It's also more difficult to make ๐
damn, well ill look into it, thanks navi
maybe look into PlayFab for stuff like login
it has a nice unity plugin
Anyways, if you're learning; don't get too attached to those problems
you can also use Firebase for Unity to build complete turn based games, and it's well documented
right, i getcha
i see that you just want the "weight" at a particular point
i guess that is just a barycentric coordinate. you can find a lot about it online
wait, can navmeshs be setup dynamically on a randomely generated set of objects? i assume yes but just wondering if you know
Yes
dope
yeah it's called the components workflow
you can even use unity navmesh out of the box for this
The official Unity one yes, but they were working on their own pathfinding
oooh sounds stable and well documented
Ha ha
IIRC you can use NavMeshBuilder.CreateNavMeshData oder .BuildNavMeshData or something with a similar name, I don't remember exactly, to create the NavMeshData at runtime,
as well as using NavMesh.AddNavMeshData and .RemoveNavMeshData
to actually add/remove it, I don't know how it's acting in terms of performance, but maybe that helps in some way
oh dope, thanks wtch. im watching CodeMonkeys tutorial for navMeshs rn so this will come in handy later
until unity vector3 supports being copied from a span, no
you just construct
there is a lot of copying when using the unity api
so it doesn't matter
There's also a NavMeshComponents package I think, but I never tried it
if you really need it super optimized, like if there is a lot of data like a mesh
you can avoid copying using native arrays
however, i am not sure if theres a way in unity you can get a network byte buffer without copying
and if you put a gun to my head and asked me to write it right now, i wouldn't know how to do it in .net
i'm sure such a thing exists
i dont think ill need it super optimized. ideally id be generating the navmesh after generating a simple grid of spaced blocks at the beginning of a level generation
i am pretty skeptical that unity's .net/mono correctly implements zero copy on all platforms
is this important to you @verbal peak
i'm just not sure if you can do this in .net. in java, this is what netty is for
i would also see if unity web request's download handler performs a copy
the particular problem that they're talking about in that article that they can't address is https://github.com/dotnet/runtime/issues/30797
but those allocations are so tiny they don't matter
@verbal peak https://github.com/nxrighthere/NanoSockets "For .NET environment, functions support blittable pointers as an alternative to managed types for usage with unmanaged memory allocator."
it's just hard to say, when Unity gets contractors to do stuff, who knows if it ever works ๐
hey anyone know of any resources for writting a material from script
im grabbing a texture from my cms in a editor tool and would like to create a material file in a folder to access
all through script
Thanks for all of the input @undone coral
I believe my bot is sending TCP, itโs a service developed by a colleague so Iโll have to check. I did some research and found that modifying a default Vector3 is slightly more efficient than constructing one, so that may be helpful
okay but it won't matter because the network buffer is copied
you can try for 0 copies, exactly 1 copy, or unlimited copies
there's not going to be significant quantitative difference in going from 11 to 10 copies
i wouldn't overthink it then
Hey, so I am trying to optimize the memory usage of an API but I can't think of what would be the best way to check different methods to see the memory impact they have, any ideas?
I was going to use benchmark.net, but that doesn't seem to play nice with Unity
Unity has its own memory profiler
Oh yeah...
Honestly, great question. All I know how to say is "_type" is a variable and not a class or a type. But like, what's really the difference?
someone else told me that its because attributes are compile time
But yea, to fix your thing pass in "Type" instead of "_type"
so i need to figure out a way to generate a property drawer without using an attribute to do so i guess
Not the most satisfying answer because variables exist at compile time too
they're right. the value of _type isn't known at compile time
In this case, maybe. But a compiler can know the value of variables in general. Some code optimization try to simplify what we write by reflecting on when and how values are assigned.
I also suspect that optimization is opened up the instance you call out to get that type set. But I'm just guessing.
Writing an Editor tool.
protected virtual void OnSceneGUI()
{
NebulaMk5 neb = (NebulaMk5)target;
if(neb.regionNodes.Length > 0)
foreach(RegionNode n in neb.regionNodes)
{
if(n == selectedRegionNode)
n.position = Handles.PositionHandle(n.position, Quaternion.identity);
switch (n.security)
{
yousawnothing
}
n.position = new Vector3(n.position.x, 0, n.position.z);
}
}
Does anyone know how I'd actually assign selectedRegionNode based on a click?
Or should I just do the regionNodes as gameObjects?
This whole thing only gets run, this is just a tool to generate data for an entirely different project
So performance isn't super important
I donโt really understand what youโre asking, also thereโs a editor tools section right under this
the if statements without braces being multi-line and not being tabbed... ๐ฐ
Is there any event that gets called every frame? I know theres onBeforeRender, but that doesnt work wtih input
you mean like void Update() ?
Describe what you're actually trying to do
https://docs.unity3d.com/ScriptReference/LowLevel.PlayerLoop.html you can inject a method into the player loop
Exactly what I needed thank you
Anyone has any idea whether it's easy to implement your own collision detection for very simple shapes and very few simultaneous colliders?
Looking for a way to avoid using hybrid between classic RigidBody and dots entities
public class AuctionVariables
{
// my constructor
public AuctionVariables(JToken data)
{
var result = JsonConvert.DeserializeObject<item_bytes_class>(data.ToString());
}
public IDictionary<string, item_bytes_class> item_bytes { get; set; }
}
public class item_bytes_class
{
int type;
string data;
public int Type { get => type; set => type = value; }
public string Data { get => data; set => data = value; }
public item_bytes_class(int t, string d)
{
type = t;
data = d;
}
}
are the values already in item_bytes, or do i have to assign them? when yes, how?
https://github.com/Matthew-J-Spencer/Ultimate-2D-Controller
You can check this 2D Player Controller It's using a simple rounded square shape Also It's using Custom Physics, Collision Detection (No Rigidbody or Colliders)
A great starting point for your 2D controller. Making use of all the hidden tricks like coyote, buffered actions, speedy apex, anti grav apex, etc - GitHub - Matthew-J-Spencer/Ultimate-2D-Controlle...
that sounds good, thanks
sadge, it's using raycasts
which only work in engine physics
@remote drift This might come in handy https://www.youtube.com/watch?v=-_IspRG548E
Physics is a part of games that has always amazed me. I find it funny how impossible it seemed to do correctly when I was younger. While making a custom game engine, it was finally demystified!
The full article: https://blog.winter.dev/2020/designing-a-physics-engine/
The background game demo: https://winter.dev/demo
0:00 Intro
0:26 Dynamics
...
yeah, I think it's coming down to making my own physics engine I guess
Indeed
hmm, any idea how Unity physics collision detection works?
does it check collisions for literally every single spawned collider
or there's a smarter way about it?
not collision detection algorithm itself, but rather when it is executed
try using Havok
how do i make my animations not overide each others?
I'm not in scope of any physics engines rn
in ridigidbody component try to use dynamic
I mean, I don't even have game objects to begin with xD
it's dots entities
and they sadly only have 3d physics engine
do you have any idea about my question tho?
so far checking collision between all colliders in double loop works for my niche case, but I really wonder if that's how things work
in big company physics engines
yeah, and this channel is specifically for those overcomplicated scripts I am trying to dig into
๐
why would you want that
i mean made a new game yesterday for now pretty basic
because I'm not working with classic Unity
huh
I don't have rigid bodies
at all
or colliders, I have to come up with them myself
u dont have standart unity package?
it's more like I specifically not using it, because I use their other package
SHOW ME your package folder in unity
which is entirely different world
what game u building?
unfortunately no
sadpepega
for now nothing
unity uses physx SDK, here is a grep on the source code, its fairly complex cpp code https://github.com/NVIDIAGameWorks/PhysX/search?p=1&q=%2F+collision and for 2d its Box2d https://box2d.org/documentation/box2d_8h_source.html
well
finally someone came
where do i add my roles again
long of the short it creates a hash table of collision flags and checks various buffers for each one that is registered in the system. that stuff is super low level
Hi
Can anyone tell me how can I make a instantiated object followed by Camera in unity
so, it still checks all posible collisions inside collision groups (colliders that collide between each other)?
Is there any way to give value of player to camera that is instantiated on photon network
Give value of player?
Yes on photon
But I am using unity engine the issue is related unity
All photon products are for unity
So the problem is when I play that offline the camera follows the player and when I play it over the internet photon the player is not followed by the camera I need to drag and drop the player to the camera
So if you want a particular prefab to do something when instantiated you can do it from Start
It can find the camera and make the required changes
If you do it that way it doesn't matter how the player is instantiated, it will work every time
If you need something more fine grained you could look into doing an RPC.
Ok but can you give me idea what I should do right now
Yes i know that
Yes
So in Start you can write the code that you want to run when the prefab is instantiated
And that will run on all clients
Ok thanks bro
But you should also check out the photon discord for these kinds of questions
Sure
Since everyone there uses photon + unity
And here it's just a minority of people who use it
Sure
Hello
correct, where collision group is basically your layer which you define your rigidbodies to interact with.
welp, looks like a perfect solution for parallelism
and single thread worst nightmare
xD
thats a project setting
but still, if number of objects is possible collisions is too high, you get to the point that every single thread is clogged
I'm designing my own physics in this case, so doubt there's any help from project settings kek
I just need super simple 2d collision detection
well threads != cores
nothing fancy
unity has that built in
not for ecs
they only have 3d, which is actually pog
but it's super unperfomant to use with 2d
as every collider will have joints to constraint axises
2d unity projects use Box2d not Physx
This is not the appropriate channel
But this is about unity
Ok
there is this sub project https://forum.unity.com/threads/unity-tiny-still-alive.1227405/
DOTS for 2d
are you sure? I looked into it, it has no 2d physics
2d entities - yes
but not physics
i see what your saying here is the forum thread, you have to homebrew https://forum.unity.com/threads/how-can-i-make-simple-2d-collision.1048313/
hmm
actually I don't need response, only events
honestly that lib looks super ghetto
so I can trigger my own physics on player (only dynamic body)
last update a year ago xD
ya just use some delegates or something
that was a few days ago, unity is politely saying to that guy f off we arent going to implement it.
good luck ๐
you could also try using https://github.com/benukhanov/box2d-netstandard
technically that should work if you bundle the dll with your release
ooor just make my own physics
which could potentially be more rewarding in terms of learning
I wouldn't say that
burst requires some super low level knowledge to get any usage out of it
at least outside of jobs
maybe, dependents on your technical ability to
[BurstCompile]
public struct ReallyToughParallelJob : IJobParallelFor
{
public void Execute(int index)
{
//Code goes here
}
}
[BurstCompile]
public struct ReallyToughParallelJob : IJobParallelFor
{
public NativeArray<float3> positionArray;
public NativeArray<float> moveY;
public float deltaTime;
public void Execute(int index)
{
//Code goes here
}
}
I don't know how to explain my issue exactly: I have a data-type block that takes 3 items: isExist, textureIndex, and colorIndex. How do I add these 3D arrays to a new block-type 3D array I'm creating without looping through it, adding them 1 by 1?
You don't
I see.
You need to loop through it
That seems... inefficient.
How unfortunate
No because they're transforming the data
Yeah
You could multithread it
No thank you
It's embarrassingly parallel
hahaha
I appreciate it though, thank you. I'll be sure to do that
Honestly for this type of bulk low level data, as tempting as it is to keep things object-oriented, your best bet performance and memory wise might be to just keep the data in the three separate arrays
I've mainly done it for the sake of keeping my head on straight. Objects help make the medicine go down.
Keeping track of millions of blocks
Depends waht you wanna do with the data afterwards
Like if you wanted to sort the blocks etc.
Gonna be a pain the butt
Indeed but they come at a cost. One being the bookkeeping cost of this ill-fated loop, the other being the memory locality cost of making these thousands of random access objects in the heap
Oh well Block should be a struct!
Instead of nice organized arrays that the CPU L1 cache will just love
Gotta be a struct
Gotta rack up a line of data for the CPU
Only the purest of data
True I assumed it's a class for some reason
looking hot
look at that staggered load
Spoiling the players with frames
amogus?
IL2CPP
Error Converting System.Drawing.Image to Sprite.
The actual conversion is perfectly fine. Converts to Texture2D with no issue. The error is when trying to use Sprite.Create(); it throws the following error
string string.Format(string,UnhollowerBaseLib.Il2CppReferenceArray`1<Il2CppSystem.Object>)
I am dumbfounded rn at this error lol
Trying to build an AssetBundle but got this. What does it mean?
Error building player because script class layout might be incompatible between the editor and the player.
UnityEditor.BuildPipeline:BuildAssetBundles (string,UnityEditor.BuildAssetBundleOptions,UnityEditor.BuildTarget)
I can provide code if needed
I don't have a lot of experience with building because I've never built unless someone was going to test my project (like 3 times)
And if none of you know the answer could you please maybe guess? We've been trying to sort this out for ages because we got our community hyped up for it and it was working beforehand
are you using perlin noise? seem not
Is there really no way to get a list of all the toggles that belong to a ToggleGroup (from the ToggleGroup)? I'm not seeing one in the docs, am I just missing something? (https://docs.unity3d.com/2019.1/Documentation/ScriptReference/UI.ToggleGroup.html)
do you have any conditional code that changes a script's serialization layout?
Hey, I was looking how to make a rope system weeks ago still can't figure it out, I was wondering if anyone can help me with, here is video showing the result needed.
you're looking at the old docs (probably) https://docs.unity3d.com/Packages/com.unity.ugui@1.0/api/UnityEngine.UI.ToggleGroup.html
Amazingly you can't get them directly, you'll need to create your own class that inherits from ToggleGroup
Something like this:
using UnityEngine.UI;
using System.Collections.Generic;
class MyToggleGroup : ToggleGroup {
public IReadOnlyList<Toggle> Toggles => m_Toggles;
}
Ah, thanks. That's too bad
No I plan on later though
why are you using system.drawing.image
what is throwing that error?
Converting Windows Media Controller Image to Unity Image
so, im trying to learn about implicit operators, and usually the thing i try to do with any C# concept is find a use for it in unity, and i figured out how to use them more or less, but is there a way to append something like the vector3 struct to add a line of code like
{
public static implicit operator Vector3(int numbers) => new Vector3(numbers, numbers, numbers);
}```
im not very familiar with the namespace operator, but i couldnt figure out a way to use it to allow me to work with the vector3 struct
Well first of all that wouldn't be an operator
ive used that line of code with a custom class and it worked fine, now im just trying to apply it to Vector3
I'm fairly certain that operators cannot be defined outside of the class/struct so you wouldn't be able to implement that implicit operator. However you could write a wrapper for Vector3 that includes that, or just write an extension method for it which would be the easiest solution
im not familiar with wrappers, so ill try using that so i can learn it. thanks for the info
ok, after looking up wrappers i dont see how i can use that here. Could you give me a short example?
That would genuinely not be an operator, it doesn't make sense as one.
struct Vector3
{
public static Vector3 UnitI32(int number)
{
return new(number, number, number);
}
}
a wrapper would just be a class/struct that effectively wraps around another to extend behaviour. this wouldn't be a good application for it, but it's doable. Your operator would just operate on your own type which would basically act as a vector3. The better option would be to use an extension method
This is what it would look like if it were implemented in the actual struct
they are referring to implicit operators, which their code (mostly) correctly reflects https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/user-defined-conversion-operators
ohhhh i see what you mean. ok. I was mainly trying to apply it to vector3's so i could write some code for a friend and be like Vector3 newVector = 3 and have that look cool
It doesn't make sense for what they're doing
right, which is why i've suggested an alternate way of going about it by using an extension method, not that it would make a whole lot of sense for it to be an extension method anyway, would be better to just be a static method or to not implement it at all since it's a problem of their own design that doesn't need a fix
exactly, i was just trying to toy around with the concept to gain an understanding of it
i worded it poorly but that's pretty much what i meant in the last part of my message
Extending operators has been talked about for easily over 10 years now in C#
If they haven't done it yet, they probably won't in the future
this is a good use for operators
public struct TimeSince
{
private TimeSince( float time )
{
_time = Time.time - time;
}
private readonly float _time;
public static implicit operator float( TimeSince ts )
{
return Time.time - ts._time;
}
public static implicit operator TimeSince( float ts )
{
return new TimeSince( ts );
}
}
That last operator is just the constructor again, no?
could you show an example of this being invoked? Im having a hard time visualizing it (sorry its 2am where i am)
This seems like a really bad example
var timeSince = TimeSince(1.5);?
It just doesn't make sense, what does this return?
It doesn't even have any fields or properties to access
yeah im not sure how you would get anything from that
private static TimeSince _timeSinceLastOperation = 0;
private static void OnUpdate()
{
if ( _timeSinceLastOperation > 5 )
{
Debug.Log( "We've waited 5 seconds..." );
// Reset the time
_timeSinceLastOperation = 0;
}
_timeSinceLastOperation = 2;
if ( _timeSinceLastOperation > 5 )
{
Debug.Log( "We've only had to wait 3 seconds..." );
// Reset the time
_timeSinceLastOperation = 0;
}
}
how are you comparing a TimeSince with an int through > ?
because its returning the float
ok, im going to feel stupid asking this, but how?
big brain time :D
OK that makes that a lot cooler than i thought
ok i think im starting to understand this. Im going to try to expiriment with this on my own for a bit, but thank you for that example!
no problem!
I need help placing objects on a pearlin noise map "procedurally"
Script: https://pastebin.com/xnbsYSSw
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.
Please weโre can I gt code that provide random game environment
Like dt if clash of clans nd RTS games
C# Question:
I'd like to substitute a T in a generic with void, e.g.
public class VoidChannel : DataChannel<void>{};
Obviously that doesn't work (for more reasons than the syntax check), is there a way to have a flexible list of arguments instead or something?
Trying to create an instance of a script that is attached to a different GameObject, but I keep getting the error that my object reference is not set to an instance of an object. What am I doing wrong?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MenuAnimation : MonoBehaviour
{
Animator animator;
StartMenu startMenu;
MainMenu mainMenu;
// Start is called before the first frame update
void Start()
{
GameObject menuA = GameObject.Find("Start Menu");
GameObject menuB = GameObject.Find("Main Menu");
animator = GetComponent<Animator>();
startMenu = menuA.GetComponent<StartMenu>();
mainMenu = menuB.GetComponent<MainMenu>();
}
// Update is called once per frame
public void Update()
{
if (startMenu.isComplete)
{
animator.SetTrigger("FadeOut");
}
}
}
Either it doesn't find one of those objects, or it doesn't find one of those components. #๐ปโcode-beginner
I switched to drive version 2022.1.0b and i got this error what can i do because i am not an expert programmer?
Is UnityAction<T> a descendant of UnityAction ?
Suppose not.
I guess delegates are first class types
could you explain this a bit further?
I have a event class (two of them, one generic, one for the "no parameters to the event" case). I'd like to unify them, for that, the generic T needs to become void or optional.
public class EventClass { }
public class EventClass<T> : EventClass { }
```?
Yes, that's the problem.
But actually thinking about it this way might get me somewhere.
The event exposes an API where you can Subscribe to it, backed by an instance variable
[NonSerialized]
public readonly UnityEvent subscribers = new UnityEvent();
and
[NonSerialized]
public readonly UnityEvent<T> subscribers = new UnityEvent<T>();
respectively.
A way to conditionally compile this so that one uses UnityEvent and one uses UnityEvent<T> would be great (again, because UnityEvent<void> isn't a thing; same with Func<void> and similar cases.
It's more valuable to have the code unified here instead of 2 classes, no matter how short. The polymorphy doesn't need to work for these two, so conditional compilation with #ifdef is an option. My brain just can't make the connection.
public class EventClass
{
public UnityEvent subscribers { get; private set; } = new UnityEvent();
}
public class EventClass<T> : EventClass
{
public new UnityEvent<T> subscribers { get; private set; } = new UnityEvent<T>();
}
Yeah, that's what I want to unify into one class.
you can't, like it's straight up not possible
Because I have 2 base classes (ScriptableObjects), and one is basically sealed, the other is basically abstract. It feels really clunky.
I could put the void one into Concrete and "pretend" it's like the others.
(there's also the problem with how older versions of unity don't like Generic ScriptableObjects, but that has become much more tenable, even if a bit clunky to read)
Let alone DOTS really hating generics, still. ๐
Well, I think these grapes will be forever sour.

though what do you mean with "a flexible list of arguments"?
0 or more.
EventClass<...>
๐
So spoiled by C++11 variadic templates, I tell you.
Soooo spoiled.
template<typename... Values> class tuple; // takes zero or more arguments
Wait though.
Tuples in C# could be a way out.
public class Tuple<T1,T2> : IComparable, IStructuralComparable, IStructuralEquatable, ITuple
ITuple.
Maybe savior of the day.
Are there empty tuples in C#?`
Well my reading work is cut out for me.
Hmm.
I need one that has no contents.
public object? this[int index] { get; }
public int Length { get; }
is all that ITuple does
Can't start at a minimum of 1, must be minimum of 0 elements.
Otherwise nothing is gained.
But that's all I need.
I can make a "Nothing" tuple to use.
i mean you can't have a generic class and instatiate it with 0 objects
it's just not possible
The main problem now is how Unity will serialize it, but...
there are Action and Action<T>, but i assume they're set up the same way, separately
Yes, but that's also like the year 2000 .NET roots.
The language has seen so many advances.
Well I'll read stuff.
Maybe I find something, the tuple idea might even work but Unity's serializer is going to throw a massive fit.
I can feel it.
(because level 2 of this, much of this needs to work as ScriptableObjects)
var mt = new MyTuple
{
new byte[] { 1, 2, 3 },
"string",
6.9
};
class MyTuple : List<dynamic>
{
}
ยฏ_(ใ)_/ยฏ
what's this dynamic keyword?
much fancier
for example;
var arr1 = new object[] { "a", 1, .5 };
var s = (string)arr1[0];
var i = (int)arr1[1];
var d = (double)arr1[2];
with object, you need to cast
dynamic infers the type automatically
well doesn't seem to help with the declarations (also for CreateAssetMenu) - because it's important the events use the right type. You musn't plug a bool responder into a UnityEngine.Transform channel.
I'll try to find out what Unity Editor has to say about 'dynamic' ๐
And IL2CPP.
Still, somehow void isn't a proper type. (which it totally should be, just like the number 0 is totally a number, and null is totally a value)
Yeah. This approach defeats much of the type safety (actually just inference...) I require.
void is the abscence of a type
Yes. Like null, in a way.
not even close right?
void can still have locality, it's just zero in size.
(you might see that I have a C background...)
null is the absence of locality, generally, but as such is a value in and of itself
"returning" from a function that returns "void" still returns, and the stack pointer is exactly where it ought to be, pointing at something that is of zero size however.
void is the absence of value
(wow that sounds philosophical)
<@&502884371011731486> is this even allowed?
No. Thanks for reporting
hey is there a way to select vertices in a buffer and replace the selected vertices with a bigger or smaller array like in the drawing?
select vertices in a buffer - well you can just loop through the buffer and check the vertices based on your criteria
replace the selected vertices with a bigger or smaller array - no. either create a new array that's longer / smaller or maybe you could use tessalation
there is a proposal on the c# github for 'typed void' iirc, maybe it's named slightly different. the language team has much interest in that proposal though, but i don't expect it to arrive super soon
does anyone know how i can change the ambient occlusion settings of urp at runtime?
by swapping the asset itself at runtime using quality settings
yeah i know how to swap quality settings, but that is not what i want since the quality settings are pre defined at compile time. i want to change the current settings at runtime
that is currently not possible since there are some extra shader variants required for ambient occlusion, which needs to be generated with the build.
what you can try is to keep ambient occlusion on by default in your assets, and at runtime try to disable it directly from the asset (GraphicSettings.currentPipelineAsset or something like that)
I'm not sure if this will work or not, but last time i tried, i had some weird artifacts on screen in 2020
correction, i do not want to necessarily add the ambient occlusion render feature to the quality preset, simply tweak some of those values. so i kinda think that should be possible? essentially i'm migrating a built in pipeline project to urp and it uses aolayer from postprocessing stack v2 and i only need to change the color and intensity at runtime
and graphicssettings.renderpipelineasset only exposes like shaders
are you saying you want insert an array into an array?
only by copying
yeah i dont think you could do that in runtime at this moment
hey everyone,so i got this error message and it raises some questions in my mind
lets say i have the relevant mesh and then i turn on read/write (it's a combined checkbox)
now IIRC, changes to this mesh happen on disk, to the asset, and persist outside of runtime, do they not?
no
if you have read/write on for a mesh, its data is stored in two places: gpu ram and system ram. It's very slow to access GPU ram from CPU, so ideally you only have the one copy. But if you really do need to access it, it's faster to modify it in system memory and upload to GPU than to try and retrieve it from GPU, modify it, and upload the changes back
here's my use case:
i have a grid world
i'm putting instances of the object into the world
and i'll be deforming the mesh to match the slope under every instance
so essentially the checkbox is to indicate to unity to use a system copy, is that right?
yes
now if i have a meshfilter referencing the mesh asset and I modify it through that reference, what happens?
the changes aren't persistent, if that's what you're asking. You probably want to write an editor tool that will let you create an asset from a Mesh, which will then work as you want
if you're trying to save your changes to disk
im more thinking of the practicalityy
i don't intend to save the changes to disk, however if the mesh filter will automatically instantiate a copy, i don't need to do so manually in code
if (unmodifiedMesh == null) { unmodifiedMesh = blockMeshFilter.mesh; }
Mesh mesh = new Mesh();
Vector3[] vertices = unmodifiedMesh.vertices;
mesh.vertices = vertices;
blockMeshFilter.mesh = mesh;```
Yeah you probably don't want to do that. This will cause you to use 4x memory instead of 2x memory for no reason
let's say i run this multiple times
will i need a copy of the original in order to work from that clean slate each time ?
๐ค oh i could actually just copy the initial vertex array, so that's all i'll change. not the whole mesh itself
if you don't want to modify the original copy, access the mesh with MeshFilter's mesh property (like you're already doing) and not sharedMesh. This will create another copy that's unique to that MeshFilter
oh, yes!
that sounds like what i need
so, this:
if (unmodifiedMeshVertices == null) { unmodifiedMeshVertices = blockMeshFilter.mesh.vertices; }
Vector3[] vertices = unmodifiedMeshVertices;
/*modify vertices*/
blockMeshFilter.mesh.vertices = vertices;```
but keep in mind you're also responsible for destroying it, otherwise it might exist in memory a long time or until Resources.CollectUnusedResources is called or a non-additive scene change occurs. That surprises a lot of people when they're profiling, same as Materials
yes
ah, i see, thanks for alerting me to that
is there a flag in the Mesh Filter that indicates when the mesh is a instantiated copy?
or shall i track that myself?
I don't think there's an existing flag for it, so you might have to track it yourself if you're only modifying it sometimes
copy that
anyone seen this before. I just started using Target Android API level of 30 in order to use Google Play Bundle Delivery. Builds fine locally. On cloud build we get "Actionable build error: The highest installed Android API Level is 29, however version 30 is the minimum required to build for Google Play."
Is this a known issue that cloud build doesn't have API version 30 installed?
Do standard unity shaders have any sort of universal fields for things like UV and etc?
Hello: I want to buffer load my music during game, and not all at once. When I load all at once, it takes 36 seconds extra time before the game even starts: https://youtu.be/D74XLepmwHM What is the proper way to resource manage? I want to load in and out of memory manually in script and link in scenes manually in script.
Hello,
I discovered linking resources in the scene raises loading times.
I need to find a way to properly buffer load them on the fly.
I have 80 tiles totalling 1.86 GB of data.... When loaded, adds 36 seconds to loading time of game!
I want it so it loads 1 music file then loads the rest as they play. I need to find out the proper way for t...
asset bundles/ adressables/ reference in the scene
Can I load and unload from resource folder?
resources is a single massive asset bundle
i can be wrong but when you load that scriptable you pull all of those sounds to memory
I heard that you load it one at a time... Well one way to find out
If I do a standalone build.
I appreciate it bro!
Now I'll look into it
Reference into the scene does not work
reference in scene loads on preload
I thought everything from the resources folder is loaded into every scene
yeah i am only sure that adressables handle that, they do ref counting and automatically unload
tho i would first look into why they take so long
doesnt seem normal, look into compression/formats things like that
I have a massive massive online omnipotent RPG mmoorpg
Gonna be 2 Terrabytes sooner than later
Right now just loading 2 gig of music assets
oof
Some people really like to have huge games on their machine
Eventually maybe get to 8 TB in a few years.
The reasoning is: If I want to invest years in a MMO, I might as well spend 100$ for ahard drive and get the max experience
Not sure if this was the correct channel to ask this in, but I'll go ahead and try.
I'm currently writing my game with a lot of async functionality (with Tasks), but I want to make sure that I'm thinking about this correctly to avoid any unpleasantry in the future (deadlocks, blocking of threads, concurrently writing to shared data structures etc)
The way I do things currently is I transition from Unity's events (such as OnMouseEnter) to the "async chain" by defining an asynchronous version of the method, which is using the async void syntax. After that it follows by returning Tasks in the asynchronous methods further down the chain:
public void OnMouseEnter()
{
OnMouseDownAsync();
}
public async void OnMouseEnterAsync()
{
await DoTask();
}
public async Task DoTask()
{
//Execute work here
}
If I'm understanding it correctly, Unity is basically using one main thread for all these features, and thus the tasks I await should be scheduled on the same thread in this case?
It's mainly the transition from the synchronous to the asynchronous method that I am mostly worried about. Is this the way I should go about it, or are there better options?
Cheers
Hi @sturdy olive , if your goal is to use CPU multi-threading more effectively, I would suggest to take a look at Unity's Burst Compile and Job System, which are features that are meant to do that.
I mean, it seems easier to use something that Unity has already been using on some of their packages than trying to create your own multi-threading system from zero.
https://docs.unity3d.com/Packages/com.unity.burst@1.6/manual/index.html
The Burst Compiler also has a lot of debug systems to check/avoid deadlocks.
Oh I actually dont want to use it for that. The reason I want to use Tasks is to more easily keep track of different stages of Tweening / Animations during my gameplay, so running on the same thread is more than fine in my case
look into UniTask
mimics async but it injects its async objects into the unity playerloop, so the methods are async, but still running on the main thread
can anyone teach me how to make my game multiplayer
because I have no clue what I'm doing
Ooo sounds interesting. I'll have a look
No offence but this probably isnโt the best channel in that case!
ok
Hiii !
I created a phone application but my school want a build in PC,
So i need to create a fullscreen in portrait on PC.
Do you have any idea of how to do it ?
Never made one myself but I have seen some people say this video have good insights and pointers to the best way of doing it https://www.youtube.com/watch?v=8_5a3B5xQHk
Unity Multiplayer Game Development #1 - New Networking Solution. Hello guys, this is my first update video showing the progress on my current Unity project. Iโm currently working on developing a multiplayer game. I hope to use this series to share my experiences and the progression of developing this game.
The current plan for this game is unkn...
Does anyone know if there is any canonical or most referenced text/book/white papers for multiplayer games? It's nice to look up a tutorial or a blog or a YouTube video but, in my experience, they are trivial 95% of the time. Creating content is hard, making programming content is even harder. I get it.
I also want to read wisdom from the ancients. Has anyone written a serious book on multiplayer?
you want a digital or a physical book?
So this one is about how Networking work in general in games : https://web.eecs.umich.edu/~sugih/courses/eecs489/lectures/34-MultiplayerGaming.pdf
and here is a huge pdf showing every part of most networking systems : https://github.blairmacintyre.me/site-archive/cs4455f13/files/2013/08/Networking_Multiplayer.pdf
No preference!
Checking these out now. I would love more resources if you or others have them to share
it will be a long reading but it's worth it
i think with them you will have everything you need, after it's just a game of experiencing , try making little multplayer game like chess , agar.io with real networking and all of those little multiplayer game and then you will be able to start massive projects
but i guess you could find documents with even more informations
but it also depends on the networking framework your going to use
I agree. I have also been surprised what multiplayer concerns are. It's less about packet transfer. It's more about client side predictions
yeah
Yea? Really? I'm sure the concepts are universal but implementation detail might differ depending on framework.
I'm between rolling my own and using mirror.
yeah that's what i meant mb , but very good choice! Mirror is very similar to Unity old networking and it's very fun to learn!
if you really want dedicated servers you could use Photon , AWS or Playfab
I haven't looked in a while but iirc photon controls the server side and your game just calls out to that servers API. It's cool and useful. For me, I have a huge amount of AWS and Linux knowledge. For me, I want to write and control the server side as well.
but Mirror also supports Dedicated Servers so you'll be able to do that!
Enjoy coding networking !
Does anyone know a method I could use to make it easy as possible to do something like have a lambda expression that can be called every time a function is called.
Say something like:
eventTrigger.AddListener("EventType", "EventName", (e) => {
//do whatever necessary here
}
//Override trigger, cause anything under EventType to perform prescribed lambda
eventTrigger.Trigger("EventType");
Sounds like you want an event bus
is this what you are talking about? or is it a pattern like singleton?
Do you happen to know where to get good dedicated servers? Maybe even one that has free dedicated servers as long as youโre only using a couple of people (for testing)
Event bus is a pattern yeah. I implemented one here, though it uses actual types instead of strings to differentiate between events:
https://github.com/PeturDarri/GenericEventBus
Playfab dedicated servers or Amazon gaming services
Can I use NativeArray in normal code? not in a Job.
It runs much slowlier
Reading the NativeArray becomes slowly
I'm running the code in editor, not sure if it do safety checks?
Sure
Slower than a normal array you mean?
so i'm working with procedural meshes and debugging this is a real pain
when there's a problem with the mesh data, all errors only point to the line where that data gets finally applied to the mesh filter
i tried to report activity in my vert and tri arrays and look for mismatches but i wasn't able to find any mistakes that way
is there an easier way to debug this?
Looping back-- this is a decent primer. I read the slide decks. Made me sad to see link rot but I was able to read most of the references.
I've started digging into more of the articles valve put out for their source engine, but they have some explanations that help things make more sense.
Link: https://developer.valvesoftware.com/wiki/Source_Multiplayer_Networking (make sure to click on the 'see also' links!)
It depends on your level of expertise.
If you want something that isn't (exactly) your computer, I recommend looking into containers (e.g. docker). It forces you to figure out how to run your server in a containerized context, which is 99% of the way there.
If you want another computer, get another computer to load your game server onto.
If you want your game available to the internet, you can upload your game onto the aforementioned container or computer. Here's a guide to get you started if you want to pursue: https://dev.to/lloyds-digital/how-you-can-host-websites-from-home-4pke
Okay, that brings us to some cloud solutions.
I recommend digital ocean for something simple and relatively cheap. It's just a virtual machine, you get a shell, go ahead and set up whatever you need (most likely Apache or nginx that points to your game server). Just like you would do in a docker container!
And then there's the 'world scale' (cringe) cloud providers. AWS, G cloud, Azure, and IBM cloud. Very challenging to set up but gives you a ton of options and optimizations. It will take an expert level knowledge to take full advantage. It's also super expensive.
And then the ultimate in terms of complexity... Kubernetes. For your multiplayer game. And whatever else you would need. Super duper hard.
Hope this is helpful!
Yes, NativeArray read write is 10x slowlier than normal arrray
when outside a Job
I've given up using NativeArray, I'm using unsafe ptr now
You can but there's no good reason to
why
What are you hoping to gain from it? The benefit of native array is that it can be accessed directly from job system code without marshalling data back and forth between managed and unmanaged memory
Outside a job you have to pay the marshalling cost every time you access it
What is the coding best practice for handling setting gameobject.isActive(bool)? In my code here i set it every update but I am wondering how expensive that is vs making an if (gameobject.activeSelf){gameobject.isActive(bool)}. ```
private void HandleGameState()
{
switch (Data.state)
{
case GameState.title:
title.SetActive(true);
HUD.SetActive(false);
break;
case GameState.ingame:
title.SetActive(false);
HUD.SetActive(true);
break;
}
}```
I think best practice is just to set it directly. By checking its value, you're not only adding branching but also the overhead of a property get accessor
Thank you very much.
Is there a reason you need to call this every Update anyway? Wouldn't it be better to simply run this code whenever Data.state changes?
You are absolutely right. I ended up doing exactly that.
Today I'd like to design and implement a content cache, fair bit of blue sky problem, but I do have a data interface with an JSON implementation that I could potentially repurpose. All of the content comes from the server, and (at this point) is pretty small - no images/video/sound, only string content. I already have the data objects defined, and the server appropriately strips out what is only needed on the server - the client still receives a fully-formed object (networking serialization is already handled).
I'd like this cache in place for obvious reasons - the server shouldn't need to send all this "constant" string content repeatedly.
I was thinking that I'd leave the content in plaintext JSON (plaintext might be easier to debug any issues with, and there's no real security/gameplay/cheating that can happen if the client modifies text in the JSON).
Before I roll my own, is there any libraries y'all might be aware of that might help? Or anything built into Unity? I don't necessarily want to have to fiddle with differences betwen IOS/Windows/Android with respect to local file storage access. Best workflow would be something that I can (simply) de/serialize plain class files to.
@misty glade for socket ?
hmm?
I already have the networking taken care of, just looking for something to cache data on the client side (in unity)
I don't need to encrypt it either ๐
just write in file ๐
That's pretty much what I thought. ๐
normal ahah x) logic thing
but json too mutch for cheat you said so make your binary structure ๐
I'm having a little bit of a tough time parsing your english. ๐ Cheating is not an issue for this data - it's already stripped out on the server before it hits the client.
oh ok
I don't know about iOS, but Application.persistentDataPath is the common path you'd write cache. I don't know of anything built-in that wraps around that.
i learn english so np np sometimes i don't understand every thing i tried ahah sorry
K - any limitations on that? I don't expect this data to be that big, but ... I'm not really pruning it over time so.. depending on the longevity of the game, it might be a little bit large
actually, no, I take that back, I can't foresee it even being more than 10-20MB, ever
here's the raw data for a very light "settings" container: https://pastebin.com/TtfSx9Gb
Just my estimation - this is just for game content
That data set is the raw data from the server, but a player will never get all of that, only a subset depending on what they're doing in the game, but obviously we don't want to send the same data over and over and over
my chunk do 482KB ๐ข need to improve it
legit
I have a question, I have a matrix. I have to check if an object doesn't already exist, but if I do that, it makes the number A power the number B and I can't afford to do that. it's too expensive it's possible to pass O^N2 to ON? With this kind of logic or it's impossible, which I know it is...
if my explain is too bad said i will change it
by draw ahah
Hard to understand your question. If you're doing your own data structure and you aren't extremely talented / experienced, you should just use the Microsoft collections and LINQ extension methods for operations, probably.
LINQ is too expensive
LINQ is not inherently expensive.. but depending on your needs, you might be right.
It depends on a lot of things - what does your matrix contain, is there a key, is it dense/sparse, can you flatten it, can you order it, how often do you need get/remove operations, etc
Maybe show us your drawing so we have a better idea of what you're trying to accomplish?
You mean you have a 2D array and you want to check for an object in that array? You can't avoid checking every element to do that.
Well.... you could but it would require some brainy stuff ๐
Flatten the matrix, make sure each element can generate a unique hashcode, put it into a hashset (once? whenever you edit it?) and then Get() on the hashset, which is O(1)
these variable names are terrible ๐
__r? it_b? b?
i dont init this here but look
i have my memories array of chunk so 1D
you have a bunch of modulus operations inside this for loop - I can't really understand what the loop does yet, but those operations are going to be extremely slow.. I don't know if there's an easier/different way for you to do them
linear memory it's better to iterate no
what's __r?
radius of viewers
Obviously
K.. I'm sorry.. I've spent a good minute staring at your code and comments and.. I can't really understand it for a variety of reasons.. I'm not sure what it's doing, your variable names are really obscure and only you can understand them.. and I don't really even understand the question. ๐ฆ
so i have my memories and i want to know if the chunk are already init or no... but if i do that i did O^memories_len
But I'd start with refactoring this code and at least making it a bit more readable.. your variable names don't need to be long but they should at least communicate your intent.. r, b, i, g, __r are all mystery black boxes that require a lot of effort from the reader to ascertain what they mean and do
hello
maybe im in the wrong channel, but any idea on how to add a azure artifact registry to unity? i checked a lot of forums but couldn't connect it, i would appreciate a little help. thanks. I'm about to work this out with github, but i wanted to use azure.
No idea, sorry! I've always just used github (and personally used VS because it plays really nice with github). I do use VS to deploy my server app, but again, via github and not azure artifacts. If you do find a good blog or info page on it, please share though, I'd be interested in learning more about it.
thanks for your hint, i think i'll go with github for now, i tried this but no result, i accomplished auth but unity wont display the registry panel in the package manager.
https://forum.unity.com/threads/npm-registry-authentication.836308/
Hello Package Manager users!
Starting from Unity 2019.3.4f1, you'll be able to configure NPM authentication for your scoped registries. This is a...
How I read this JSON from Unity Web Request?
I tried this, but in Debug.Log return null
Create a class that matches that structure and deserialize into it
I think it's case sensitive. User != user
How would I go about making a housing system (such as Terraria's) in the sense of the NPC requirements?
Such as... if a user has to have at least 100 "coins".. or if they have to play the game for at least an hour.
I wouldn't think it'd be checking every frame via an if statement in the Update() function.. but I can't think of any other ways..
Really, it's working now, thanks!
check periodically (e.g. in a coroutine) every n seconds, or check when certain events happen (e.g. check when gaining coins for the 100 coins one)
ok... i'd probably check every couple of minutes via the coroutine, thanks for that!
and yes... when a player picks up a coin, i can check their count then... that's smart. thanks!
Is there an annotation I could add so that my objects don't have to exactly match the JSON payload?
If not, no biggie. It's no problem; I can map the object to another object that has my preferences.
Just trying to avoid leaky abstraction (if I'm using that term right); I'd dislike it if I could easily tell "oh, this was hydrated from a REST endpoint."
Not with Unity's JsonUtility afaik. If you used Newtonsoft JSON then there is yes
Word. Yea I don't see anything in the scripting API https://docs.unity3d.com/ScriptReference/JsonUtility.FromJson.html
Oh well! No biggie
There's this but that only lets you read the data with that name not also write it afaik https://docs.unity3d.com/ScriptReference/Serialization.FormerlySerializedAsAttribute.html
I wonder how hard it would be to write an annotation instead of doing the json -> json object -> domain object conversion. Hmm ๐ค
anyone know a decent gif decoder? just trying to turn gifs into frames and play on an array automatically
Not sure if this is an advanced topic but im trying to find a way to change override clips with a editor script. I'm looking to edit the content of assets basically.
Is there a way to do this in editor or do I need to edit the content of the file and the .meta externally?
The editor is just a runtime environment for .net, you can do anything you like
Hi guys, I'm trying to create a simple attribute system and I want to show the value of the each attribute via a progress bar. Currently, I've got an abstract class called BaseAttribute which has Value and MaxValue. I've then created a HungerAttribute which derives from BaseAttribute and I'm wanting to show the Value's increase or decrease via a progress bar. The plan is to have a generic progress bar (which consists of a background and foreground and the typical fill amount etc) and for every new attribute I add, I want to associate it to the generic progress bar. The attributes I will create are added to the player script and I want to somehow read the values of each attribute attached to the player via the each of the progress bars. what is a good, and structured way to achieve this?
one solution I was thinking of doing was to create an abstract class called AttributeBar and I create concrete classes which derive from the AttributeBar class to represent the UI part of for each of my attributes.
Good candidate for the Observer pattern (events)
your view (progress bar) should know nothing about your attributes and vice versa
if you donโt like events you can have a third 'presenter' class that reads the attributes and writes any changes to the progress bar in every update
a solution based on inheritance is a dead end
I just did a quick diagram to show the structure. Just wondering how to use observer pattern in this instance? how will the progress bar class know which attribute needs to update? would I have to have an event for every possible attribute inside the progress bar class?
In almost all my projects I use an event manager for notifying observers of a specific event (enum based) firing off. I use dynamics so that it can pass any type of data to the observer in the function handling the event when it fires off
Thanks guys, I'm gonna try and have a read through the observer pattern and see how I go, in failing which, I think I've got an alternative solution.
make sure you do not overthink it, its a very common problem with a very common solution
Yes, you're right, it's very simple but I really want to use good practise and use the right pattern where necessary without having bad code or anything. Super easy to do something the wrong way, this can be done in a lot of wrong ways too..
Roughly this
but with string enums to identify the specific event
Thanks for that!, love diagrams as it helps with the thinking
The code I use is almost identical to the event manager in this
The event manager approach keeps things decoupled in a way
How can I compres stack list in game to reduce size of the rewindable actions in RAM ?
is it bad if i have coroutine checking every 10-20 minutes?
Like is there a better way to do it if i'm having to check not as often, or is coroutines the best option
Edit - What about InvokeRepeating()?
gonna ask because you never know ...
is anyone understand math here ? I'm trying to make a 8bit sector raycaster with rectangle sector, can't do MUL, DIV, SQR and only integer ADD, SUB and bitshift.
I'm trying to get an early out test, that guess which face will be hit and check side solidity using a bitmask, if test pass then I just directly draw the wall span, ELSE I compute expensive ray intersection with raycasting, then use the delta to march through sectors.
...
problem is that using symmetry I reduce the problem to finding if a point is below or above a slope, so it seems like I can use Bresenham line algorithm can help?
Check out Acegikmo's server. Can't share the invite here but head to the site and look for the Discord link. There's a math channel there, they know their stuff https://acegikmo.com/
ik thanks
How to make UI right?
I cant find tutorials on YT. I want a little more than just static dialog box.
How to do it with diffrent title, text, button captions and onClick actions.
make one abstract class and then inherit it in another scripts?
is there a Unity Gaming Service discord?
or anyone who knows how to use the new Analytics?
would anyone know how to get the compiler to understand that I am properly verifying that the values self and other are assigned without adding a lot more lines?
bool selfIs = Current is T self;
bool otherIs = compare is T other;
if(!selfIs && !otherIs) return null;
V selfValue = selfIs ? getValue(self) : default(V);
V otherValue = otherIs ? getValue(other) : default(V);
for both self and other, the compiler is saying they are not assigned when I throw them in my local getValue Func
What's the actual error message and which line is it on?
Yeah I've done this in the past where I've made a ScriptableObject named DialogBoxParams or something. I give it fields like title, prompt, cancelButtonText, confirmButtonText, altButtonText. Pass one of these assets to a dialog box class to populate the UI dynamically, along with a set of actions that you can cache and then invoke dependent on button presses.
Maybe an icon field as well if you're really tripping
I'm not sure how to google this and found a solution with reflection that dosen't really work for my use case. Is there a native way to parse a string with variables in Unity? So something like ("Hello {0}!", "World") or maybe a list.
are you talking about formatting a string? https://docs.microsoft.com/en-us/dotnet/api/system.string.format?view=net-6.0
Converts the value of objects to strings based on the formats specified and inserts them into another string. If you are new to the String.Format method, see the Get started with the String.Format method section for a quick overview. See the Remarks section for general documentation for the String.Format method.
That's it, thanks!
In the Profiler, under Memory, the count for "GameObjects in Scene", how is this value being obtained and can I get it myself in script?
And is there a way I can get more information on what these objects might be and where they are?
Hey all. Mess of a question since I am a bit lost on some high level concepts but I did my best. I am currently writing a fog of war implementation (which is generally working, this is a question about design paradigms not functionality). Initially, I thought I would use a singleton class for the grid generation and value storage that tracks the movement / vision of the units. However, I read dependency injection is an alernative to singletons. That said, in terms of solving for sharing static state of objects I'm beginning to think that maybe isn't the case and I took the DI / singleton cosntrasting example out of context. I was initially seeing issues with the shared resource not getting updated properly. I was able to get that to work by just marking the int array inside the class static. I think because it's primitive this didn't mess up my DI implementation and I am able to send it through an interface etc successfully. But I have this feeling it's a bad code smell. And I'm getting some funky behavior that's likely being caused by multiple instances of the class running still since I have some other non primitives that are not static.
So all of that is to say, how do you solve for access of multiple monobehaviors to a shared resource / data structure? Everyone says singletons are bad, but I can't find many examples (other than maybe a database or file object) that are a good alternative. Apart from a static class but that has it's own problems. Also, I plan on updating the above graph with coroutines calculations every n interval at some point, so I want it to be thread safe in that context. Perhaps coroutines will magically handle thread safety from a bit of reading I did, but I am not betting on it.
I have a coroutine that is persisting across scene loads, despite there being StopAllCoroutines in OnDestroy. This means that, in the next scene, when I call to stop any running coroutines, it throws an error that it is trying to access an object that has been destroyed.
The fact that you're running it in OnDestroy means the coroutine is definitely not running on that script
coroutines die when their associated MonoBehaviour dies
make sure you're starting your coroutines from the correct MonoBehaviour
I am. They are on a singleton Monobehaviour that acts as a manager.
how can you call it to stop running coroutines if you destroy it
If your singleton is being destroyed then it can't possibly run coroutines across scene loads
Actually that might be part of the problem. If it's DDOL, it's not going to be destroyed, and StopAllCoroutines will not run either (if it's in OnDestroy). Which I think vertx already realized before me?
All I'm saying is that if apparently it is being run then "in the next scene, when I call to stop any running coroutines" why is that a thing, and why wouldn't you expect an NRE from it
Maybe you want to have your GameManager listen to this event and call StopAllCoroutines when it happens? https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager-sceneUnloaded.html
Or just do it when your other code changes the scene
Either way, you are very right, if the object is being destroyed it cannot run coroutines, that is fundamental
For clarity: I am calling OnDestroy() { StopAllCoroutines(); }.
You do not need to do that ever
as a destroyed object will have all of its coroutines stopped
Either it's being destroyed and all coroutines will stop anyway, or it's not being destroyed and therefore that code won't run.
Can't you just change your "scene changing" code to effectively this:
SceneManager.LoadScene("blah");
GameManager.Instance.StopAllCoroutines();```?
That's...really odd to hear, given that in my experience this use case of StopAllCoroutines is incredibly common
Including, say, part of both the Oculus and Vive APIs
Well then they're also wrong
A coroutine also stops if youโve set SetActive to false to disable the GameObject
the coroutine is attached to. Calling Destroy(example) (where example is a MonoBehaviour instance) immediately triggers OnDisable and Unity processes the coroutine, effectively stopping it.
Aren't all objects destroyed at the end of the last frame? Wouldn't that also destroy the Coroutine?
Huh? Coroutines are not unity Objects
The coroutines are stopped by the gameobjects/components being destroyed, as mentioned in that quote from the docs
That's what I thought, as well, which is why I am very confused that this coroutine is persisting after the GameObject which handles the coroutine has been destroyed. It shouldn't do that. So something is amiss, and I'll keep investigating.
The most likely culprit, as I mentioned above, is that you started it on a different MonoBehaviour that is not being destroyed.
The prime place to look is wherever you run StartCoroutine() and pay attention to the receiver of that method call
OK, so this gets slightly more interesting. The coroutine is being stored on a script which is how it's able to persist. However, the reason it's not being stopped is because when the scene loads, it has a check based on the LoadSceneMode. The problem is, despite LoadSceneMode being only Single or Additive, SceneManager is calling OnSceneLoaded and passing 4 as the LoadSceneMode. I don't know why it does this, but my script is checking for Single mode, so it assumes the load was additive and doesn't clear the coroutine
I haven't been able to discern why SceneManager is passing 4 as the LoadSceneMode but I'm searching. If anyone knows, I'd appreciate
Yep, it is definitely passing 4 to the OnSceneLoaded event. I bet it has to do with running in Editor.
Just created a sample project and confirmed that you get a 4 when you use Application.LoadLevel instead of SceneManager.LoadScene.
Or if you hit play in the editor and it loads
Interesting. Similarly, I did a build of my game and had no issues or errors, because I assume SceneManager passed the right value in build.
Do you know if the values that get passed in this way are documented somewhere? It'd be helpful if I can document it in my code as I work around this.
Don't think so
No worries. Thank you again!
how to make one of the parent objects(FPSHand) move so that the AimingPoint is in the middle of the screen?(
I would definitely use a singleton. People who say singleton's are "bad" are being reductive. If it wasn't a useful pattern in certain scenarios, it wouldn't exist. This absolutely seems like a valid use case. Just make sure it's incredibly encapsulated and derive it from the best implementation of the singleton pattern I've found, courtesy of a benevolent SE stranger: https://gamedev.stackexchange.com/questions/116009/in-unity-how-do-i-correctly-implement-the-singleton-pattern/151547#151547
Also if you do end up using coroutines for this, make sure to cache your yield instructions https://github.com/galenmolk/Unity-Yield-Registry
Id first place the gun in the correct position
Then id have the gun and hand as a child of camera
That way it follows the camera when you look around
And to place id use LookAt
First argument being the camera position + camera front vector + camera up vector multiplied by the distance up/down the weapon needs to go go for the sight to lign up to the camera
Second argument id put same position as first argument + little further ahead
As a beginner into making AI for my games, would it be better to learn how to make my own AI from scratch or use something like A*?
A* is just navigation. I don't think reinventing that part is terribly beneficial compared to focusing on the high level parts, which generally don't have ready made packages you can drop in.
I see, and I saw that A* makes the game object fly, does it have a built in option to disable fly and enable jump? Or will I need to make it myself?
Talking about the A* project?
Yes
You should know that A* itself is an algorithm that handles the path finding part https://qiao.github.io/PathFinding.js/visual/
Yes I know, but in the tutorial I watched A* calculates the path and then moves to the target, but the game object the scripts are on basically flies. Is there a way to make it jump instead using A* or do I need to code it myself?
A* is not a movement system. You can implement your own movement to follow the A* path with or without the A* Project.
I don't remember what controllers it ships with.
Can you show a video of the movement?
I've watched Brackey's tutorial
https://www.youtube.com/watch?v=jvtFUfJ6CP8&list=WL&index=9&ab_channel=Brackeys
Let's learn how to make 2D pathfinding using A* with and without code!
โ Check out Skillshare! http://skl.sh/brackeys17
โ A* Pathfinding Project: https://arongranberg.com/astar/
ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท
โฅ Subscribe: http://bit.ly/1kMekJV
๐ Check out Line of Code! https://lineofcode...
Oh maybe it's because he disabled gravity
Is this crashing my game?:
##utp:{"type":"MemoryLeaks","version":2,"phase":"Immediate","time":1644327383120,"processId":1724,"allocatedMemory":203031,"memoryLabels":[{"Permanent":40},{"NewDelete":216},{"Thread":72},{"Manager":1360},{"GfxDevice":196744},{"Serialization":456},{"WebCam":32},{"String":195},{"HashMap":1536},{"PoolAlloc":56},{"GI":296},{"VR":1560},{"NativeArray":372},{"Subsystems":96}]}
Do not cross-post
Hi, I made a resolution changing option and it's working fine but there is one problem, there is a resolution for every refresh rate my monitor has.
I was told to filter out refresh rates or something like that in this server but I am really not sure how to do that.
Can someone please help me?
Thanks so much for both of those replies. Singleton definitely seemed to work well, so glad to hear that was complete insanity :). I get the impression that singletons are less useful in the business world compared to game dev. That might be fallacious, but game devs seem much more keen on them like due to use cases. Also, good to know on the coroutines. That sort of thing tip up front save a lot of headache!!
No problem! Yeah, they might be less popular outside game dev, I'm not sure. My supervisor used to work at EA and he's encouraged me to use more singletons in certain scenarios, so that's given me confidence in them. Probably one area where the pattern tends to be less useful and potentially dangerous is networked projects with multiple clients.
oh also that should read wasn't complete insanity. You probably figured that out though haha.
Yeah, I am trying to pretend that I am building a multiplayer game so the option is there but in practice it sounds like a nightmare lol
(if anything though it would be 2-4 people, nothing totally out of control. Still, if I have learned anything in programming 2 copies of a thing is about 10 times more than one in terms of fragility).
At that point you maybe pipe the vision texture to a file and pull it from a network cache maybe? Would be really interesting to know how starcraft 2 for example handles that sort of state management. But not important at the moment.
Hello. I have a character and Randomize button randomizes sprites. I want to save the result in json and after opening game I want to change sprites in coressponding spriterenderers using that stored data. can you help me? how this is done. how to store images with json. I want to save that json file on database and get info from there. Thanks
question
Your json should hold a string spritePath field that you can download with UnityWebRequest
public IEnumerator DownloadSprite(string spritePath, Action<Sprite> callback)
{
if (string.IsNullOrWhiteSpace(spritePath))
yield break;
using UnityWebRequest www = UnityWebRequestTexture.GetTexture(spritePath);
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.LogError(www.error);
yield break;
}
Texture2D texture = ((DownloadHandlerTexture)www.downloadHandler).texture;
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0, 0), 100F, 0, SpriteMeshType.FullRect);
callback(sprite);
}
Thank you! so I will upload my sprites on drive and download with this code
there is 5 spriterenderers for each body parts. How can I implement elegantly to keep which sprite coresponds to which spriterenderer.
I have to download each sprite individually? and assign to corresponding spriterenderer?
And another question. Can I use this code to get 3D objects, for example .fbx file from database?
Not this exact code, this is specific to sprites. But you may be able to download the raw data of a .fbx file with a different method in UnityWebRequest and convert it to a Unity object. I'd check out the docs for that https://docs.unity3d.com/ScriptReference/Networking.DownloadHandler.html
https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.html
Yeah I'd create a serializable UnityEvent<Sprite> class for this somewhere:
[Serializable]
public class SpriteEvent : UnityEvent<Sprite> { }
Then create an event for each body part:
public SpriteEvent TorsoSpriteReceived = new SpriteEvent();
public SpriteEvent LegSpriteReceived = new SpriteEvent();
// etc...
Then invoke those events in your DownloadSprite callback:
StartCoroutine(DownloadSprite("www.database.com/my-sprite.png", sprite =>
{
TorsoSpriteReceived.Invoke(sprite);
}));
Then all you have to do since SpriteEvent is serialized is in inspector hook up a class on your SpriteRenderer objects so they're listening for the event that you want them to care about.
You could also hook them up via code if you make the class that's firing the events static or a singleton or something
Thahk you for your answers!
What's this?
Docs are really weird about it.
New project, how do I get the best experience?
Because these are like Porridge and Potatoes.
Generally use .NET Standard 2.1 unless you need some of the more advanced/offbeat .NET APIs.
What's the benefit?
There's more functions that you can call in .NET Framework... but, if you don't call those functions, and most of them are kinda weird, then it's a bit heavier and possibly a bit worse compatibility going forward.
It's for example when you need to include your own class libraries or DLLs that aren't available in the Package Manager, also. So you know what versions are compatible with the project, and what you should be compiling to if you're developing a class library.
Yeah.