#archived-code-advanced

1 messages · Page 175 of 1

sly grove
#

You can literally just do it from anywhere

#

It's static

arctic robin
#

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.

undone coral
arctic robin
undone coral
#

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

arctic robin
undone coral
#

what is the application?

arctic robin
#

CPU is the problem, but it looks like it gets clogged by Hololens scripts?

undone coral
#

at 33ms GPU is also a problem

#

that's less than 30fps on an HMD

#

people will barf

#

maybe try running a demo project

arctic robin
undone coral
#

and see if something is wrong with your hardware

arctic robin
undone coral
#

is this hololens or hololens 2

arctic robin
#

How can I deduce if it is one of my scripts from this profiling?

arctic robin
undone coral
#

or hololens 2022 datacenter server, dynamics edition

undone coral
#

from flame view to the other one

#

that shows times

arctic robin
undone coral
#

yes*

#

show more of it lol

#

it's telling you. sort by self ms

arctic robin
#

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?

undone coral
#

not sure

#

looks like your hololens is busted

arctic robin
#

Kk, will look into that

arctic robin
#

I did a fresh build pack a while back and default settings are ARM, not ARM64

#

5 hours spent on tracking down that bug

limpid badge
#

hi unity friends, is it possible for player to edit define symbol on build?

mint sleet
#

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!

craggy spear
#

What is AdminUser?

fresh salmon
#

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
}
mint sleet
#

Yes I did it with this way. thank you

hazy hearth
#

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

analog nexus
#

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?

hushed sparrow
#

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

remote pumice
#

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?

hushed sparrow
#

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

remote pumice
#

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

hushed sparrow
#

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

remote pumice
#

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

remote pumice
hushed sparrow
#

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

remote pumice
#

Sure! But Images and stuff may take a while to load, my wifi is almost non-existent

hushed sparrow
#

i see

#

should i just copy and paste the bits of code then?

remote pumice
#

It's fine! It did load already, since it's very small

hushed sparrow
#

i see

remote pumice
#

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?

hushed sparrow
#

the target is selected dependant on which lane the card is played in

#

since characters are also in said lanes

kind sigil
#

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?

cerulean scaffold
#

Where can I find more in depth docs on UniRx?

hallow cove
#

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-

jovial totem
#

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

green river
#

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?

remote pumice
remote pumice
remote pumice
# jovial totem Is there a good package for rendering html in Unity? I don’t need a JS VM or any...

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

frank peak
#

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?

drifting galleon
#

there are lots of ways for custom OC

frank peak
#

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)

green river
#

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.

sage radish
green river
#

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

sage radish
#

@green river What Unity version are you on?

green river
#

currently 2019.4.15f1

#

i could be talked into upgrading haha

#

just kinda trying to go early access beta in a month or so

sage radish
#

I just noticed Graphics Jobs is experimental in your screenshot, but it's not in newer versions. Have you tried having that option on?

undone coral
green river
#

interesting...

#

i only arrived at that b/c that one commanline arg resolved the issue

#

really all i had to go on

sage radish
#

If you're releasing this on Steam, you can configure your app to run with command line arguments

#

But not a great solution still

undone coral
#

you should roll with that

green river
#

that's a really good point tho.. i had no idea.. i knew you could have people add them by right clicking .. etc

undone coral
#

write a shortcut with command line args

green river
#

its' a nice last ditch fix

undone coral
#

lots of approaches

#

don't overthink it

frank peak
#

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

green river
#

wow big win 😄

frank peak
#

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

undone coral
#

you can run the frame debugger / render doc and freeze the frame when it occurs

#

and it will tell you exactly what happened

green river
#

few complications

#
  1. doesn't happen in editor
#
  1. doesn't happen on mac
#

😉

undone coral
#

it sounds like you're making a shortcut

green river
#

yeah maybe lol

#

unless someone comes along with a better checkbox

undone coral
#

there is no checkbox no

green river
#

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

undone coral
#

there's no checkbox to disable multithreading

green river
#

right.

#

i dont think so either

#

so... shortcut

undone coral
#

yes

green river
#

yep.

#

thanks that's like... divinely simple

