#archived-code-advanced
1 messages · Page 175 of 1
Got it
Furthermore, is there a channel here best for profiling? My Hololens app is running horrendously, and I'm not quite sure what to take from the profiling.
is this in editor or standalone?
Standalone, remote profiler
try scrolling down in the profiler screen a tad
it's telling you what is slow
there's another view that shows you the amount of time
GPU is 33ms, really bad
CPU is 90ms, really bad
This is all I can see
what is the application?
CPU is the problem, but it looks like it gets clogged by Hololens scripts?
at 33ms GPU is also a problem
that's less than 30fps on an HMD
people will barf
maybe try running a demo project
Audio sequencer in Unity, however it instantly halts on startup.
and see if something is wrong with your hardware
Building a demo scene now to test
i remember now 🙂
is this hololens or hololens 2
How can I deduce if it is one of my scripts from this profiling?
2
or hololens 2022 datacenter server, dynamics edition
switch the view
from flame view to the other one
that shows times
Kk will do
Building the demo project to the hololens now to compare
@undone coral Ok so this is the profiling from the demo app. I assumes this means there's something wrong in the build settings?
Kk, will look into that
Nope just turns out I'm an absolute moron
I did a fresh build pack a while back and default settings are ARM, not ARM64
5 hours spent on tracking down that bug
hi unity friends, is it possible for player to edit define symbol on build?
Hello people!
private IEnumerable<Claim> SetClaims(IEntity xUser, List<OperationClaim> operationClaims)
{
var claims = new List<Claim>();
if (xUser is AdminUser)
{
claims.AddNameIdentifier(xUser.RecordId.ToString());
claims.AddEmail(xUser.Email);
claims.AddName($"{xUser.FirstName} {xUser.LastName}");
claims.AddRoles(operationClaims.Select(c => c.Name).ToArray());
}
return claims;
}```
How can I cast xUser to 'AdminUser'
I got confused!
What is AdminUser?
A type that implements IEntity probably, you can extend the pattern matching of your if statement to do the cast for you
if (xUser is AdminUser asAdmin) {
// 'asAdmin': variable 'xUser' casted for you
}
Yes I did it with this way. thank you
got any source on what you refering to? any link of a tutorial in order for me to implement it the correct way?
So you telling me I wont need a local save for that kind of thing
I am trying to debug an unity package by loading it from disk instead of the registry
but as soon as I make that change, my other assemblies can't resolve it anymore
I guess there is special handling that integrates unity packages into the default list of engine assemblies?
im struggling with a concept ive been trying to code for a while, if someone could help me figure out how to go about what im trying i would appreciate the help
In this game im trying to program, a character can play 3 cards onto a field, with 1 being a primary action and 2 being secondary. Im trying to make these actions configurable scriptableobjects but im struggling to figure out how to go about making them. (Here is a sketch of how it sorta works, with blue numbers to show the order of the types of cards that should activate)
the numbers in front of the letters reperesent turn order, the letters just represent different characters
Skills are individual, and go last. Modifiers should go first to modify the primary action, in this case a weapon, and THEN the primary action occurs
Sounds interesting, what exactly are you struggling with? Basically, i think you'd have a List of these Actions and evaluate from Last to First, and the Current Evaluation affects the Evaluation of the next one?
just trying to figure out how to make the system work, i want to see how other people would try going about it
im struggling with setting up ScriptableObjects for the cards
since many cards would have different abilities/modifiers and all that
also cards affect lanes/targets dependant on which lane theyre in and i feel like ive gotten myself into a complicated mess :p
Mhmm I see, you could, for example, make Abilities and Modifiers as standalone Scriptable Objects as well
For affected Lanes and Targets, you >could< use Enums
enum AffectedLaneType { Left, Right, Center }
enum AffectedTargetType { PrimaryAction, SecondaryAction, // some more concrete ones }
Just as an example.
I've got a Gwent-Like (The Witcher 3) Game Vision from your explanation
ill see what i can do
im also not sure how to handle the targeting, since this is how i have the lanes set up but it could be subject to change if need be
and this is how ive got my current Card class set up
You could for example substitute the abstract onPlay() and have another class
PSEUDO
class CardBehaviour : ScriptableObject void Execute(Card card)
and your Card would have a list of Behaviours assignable in the Inspector
You'd still need to create concrete Implementations of CardBehaviour, but it's eleminating the need of subclassing Card
Targeting, IMO, should target a Lane in the first step, not it's Contents
Validating that the contents are what you expect for your Cards Action would be following this
Eventually, each Lane could have a visual representation with a Collider, hence allowing targeting via, for example, Raycast
i actually did a little work, let me show you what i came up with for targeting
its basic and a little messy, but it works for now
Sure! But Images and stuff may take a while to load, my wifi is almost non-existent
It's fine! It did load already, since it's very small
i see
From that snippet, what is not obvious to me is, do the Players manually select their Target or is it abstracted away into the Cards Actions?
the target is selected dependant on which lane the card is played in
since characters are also in said lanes
I want to take a crack at making my own 2D UI (Canvas-based) visual graphs. Am I better off drawing the texture (pixel by pixel) each frame using Compute Shader and Burst Jobs? Or is there a more efficient approach using other UI elements besides RawImage?
Where can I find more in depth docs on UniRx?
so this is a little peculiar, but I want something like the shader graph search window
but with the UnityEngine namespace
I have a graph view where I can add nodes
so first I would search for a GameObject node
and then I could search for GameObject.FindObjectWithTag for example
and connect them
is there any way I can get like
a search window with that
I'm not sure how to explain it better-
Is there a good package for rendering html in Unity? I don’t need a JS VM or anything, just text and images
Either that or a Markdown renderer that also supports images
can anyone direct me to the best thread to ask some ui rendering issues in more detail than the following.... I am having an issue on windows threads where, it seems like multithreaded rendering + framerate drops can cause the ui to draw from the wrong atlas for a frame or two causing flickering
what's the right channel for that convo?
Sry, late reply, after all I think you should follow your approach, and only rethink it when you're hitting a border, seems like you're on a good route
I'd say #📲┃ui-ux, inside here or #💻┃unity-talk
I'd also suggest to precisely find the cause of that issue, but just if that's possible somehow
A quick Google search brought me to that
https://stackoverflow.com/questions/46827297/how-to-load-an-html-webpage-inside-unity3d
Maybe that's helpful somehow
hmm so i don't think unitys default occlusion culling works with runtime terrain generation since theres nothing to bake
is there any way i could implement occlusion culling?
there are lots of ways for custom OC
word, thats good to hear
something simple like OnBecameInvisible didn't work, im guessing due to the staggered z levels of the tilemaps
well you can only see one plane here
but it extends back
maybe thats not the issue idk
(screenshot taken before i wrote the script)
regarding the flickering... here's what we are seeing on many Windows machines. We did some digging and it looks like a lot of the issue is occasionally the game is drawing things from the wrong atlas, particularly in the UI canvas elements, for a frame
doesn't happen for any of our mac users.. so there was a hunch it might be to do with multithreaded rendering on dxd11
(metal doesn't have issues)
QualitySettings.maxQueuedFrames = 1; did not work sadly to resolve it.
-force-gfx-direct does resolve the issue but that would require players to add CLI args
we tried doing opengl-core, dxd12 builds to no avail
here's a still of some of the sprites drawing from the wrong atlas for a frame
whereas... that section should look like this
so... it SEEMS like due to MT rendering... it's just the framerate dips and 2 threads are maybe changing the loaded ui atlas at the same time... and 1 thread just draws from the wrong atlas
i know i need to do a performance pass, but even still.. this will just happen on lower spec machines.
You should be able to turn off multithreaded rendering in Project Settings.
as far as i can tell... and this is agood Q for the group... unity determines whether to use MT rendering by a variety of factors
lemme screenshot project settings rq
afaik.. it's supposed to be in this section
what we'd done to test on various APIs for windows was just go in here and
just sort of swap out what's here
we were hoping like... well maybe OpenGL works better than DXD11
if there's some checkbox hiding somewhere, i'll buy someone a beer.
although, bribery may be against ToS so...
@green river What Unity version are you on?
currently 2019.4.15f1
i could be talked into upgrading haha
just kinda trying to go early access beta in a month or so
I just noticed Graphics Jobs is experimental in your screenshot, but it's not in newer versions. Have you tried having that option on?
the multithreading is a red herring
interesting...
i only arrived at that b/c that one commanline arg resolved the issue
really all i had to go on
If you're releasing this on Steam, you can configure your app to run with command line arguments
But not a great solution still
you should roll with that
that's a really good point tho.. i had no idea.. i knew you could have people add them by right clicking .. etc
write a shortcut with command line args
its' a nice last ditch fix
so i figured out that using chunk rendering and a custom sorting axis was the way to solve my occlusion culling problem
i thought you needed individual mode for it render correctly with stacked sprites but ye sort axis
400% increase in FPS, 100% increase in cpu ms response time lol on a 49x49x6 layer map
wow big win 😄
now i gotta figure out chunk loading for 49x49 chunks of map
so i can do 249x249 or w/e
these are the stats for 249x249x6 layers at max zoom out. not ideal but nooot terrible
the bug looks like a gpu & underlying unity engine issue
you can run the frame debugger / render doc and freeze the frame when it occurs
and it will tell you exactly what happened
it sounds like you're making a shortcut
there is no checkbox no
if someone wants to screenshare with me to find this checkbox...
or even a line of code
clearly that cli switch is doing something deep in unity town
there's no checkbox to disable multithreading
yes
you're on the start of a very long journey
There definitely has been, and you can see remnants of editor code for that option. I've maybe only seen it with Android selected as the build platform. Seems to be hidden on some platforms.
https://github.com/Unity-Technologies/UnityCsReference/blob/e740821767d2290238ea7954457333f06e952bad/Editor/Mono/Modules/DefaultPlayerSettingsEditorExtension.cs#L118
don't use scriptable objects for this. try programming every card as its own script that implements an abstract monobehaviour. use a function of the form abstract IEnumerator OnPlay(GameContext context) to implement a card. if you need to ask the player for something, do var requestPlayerAction = new RequestPlayerAction(); yield return requestPlayerAction.Request();
great. thanks for finding that
@green river go into your ProjectSettings/ProjectSettings.asset file
and set the field m_MTRendering: 0
and for good measure you can change mobileMTRendering: fields to 0
That's worth a try, but if they're hiding that property on certain platforms, I don't think it's unlikely they're also ignoring the property value altogether on those platforms.
intersting. lemme try that
Does anyone have any experience with Animation Rigging package? specifically about the Constrained Axis. The constrained axis options do not change any of my behaviour. any solution?
we changed the m_MTRendering: 0 but it doesn't do anything so... best fix is gonna be the steam shortcut solution for now.. this is a truly bizarre rendering bug.
so .. somehow disabling mtrendering in the player profile file is different from -force-gfx-direct
yeah like i said the multithreaded rendering is a red herring, -force-gfx-direct has other side effects that paper over the gpu & unity bug
you can use renderdoc to see what happens.
did you try switching to screen space UI?
UGUI might respond specifically to -force-gfx-direct's side effects
never heard of renderdoc so i'll look into it
"did you try switching to screen space UI?" also, nope i'll look into it
thanks for the suggestions
have you guys been able to connect renderdoc to standalone builds?
the docs say you should be able to attach it
without any further configuration
set up a rig. visit the samples for the big picture
ty
does UGUI use the sprite outline shape?
you can also try using one big atlas
then you've narrowed it down 100% to the way UGUI renders in batches
ive setup my rig, and understand how to use it, but the constraint axis have no effect on my rig. the docs say one thing, but it does not reflect in my usage. ill still take a look but ye.
Hello all, I'm working on a NFT based multiplayer racing game. I am using Photon Unity Networking(PUN) for multiplayer server. But I can only spawn prefabs into the game. My goal is to spawn their own nft in-game. I'm sorry if the answer to this question is too beginner level. I'm a hobby unity dev. It would be so nice if anyone could provide me a solution or any related resource material. Thank you.
you're at the beginning of a years long journey
didn't figure out chunkloading yet as i took a break for the day but that batch rendering is wildly more efficient damn
can't believe i had it set to individual loooooool
Wow thanks
has anyone written an A* pathfinding algo? any thoughts?
Many of these on youtube
yeah fair, i watched a few vids but was curious what the discord thought
Many have tried to reinvent the wheel of A* but not much of a difference from one to another tbh..
are there docs on when tasks get executed in unity? like, is it after updates, is it only on the main thread, can I spawn game objects in tasks in worker thread if they're not being executed on the main thread? does it queue the spawning then, or does it block? do Awake and Start get run immediately after it has spawned, how do I ensure they have run?
same with coroutines
there's no info on async
and there's no info on spawning objects either
within coroutines
The default task syncronization context is synchronized with the MainThread and it will invoke after WaitForFixedUpdate You can
not use any (well some but easier to assume nothing works) UnityEngine methods from another thread.
.. like, is it after updates, is it only on the main thread,.. depends, Task.Run will run in separate thread. Also, async doesn't mean it's multithreaded
Save the hassle, and use UniTask instead https://github.com/Cysharp/UniTask
You can comfortably switching between Unity's main-thread and threadpool very comfortably
to switch to threadpool with UniTask you just need to await UniTask.SwitchToThreadPool();
Just like async in general, you'd need to manage the cancelation tokens on your own, or by using MonoBehaviours built-in (I think there's one to handle this automatically)
Hey I wanted to learn more about vertices by testing out different shapes
- Load a prefab into memory (
LoadAssetAsyncor whatnot, via addressables). This step is not a problem. - Instantiate the prefab.
- Call all initialization hooks (Awake, OnEnable, Start).
- Prevent any Updates from being called.
- Initialize the objects externally (I need to control the order more accurately, plus I need to propagate so info from other systems).
- Enable Update's
So
But I don't udnerstand why this isn't becoming a Square?
The external initialization needs to happen after the internal one happens
The internal one being step 3
I'm very little experienced with vertices yet so I don't quite get why it isn't becoming a square
What you're seeing is known as backface culling
Unity uses clockwise culling order
So you want your triangles to go clockwise
well it's going from left top back to right
Did you generate the mesh manually?
so it's kinda clockwise
what do you mean by that?
it's in Update()
so I can see the changes in realtime
I have 4 vertices
you only have one triangle defined
yep
So you only have 1 triangle
no 3
.
I made it so it automatically adapts to the vertices
the first triangle should be the first 3 vertices
yes?
and the second triangle should the vertices 2, 4 and 3
hold on
(depends on how you arrange them)
I know but why in that order?
yes
if you do 1, 2, 3 it would go counterclockwise
If you specify a triangle as vertices in a clockwise order, then the triangle will be facing the screen
I.E the normal is "forward" of clockwise (if that makes any sense)
not 1, 3, 2?
?
but why is 1, 2, 3 clockwise?
but from the front it would get culled
it isnt
he never said that
"if you do 1, 2, 3 it would go counterclockwise"
.
ups
I misread that my fault
So any ideas on this? how do I ensure no Update's run?
Do Awake's run on disabled objects?
awake is called whenever the script is beeing loaded in
"loaded in" is vague
hold on a sec
- When the gameObject is beeing enabled
- When the script is being enabled
If it's disabled then no, it's not called
- When the scene is being loaded with a non-static object
yep
Instantiating a gameobject does not run its Awake immediately, right? It waits until the next frame
It's immediate if it's enabled
aah, ok, then disabling it after instantiating it should do what I want
Because you only have one triangle
You only put 3 indices into there
ohh wait a sec
so when the vectors.Count /3 * 3 is becoming 3, it means it hast only one triangle?
? It's immediate, if it's instantiated and it's enabled as a prefab, then Awake will instantly run before your code continues
Yes, that's fine
Yeah basically this is the order:
Instantiate()
-> Awake
-> your code continues
-> (next frame) Start is called if the object is enabled
Show the code where you set up indices/triangles
That still adds only 3 indices,not 6
"triangles" is a confusing name here
it should be "indices"
Here's me doing a quad from its bottom center
In my code I just manually write the arrays as it's easier in my head:
var vertices = new[]
mesh.triangles = tris;
{
new Vector3(-0.5f, -0.5f, 0),
new Vector3(0.5f, -0.5f, 0),
new Vector3(-0.5f, 0.5f, 0),
new Vector3(0.5f, 0.5f, 0)
};
mesh.vertices = vertices;
var tris = new[]
{
// lower left triangle
0, 2, 1,
// upper right triangle
2, 3, 1
};
mesh.triangles = tris;
but it can't be higher than the vertices number
yes
exactly
Also I'm confused on your Elemet2 of Vector array
It's got 3 axis worth of values, but your others only have 2
so if I want a full "cube" I want 8 vertices right?
but then I can only have 3 6 triangles?
you'll probably want do double up some vertices
because otherwise the normals will be wrong
and you will need 6(faces) * 2(triangles) * 3(indices per triangle) indices
what are indices anyway?
it's just an int array saying which vertex makes a triangle
it's always a multiple of 3 as all triangles need 3 vertices
Learn OpenGL . com provides good and clear modern 3.3+ OpenGL tutorials with clear examples. A great resource to learn modern OpenGL aimed at beginners.
then it's just "vertex 0, 3, 5" makes a triangle, then repeat for all triangles
I get that
why is it in this oder?
and not 0.0f etc. in the second line?
That's completely arbitary and depends on where you want your quad to originate from
Mine for instance has a "origin" in the middle as it's easier for me to use, for my use case.
only 3 vertices can be connected, not 4 or, 5?
the gpu only renders triangles
GPU can only ever draw a triangle
you're right
Yes it works!
thanks for the help!
ok I got one more question though
why is the square rendered there?
oh right
got it
how do I make the collider adapt to the mesh?
I already have a mesh collider
why is it drawn like this?
I can see the other triangles if I go to the other side
flipped normals?
that means they are facing each other's opposite direction
what do you mean by that?
this is only for all except the top and bottom
?
This is the same issue as you had before, only on another axis.
You're giving the indices in wrong order, or not at all
Why do you have 6 vertices for one side?
You only need 4
I think you've confused some terminology somewhere or you're missing something
you only need 4 vertices (corners) for a side
then you need an array (indices) that says which index in the vertex array makes a triangle
the indice array needs to be 6 points, because one side is 2 triangles
So if you have 4 vertices where 0 = top left, 1 = top right, 2 = bottom right, 3 = bottom left
var vertices = new []
{
[0] = new Vector3(0, 0, 0),
[1] = new Vector3(1, 0, 0),
[2] = new Vector3(1, -1, 0),
[3] = new Vector3(0, -1, 0),
}```
then to make 2 triangles you make a indices array and construct it as follows:
var indices = new[]
{
0, 1, 3, 1, 2, 3
}```
note that it's not actually pairs, I just wrote my text to indicate that a triangle is made up of 3 points each.
ohhh
For even more clarity, the indices array is just a reference to which vertex it will use:
so the vertices are for the hole cube, not for every side?
no wait
for every side right?
but a cube has 8 vertices
Note that the above suggestion is simply for reducing memory foot print. The issue with face culling is due to incorrect normals.
ie you're drawing the vertices in the wrong order.
A cube is 8 vertices, BUT having 8 means it will appear smooth, so in this case you want 24 instead:
So basically whenever a triangle is using a vertex that another triangle is using (sharing it) the normal will be averages across the triangles normal direction, causing it to look smooth.
the whole mesh
so if you have 24 vertices some of the indices will need to refer to vertex 22, 23, 24 etc
indices are simply which vertex to use for drawing a triangle
3 indices make a triangle
It is important to give this order in clockwise direction. Because most of the default shaders render only one side of the mesh. Drawing it anticlockwise would mean, the object is rendered from the other side.
Which would induce back face culling - what you're seeing.
That's like a future issue, right now the issue is that each side of his cube has 6 vertices
It's his issue relative to #archived-code-advanced message
so what do I need to write into each draw() function (each side)?
Yes definitely, but it stems from having 6 vertices per face
Start by making sure on side works fine using 4 vertices and 6 indices
then it's just a matter of repeating it to the other sides
Well it's up to you how you want to solve it, you could manually enter the numbers like I showed in my example (way above) or you could use some algorithm like AntonC showed as well
Just make sure that one side is exactly 4 vertices and 6 indices
Then you repeat that process for all the sides of your cube, and you end up with a cube that is 24 vertices and 36 indices. 36 indices being 12 triangles since every 3 pair of indices is 1 triangle.
If at that point you have triangles "missing", check if they're drawn inside of the cube, if that's the case it's because you didnt specify the indices in the correct clockwise order, like Dalphat talked about
Okay, now you probably have what Dalphat menitoned, are the missing sides being renderer inside instead?
?
If you move the camera inside of the cube, can you see the missing faces then?
Is it inside out basically?
nope
alight now it works correctly
I fixed it by assigning the correct uvs
even though I don't know what it means and does and why it works it does work
singleton vs static class for a manager class
why would i choose singleton?
example say an api manager or deeplink manager
I know i will be using these classes throughout the application life
so im confused when i might want to use one over the other
can anyone combine these two codes please? One clamps rotation on X axis, and the other clamps rotation on y axis. But, I need to do both at the same time. I tried feeding two of the scripts together but that doesnt seem to work.
https://pastecode.io/s/jd9ir69s
https://pastecode.io/s/07uxzxgb
I'd say i would use singletons if I need to manage/affect gameobjects in scene and static otherwise
how does heap vs static memory play a part in singleton vs static?
I'm not sure i understand your question.. Static members should in fact be in the heap
Singleton classes can be inherited and also implement interfaces.
Static cant.
Singleton instance can also be passed as object. You cant do that with static
Hello i have the following problem: i want to make 1000+ scriptableobjects, objects or what is the best to store/handle such amount of different items , where the player can choose from. What is the best way to store them? It is the best way to create 1000+ scriptable Objects and drag them to a List<Item> in a gameobject or what is the way to go, dealing with a large amount of different objects, which will be used dynamically? (like here in the crafting-video (in the pinned time-stamp), he adds for each item a scriptable ojbect in its folder and add it manually in the editor to the list: https://www.youtube.com/watch?v=E91NYvDqsy8&t=1045s)
i wonder how a game like Hearthstone handles their 4.000+ Cards? do they really have long list of Scriptable-Ojbects and add each card in the editor? do they have a long config-file with every card? How do you handle such a big amount of data?
✅ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=E91NYvDqsy8
Let's take our Crafting System and make it super easy to add new Items and Recipes using Scriptable Objects!
👇
🌍 Get Code Monkey on Steam!
👍 Interactive Tutorials, Complete Games and More!
✅ https://store.steampowered.com/app/1294220/
Make Your Games De...
depends what's in the scriptable object, if it's just a few data fields you could certainly store them in a config file, though you would then have to reference things by string rather than reference to an object
Images and texts are in the scriptable object. I don't find the next step, from setting up my x items as ScriptableObject and then grab them dynamically
or maybe there is a better solution
any1 have any clue to how to smooth client side movement in a online game
This article discusses the theory behind client-side prediction. https://www.gafferongames.com/post/what_every_programmer_needs_to_know_about_game_networking/
Introduction Hi, I’m Glenn Fiedler and welcome to Networking for Game Programmers.
Have you ever wondered how multiplayer games work?
From the outside it seems magical: two or more players sharing a consistent experience across the network like they actually exist together in the same virtual world.
But as programmers we know the truth of what i...
ty
It's a starting point, but does not give Unity specific solutions.
At least i understand know where I have to start coding
Cool, personally I used tile based movement in my tower defense game. The client just smooths movement between updates received.
I think i'll remove the server authorition to move bc its a coop game
For detail discussion, post to #archived-networking
I can't for the life of me get some images to download to my game from a specific folder on my PC, at runtime.
if (!GameObject.Find(Path.GetFileName(files[count]))) {
print("Image name: " + Path.GetFileName(files[count]));
Material newMat = defaultMat;
using (UnityWebRequest imgReq = UnityWebRequest.Get("file:///C:/Users/xxx/xxx/prof670.jpeg")) {
print("URL: " + imgReq.url);
yield return imgReq.SendWebRequest();
while (!imgReq.isDone) {
print("Image loading: " + imgReq.downloadProgress);
yield return null;
}
if (imgReq.result == UnityWebRequest.Result.ConnectionError)
print("Icon ERROR: " + imgReq.error);
else {
Texture2D tex = new Texture2D(2, 2, TextureFormat.DXT5, false);
tex.LoadImage(imgReq.downloadHandler.data);
newMat.SetTexture("_MainTex", tex);
newMat.name = "Mat" + Path.GetFileName(files[count]);
GameObject icoPrtcl = GameObject.Instantiate(iconParticle, gameObject.transform);
icoPrtcl.name = Path.GetFileName(files[count]);
icoPrtcl.GetComponent<DeleteIcoParticle>().iconName = icoPrtcl.name;
icoPrtcl.GetComponent<ParticleSystemRenderer>().material = newMat;
yield return new WaitForEndOfFrame();
icoPrtcl.GetComponent<ParticleSystem>().Play();
icoPrtcl.GetComponent<DeleteIcoParticle>().DelayDelete();
}
} ```
It seems that the lower photos are different types of quality images. How do I find out how to make these images load in my game properly?
Each game will architecture data loading differently. I bet HearthStone used an external database and tools to build all this data yeah. You can start looking at Addressables or Resources for example, it might give you ideas. Two random links to start explore, though you can find better info I'm sure
https://unity.com/fr/how-to/simplify-your-content-management-addressables
https://docs.unity3d.com/ScriptReference/Resources.html
Someone knows how to do VR movement without VR?
How to test your game without a VR Headset with the new XR Device Simulator and the HMD Mock.
▶ Get access to the source code: https://www.patreon.com/ValemVR
▶ Join the Discord channel: https://discord.gg/5uhRegs
found this but it'S obsolete
Half the team doesn't have VR(or the pc that can run it) so need a non-vr way to test
the xr interaction toolkit samples have the xr simulator prefab in them
it takes a lot of fiddling. there is no out of the box demo ready from unity
don't create a Texture2D use the docs (https://lmgtfy.app/?q=unitywebrequest+to+texture2d)
is your goal to make a multiplayer game?
i wonder how a game like Hearthstone handles their 4.000+ Cards?
they made a tool for it. their game lives as a c++ binary and as a unity client
1,000 scriptable objects is fine. make an editor script that enumerates all S.O.'s in a directory and adds it to your asset list.
is there a photon sample that does your game closely?
online coop
Im making it with a self hosted server and my own networking soluction
use interpolation to move between ticks and show the other client's past by X server frames where X is any convenient number based on your interpolation logic
You are at the beginning of a long journey
and painfull...
is this for education purposes
yes
make a working version of your game over the network without interacting with unity at all
master that first
meaning, make something you can prove works at all, in some simple way
my dream
inspector reference
(field in the getter isn't a thing)
[field: SerializeField]
Collider2D Collider2D => field.ValidateAndReturn();
component
(unity null equality broken)
Collider2D? collider2D;
Collider2D Collider2D => collider2D ??= GetComponent<Collider2D>().ValidateAndReturn();
(non-static property field assignment in declaration)
Collider2D Collider2D { get => ValidateAndReturn(field); } = GetComponent<Collider2D>();
Hi, im using IDragHandler with OnDrag is there away i can stop the drag from entering certain space i.e like a box colider, i have two issues i can drag out of bounds and there is a block i dont want it to pass through
thanks
void OnDrag(PointerEventData pointer) {
if (pointer.hoverList.Any(go => go.GetComponent<Impassable>() != null)) {
return;
}
draggingTarget.transform.position += pointer.delta;
}
Gotta ask this but if you make such a big game can it literally crash unity?
There are a lot of things that can crash a piece of software. But bigness is a very vague, pretty much meaningless term.
You can certainly create a game that exhausts all of the system's memory and that can crash the process, yes.
but that can be done simply with a few lines of code, it doesn't necessarily mean the game is "big" in any human sense
example: if you try to manually use Toggle.isOn in the toggle OnClick() method and turn it on when the toggle is clicked (instead of using toggle groups lol), it will cause a stack overflow error and crash unity
doesn't matter the size of game, but the solution is to use a toggle group component to group toggles so only one is on at a tme
A StackOverflow won't crash Unity
it did for me 😬
I guess it depends if it's a stack overflow in the engine or in the C# scripting module
ah i see
which can get fuzzy if you're doing things like using UNityEvents on a Toggle
i was just trying to disable all the other toggles and turn that toggle you click on xD
ie the same functionality a toggle group provides (i learned about toggle groups shortly after)
but like this won't crash:
public int MyProp => MyProp;```
but will cause a purely C# stack overflow
🤔 interesting
Yep just tested that
at least in the editor it won't - dunno if that's true in all cases
makes sense
i saw the scriptableobject asset "channel" pattern being used in some unity youtube tutorials, i was wondering if i'm missing something or if just making a static class would basically be better? like the pattern seems to be just the scriptableobject holding events and being the thing passed around into inspectors so components can either subscribe to or fire the events
assuming i don't use UnityAction and UnityEvent - or is there a reason to prefer those? being able to serialize them in the inspector is handy but i wasn't a fan of the GC and other people seem down on them too
The pattern is specifically to make designer work easy. For instance a level designer can easily hook up events and have stuff happen as wanted without writing a single line of code. For example a box trigger causing the player to take damage.
Sure you can write it in code, and it will be more performant. But then you also have to write it in code
ah good point, yeah that's moot for me in my single person hobbyist operation
Then it's completely up to you how you want to work with it. But the general rule of thumb is that you make performant tools that allows a designer to rapidly iterate. In iteration speed is more important than pure performance.
Something that would affect you though is that the ScriptableObject pattern will automatically track scene dependencies (to some extent), where as manual implementation in C# event you'd have to handle that as well, to avoid references disappearing when loading/unloading scenes
my understanding is there wouldn't an issue with scene transitions with a static class with static events that the monobehaviours subscribe/unsubscribe to on their unity enable/disable, like if an unity object is going away for unity reasons it's always going to call its OnDisable and then the static object will know - or is there something i'm missing
Nah you're correct here.
ok, thanks!
Anyone here have any experience with optimization? I have an issue where I have to determine if having 300 objects with public variables is less processor intensive than a 3 dimensional ArrayList
simply benchmark it
Theoretically, it should be heavier, since each object contains additional data and components, like the transform, that a 3d array of values doesn't. Now for how much of an impact it has, you'll have to test it. Probably not much, but there would be different numbers on different platforms.
thank you, that's what I was wondering.
I am just not familiar with how Unity handles 3d objects vs how it handles arrays in memory I know that an array has to be processed during every update cycle. If 3d objects have to be processed on that same level too then it would be heavier 😐
which means no matter what i'm pushing how much upper memory is being sucked up with my board game. Not sure how to optimize those values in the array to reduce the processor load.
It might cause really nasty lag no matter what 😦
each segment on the board (it's a 17x17 board) has 7 values that need to be recorded
Wdym by "array has to be processed on every update"? Where did you hear that? An array defined by you only gets processed whenever you process it.
😮 so it is different in C# than gamemaker?!
oh
in gamemaker a 3d arraylist is processed every step because it's retained in upper memory
Not in C#, arrays are stored in the memory once, and your variables point to that array in the memory
So you could make a Tile[,] where Tile is a custom class/struct containing your 7 values
I've no clue about gamemaker, but it sounds wild that something would be processed every frame just because it exists.
I'm also not sure what the upper memory refers to. In C# you have the stack and the heap memory, but it doesn't make things access/process it for no reason.
Ok thank you 😄
is it possible to reference a boolean in script via a string field from another script ? Something like "string RandomText1" and "bool randomText1=false;" "bool randomText2=false;" "bool randomText3=false;"
so that i change the string name to match the boolean name?
how do one reference a list in another script
a c# class object does not have transform that would only apply to a gameobject. and between saving a c# class object with 3 values, or a 3 dimensional array, in another array, this should be pretty similar, so they should benchmark it.
I was assuming they meant monobehaviours, but if not, true that. Although, having an array of reference types should still be a bit heavier than an array of value types. Maybe not in terms of per frame performance, but in terms of memory consumption and garbage collection.🤔
no it's not. everything is stored on the heap and not on the stack anyway
Donno, I think even an empty class instance allocates some memory for itself. So it should still be more than just a value in an array.
an empty object allocates 1 byte. but so would an empty array
Yeah, but you don't have an empty array in this scenario. You have an array of 300 value types vs array of 300 reference types. Meaning 300 more bytes(assuming that's a correct number). Sure, that's not a lot, and probably shouldn't be taken into account, just saying.
an c# class object is a reference type, a c# array is also a reference type. there is no value type here
It's all on the heap, but value type arrays can still be faster to work with because of better data locality.
c# class with 3 values would also have total data locality since they're all predefined size types
If you have an array of a struct which you then change to a class, I'd expect more memory usage because now it's storing both the objects somewhere in the heap and also the 8-byte pointer to it.
it's always storing them on the heap
How would that work? The runtime figures out that all these objects are referenced in an array together and stores them all in the same sequential piece of memory?
if you put them in an array, this is possible
if you have a int[] it's a reference type - value types. If you have a Class[] with value types in the class, it's reference type -reference type - value types. You still allocate some space for the class instance pointers as well.🤔
class[] is reference type - value type
Only the pointers would be stored sequentially. But each pointer could be pointing anywhere in the heap, destroying locality.
not if you initialize the array
You have a pointer to the array itself and to each of the objects it references, so it's reference - reference - value.
So it behaves differently based on whether you create the object at the same time as creating the array? So if I create a second array that references the same objects as the first array, the second array would perform worse?
int[3][300] is the same as class[300]
no, he's talking about an array of 3 dimensional arrays
int[x,y,z]
They definitely said "3 dimensional arraylist". Although go figure what they meant by that.
im trying to reference a list in another script
i just tried a script and it didnt work
is at least how i understood it 3-dimensional-array list (although if list or array is unimportant, the same under the hood anyway)
bt the same script worked for someone else
why
then
is it not working
is this an issue with unity
it doesnt seem to be anything wrong with the script but with unity itself
no
That doesn't mean it's advanced
its not working but it worked for someone else
Something in your code fails, debug it
it's 1000000000% not unity. because these issues never are
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class test : MonoBehaviour
{
public List<Rigidbody> rigidbodyList = new List<Rigidbody>();
void Start()
{
rigidbodyList.Add(GetComponent<Rigidbody>());
}
void Update()
{
Debug.Log(rigidbodyList);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class test2 : MonoBehaviour
{
test aG;
void Start()
{
aG = GetComponent<test>();
}
void Update()
{
Debug.Log("list return "+ aG.rigidbodyList.Count); // not returning list??
}
}
you can test it for yourself
it will proabblyh work
But just so we're on the same page, you understand what I mean right? How an array of pointers will be slower and more likely to cause CPU cache misses than an array where all the data is stored sequentially? So the only thing you don't agree with is that all reference type arrays in C# behave as pointer arrays?
stop! it's not advanced, and it's not scripting related, and it's crossposting #854851968446365696
its not working for me though
This is a #💻┃code-beginner issue
no i understand that and i agree. just seems we were talking about int[,,] = new int[300] and int[3][300] respectively
i have checked this script 10 times
A null reference exception is one of the most basic issues you can run into.
Move to #💻┃code-beginner .
i have 500% sure there is nothing wrong with this script
wrong
bc the exact same script worked for someone else
Move to #💻┃code-beginner
The difference between multi-dimensional and jagged arrays?
https://answers.unity.com/questions/588294/anyway-to-access-a-list-from-another-script-c.html i literally just copied this script
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
Move to #💻┃code-beginner
Or the mod will make sure you do
i am going to set this script now
word for word
bruh indeed
and we will see wether this question is a #💻┃code-beginner question or a #archived-code-advanced question
!mute 416215683089563649 1h You do not have a test component attached to test2's gameObject. This is a basic issue, stop posting in here after being told to move many times.
𝕓𝕣𝕦𝕙#4755 was muted
well you also need to make sure the references are actually referencing something, just the script alone won't do that
nvm 
i mean the original question is very multi-interpretable
Hey quick question, is there anywhere some documentation on how to run code instead of quitting whenever someone press alt-f4 (or press the x in windowed mode) ?
You cannot intercept alt-f4
you'll have to hook into the low level windows api for that
The X on the otherhand, there's OnApplicationQuitting or something, it's not hard to find
https://docs.unity3d.com/ScriptReference/Application-wantsToQuit.html
but i highly recommend against it. there's a reason for alt f4
https://forum.unity.com/threads/reusing-shadowmaps.590029/ - i find myself needing basically the same thing as this person, the answer seems to be SRP but looking into it it seems like a whole freaking lot to learn and implement just to achieve "the default built-in pipeline except with one thing different" - is there anything easier i could do for this?
It's fine if I don't intercept alt f4, I just thought the two came together
Thanks I'll look into it
i.e. i'm calling Camera.Render, just two times in my case, and don't want/need the shadow pass on the second time
HDRP has a dropdown on a light to do this
Not sure about URP
i'm not using either and aren't far enough along the project to commit
ah, sorry. Yeah I haven't used the built-in pipeline in forever, so I can't say
can anyone help me find the best multiplayer networking for free
Is there a way to make it so that you have a static script which captures any kind of errors from any kind of script and then creates one of those error dialogue boxes that displays the error as well as the source of the error during a build? I know how to create a error dialogue box but im not sure how to capture a error from other scripts and methods. Could be useful in case someone creates a weird bug of some sort and i need to display a crash message that safely quits the game. I know one game that prints out a lot of warning dialogue boxes in case you mod it but you mod it in the wrong way and i doubt they coded every dialogue box message in every possible script.
basically an universal try catch-ish function? hope this makes sense
i recommend photon
I tried but the Instantiate function just returned a NullException
how do I fix the nullException
This is not an #archived-code-advanced question
hi, I need some advice about automatic tests. I have some little test suite that works very well when I run tests one-by-one, but some of these tests doesn't work when I run ALL the tests. The problem is that previous tests sometimes don't "clear" very well the scene so the next one will fail because of the presence of unexpected game objects in the scene. How could I make sure that each test is run in a clear environment?
seems like Application.logMessageReceived is what im searching for 
Are the tests edit-mode tests? What's the context here?
So it turns out application.wantstoquit also intercept alt f4
no, they are PlayMode tests
Huh, so it does... well, that's news to me 😄
where does it say that?
Can you just make the [SetUp/UnitySetUp] or [TearDown/UnityTearDown] method reload the scene?
or just clean up anything you've specifically done
now that i have started talking about this, what are the differences between errors and exceptions? logMessageReceived has an enum of LogType and apparently Exception exists and i never used those (unless i did without noticing). i know it's not an advanced question, but i dont really wanna crosspost when its about the same topic
ahh i see
I just tried it, I don't see that written anywhere though
hmm true true. what about asserts though?
i just tried it. didn't work
Weird
It works for me. 2022.1
Fwiw, the LogType Exception probably just corresponds to Debug.LogException
does anyone have some good references on optimizing procedural mesh tile map stuff?
at the moment i'm removing and generating the whole visible map at certain intervals (player moving to new tile or depending on size, group of several tiles) which is obviously not ideal since it should only need to create/remove new rows/columns as the player moves
https://i.imgur.com/fVPn1PY.png
the colliders for walls (MapU Walls in profiler) should be the easy part, but i'm not sure how to go about that in terms of generating the mesh (MapU Mesh in profiler) - currently it's one big mesh in one game object; maybe i need to split it into multiple object chunks, so i can create/remove those as row and column groups as needed?
or maybe there are other approaches i can try to reduce these spikes
The image you have looks like the mesh is mostly on screen, I assume it gets bigger than that?
yes, i'm doing some basic/scuffed culling when the player is still smaller
for context; you start small and tiles are big, as you grow you see more tiles, eventually i'll have to essentially change the resolution because too many tiny tiles on screen won't be viable, but first i want to optimize the one-map-layer approach
Is it just the "recalculate normals" call that is expensive?
not just that but it's a big chunk
Well one thing that sticks out is that it seems that you have too many vertices
Are these black pixels all edges?
yeah, i probably want to reduce geometry the more further out it is as well
those currently don't seem important but that's because i have randomization for a more natural look turned off
Probably won't solve your whole problem, but if you can simplify the flat areas it should help ease the problem
the main problem is definitely that it redraws the whole thing instead of just what's "needed", the geometry is still relatively low-poly
Other than that splitting it into chunks like you said should help ease frame delay.
i'll make a quick vid with randomization on, that should make it more clear
I think you were right the first time, the solution is likely chunking based on what's on or nearby the screen.
thanks!
If you can write code to just generate some rectangle of coordinates then you can load meshes in as required and just place them on the edges
Looks like you already have that.
for some reason these two lines are super expensive as well
Vector3[] verts = new Vector3[SW.TILE_VERTICES * totalTiles];
Vector2[] uv = new Vector2[SW.TILE_VERTICES * totalTiles];
Hm. Just allocating the arrays?
let me make sure that's what it is, but i think so
Hm, this is annoying. It seems you can't provide a vertex count
to be fair it's 108 verts per tile, so it would be allocating quite a bit of memory
hah maybe i should cache the entire map as vertex/uv data
Allocate a huge array up front
And store it as a static
static Vector3 _vertices = new Vector3[SW.TILE_VERTICES * MaxTileCount];
Mesh Generate(...) {
var mesh = new Mesh();
var count = width * height;
if (count > MaxTileCount) {
throw new InvalidOperationException($"{count} > {MaxTileCount}");
}
for (var i = 0; i < count; i++) {
_vertices[i] = ...
}
mesh.SetVerticles(_vertices, 0, count);
This way you don't need to allocate a new array each time
oh let me try that, thanks
There's also this: https://docs.unity3d.com/ScriptReference/Mesh.SetIndices.html
Oh, you can even use a List if you want to make it flexible enough to render an infinite size, just beware that copying Vector3s from a list is slower than an array.
yeah i'm trying to use arrays as much as i can
I think creating an array of some maximum size makes sense anyway
If you want to generate more than that you should batch it over several frames
yeah, since i already know the max size of each map layer
and it'll probably stay the same for each, just the scale will change
Another thing you might explore is using a normal map instead of having that many vertices on each tile
Esp. for the floor tiles
If you want to compare performance you coudl try just rendering perfectly flat tiles and see how fast it is
It's quite possible that doing that would mean that you won't need to optimize nearly as much if you do that.
i'd definitely like to make sure i have some leeway for actually geometry, since i still want environment objects and make the place feel more alive etc.
but i'll put that in my notes yeah
Sure, well you can always scatter geometry on top.
at least i managed to keep the object count low, maybe to a fault haha
Well you still get batching if meshes share a material
In fact having one big object might be bad because it can't be culled when it's mostly offscreen
But chunking it should address that
(I'm not actually sure about this one)
yeah, that's why i was doing the culling manually
oh, i could also consider calculating normals beforehand
Yeah, I thought of that too.
since i'm doing hard edge low poly style anyway, so normals are always the same relationship to the face
I reckon you'd get pretty good mileage with 12 random normal maps just assigned at random to tiles
Fewer even if you rotate them 6 ways
Hey everyone, do you know how I'd be able to send data to nativ android app when I use unity as a library? I know how to send data to the unity module with unityPlayer.SendMessage(gameObject, functionName, parameter) but not the other way around. Any idea?
The purpose is to provide to the android developper some kind of event to hook to to grab data from the unity module when he needs it
I have done it for webgl by writing a jslib file that calls a function the web dev has to create on his side with the same name (if he doesn't the module crashes because it's trying to call a non existing function, but that's the idea)
Do I need to write a IOS / android plugin in unity ?
I don't believe it's possible to use Unity as a library. Additionally you've misunderstood what SendMessage is.
Hm, actually maybe this is some android thing I'm not aware of, nvm.
https://forum.unity.com/threads/using-unity-as-a-library-in-native-ios-android-apps.685195/?_ga=2.205123536.1569881299.1647856286-393579739.1636282145 Might be a good read if you're interessted 🙂
You will indeed probably need to write a plugin in Java/Kotlin for android. You'll likely want to use Unity's AndroidJavaClass and AndroidJavaObject classes to call methods from Unity.
As a general idea of how these things can be structured, here's a small class I set up that tells my android service to play some audio in the background:
public class AndroidAudioPlayer : IAudioPlayer
{
private const string CurrentActivityName = "currentActivity";
private const string UnityClassName = "com.unity3d.player.UnityPlayer";
private const string AudioPlayerClassName = "com.datapad.audioplayer.AudioPlayer";
private const string SetActivityInstanceMethodName = "setActivityInstance";
private const string PlayAudioMethodName = "PlayAudio";
private const string StopAudioMethodName = "StopAudio";
private AndroidJavaClass _unityClass;
private AndroidJavaClass _audioPlayer;
private AndroidJavaObject _unityActivity;
public AndroidAudioPlayer()
{
InitializeAudioPlayerPlugin();
}
public void PlayAudio(AudioAssetConfig asset)
{
_audioPlayer.CallStatic(PlayAudioMethodName, asset.LocalPath);
}
public void StopAudio()
{
_audioPlayer.CallStatic(StopAudioMethodName);
}
private void InitializeAudioPlayerPlugin()
{
_unityClass = new(UnityClassName);
_audioPlayer = new(AudioPlayerClassName);
_unityActivity = _unityClass.GetStatic<AndroidJavaObject>(CurrentActivityName);
_audioPlayer.CallStatic(SetActivityInstanceMethodName, _unityActivity);
}
}
thanks @quartz stratus , i've already setup some of these methods in unity, do you know if the android developper creates those corresponding methods on his side if they'll get called? What I mean is I don't know in advance what he wants to do with the value i provide so the idea is that I just give him the name of the method to create and what parameter it takes and he writes the body itself
Yes, as long as you and your android dev are using the exact same method signature, they will be called.
Also keep in mind the distinction Unity makes between Call and CallStatic, that' definitely something to communicate with your dev about
thanks again. Last question, do you know how I could add some security if the method does'nt exist on his side instead of just crashing the module?
I'll look into it
If I do create a library in unity with this function with an empty body, can he override it on his side?
I don't know if this is possible. My instinct is that it's probably not, although I might be unaware of something. But because of the externalized nature of the Java/Kotlin code, I don't think Unity can check for the existence of a particular member.
I'm not sure I follow the question. You will not be defining the bodies of these functions on the Unity side, he will have to do that on the Android side. You guys simply have to agree on method signatures and what the expected functionality of the method is.
it's just that if the function is not defined on his side then it falls back to the one I made in unity where the body is empty (It also would help for apk test purpose so I don't have to disable part of code where i usually call this method when I test it directly as an apk)
should a api manager be a singleton or static or neither
it basically just a class that does unitywebrequests to our cms
every method is a coroutine
but debating how it should live
a singleton isnt a bad idea if you only need a single, easily accesible instance
helps coordinate actions across that system
does the api manager need to remember anything? if no, you can make it a static
it does not remember anything
there ya go
just pure methods
That's generally the question I ask when I'm trying to decide if I can make something static
so static is a good option. I had a thought around just making it a normal class that one instantiates but then i was worried about thread safety with the async stuff
that makes sense
I actually currently have it as static atm 🙂
but could just be overthinking it to death lol
I also suffer from that problem
say its a normal class just out of curiosity is it thread safe to have multiple instances of it
just in theory
i've really fallen in love with dependency injection
over singletons
its all coroutines
basically think usermanager.getuserprofile
or usermanager.updateuserprofile
etc
Wait so its a Monobehavior?
It inherits from mono then because of coroutines?
so the monobehaviour class calls startcoroutine(useclient.getuserprofile)
this is just a pure class that holds the methods
I might be wrong but I thought the class containing the coroutine has to inherit monobehavior
Oh okay, you use the class as palceholder mono for your static
it does but this does not technically use the startcoroutine function
just holds the Ienumator method for it
exactly @soft hawk
its just a library of methods really that monobehaviours call
Your question was, if API Manager should be static?
basically
it does not inheret nor need a monobheviour either
forgive the spelling
So right now I am working on a system and I put my managers as normal monos but with static delegates, params and what not to make them easily accessable and not having that .instance. thing goin on
So I guess my previous statement is wrong. I don't know why I thought that?
a class that needs a coroutine does need to inherit from mono, or use editor coroutines
but the Ienumator is built into the c# language so that doesnt
basically if you startcoroutine <- requires mono
but the parameter doesn't
@soft hawk
Yea I think I just had a brain fart yesterday when I was setting up something, now I've gone back and fixed it
So new question
If I have a IEnumerator coroutine with waits, and I call it as a method, what happens?
Trying to avoid some code duplication
what do you mean by waits?
WaitForSeconds()
you can do a yield return for the method
additionally there is a pattern thats equivalent to like a promies.all
you receive an IEnumerator
{
while (true)
{
yield return _wait;
// Build new MegaBlocks & Expand
FindAllMegaBlocks();
yield return _wait;
// Execute Block Breaks
if (AnyExecutes())
{
yield return _wait;
// Drop all blocks
DropAllBlocks();
yield return _wait;
// Increment Multiplier
_board.Multiplier++;
// EvaluateBoard
continue;
}
break;
}
_board.Multiplier = 1;
}
@soft hawk what is your objective?
FindAllMegaBlocks();
this is anIEnumerator FindAllMegaBlocks()?
Well sometimes I want it to wait, and sometimes I don't (when AI is evaluating future moves)
no that's the coroutine I have, EvaluateBoardCoroutine()
StartCoroutine(MethodReturningIEnumerator()) does not wait
yield return StartCoroutine(MethodReturningIEnumerator()) waits for the coroutine MethodReturningIEnumerator to finish
Right I get that, but if I just had a call to
EvaluateBoardCoroutine()
MethodReturningIEnumerator() returns an IEnumerator. no code will execute unless you interact with the returned IEnumerator instance. the best way to "interact" with it is using StartCoroutine()
Oh ok
that will return an IEnumerator
Got it, thanks
Does anyone tried / know how do hot load in Unity? for easier testing
also for testing script for card game effect, want to try to help GD for easier script implementation
Are async operations still unsupported in WebGL builds?
TAP or other async calls
I guess it doesn't really matter cause I probably need to use the jobs system
Thanks, i seem to get an error it doenst no what pointer.hoverList is
sorry, it's called hovered
read the docs for PointerEventData
what do you mean
what are you trying to do?
what is _wait
async / await works in WebGL
it works on every platform
Remembered it doesn't really matter about WebGL, but what I am trying to do is translate my synchronous depth first search AI into an asynchronous multithreaded approach for the purposes of training an agent
okay
Current search depth is 4
did we discuss your game already? this is a puzzle fighter game right?
Yes, it is
and you're trying to write the conventional bot?
I have the conventional bot, its just synchronous, finds a best move everytime a piece is called
but its only able to go about 4 deep without major slowdown
got it
So i'd like to make it asynchronous and build a queue of moves
okay
The thing is, once I have a trained agent I can just use that in a webGL build so that point is moot 😄
but I've never done multithreaded before and im stumped
yes
okay
ML-Agents
There are three main parts: Move generation, Move Evaluation, and then pathfinding. That part is simple
while (gameStateStack.Length > 0) {
var v /* as in vertex */ = gameStateStack.Pop();
if (isTerminal(v) { compute score and set it on the vertex }
if (isInterruptedOrRunsOutOfTime()) { exit }
pruneStack(gameStateStack);
var depth = v.depth;
var edges = v.context.validMoves();
if (edges.Length == 0) continue;
foreach (var edge in edges) {
executeOneMoveOfGameAndAppendNewStateToStack(gameStateStack, v, edge, depth);
}
}
@soft hawk does this make sense?
it is depth first depending on how you append the state to the stack
to make this parallel
the foreach is replaced with...
Parallel.ForEach(edges, edge => {...})
that's it
do you know what a greedy algorithm is?
Im sure I knew when I did this in college, but that was a long time ago lol
But your pseudo code sort of makes sense to me, and I should probably refactor my solution to look like that
right, does it matter that evaluating the gamestate (getting a score) is destructive?
which will turn your thing from (moves ^ depth) to (moves * depth)
"[destroying the game state by getting a score] was a mistake"
well I can always make a copy of the board
yes
you will have to make a copy of the board
you should represent your board as a struct with fixed size arrays
otherwise you will spend like 20-40% of your CPU time copying game states
you will need to do this anyway if you want a hope and a prayer of making the deep learned agent work
which is the whole reason i told you to try writing a conventional bot first!!
and now look at you
look at you thrive
So right now my board is a class with a Block[] array
But I could just make the block array a struct
Ok i think I get that
someone more knowledgable will have the answer online
for how to declare a struct that contains a fixed size array you can copy easily
and how to do that copy
you should look what a greedy bot is
This gives me good direction, thanks
I might not even need to bother with multithreaded
The bot does pretty well even at just depth 4
@undone coral Ah ok, So a greedy algorithm probably doesn't work in this case
Because you get big bonuses for setting up chains of blockbreaks
So the greedy move is not necessarily the best move in this game
I have incentives that help the bot naively pursue organized board states and avoid losing board states, but I'm not sure how I'd balance those incentives to make a greedy algorithm effective
you can also prune
heuristically
until you've
- run out of game states
- run out of time
prune the game states you want to evaluate
get a vertex in your DAG
finish a terminal one - score it and record its predecessors.
otherwise, expand it by appending the game states onto your
stack created by taking all this vertex's actions
you can also change the order you evaluate the game states in
you don't always do depth first
you can order it greedily
to save time
OR maybe in this game the worst move tends to be the best one to start with
so do it a different way
@soft hawk does that make sense?
i haven't looked, but puzzle fighter might be solvable?
Not sure what solvable means in this regard, since its an adversarial game
Right now im just using score as a heuristic for success
does anyone know
if on vulkan, it is expected that resizing a render texture DOES NOT change its native texture pointer?
hey, not too sure if this is advanced worthy, but i havent been able to change the color of one of my characters. I used to change it with the SpriteRenderer, but i've changed from using sprite sheet animations to skeleton rigged. any ideas??
this is the guy im trying to change colors
i used to do it with this line of code:
objZombie.GetComponent<SpriteRenderer>().color = new Color32(229, 228, 146, 255);
@undone coral So I need to make my Block structs out of blittable data-types and the Board is then an (unsafe) fixed array of those Blocks, and that will be compatible with the jobs system, is that right? I've been reading a lot of stuff and trying to map out my next steps
That will make a Board a non-nullable array of structs containing blittable data types only
the board should be a struct
i.e., a game state
Right, ya
everything that the bot needs to know should be in 1 struct
which itself can have that fixed array
native array is already a friendly fixed array
if you want to use burst, https://docs.unity3d.com/Packages/com.unity.burst@0.2-preview.20/manual/index.html
burst speeds up your thing, jobs can make it parallelized
"Burst supports fixed array fields."
yea
ok but I can have a fixed array of structs, right?
yes, i'm pretty confident
struct Board {
fixed Block[] blocks = new ...
}
struct Block { ... }
is supported
yea
Ok, I know what Im workin on tonight lol
4th iteration of this game now
learning a bit more every time
but i don't think this is a performance issue now
it's a little premature
pruning is more important
copying game state is expensive
but not as expensive as expanding it
you can write a simple deep copy for now
the reason i went for classes at first was i figured shallow copy would be faster than even an optimized deep copy
well you can't shallow copy anything
cause right now im just cloning an array of reference types
for bot writing purposes
unfortunately that means i can't do anything w/ jobs
without writing some kinda mapping interface
not sure that's the correct language
🤷♂️
I have no idea how to prune here is the problem
roger
simple pruning strategies:
symmetry (are moves A-B the same as B-A)
score (remove the lowest N scores)
do you model what the opponent does?
you have to assume they maximize their score
No because they're fairly disconnected, its not they move you move
both play simultaneously on their own gameboards, scoring points "attacks" the other board with random pieces
the idea is to make the other guy game over before you do
the attacks are not predictable so there is no point in modeling them here
just fyi you can't make a fixed array of Block structs 😦
Fixed-size buffer element type should be one of sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, or bool
But I can make a native array of structs so i guess I do that? im very confused about all this stuff
Don’t overthink it. You can flatten it out onto separate arrays
Is it possible to extend the functionalities of unity classes? specifically GameObject? I was thinking of making a partial class of it that would implement IDispose. Not sure if there is a better way on handling how it destroys itself
for context: I would want to list game objects in a dictionary using their instance id as key, however, if a user decides to do a Destroy(this.gameObject), I would want the game object to derefence itself from the object list
that's sad. alright thanks!
Hi! i'm new to the ScriptableSingleton thing, and i can't seem to find the instance of my singleton. here's my snippet:
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[FilePath("Assets/ChipsAssets/ChipsList.asset",FilePathAttribute.Location.PreferencesFolder)]
public class ChipsListSingleton : ScriptableSingleton<ChipsListSingleton>
{
public List<ScriptableChips> chips = new List<ScriptableChips>();
public void FetchChips() {
Object[] chipsObject = AssetDatabase.LoadAllAssetsAtPath("Assets/Scripts/Chips/Data/Player");
ScriptableChips[] chipsGotten = new ScriptableChips[chipsObject.Length];
for (int i = 0; i < chipsGotten.Length; i++) {
chipsGotten[i] = (ScriptableChips)chipsObject[i];
}
chips.Clear();
chips.AddRange(chipsGotten);
chips.Sort();
for (int i = 0; i < chips.Count; i++) {
ScriptableChips item = chips[i];
item.ID = i;
}
}
}
Does anyone know why when I play my games in unity on my college computer all the inputs are delayed and act like as if they queue up one after the other? If I would hold A for 5 seconds and then switch to W, my character would carry on left for a couple seconds more and then switch to W even after I have let go.
Hello, i have a slight problem, i have a method converting world coordinates to grid coordinates (the game is 2D and i use a grid for it) and it works as intended with a slight exception:
(int)(WorldPosition.x / CellSize.x) expression returns 4, when WorldPosition.x is 3.2 and CellSize.x is 0.64
I already thought about WorldPosition.x being just a bit under 3.2 so the overall expression would result in 4.99 aprox. and it would then get rounded down to 4, but the VS code debugger shows a clean 3.2 value for it, and the code works for other values(such as WorldPosition.x being 1.28, or equal to 2 in grid position)
anyone got any ideas? I can share the whole method but I doubt it would provide further insight as WorldPosition and CellSize are not modified in the example i used.
did your debugger display all digits?
no, but it does display digits when there are digits
try logging the values with :F8 number format
this is why I always work with a grid size of 1
sorry, i don't quite get what shoudl I do, i have my variable in a watch
it should display digits since its a float
the weirdest thing is that it does this strange behavior only when the value is 3.2, it works for other values
in any case your grid code should never require an exact float-value
I guess I will just use Mathf.floortoint
that won't change anything 🤔
ah right, hmm
also, just so you know (as an example), 3.2f is actually 3.20000005f when assigning it directly in code, so it is likely that your world position is actually not exactly 3.2 (due to compound errors in its transform calculations) and thus your math doesn't work.
with direct value assignment the calculation works, so there is no other explanation
thre's no need for compound errors to cause this one. 3.2 is just not possible to represent in binary with a finite number of digits
same way 1/3 cannot be represented in decimal with a finite number of digits
yes, but as you see in the calculation the error when assigning 0.64 corrects it and you get a perfect 5
well if 3.2 is like 3.200000005
I think the point is that it has to be less than 3.2 to cause a result of 4
interesting
that's where the error comes in
it should round down to 5 when divided by .64
3.200000005 is greater than 3.2
so in other words, your 3.2 is not 3.2 @serene girder and is actually ~3.19999
yeah but now im trying to figure out why
because your transform.x is not a perfect 3.2
what are you doing where it matters this much that it's exactly 3.2
Floating point format explorer – binary representations of common floating point formats.
it was said before, your code is inherently flawed if you need exact float values
( https://ciechanow.ski/exposing-floating-point/ companion to this writeup)
Within the code that deals with the grid, you should use nice, predictable integers. Only convert things to float when you need to finally present things in world space
or just use a grid size of 1 like me
using netcode for game objects, Im using NetworkManager.Singleton.SceneManager.LoadScene to load a scene on all clients, is there a way to do LoadSceneAsync like this?
@sly grove I am getting the world pos and need to convert it, I will think of a better way to do it
Hi everyone! I'd like to create a prefab that when dragged into the hierarchy, the user will be prompted to input an integer. Then that number of prefabs will be created as children of an empty game object. Is this possible with code? If prompts aren't possible, public variables in the inspector should be fine as well!
someone may respond here, but also try #↕️┃editor-extensions
you could throw down with this: https://docs.unity3d.com/ScriptReference/EditorApplication-hierarchyChanged.html
it's not much and it might be a bit hacky, but it's something you could start with. keep track of the objects in the hierarchy. when it's changed, compare the new list of objects with the old and pinpoint the new one. Then create a new GameObject and parent that object to it. Then duplicate it as many times as you want. Lol it might work!
Oo thanks! Will have a look
not sure exactly how the integer prompt would tie into this, but I'm sure it's doable.
Just worried hierarchyChanged would affect other objects in the future, will have to find a way to ignore it once the objects have been added
OK i bring news, @granite viper @compact ingot
apparently if i make a float and do the division in it, then convert it to int, it works
crazy stuff
I have legit one of the weirdest bug yet I found.
I have 0 clue if someone even remotely knows whats going on here.
tdlr: One of my weapons is not beeing rendered if it's not visible in the scene view in the editor????
I checked both models and they appear to have everything the same in terms of settings.
How does that even happen? Why does the scene view effect rendering in the game window?
Sceneview is basically another camera that will trigger onrender, onbecomevisible and so on functions when being used in scripts.
Yep - do you have an OnBecameInvisible thing going on?
If you want to test occlusion culling for example, you gotta turn off sceneview to get legit results
I had the same results in my build
is this for education purposes?
There is no scene camera in build
That's why it's so weird
it acts like there is one but there is no other camera besides my FPS