undone coral
sage radish
undone coral
undone coral
#

@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

sage radish
#

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.

green river
#

intersting. lemme try that

hot aspen
#

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?

green river
#

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

undone coral
#

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

green river
#

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?

undone coral
#

without any further configuration

undone coral
green river
undone coral
#

you can also try using one big atlas

#

then you've narrowed it down 100% to the way UGUI renders in batches

hot aspen
digital relic
#

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.

undone coral
frank peak
#

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

digital relic
#

Wow thanks

frank peak
#

has anyone written an A* pathfinding algo? any thoughts?

novel plinth
#

Many of these on youtube

frank peak
#

yeah fair, i watched a few vids but was curious what the discord thought

granite viper
#

Any thoughts about what?

#

What about A*?

novel plinth
#

Many have tried to reinvent the wheel of A* but not much of a difference from one to another tbh..

maiden turtle
#

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

maiden turtle
#

and there's no info on spawning objects either

#

within coroutines

novel wing
novel plinth
#

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)

maiden turtle
#

I'm trying to achieve something like the following

#

:

median cosmos
#

Hey I wanted to learn more about vertices by testing out different shapes

maiden turtle
#
  1. Load a prefab into memory (LoadAssetAsync or whatnot, via addressables). This step is not a problem.
  2. Instantiate the prefab.
  3. Call all initialization hooks (Awake, OnEnable, Start).
  4. Prevent any Updates from being called.
  5. Initialize the objects externally (I need to control the order more accurately, plus I need to propagate so info from other systems).
  6. Enable Update's
#

So

median cosmos
#

But I don't udnerstand why this isn't becoming a Square?

maiden turtle
#

The external initialization needs to happen after the internal one happens

#

The internal one being step 3

median cosmos
#

I'm very little experienced with vertices yet so I don't quite get why it isn't becoming a square

maiden turtle
#

Unity uses clockwise culling order

#

So you want your triangles to go clockwise

median cosmos
#

well it's going from left top back to right

maiden turtle
#

Did you generate the mesh manually?

median cosmos
#

so it's kinda clockwise

median cosmos
#

it's in Update()

#

so I can see the changes in realtime

maiden turtle
#

So do you have 4 indices in total?

#

hold on

#

no you got just 3

median cosmos
#

I have 4 vertices

long ivy
#

you only have one triangle defined

maiden turtle
#

4 / 3 = 1

#

1 * 3 = 3

median cosmos
#

yep

maiden turtle
#

So you only have 1 triangle

median cosmos
#

no 3

median cosmos
maiden turtle
#

a triangle is 3 vertices

#

3 indices

median cosmos
#

I made it so it automatically adapts to the vertices

maiden turtle
#

the first triangle should be the first 3 vertices

median cosmos
#

yes?

maiden turtle
#

and the second triangle should the vertices 2, 4 and 3

median cosmos
#

hold on

maiden turtle
#

(depends on how you arrange them)

median cosmos
#

I know but why in that order?

maiden turtle
#

0, 1, 2

#

1, 3, 2

#

are going to be the triangles in this case

median cosmos
#

yes

maiden turtle
#

if you do 1, 2, 3 it would go counterclockwise

novel wing
#

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)

median cosmos
maiden turtle
median cosmos
#

like clockwise isn't 1, 3, 2?

#

top right, bottom, left

#

so clockwise?

maiden turtle
#

it should be clockwise, yes

#

otherwise you'd see the face from the back instead

median cosmos
#

but why is 1, 2, 3 clockwise?

maiden turtle
#

but from the front it would get culled

novel wing
#

he never said that

#

"if you do 1, 2, 3 it would go counterclockwise"

median cosmos
#

ups

#

I misread that my fault

maiden turtle
#

Do Awake's run on disabled objects?

median cosmos
#

awake is called whenever the script is beeing loaded in

maiden turtle
#

"loaded in" is vague

median cosmos
#

hold on a sec

#
  1. When the gameObject is beeing enabled
#
  1. When the script is being enabled
novel wing
#

If it's disabled then no, it's not called

median cosmos
#
  1. When the scene is being loaded with a non-static object
median cosmos
maiden turtle
#

Instantiating a gameobject does not run its Awake immediately, right? It waits until the next frame

novel wing
#

It's immediate if it's enabled

maiden turtle
#

aah, ok, then disabling it after instantiating it should do what I want

median cosmos
#

I still don't quite get why mine isn't clockwise

maiden turtle
#

You only put 3 indices into there

median cosmos
#

ohh wait a sec

maiden turtle
#

While it should be 3 per triangle

#

so 6 in total

median cosmos
# median cosmos

so when the vectors.Count /3 * 3 is becoming 3, it means it hast only one triangle?

novel wing
maiden turtle
#

Yes, that's fine

novel wing
#

You can instantiate disabled prefabs, then it will do nothing until enabled

#

Ah okay

maiden turtle
#

I don't want any Updates to run

#

Awakes running is something I actually want

novel wing
#

Yeah basically this is the order:

Instantiate()
-> Awake
-> your code continues
-> (next frame) Start is called if the object is enabled

maiden turtle
#

Oh so start is not affected, hmm

#

I guess that's still fine tho

median cosmos
#

still not a square

novel wing
median cosmos
maiden turtle
#

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

novel wing
#

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;
median cosmos
maiden turtle
#

yes

median cosmos
#

exactly

novel wing
#

Also I'm confused on your Elemet2 of Vector array

#

It's got 3 axis worth of values, but your others only have 2

median cosmos
#

so if I want a full "cube" I want 8 vertices right?

#

but then I can only have 3 6 triangles?

maiden turtle
#

because otherwise the normals will be wrong

novel wing
#

and you will need 6(faces) * 2(triangles) * 3(indices per triangle) indices

median cosmos
#

what are indices anyway?

novel wing
#

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

maiden turtle
novel wing
#

then it's just "vertex 0, 3, 5" makes a triangle, then repeat for all triangles

median cosmos
#

why is it in this oder?

#

and not 0.0f etc. in the second line?

median cosmos
#

ohhhh wait

#

I think I get it now

novel wing
#

Mine for instance has a "origin" in the middle as it's easier for me to use, for my use case.

median cosmos
#

only 3 vertices can be connected, not 4 or, 5?

maiden turtle
novel wing
#

GPU can only ever draw a triangle

median cosmos
#

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

novel plinth
#

flipped normals?

median cosmos
#

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

#

?

novel wing
#

You're giving the indices in wrong order, or not at all

median cosmos
novel wing
#

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.

median cosmos
#

ohhh

novel wing
#

For even more clarity, the indices array is just a reference to which vertex it will use:

median cosmos
#

so the vertices are for the hole cube, not for every side?

#

no wait

#

for every side right?

novel wing
#

yes the vertices is your entire mesh, in this case the entire cube

#

defined as points

median cosmos
#

but a cube has 8 vertices

orchid marsh
#

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.

novel wing
#

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.

median cosmos
#

and the indices are for each side?

#

or for the whole mesh, too?

novel wing
#

the whole mesh

#

so if you have 24 vertices some of the indices will need to refer to vertex 22, 23, 24 etc

median cosmos
#

oh wait

#

so the indices are basically the sides?

#

I'm kinda confused

novel wing
#

indices are simply which vertex to use for drawing a triangle

#

3 indices make a triangle

orchid marsh
# median cosmos why is it drawn like this?

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.

novel wing
median cosmos
#

so what do I need to write into each draw() function (each side)?

novel wing
novel wing
#

then it's just a matter of repeating it to the other sides

median cosmos
#

but what should I do with the indices exactly?

#

like programmatically?

novel wing
#

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

median cosmos
#

got it

#

finished with that soon

#

alright now it looks like this

novel wing
#

Okay, now you probably have what Dalphat menitoned, are the missing sides being renderer inside instead?

median cosmos
#

?

novel wing
#

If you move the camera inside of the cube, can you see the missing faces then?

#

Is it inside out basically?

median cosmos
median cosmos
#

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

alpine adder
#

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

winged mirage
amber vale
alpine adder
#

how does heap vs static memory play a part in singleton vs static?

amber vale
#

I'm not sure i understand your question.. Static members should in fact be in the heap

tough tulip
#

Singleton instance can also be passed as object. You cant do that with static

prisma mortar
#

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

▶ Play video
umbral trail
#

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

prisma mortar
#

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

light thistle
#

any1 have any clue to how to smooth client side movement in a online game

winter yacht
# light thistle 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/

winter yacht
light thistle
winter yacht
light thistle
winter yacht
wintry dragon
#

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?

broken socket
# prisma mortar Hello i have the following problem: i want to make 1000+ scriptableobjects, obj...

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

hollow cedar
#

Someone knows how to do VR movement without VR?

#

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

undone coral
#

it takes a lot of fiddling. there is no out of the box demo ready from unity

undone coral
undone coral
#

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.

undone coral
light thistle
light thistle
tough tulip
undone coral
light thistle
undone coral
light thistle
undone coral
# light thistle 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

cedar ledge
#

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>();
finite yew
#

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

undone coral
still sigil
#

Gotta ask this but if you make such a big game can it literally crash unity?

sly grove
#

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

frank peak
#

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

sly grove
frank peak
#

it did for me 😬

sly grove
#

I guess it depends if it's a stack overflow in the engine or in the C# scripting module

frank peak
#

ah i see

sly grove
#

which can get fuzzy if you're doing things like using UNityEvents on a Toggle

frank peak
#

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)

sly grove
#

but like this won't crash:

public int MyProp => MyProp;```
#

but will cause a purely C# stack overflow

frank peak
#

🤔 interesting

sly grove
#

Yep just tested that

#

at least in the editor it won't - dunno if that's true in all cases

frank peak
#

makes sense

gilded wing
#

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

novel wing
#

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

gilded wing
#

ah good point, yeah that's moot for me in my single person hobbyist operation

novel wing
#

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

gilded wing
#

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

gilded wing
#

ok, thanks!

languid isle
#

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

drifting galleon
#

simply benchmark it

untold moth
languid isle
#

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

untold moth
languid isle
#

😮 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

fresh salmon
#

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

untold moth
#

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.

languid isle
#

Ok thank you 😄

static reef
#

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?

regal olive
#

how do one reference a list in another script

drifting galleon
untold moth
drifting galleon
untold moth
#

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.

drifting galleon
untold moth
#

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.

drifting galleon
sage radish
drifting galleon
sage radish
#

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.

drifting galleon
sage radish
drifting galleon
#

if you put them in an array, this is possible

untold moth
drifting galleon
sage radish
drifting galleon
untold moth
sage radish
# drifting galleon not if you initialize the array

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?

drifting galleon
untold moth
#

I thought we were talking about a 3d array

#

not jagged array

drifting galleon
untold moth
#

int[x,y,z]

#

They definitely said "3 dimensional arraylist". Although go figure what they meant by that.

regal olive
#

im trying to reference a list in another script

#

i just tried a script and it didnt work

drifting galleon
#

is at least how i understood it 3-dimensional-array list (although if list or array is unimportant, the same under the hood anyway)

regal olive
#

bt the same script worked for someone else

#

why

#

then

#

is it not working

#

is this an issue with unity

fresh salmon
#

Not sure this is advanced issue

#

Why are you cross-posting

regal olive
fresh salmon
#

That doesn't mean it's advanced

regal olive
fresh salmon
#

Something in your code fails, debug it

drifting galleon
regal olive
#
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

sage radish
# drifting galleon not if you initialize the array

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?

drifting galleon
regal olive
#

its not working for me though

austere jewel
regal olive
drifting galleon
regal olive
#

i have checked this script 10 times

austere jewel
#

A null reference exception is one of the most basic issues you can run into.

regal olive
#

i have 500% sure there is nothing wrong with this script

regal olive
#

bc the exact same script worked for someone else

fresh salmon
sage radish
regal olive
regal olive
#

i am going to set this script now
word for word

drifting galleon
#

bruh indeed

regal olive
austere jewel
#

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

thorn flintBOT
#

dynoSuccess 𝕓𝕣𝕦𝕙#4755 was muted

sinful pecan
#

well you also need to make sure the references are actually referencing something, just the script alone won't do that

#

nvm LUL

drifting galleon
plush lion
#

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

austere jewel
#

You cannot intercept alt-f4

drifting galleon
austere jewel
drifting galleon
gilded wing
#

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?

plush lion
#

It's fine if I don't intercept alt f4, I just thought the two came together

gilded wing
#

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

austere jewel
#

Not sure about URP

gilded wing
#

i'm not using either and aren't far enough along the project to commit

austere jewel
#

ah, sorry. Yeah I haven't used the built-in pipeline in forever, so I can't say

feral lake
#

can anyone help me find the best multiplayer networking for free

quiet bolt
#

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

quiet bolt
feral lake
#

I tried but the Instantiate function just returned a NullException

#

how do I fix the nullException

austere jewel
steep robin
#

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?

quiet bolt
austere jewel
plush lion
steep robin
austere jewel
drifting galleon
austere jewel
quiet bolt
#

ahh i see

plush lion
quiet bolt
#

hmm true true. what about asserts though?

drifting galleon
plush lion
#

Weird

austere jewel
#

It works for me. 2022.1

quiet bolt
#

hmm i guess so

#

well then, atleast i know something new, thanks!

agile yoke
#

Fwiw, the LogType Exception probably just corresponds to Debug.LogException

sinful pecan
#

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

kindred tusk
sinful pecan
#

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

kindred tusk
#

Is it just the "recalculate normals" call that is expensive?

sinful pecan
#

not just that but it's a big chunk

kindred tusk
#

Well one thing that sticks out is that it seems that you have too many vertices

#

Are these black pixels all edges?

sinful pecan
#

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

kindred tusk
#

Probably won't solve your whole problem, but if you can simplify the flat areas it should help ease the problem

sinful pecan
#

the main problem is definitely that it redraws the whole thing instead of just what's "needed", the geometry is still relatively low-poly

kindred tusk
#

Other than that splitting it into chunks like you said should help ease frame delay.

sinful pecan
#

i'll make a quick vid with randomization on, that should make it more clear

kindred tusk
#

I think you were right the first time, the solution is likely chunking based on what's on or nearby the screen.

sinful pecan
#

yeah i'll probably try that first and see if i can squeeze the load down enough

kindred tusk
#

oh yes I understand!

#

Looks great btw

sinful pecan
#

thanks!

kindred tusk
#

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.

sinful pecan
#

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];
kindred tusk
sinful pecan
#

let me make sure that's what it is, but i think so

kindred tusk
#

Hm, this is annoying. It seems you can't provide a vertex count

sinful pecan
#

to be fair it's 108 verts per tile, so it would be allocating quite a bit of memory

kindred tusk
#

oh wiat!

#

Here we go

#

Try this

sinful pecan
#

hah maybe i should cache the entire map as vertex/uv data

kindred tusk
#

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

sinful pecan
#

oh let me try that, thanks

kindred tusk
#

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.

sinful pecan
#

yeah i'm trying to use arrays as much as i can

kindred tusk
#

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

sinful pecan
#

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

kindred tusk
#

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.

sinful pecan
#

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

kindred tusk
#

Sure, well you can always scatter geometry on top.

sinful pecan
#

at least i managed to keep the object count low, maybe to a fault haha

kindred tusk
#

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

kindred tusk
sinful pecan
#

yeah, that's why i was doing the culling manually

#

oh, i could also consider calculating normals beforehand

kindred tusk
#

Yeah, I thought of that too.

sinful pecan
#

since i'm doing hard edge low poly style anyway, so normals are always the same relationship to the face

kindred tusk
#

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

maiden gull
#

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 ?

kindred tusk
#

Hm, actually maybe this is some android thing I'm not aware of, nvm.

maiden gull
quartz stratus
quartz stratus
# maiden gull Do I need to write a IOS / android plugin in 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);
        }
    }
maiden gull
#

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

quartz stratus
quartz stratus
maiden gull
#

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?

maiden gull
#

If I do create a library in unity with this function with an empty body, can he override it on his side?

quartz stratus
quartz stratus
maiden gull
#

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)

alpine adder
#

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

frank peak
#

a singleton isnt a bad idea if you only need a single, easily accesible instance

#

helps coordinate actions across that system

soft hawk
#

does the api manager need to remember anything? if no, you can make it a static

alpine adder
#

it does not remember anything

frank peak
#

there ya go

alpine adder
#

just pure methods

soft hawk
#

That's generally the question I ask when I'm trying to decide if I can make something static

alpine adder
#

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

soft hawk
#

I also suffer from that problem

frank peak
#

ye same

#

i used singletons and still question if im making an antipattern or w/e

alpine adder
#

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

frank peak
#

hmm i wonder eh, idk

#

its mostly coroutines too eh?

alpine adder
#

its all coroutines

#

basically think usermanager.getuserprofile

#

or usermanager.updateuserprofile

#

etc

soft hawk
#

Wait so its a Monobehavior?

alpine adder
#

it is not

#

userclient.getuserprofile

#

i mean

midnight violet
#

It inherits from mono then because of coroutines?

alpine adder
#

so the monobehaviour class calls startcoroutine(useclient.getuserprofile)

#

this is just a pure class that holds the methods

soft hawk
#

I might be wrong but I thought the class containing the coroutine has to inherit monobehavior

midnight violet
#

Oh okay, you use the class as palceholder mono for your static

alpine adder
#

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

midnight violet
#

Your question was, if API Manager should be static?

alpine adder
#

basically

#

it does not inheret nor need a monobheviour either

#

forgive the spelling

midnight violet
#

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

soft hawk
#

So I guess my previous statement is wrong. I don't know why I thought that?

alpine adder
#

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

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

alpine adder
#

😄

#

love to hear it

soft hawk
#

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

alpine adder
#

what do you mean by waits?

soft hawk
#

WaitForSeconds()

alpine adder
#

you can do a yield return for the method

soft hawk
#

No i mean

#

here lemme show you

alpine adder
#

additionally there is a pattern thats equivalent to like a promies.all

soft hawk
#
    {
        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;
    }
undone coral
#

@soft hawk what is your objective?

#

FindAllMegaBlocks();
this is an IEnumerator FindAllMegaBlocks() ?

soft hawk
#

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

undone coral
#

StartCoroutine(MethodReturningIEnumerator()) does not wait
yield return StartCoroutine(MethodReturningIEnumerator()) waits for the coroutine MethodReturningIEnumerator to finish

soft hawk
#

Right I get that, but if I just had a call to
EvaluateBoardCoroutine()

undone coral
#

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

soft hawk
#

Oh ok

undone coral
soft hawk
#

Got it, thanks

ruby hare
#

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

soft hawk
#

Are async operations still unsupported in WebGL builds?

flint sage
#

TAP or other async calls

soft hawk
#

I guess it doesn't really matter cause I probably need to use the jobs system

finite yew
undone coral
#

read the docs for PointerEventData

undone coral
#

what are you trying to do?

#

what is _wait

#

async / await works in WebGL

#

it works on every platform

soft hawk
#

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

undone coral
#

okay

soft hawk
#

Current search depth is 4

undone coral
#

did we discuss your game already? this is a puzzle fighter game right?

soft hawk
#

Yes, it is

undone coral
#

and you're trying to write the conventional bot?

soft hawk
#

I have the conventional bot, its just synchronous, finds a best move everytime a piece is called

undone coral
#

cool

#

and you want it to be faster

soft hawk
#

but its only able to go about 4 deep without major slowdown

undone coral
#

got it

soft hawk
#

So i'd like to make it asynchronous and build a queue of moves

undone coral
#

okay

soft hawk
#

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

undone coral
#

when you say trained agent

#

you mean a different AI

soft hawk
#

yes

undone coral
#

okay

soft hawk
#

ML-Agents

undone coral
#

okay

#

so your conventional bot should have something of the form

soft hawk
#

There are three main parts: Move generation, Move Evaluation, and then pathfinding. That part is simple

undone coral
#
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?

soft hawk
#

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

undone coral
#

you only expand the game state with the best score

#

instead of expanding them all

soft hawk
#

right, does it matter that evaluating the gamestate (getting a score) is destructive?

undone coral
#

which will turn your thing from (moves ^ depth) to (moves * depth)

undone coral
soft hawk
#

well I can always make a copy of the board

undone coral
#

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

soft hawk
#

So right now my board is a class with a Block[] array

#

But I could just make the block array a struct

undone coral
#

it has to be a fixed array and you should use unsafe

#

you will see this online

soft hawk
#

Ok i think I get that

undone coral
#

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

soft hawk
#

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

undone coral
#

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?

soft hawk
#

Not sure what solvable means in this regard, since its an adversarial game

#

Right now im just using score as a heuristic for success

undone coral
#

does anyone know

#

if on vulkan, it is expected that resizing a render texture DOES NOT change its native texture pointer?

heady pilot
#

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

soft hawk
#

@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

undone coral
#

i.e., a game state

soft hawk
#

Right, ya

undone coral
#

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

#

burst speeds up your thing, jobs can make it parallelized

#

"Burst supports fixed array fields."

soft hawk
#

yea

undone coral
#

there is a ton of noise on google

#

re: copying structs with fixed array fields

soft hawk
#

ok but I can have a fixed array of structs, right?

undone coral
soft hawk
#

yea

#

Ok, I know what Im workin on tonight lol

#

4th iteration of this game now

#

learning a bit more every time

undone coral
#

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

soft hawk
#

the reason i went for classes at first was i figured shallow copy would be faster than even an optimized deep copy

undone coral
soft hawk
#

cause right now im just cloning an array of reference types

undone coral
#

for bot writing purposes

soft hawk
#

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

undone coral
#

@soft hawk parallelize first

#

make your bot look like mine

soft hawk
#

roger

undone coral
#

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

soft hawk
#

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

soft hawk
#

But I can make a native array of structs so i guess I do that? im very confused about all this stuff

undone coral
green rock
#

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

austere jewel
#

Not possible

#

Create a component that handles that with callbacks instead

green rock
#

that's sad. alright thanks!

bold mountain
#

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;
        }
    }
}
frank ferry
#

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.

serene girder
#

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.

compact ingot
serene girder
compact ingot
granite viper
#

this is why I always work with a grid size of 1

serene girder
#

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

granite viper
#

it's probably getting rounded for display

#

and is actually just under 3.2

compact ingot
#

in any case your grid code should never require an exact float-value

serene girder
#

I guess I will just use Mathf.floortoint

granite viper
#

that won't change anything 🤔

serene girder
#

ah right, hmm

compact ingot
#

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

sly grove
#

same way 1/3 cannot be represented in decimal with a finite number of digits

compact ingot
#

yes, but as you see in the calculation the error when assigning 0.64 corrects it and you get a perfect 5

serene girder
#

well if 3.2 is like 3.200000005

granite viper
#

I think the point is that it has to be less than 3.2 to cause a result of 4

sly grove
#

interesting

granite viper
#

that's where the error comes in

serene girder
#

it should round down to 5 when divided by .64

granite viper
#

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

serene girder
#

yeah but now im trying to figure out why

granite viper
#

float error?

#

why else

#

not really much of a mystery

compact ingot
#

because your transform.x is not a perfect 3.2

granite viper
#

what are you doing where it matters this much that it's exactly 3.2

austere jewel
compact ingot
#

it was said before, your code is inherently flawed if you need exact float values

austere jewel
granite viper
#

I like that 2d graph @austere jewel

#

that's fun

sly grove
#

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

granite viper
#

or just use a grid size of 1 like me

crisp narwhal
#

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?

serene girder
#

@sly grove I am getting the world pos and need to convert it, I will think of a better way to do it

regal olive
#

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!

quartz stratus
# regal olive Hi everyone! I'd like to create a prefab that when dragged into the hierarchy, t...

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!

quartz stratus
regal olive
serene girder
#

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

unique ermine
#

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?

https://i.gyazo.com/3146b947a3a4784e33bbc04c4c94eaf7.mp4

midnight violet
sly grove
#

Yep - do you have an OnBecameInvisible thing going on?

midnight violet
#

If you want to test occlusion culling for example, you gotta turn off sceneview to get legit results

unique ermine
#

I had the same results in my build

undone coral
sly grove
unique ermine