#archived-code-advanced

1 messages · Page 137 of 1

kindred tusk
#

In your case you'll just be flipping bits in a mask

#

How far is your vision?

#

Infinite?

lavish epoch
#

I don't understand
in my case I am spawning particles

kindred tusk
#

Oh sorry I thought you were generating a field of view

#

Oh you are

lavish epoch
#

vision of around 20 tiles should cover the screen

kindred tusk
#

Okay, do all you do is spawn a particle in every square that isn't visible

#

And you have to detect which are visible

#

The particles thing isn't really relevant

lavish epoch
#

No, raycasting to all tiles too expensive

kindred tusk
#

So just do the perimeter?

lavish epoch
#

I cast from all walls and spawn particles at the points

lavish epoch
kindred tusk
#

I don't know what the particles are

lavish epoch
#

1x1 squares

kindred tusk
#

But what do particles have to do with fov?

#

Oh, I get it!

#

Yep I understand

#

So yeah, forget that approach, it's inherently flawed

#

What you want is to have a grid of all tiles, and know which are visible

#

Once you have that you can spawn a particle on every tile that is invisible

#

That's fairly straight forward

lavish epoch
#

Cast from player to walls all points = visible and fill rest?

kindred tusk
#

In my game (which is not tile based) I do 120 casts every frame

#

Radially

#

And that's enough

#

For my particular thing

#

You could say... cast to every tile in a ring around the player that is of radius 10

kindred tusk
#

Or radius 5

#

Yeah and then you need to turn that into triangles

lavish epoch
#

triangles?

kindred tusk
#

Draw a line around the edge, connecting the point of each ray

#

The area contained is your vision

lavish epoch
#

And then what?

kindred tusk
#

Then spawn particles on every square that is not within that area

#

It's a bit involved

#

I would research roguelike tutorials, I'm not sure that my method translates to a grid perfectly

lavish epoch
#

I'm gonna look around in reddit post u sent

kindred tusk
#

I reckon this is your guy

lavish epoch
#

ok

kindred tusk
#

There is also a roguelike dev discord that's pretty good

lavish epoch
#

oh god

kindred tusk
#

Yeah it's hectic

#

It's a tough problem

#

I swear I've seen this method explained in a way that seemed simple, but it was ages ago

#

There is the page of techniques

#

You could probably find YouTube videos on it

#

Gtg, good luck

compact ingot
# lavish epoch oh god

You can make a mesh of all your walls … extrude them very high. Make them render black… Put a camera directly above your player, looking at it… this camera will then render a mask of your LOS…. Check Ape out or teleglitch for how it looks… this is effectively shadow casting… but through a special case of perspective projection that is almost free

#

You can also render to a render texture and map the pixels to your tiles… you can then even compose multiple such RTs to have multiple ‘eyes’ eg to reveal stuff temporarily etc.

hushed aurora
#

Hello, i have rig builder that have many rigs in layers but all layers are inactive. Why rigbuilder affect my animations even when there is no layer active? animations are speeded up and sometimes (like every 3 seconds) break and for few frames it looks like every bone is twisted. When i disable rigbuilder in runtime everything looks fine

mild laurel
#

I can not find the problem...

#

(29,34): error CS1002: ; expected

#

but I do not know what is the problem, I know ";" but where...

cursive horizon
#

and maybe a closing one? basically it thinks you need a ; because it's confused about how many blocks you have there

shadow seal
#

Maybe it's the capital I?

cursive horizon
#

oh wow

#

also that

mild laurel
#

look "(27,34): error CS1002: ; expected"

sly grove
vestal heath
river musk
#

Using MLAPI, I need to take hosts mapseed INT and give to client before he loads game, how do I do this?

#

Maybe call an RPC and if host, then for each client give the mapseed? then load game.

shadow seal
#

Yeah you'll need to use an RPC for this

river musk
#

ok, thank you 🙂

dense pecan
#

What is the damn shortcut for changing a method name throughout a script?

shadow seal
#

Try and stick to one channel, rather than three

dense aspen
#

@dense pecancontrol f, enter name, and replace all?

#

idk

dense pecan
#

I thought there was a way to select all the same text in a script then as you typed/edit it changed them all at once

dense aspen
#

if you are using visual studio, after changing a method name, there should be a wrench icon next to the line number

hard lily
#

I already replied to you in the other thread

dense pecan
#

That did not work

dense aspen
#

that's why crossposting is not allowed

hot gale
#

does anyone know if there is any way to get a reference to a Function, or MonoBehaviour, or something; so that I can have different abilities per character? I am storing my character's stats in Scriptable Objects and want to have different abilities per character. I'm using a script inheritance/override system for each characters abilities;

public class AssaultRecruit : OperativeBase
{
    public override void Ability()
    {
        return;
    }
}
#

I'm not sure how I'd call the Ability from the player either, to be fair.

#

Ideally, i'd be able to set the function like you can with the OnClick section or OnUpdate function of a slider

hot gale
#

cheers 🙂

frail dock
#

I want to execute some code on a separate thread but it's a situation where more work might be triggered and I want it to execute right after the initial work so they are executed in order, it's doesn't all have to be in the separate threads but it does need to be in a separate thread from main and execute in order

#

I looked at Join(), but I'm a bit confused how to sync them up if the first thread finished already

hushed fable
#

Jobs might have more of this kind of control flow built in

frail dock
#

I'm really not sure how to implement this with jobs since it's not touching unity at all

untold moth
#

What does it touch then?

frail dock
#

As far as i see jobs are about updating unity components

frail dock
untold moth
#

Jobs are just generating data.

#

Wether you apply it to components later on is up to you.

frail dock
#

hmm okay then i misunderstood how jobs work, i'll look further into it

#

does anyone have good examples of the job system for generating some data with multiple jobs?

modest lintel
#

..what kind of data?

frail dock
#
new Dictionary<string, Dictionary<int, List<Vector2>>>();
modest lintel
#

What is it actually? I don't have a lot of experience with jobs but I doubt you'd be able to generate and populate such a complex data type without banging some heads

frail dock
#

the data is already being generated and being populated but assigning it can take a long time, so i have to schedule it all somehow, the list contains collision paths to be assigned to a Polygon Collider 2D

#

so it has to be something like

#

Generate Collider data 1
Generate Collider data 2
if both done then assign collider data to Polygon Collider 2D

#

if not then wait for all Generation to finish and then assign the data

#

looks like this

#

basically every time you place a block all collision is recalculated for that chunk and then assigned to the polygon collider 2d for that chunk

tropic lake
frail dock
#

1000000x slower

#

it literally took minutes to generate and assign all the collider data where as this takes 10 miliseconds

tropic lake
#

oh ok

frail dock
#

i have a video of how slow this is 😄

tough tulip
frail dock
tough tulip
#

spawning a new thread is very expensive and a new thread is not at all faster than the main thread unless you're using the other thread for I/O in which cpu is mostly idle or is waiting for signals from some other hardware

frail dock
#

or just start more work on the same thread? 🤔

tough tulip
#
static AutoResetEvent as = new AutoResetEvent();
static bool isRunning = true;
void Awake() 
{
    new Thread(DoWork).Start() ;
}

static void DoWork() 
{
     while(isRunning)
     {
           as.WaitOne();
           if(isRunning) 
               Debug.Log("Print from thread");
     }
}

void Update() 
{
    if(Input.GetKeyDown(KeyCode.K)) as.Set();
}

void OnApplicationQuit() //gracefully end the thread when application is trying to quit
{
    isRunning = false;
    as.Set();
}

#

written from mobile, there maybe some syntax issues but you get the basic idea of it

frail dock
#

not sure what you're doing with the AutoResetEvent, but i think I get the basic gist of it, you're just keeping it alive with a while loop and using that loop to poll for work

tough tulip
#

AutoResetEvent is used for signalling. Until you call Set function your thread is blocked at that line

frail dock
#

ohh really 🤔

#

yeah thats very useful then

tough tulip
#

There's an alternative ManualResetEvent which does similar work but has some difference in how the signalling works. Read more about it from ms docs

frail dock
#

okay, that makes sense, ty

compact ingot
# frail dock I looked at Join(), but I'm a bit confused how to sync them up if the first thre...

why not use async ... await for synchronization and combinations of await Task.WhenAny(a, b, c) and await Task.WhenAll(a, b, c) to join. Threads will be created on the thread pool and thread reuse is no issue... you can create a simple main thread callback by pushing callback actions into a ConcurrentQueue<Action> and popping items off in Update().... using signalling primitives is usually much more prone to concurrency bugs that that are a PITA to debug. Depending on your use case, i.e. if you want performance (full IA level optimization)... IJob is the only real ticket and I wouldn't bother with C# stuff for anything but scheduling & sync.

ivory prawn
#

I want to generate a direction vector that points to a random point on a (northern) hemisphere around a point. I could do a random vector like x(-1,1) y(0,1) and z(-1,1) but I'm worried it won't produce an equal spread. And I don't really know how to figure it out. Is there anyone who knows a good way?

severe grove
#

Why I try to reference an action this way it is returning null. Any ideas what I am doing wrong here? ```
public enum EffectID
{
none,
damage,
changeSTR,
healByPercent,
healByValue
}

public class EffectDB
{
public static Dictionary<EffectID, Action<Effect, Character>> effects =
new Dictionary<EffectID, Action<Effect, Character>>()
{
{EffectID.none, None},
{EffectID.damage, Damage},
{EffectID.changeSTR, ChangeSTR},
{EffectID.healByPercent, HealByPercent},
{EffectID.healByValue, HealByValue},
};

private static Action<Effect, Character> None = (effect, character) =>
{
    return;
};

private static Action<Effect, Character> Damage = (effect, character) =>
{
    float value = Mathf.Floor(effect.Power * UnityEngine.Random.Range(.8f, 1f));
    value += Mathf.Floor(value * (GameData.source.GetDerivedStat(effect.Base.scalingType) * .1f));
    value = character.CheckProtection(value, effect.Base.damageType);

    if (value != 0)
    {
        if(effect.Base.hideInUI)
        {
            GameEvents.OnGenerateDialog(DialogType.combat,
                $"{GameData.source.CharacterName} dealt " +
                $"{value} {effect.Base.damageType} damage to {character.CharacterName}.");
        }
        else
        {
            GameEvents.OnGenerateDialog(DialogType.combat,
                $"{effect.Base.effectName} dealt " +
                $"{value} {effect.Base.damageType} damage to {character.CharacterName}.");
        }


        character.ChangeHP(-value);
    }
};```
compact ingot
severe grove
#

if I just declare them like this in the dictionary instead of referencing an action they work though ()=>

#

changing the variables to public changes nothing.

ivory prawn
ivory prawn
hallow cove
#

I'm asking this again since I don't know how to do it

#

I have a class that holds a item scriptable object, an int for the amount of that item, and a string

#

I wanna be able to save these with a binary formatter

#

you can't serialize scriptable objects tho

#

and people say I should make an item database

#

but I don't know how to make that work with the class I mentioned before

frail dock
hallow cove
#
    public class ItemSlot
    {
        public Item item;
        public int amount;
        public string scene;
    }```
#

should I just somehow save the id of an item and then save the int and string separately?

#
    public class ItemSlot
    {
        public int itemId;
        public int amount;
        public string scene;
    }```
#

like so?

tropic lake
#

for each scriptable object for an item, assign it either an int or a string as an identifier, then have a dictionary of type <int, Item>

#

then yeah do that class it would be able to be serialized

hallow cove
#

and then I can just get the id from a database using that int

#

I'm using this during runtime tho

#

so I would have to get the item id a lot

#

is that performant?

tropic lake
#

you can do it once in Awake and make another class that has Item instead of int

#

then pass it in this serializable class to construct from

hallow cove
#

oh

#

uhh

#

is this good?

#

idfk I'm tired

#

wait I need to make it an int

tropic lake
# hallow cove

in your ItemSlot class, have a constructor like

void ItemSlot(SerializableItemSlot data)
{
    item = database[data.itemInt];
    amount = data.amount;
    scene = data.scene;
}
hallow cove
#

alright!

tropic lake
#

then call that in Awake like
ItemSlot thisSlot = new ItemSlot(theSerializableItem)

hallow cove
#

I'm getting an error

tropic lake
#

database would be the name of your dictionary

#

and your itemInt is what you called the int that stored the id in the serializable class

hallow cove
#

how would I make the database

#

I've never had to make them

#

can I make a scriptable object a singleton?

#

that's what I did

#

I'm still getting an error on ItemSlot

tropic lake
tropic lake
hallow cove
tropic lake
#

i told you, database isn't defined you need to make a dictionary for it

#

and i don't know what you've named your itemId in your serializable class

hallow cove
#

ok I get that but like, how do I make the database

#

how do I make it so I can just drag in all the items in the editor

#

it has a dictionary and everything

#

but idk what it should be

tropic lake
#

you'd need a serializable dictionary which can appear in the editor

#

i don't know of any off the top of my head but you can search for one

#

or you can have normal SO fields and list out the dictionary manually

hallow cove
#
using UnityEngine;

[CreateAssetMenu(fileName = "New Item Database", menuName = "Inventory/Item Database")]
public class ItemDatabase : ScriptableObject, ISerializationCallbackReceiver
{
    public Item[] items;
    public Dictionary<Item, int> GetId = new Dictionary<Item, int>();
    
    public void OnBeforeSerialize()
    {
        GetId = new Dictionary<Item, int>();
        for (int i = 0; i < items.Length; i++)
        {
            GetId.Add(items[i], i);
        }
    }

    public void OnAfterDeserialize()
    {
        
    }
}
#

I found this online

#

I could just make the dictionary serializedDictionary but yeah

#

I was thinking of having something like this

tropic lake
#

an array?

hallow cove
#

yes

#

that holds all the items

tropic lake
#

yeah then refer to the items with their index

hallow cove
#

so I don't need a dictionary then?

#

later on I could probably make it get all the items from the resources folder

tropic lake
hallow cove
#

wait wait wait

#

can I make the scriptable object a singleton?

tropic lake
#

yes you could

#

but in that case you can't make more than one of the SO

hallow cove
#

I know

#

that's all I need

#

but I still don't understand why this is marked as an error

tropic lake
#

what does the error say?

hallow cove
#

member names cannot be the same as their enclosing type

#

yeah ok

tropic lake
hallow cove
#

bruhhhhhhh

#

right

tropic lake
#

forgot how to make a constructor

#

and you'd want it Public i think

hallow cove
#

Inventory.ItemSlot itemSlot = new Inventory.ItemSlot(new Inventory.SerializableItemSlot { itemId = ItemDatabase.instance.GetId[itemSlotToDrop.item], amount = 1, scene = SceneManager.GetActiveScene().name });

#

well that just turned into a monstrosity

hallow cove
#

and now if I wanna save them?

#

do I give the serializable item slot class?

austere sundial
#

Q: How can I check system processes from android build while on emulator?

tropic lake
hallow cove
#

and when I wanna load the data?

#

cause now they're different types

#

I wanna set the list of items be equal to the list of serializable items

tropic lake
#

you make a new ItemSlot with the argument of the serializable class

hallow cove
#

kinda like this?

#

wait no

#

like this and then add the variables there?

tropic lake
#

yes but not making a new serializable class but loading it from data

#

you would load the serializable class

#

then pass it into the ItemSlot constructor

hallow cove
#

uhhhhhhhhhhh

#

like that?

tropic lake
#

yeah

hallow cove
#

great

#

so

#

that should be done?

tropic lake
#

well test it out

hallow cove
#

here is the item database

#

just in case anything is wrong?

tropic lake
#

it looks fine to me you just don't need the GetId dictionary anymore

#

what are you using that for

hallow cove
#

uhhh

#

this

#

here I wanna add a new item with the amount of just one

#

Constructor 'ItemSlot' has 1 parameter(s) but is invoked with 0 argument(s)

tropic lake
#

you need brackets?

hallow cove
#

uhh

#

I need to give that itemSlot but I need the amount to only be one

tropic lake
#

you use () for passing in arguments

#

not {}

hallow cove
#

but how do I overwrite the amount?

#

to be 1?

tropic lake
#

or you can make another constructor for ItemSlot

#
//not real code
ItemSlot(Serializable data, int overrideAmount)
{
  //same as before
  amount = overrideAmount;
}
hallow cove
#

uhhhhhhh

#

damn I'm dumb

tropic lake
#

yeah that works as well

hallow cove
#

it doesn't

tropic lake
#

you need ()

#

not {}

hallow cove
#

OHHHHHH

#

I SEE-

tropic lake
#

and you don't need to do item = ... if your arguments are in the same order as in the constructor

hallow cove
#

yeah

#

I figured

#

oh

#

the constructor for playerdata is the last error

tropic lake
#

what does it say

hallow cove
#

one is itemslot and other is serializableitemslot

tropic lake
#

then change the type?

#

of savedata's itemList

#

or is it that you need to serialize the data

hallow cove
#

this constructor gets the data from a monobehaviour of playerdata

#

and it takes that in as data to save

tropic lake
#

itemList.indexOf()

#

to get the itemId

#

and i think you need to make a constructor for serializable data?

hallow cove
#

how do I write that line

tropic lake
#

like for the non serializable but the other way round

hallow cove
#

uhh

#

I just need to convert the serializable data to non serializable

#

like, make it equal to

tropic lake
#

you want to serialize the data

#

in order for it to be able to be saved

hallow cove
#

there

tropic lake
#

because if not then the index you passed in won't refer to the right index of the database list

hallow cove
#

it's an array of items

#

so no

#

itemList is a list of itemSlots

#

I also have class, can we wait 10 - 20 minutes or so?

tropic lake
#

to get the index of that item

tropic lake
hallow cove
#

alright!

#

can we call or something after?

#

it'd be easier to just share my screen

untold moth
#

@frail dock Did you manage to solve your issue?

tropic lake
#

won't be for a few hours

hallow cove
#

oh, alright

#

ok!

#

that's fine!

#

can we then?

hollow wing
#

Question
what is known about private variable initialization in a MB?
For example string s; is not null, which means it's not default(string). So Is it documented somewhere how they are initialized?
(If have resources, e.g. documentation please mention me)

frail dock
tropic lake
hallow cove
#

aight!

untold moth
frail dock
frail dock
untold moth
# frail dock ahh no, i still have a lot of things i have to use it for haha, such as chunk lo...

Okay. So I think the workflow of jobifying something is to define the algorithm first. Something that you do in 1 function. Then see how you can turn everything from references to just data processing. Maybe picking data from 1 or several arrays and processing it with a certain algorithm. Then saving the result in another array. The result array is then used on the main thread for whatever you want.

untold moth
frail dock
# untold moth Okay. So I think the workflow of jobifying something is to define the algorithm ...

hmm, well in my current scenario i made an algo to calculate the exposed faces and points around them for collision data, it's just a few loops finding out target blocks and scanning around them, i assumed that the scanning around them would take a long time since a chunk has 10000 blocks but it only takes around 8ms so i can actually just run that in the main thread without seeing hangups, i'm only seeing hangups when the paths are actually allocated to the Polygon colliders 2d

untold moth
frail dock
#

look at that baby go 😄

untold moth
#

Nice

frail dock
#

you can see the execution times there

#

last step is s4 which is assignment

#

that's what takes the most time the more and more paths get added

#

each single block or holes or separated blocks need their own path..

#

so you can end up with 100 paths.. which makes the assignment take 100-300ms

untold moth
#

By assignment you mean what? Can I have a look at that part of code?

frail dock
#

it's just this

#
        foreach (var each in collisionPathsList2) {
            PolygonCollider2D pc2D = colliderPairs[each.Key];

            pc2D.pathCount = each.Value.Count;

            var counter = 0;

            text.text = "UPDATING CHUNK " + each.Key;

            foreach (var each2 in each.Value) {
                pc2D.SetPath(each2.Key, each2.Value);
                
                if (counter % 5 == 0) {
                    yield return null;
                }
                counter++;
                
            }
        }
#

yield every 5 seems to remove any hangups

#

but i'm getting index out of bounds, possibly cause it's executing out of order, so i'll have to think of something about that

ivory prawn
#

Can't each block just have a square collider?

frail dock
compact ingot
compact ingot
lavish epoch
compact ingot
#

it doesn't even have to be a visible renderer... its just a way to compute LOS with a camera projection and stuff that is very fast/optimized in unity...

lavish epoch
#

what is a camera projection and stuff?

compact ingot
#

In computer vision a camera matrix or (camera) projection matrix is a

    3
    ×
    4
  

{\displaystyle 3\times 4}

matrix which describes the mapping of a pinhole camera from 3D points in the world to 2D points in an image.
Let

      x
    
  

{\displayst...
compact ingot
#

related application is in the idea of https://en.wikipedia.org/wiki/Shadow_volume

Shadow volume is a technique used in 3D computer graphics to add shadows to a rendered scene. They were first proposed by Frank Crow in 1977 as the geometry describing the 3D shape of the region occluded from a light source. A shadow volume divides the virtual world in two: areas that are in shadow and areas that are not.
The stencil buffer impl...

#

sometimes 2D problems can be solved more easily by adding a 3rd dimension....

lavish epoch
#

but I dont understand what it is or how it works

compact ingot
#

can't help you with that i'm afraid... takes some reading i guess

#

what i described yesterday is the most straight forward way to do it without any special 3D-math knowledge

#

i.e. camera above the player, looking down with walls extruded high as occluders/pseudo-shadow-volumes

#

kinda funny that hardly anyone uses that trick... its so elegant

lavish epoch
#

make mesh that covers all walls
making it an occluder so things behind it dont get rendered?

untold moth
#

How about having your stats and effects as scriptable objects. So you can have a base effect SO and many different types of child effects, like ModifyStatEffect and RestoreStatEffect. Then you can even combine them in a CombinationEffect that would run both of the effects immediately/in order, etc... The Stat SO would hold a list of all the current effects, an unmodified value and a property that returns modified value. The effects will handle adding and removing themselves to the Stat effects list.

untold moth
#

things like movement speed are contained in a "movement" component that's attached to anything that can move.
Everything that can move? like, non character objects too(cars or rolling stones)? Do you want your effects to affect these objects too?

The benefit of an SO is indeed the fact that you can create many instances in the inspector and configure them the way you want. With what I mentioned, you can have one CombineEffect and one ModifyStatEffect SOs and make hundreds of combinations just with these by just creating new instances and dragging the references around + setting some numbers. No need for a separate class for each stat or creating(hardcoding) thing in code. It's also easier to reference them from anywhere in your project as opposed to regular or Mono classes.

#

Regarding the first issue, you could either have a special class that would contain stats of the object, or make your classes, like "movement" implement some kind of interface that would return a list of stats.

#
scriptableobject that's editable in inspector, with effects like
ModifyMovementSpeed, EnableBleeding, TeleportRandomly, GiveItem, ReduceArmor, InstantiateObject  and anyone could add these effects through inspector but wouldn't that be limiting for what the effect can do?

It will not be limiting, because you will write generic effects and configure them in inspector for whatever effect you want. For example, ModifyMovementSpeed would be ModifyStat instead, and you'll be able to set any kind of stat, like movement speed. EnableBleeding would be ModifyStatOverTime following the same logic as the previous one. Could even make it ApplyEffectOverTimeEffect and plug the ModifyStatEffect that reduces Health stat into it. It's super configurable and extendable.

lavish epoch
#

is that a function as a parameter?

#

thanks for reminding me I can do that

untold moth
#

It's called lambda expression👍

#

or anonymous function🤔

lavish epoch
#

can I use a variable in it, that I replace where I call it?

#

if you know what I mean

untold moth
#

Depends on the context. You can use captured variables in the expression itself (inside the curly braces). The only time I ever passed anything in the parenthesis is in Linq functions.

#

Ah, I guess if you use it as a delegate, the stuff in parenthesis has to match the delegate parameters.

lavish epoch
#

so I can add parameters to functions that are parameters?

untold moth
lavish epoch
#
A = new A( ()=> { ABC.GetComponent<SpriteRenderer>().sprite = null; } )

public class A
{
    GameObject Asigned;

    public A(Func function)
    {
         // call function but replace "ABC" with "Asigned"
    }
}

how do I do this?

vivid nimbus
#
    while (!assedUnload.isDone)
      yield return null;```
Anyone can explain to me why right after this memory is still occupied, but if i wait a little bit longer it actually gets freed?
lavish epoch
agile yoke
#

So, basically, in () => { ... } you can replace the () with a single argument, or with (arg1, arg2, etc.)

lavish epoch
#

Oh?

agile yoke
#

And then, where you want to take the function in (the A constructor in this case), you need to declare what kind of function you want, i.e. what arguments it takes and what it returns

#

You can use predefined types like Action<T>, Action<T1, T2> etc. (or Func<T, TReturn> etc.) or declare your own such type using the delegate keyword

lavish epoch
#
new A( c => { c.GetComponent<SpriteRenderer>().sprite = null; } )

public class A
{
    GameObject Asigned;

    public A(Action<GameObject> function)
    {
         f(Asigned);
    }
}

so this works?

untold moth
agile yoke
#

You can also do fun things like storing the Action in a field in the class and invoke it later in another method and so forth

untold moth
#

Although maybe, you don't need the parenthesis.🤔

lavish epoch
#

assuming "f" = "function", the name of the parameter?

untold moth
#

Yeah, that too

agile yoke
#

Yeah, you can omit the parenthesis if you have exactly one parameter in a lambda expression

lavish epoch
#

I only used lambda with lists

untold moth
#

As I mentioned previously all of the stats will be SO themself. Like MovementSpeedStat : BaseStat. Then you just drag them wherever you want. In the effects and in the Stats component.

#

Actually, Maybe just Stat : ScriptableObject is sufficient. Then it can have string statName field to identify each stat.

#

Yep

#

Unless you want some stats to have special functionality.

#

But I can't think of any examples.

#

Hmmm...

#

That should be handled by either effects or your leveling system or something

#

Yep

vivid nimbus
untold moth
#

In my opinion prefabs would be more messy.

untold moth
vivid nimbus
untold moth
#
BUT. Using strings for identifiers doesn't sound right to me, imagine I have hundreds of projectiles and every of these projectile when hitting an object it has to check stats like physical resistance. Finding them with string would be inefficient, right?

They don't need to check strings. They just need to have a reference to the right stat.

vivid nimbus
untold moth
vivid nimbus
#

i mean the resources that are supposed to be unloaded get unloaded N frames after asyncop.isdone

untold moth
#

Well, stats can have a set of default stats that it get from StatsDatabase or something. Or all enemies could be variants of a base prefab that already has the base stats set up.

vivid nimbus
#

because the game crashes

#

because if i wait a second instead than trying to load stuff right after asyncop.isdone then it works

untold moth
#

Hmmm... Well yeah. I see what you mean. In this case having a different class for each stat is better, since you can just check the list of Stats with is PhysicalResistance.

untold moth
#

maybe it's not true when you try to load?

vivid nimbus
untold moth
vivid nimbus
#

to make it more clear:

  • I'm in a IEnumerator coroutine
  • I unload my scene "A"
  • I create an empty scene so unity has something to hang on
  • I call AsyncOperation assetUnload = Resources.UnloadUnusedAssets(); and now i have an AsyncOp i can wait for
  • I wait for said AsyncOp to be done in this loop: while (!assetUnload.isDone) yield return null;
  • If I load a new scene "B" right now, i have a memory spike as the assets from the old scene are not unloaded yet (even though my while loop had me waiting until asyncop isdone)
untold moth
vivid nimbus
vivid nimbus
untold moth
vivid nimbus
#

i unload right before that while loop and i load right after it

devout hare
#

Probably garbage collection hasn't had time to run yet

vivid nimbus
untold moth
devout hare
vivid nimbus
untold moth
#

So why not use separate SO classes for each stat?

vivid nimbus
#

the problem only occurs only if scene A and B are big enough that the memory spike that comes from A not being unloaded when i try to load B is bigger than the memory of the platform i'm building on

#

if i do this with two empty scenes nothing happens

untold moth
#

Better than enums in my opinion. Also, you probably only need to check it in specific places, like Stats.DealDamage or something.

public void DealDamage(int amount, DamageType damageType)
{
  foreach(var s in stats)
     if(s is DamageResistance dr)
        amount = dr.AdjustAmount(amount, damageType);
  health -= amount;
}
vivid nimbus
devout hare
#

I think you can force GC to run in C#? Dunno, never really needed to do anything like that

vivid nimbus
#

yeah but the point seems to be that GC is not instant

vivid nimbus
untold moth
#

Sooo... is it actually the way you use your coroutine?😛

devout hare
#

The Internet says that GC.Collect is instant (i.e. blocking)

#

with caveats

vivid nimbus
untold moth
devout hare
#

so just calling GC.Collect might work

untold moth
#

Yep. Sounds like a plan.

vivid nimbus
# devout hare so just calling GC.Collect might work

As I said, had it in, no difference. turns out the resources.unload calls it anyway,
https://forum.unity.com/threads/resources-unloadunusedassets-vs-gc-collect.358597/
"liortal's guess is correct, Resources.UnloadUnusedAssets is indeed calling GC.Collect inside. So if you already calling Resources.UnloadUnusedAssets, you shouldn't call GC.Collect"

#

but these could be the thing

#

GC.WaitForPendingFinalizers();
GC.WaitForFullGCComplete();

#

though i don't know how advisable is to use those

devout hare
#

yeah I don't really know enough to say anything about it

vivid nimbus
untold moth
#

Just the fact that you don't want to show your code.

untold moth
#

Yeah, that's one way of doing it, although it means that there are some hardcoded stats. Maybe you can have some basic ones like that and additional in a list of additional stats.

vivid nimbus
#
                AsyncOperation unload = SceneManager.UnloadSceneAsync(CurrentLevel.name, UnloadSceneOptions.UnloadAllEmbeddedSceneObjects); // start unloading scene A
                while (!unload.isDone) // wait until scene A is unloaded
                    yield return null;
AsyncOperation assedUnload = Resources.UnloadUnusedAssets(); // start unloading unused assets (now that scene A is unloaded there's a lot of them)
            while (!assedUnload.isDone) // wait until unload has finished
                yield return null;
AsyncOperation sceneLoad = SceneManager.LoadSceneAsync(scene, LoadSceneMode.Single); // start loading scene B
            sceneLoad.allowSceneActivation = true;
            while (!sceneLoad.isDone) // wait until loaded
                yield return null;```
vivid nimbus
#

also discord code formatting is really bad

elfin tundra
#

then don't paste directly into discord

untold moth
elfin tundra
#

use something like paste.ofcode or hastepaste

untold moth
vivid nimbus
#
                AsyncOperation unload = SceneManager.UnloadSceneAsync(CurrentLevel.name, UnloadSceneOptions.UnloadAllEmbeddedSceneObjects); // start unloading scene A
                while (!unload.isDone) // wait until scene A is unloaded
                    yield return null;
AsyncOperation assedUnload = Resources.UnloadUnusedAssets(); // start unloading unused assets (now that scene A is unloaded there's a lot of them)
            while (!assedUnload.isDone) // wait until unload has finished
                yield return null;
AsyncOperation sceneLoad = SceneManager.LoadSceneAsync(scene, LoadSceneMode.Single); // start loading scene B
            sceneLoad.allowSceneActivation = true;
            while (!sceneLoad.isDone) // wait until loaded
                yield return null;```
#

mmh

#

not really

elfin tundra
#

i think you need a hashbang or something similar

untold moth
#

Well, you can use the base stat references directly where you need them. For example in the damage function. For listed stats, you'll still need to look them up.

vivid nimbus
untold moth
#

And the code on the new line

vivid nimbus
#

anyway

untold moth
#

Why?

vivid nimbus
#
Scene tmpScene = SceneManager.CreateScene("TmpLoad"); //create temp empty scene cause unity alays need an active scene
AsyncOperation unload = SceneManager.UnloadSceneAsync(CurrentLevel.name, UnloadSceneOptions.UnloadAllEmbeddedSceneObjects); // start unloading scene A
  while (!unload.isDone) // wait until scene A is unloaded
    yield return null;

AsyncOperation assedUnload = Resources.UnloadUnusedAssets(); // start unloading unused assets (now that scene A is unloaded there's a lot of them)
  while (!assedUnload.isDone) // wait until unload has finished
    yield return null;

AsyncOperation sceneLoad = SceneManager.LoadSceneAsync(scene, LoadSceneMode.Single); // start loading scene B
sceneLoad.allowSceneActivation = true;
  while (!sceneLoad.isDone) // wait until loaded
    yield return null;```
#

its just 3 asyncops, unload A, clean up unused stuff, load B

#

if A and B are small enough it works, if they are too big it doesnt, cause it seems A doesnt get cleaned up properly

#

the problem is that load B only happens after "supposedly" the cleanup asyncop is done

untold moth
#

Actually yeah, I kinda see the problem. So, whatever you do it's gonna result in a kind of a look up.

vivid nimbus
#

which seems not to be the case

#

so yeah, to get to what was the question all along:

AsyncOperation assetUnload = Resources.UnloadUnusedAssets(); // start unloading unused assets (now that scene A is unloaded there's a lot of them)
while (!assetUnload.isDone) // wait until unload has finished
  yield return null;```
how do I get this to ACTUALLY wait until garbage, ALL garbage, has been collected?
untold moth
#

Technically it should be collected by the time the asset unload is done. Maybe you have something referenced somewhere that prevents it from being collected..?

#

And I wouldn't rely too much on the memory profiler, especially in the editor. You can't be sure at what point in the frame it's collecting the data.

vivid nimbus
untold moth
vivid nimbus
#

will have time tomorrow to test

vivid nimbus
undone coral
untold moth
undone coral
undone coral
#

are you trying to memory manage textures?

#

there is a checkbox in unity to help you do this

#

many checkboxes

#

it's a really, really common problem

#

the thing is you don't know how your resources are being used. for example, even though an hdri is not visible in a scene, referencing a volume profile that has a deactivated override that references an hdri will still use the hdri, which can easily be gigabytes large

undone coral
#

if you have a way to measure the process memory usage in game, you can try to detect when that declines

#

i'm not sure if that's going to be meaningful though

#

if you're a unity pro subscriber maybe ask in a support ticket

#

you develop for consoles they'll just tell you

#

it should be clear though, that you have a halting problem esque situation

how does @vivid nimbus tell the difference between the unity api not working and @vivid nimbus still using assets and thus they are not freed?

#

Resources.UnloadUnusedAssets() by itself cannot tell you whether your mental model of which assets you're using is wrong

#

you're probably going to discover you're still referencing something, and that's going to be a very frustrating experience, and that the API has been working all along and we'll never hear from you again

vivid nimbus
# undone coral are you trying to develop for a switch?

yes I am
besides, I have the feeling the asset usage is fine, it's mainly about when I try to change the reference to a lot of them e.g. by going from a a scene to another that shares very few of the textures and meshes in the first one
that's why i would like to unload everything before attempting to load new stuff

vivid nimbus
sacred orchid
#

Anyone here any good with Photon?

vivid nimbus
# undone coral what are you actually trying to do

We ran some tests and it seems like this is whats happening: if you unload a scene and, immediately after, you load a new one unity will have them active at the same time because it seems like always need at least one active scene

undone coral
#

you can also build your game like

single scene:

global unified canvas
 -> loading screen panel
level prefab 1

then, to transition to a different level, destroy level prefab 1. then instantiate level prefab 2

#

that's it.

#

it would have the same exact same end user experience as switching scenes, but the api is cleaner

ancient talon
#

In a mid-life crisis struggle trying to get a plugin to reference through assembly definition 😢

#

Apparently the developer told us that the plugin was depreciated and ended product support three years ago. They want to charge us to get their latest plugin... Luckily me, I just so happen to have ILSPY installed 😉

vivid nimbus
undone coral
#

it will edit

#

prefabs are nested

vivid nimbus
#

Not to mention if you have lighting data that differs from level to level

undone coral
#

behaves better than a scene in almost every way

vivid nimbus
#

Plus light maps

undone coral
#

yes you will have to use lightsettings

#

but your goal is to manage memory, so you would have to interact with that anyway

daring gate
vivid nimbus
#

Come on, I get where you’re going and yes, it could work better on that side, but it’s like buying a car and drive it backwards cause this way it has a smaller steering radius

#

All I’m asking is, what is the best way to unload stuff and actually make sure that the memory is free before attempting to load new stuff

undone coral
vivid nimbus
#

I’m not asking for a new workflow

undone coral
#

for dealing with that problem

vivid nimbus
#

Nor for new plugins to add to my project

undone coral
#

i'm actually buying it right now 🙂

#

yeah i hear you 🙂

#

i want it to work too

#

it sounds like you should create a loading scene

#

and switch to it

#

and unload unused assets inside it

#

then load the next scene

#

nbd

vivid nimbus
#

Oh my god did you even read the conversation

#

Before getting into it

undone coral
#

i did

vivid nimbus
#

That’s exactly what I explained I’m doing

vivid nimbus
undone coral
#

it sounds like you are creating a scene

#

at runtime

#

and i'm saying you should just make a scene at build time

#

called loading

#

and switch into it

#

and take care that it doesn't have anything that references the resources you're trying to unload, which can be kind of tricky

#

since you probably do the whole DontDestroyOnLoad thing

#

and those objects might have references to things you need to unload

#

if you already know you just have to wait and then, it does "GC", i think just wait

#

but like i said, if you look at some outside side effect like memory decreasing, it's not guaranteed to do that

#

you will need to timeout that measurement

undone coral
#

so try to not do that, use a build time scene

#

it might just fix the problem, because the scenes api is horrible

#

sounds like this guy is pretty frustrated huh

vivid nimbus
#

Is there any benefit from creating an empty scene at build time, rather than at runtime? The load new level script is literally called every half an hour

#

Apart the fact that I could recycle the little resources creating an empty scene at runtime requires?

undone coral
#

and may behave in surprising ways

#

the only other dubious thing is using a coroutine to do this

#

but i really doubt that's going to be a problem

vivid nimbus
#

The memory used is literally the same, we’ve been running tests for some days already

undone coral
#

it's not about the memory usage

#

it's that, just because, unity might unload assets correctly when you switch between build time scenes, and not when switching runtime created scenes

#

like i don't want to use the word bug, there's definitely a bug (you expect the memory to be released, and it's not)

vivid nimbus
#

And as I said, the code already works if I put in an arbitrary time wait after unloading A, before I load B

undone coral
#

you could try it?

#

or file a bug and wait 9 months

#

for unity QA to get back to you and ask you to see if it repros on the latest unity

#

i'm telling you the only two possible things wrong with your code

#

i don't mean wrong*

#

i mean two opportunities for a workaround

#

one is try a build time loading scene, and another wil lbe to not use a coroutine

#

because coroutines running on objects that cross scene loading boundaries (i.e. dontdestroyonload)

#

sounds very finnicky

vivid nimbus
#

I will when I’m back at work tomorrow, but my question was “is GC.Collect immediate, cause it doesn’t seem it is”

undone coral
#

it is not immediate

#

you already knew that though

vivid nimbus
#

Without destroying and reloading everything

undone coral
#

dontdestroyonload is fine

#

i'm just saying that a coroutine running on an object with dontdestroyonload, that is itself doing scene changes, i don't know, i can see that being buggy

#

but that would be the last thing i try testing

#

if i were you

#

GC.Collect isn't immediate, it never was

#

it's just a copy of Java's gc behavior exactly, which is a request, not an order

vivid nimbus
#

Cool, that was the only answer I needed

undone coral
#

i think you're going to find the thing

#

it's probably going to be a coroutine from the previous scene

#

and that's why it's time related

vivid nimbus
#

Except for, question 2: is there a callback or a way to know when go has collected and memory is free for real

undone coral
#

there's some object that is sticking around, with all its references

#

something with an animation expressed in a coroutine*

#

pretty common unity gotcha

#

so technically it's still being referenced

undone coral
#

i don't know what to tell you, the likely outcome is that the bug is that you're referencing something "still"

#

and it's just going to be surprising what it is

#

and the fact that it appears to go away "a short while later" is a red herring

#

it sounds like a coroutine-expressed animation that's still running

#

and instead of like, stubbornly asking the same questions over and over again which you know the answers for, let's just brainstorm what you might be referencing

vivid nimbus
#

The loading scene is the only coroutine in the game afaik, unless there’s some in the only external bit of code we use for aUi

undone coral
#

you might have invoked something that is a coroutine on a dontdestroyonload object

#

yeah

#

it might be like DOTween or whatever

#

i know iTween has this bug

#

i don't know about dotween, i stopped using itween years ago

#

but yeah, maybe that's not it

#

another thing is a scene wide thing, i know you don't use hdris

vivid nimbus
#

We had that in from more than 6 months now tho, so I guess that would have surfaced before if it was so game breaking

undone coral
#

but it may be something lightmaps related

#

yeah

#

it's really tricky

#

you can test your code switching between scenes that don't have any code

vivid nimbus
undone coral
#

like are just static unity scenes

#

i don't know, i'm just spitballing

#

all this stuff is glitchy 😦

#

let me know tomorrow when you try some stuff

#

you'll figure it out

vivid nimbus
#

I really wish I didn’t have to 😩

lavish epoch
#

2d bool array is size 3000 by 3000
v2int2 is same thing as vector2
with this size I can check positions -1500 -1500 to 1500 1500
(positions are int and can be true or false, tilemap sort of)

doing this 45000 times causes lag, how improve?

long ivy
#
  1. do it less often, or with smaller queries, or over multiple frames
  2. do it in parallel
  3. find a more efficient way to do whatever you're doing
austere jewel
austere jewel
humble leaf
frail dock
hot gale
#

Can you pass a GameObject that's present in the scene into the variable slot of a Component in a prefab?

#

I want to put one of my UI elements into a Scriptable Object so that I can change it's Sprite

elfin tundra
#

nope you're gonna have to assign it in a script

#

but that's easy with GameObject.Find

#

and similar funtions

hot gale
#

Yeah, that's what i've been using so far. Was wondering if there was a better way, but good to know that there isn't :c

elfin tundra
#

nah sorry idk if there is

austere jewel
#

Usually you should have whatever instances it call an initialise function with the parameters it needs to configure those missing instances

hot gale
#

What i've done is a Scriptable called HUD Elements and it just assigns all the needed UI elements to their necessary variables in the Awake function

queen fable
#

I wish I never checked this channel

#

😐

unkempt nova
#

Can learn a lot lurking here

hard lily
queen fable
#

😔

hot gale
#

Do I need to create two different scriptable objects if, for example, I want two players to have the same ability?

hot gale
#

yes

cursive horizon
raw ruin
#

yeah

#

no need to use two

#

I mean you could do like this if this is what you mean

#

MonoBehaviour>Health(SO)>Ammo(SO)>PlayerController

#

Like this would reference from those scripts

#

i think

hot gale
#

I'd only call the Initialise from the player if they're the local player though, right?

raw ruin
#

What networking solution not that it matters?

hot gale
#

Mirror

#

I'm just wondering if, for example, if two people in a MOBA are playing as "Speedster"

raw ruin
#

Yeah i assume that is how it works i think they have a HasAuthority thing or somin

#

Are you trying to check whether they are local based on their names is that how mirror works?

hot gale
#

i have a Handler variable in my scriptable objects in order to tell who is using the ability but

#

Thinking back... that's probably a bad idea; and parsing in the gameobject that calls it would be better

vestal heath
#

Bro scriptable objects are just data containers

#

Think of it as if you’re playing dungeons and dragons

hot gale
#

I need my scriptable objects to have functions in them; so a little more than data containers in a sense but

#

I get what you're saying

vestal heath
#

you have your character and its stats and abilities

#

But you are the player instance

#

And you manipulate those stats

hot gale
#

yeah; I just need to parse the player in on function calls

vestal heath
#

You use abilities

#

No

#

Rethink that

#

SOs are not intended to manipulate gameobjects

#

Sure you can do that with bunch of callbacks etc but it’s usually wrong approach

hot gale
#

It's literally what it says on Unity's official website regarding using SOs to create a MOBA

unkempt nova
vestal heath
#

Yeah i’ve done it too

hot gale
#
Unity Learn

In this recorded live training session from August 2016, we create a flexible player ability system which includes player abilities with cool downs, similar to those seen in MOBA or MMO games. The approach uses scriptable objects and is designed to allow game designers to create multiple variations of an ability and swap between them easily.

vestal heath
#

To get callbacks on dialogue options

unkempt nova
#

Interesting. I kinda like that

hot gale
#

the thing that's throwing me

#

is where the tutorial has a variable called rcShoot

#

and sets it to the Triggerable Component of the object that parsed in

#

like; would that not just set rcShoot to the same Triggerable on all clients...?

unkempt nova
#

Nope, each SO is its own instance

#

You can multiply them at runtime

#

Same idea as having multiple Monos, setting a field on one doesn't affect others

hot gale
#

I have Gun (ScriptableObject),

and I have GunAssaultRifle (Gun)

GunSubMachineGun (Gun)

#

so if I create an SO from GunAR and call it M556

#

then put M556 in the PlayerGun script's Gun firearm field

#

each GameObject would have an independent M556?

unkempt nova
#

You mean just dragging the SO to multiple Monos? No, they'd all reference the sameSO

#

You can get around this with ScriptableObject.CreateInstance I think

hot gale
#

That's what I was looking for 😄

#

Thanks! 🙂

unkempt nova
#

That comes with its own issues, sometimes the Data and references don't get copied properly, if I remember correctly

#

So you might want some sort of Init method

#

You're just creating an instance of the SO in that case, IIRC, so its fields, etc aren't copied over like you may think it is. (I think, just keep an eye out for it)

hot gale
#

Hmmm, wouldn't Object.Instantiate not be a better option in that sense?

unkempt nova
#

I vaguely recall being told to use CreateInstance instead

#

Not sure why

hot gale
#

Store my M556 SO in a dictionary (I made a custom dictionary serializer for Unity's Editor) and then use Object.Instantiate?

I vaguely recall being told to use CreateInstance instead
Hmmm, I see

#

Instantiate clones the original object, and returns a clone;
Whereas CreateInstance creates an instance of a ScriptableObject

#

so I think in this case; Instantiate would Clone M556, whereas CreateInstance would just create another GunAssaultRifle, and not an M556

#

which is why you're encountering issues where data doesn't transfer over

unkempt nova
#

Very well could be. I haven't tried to use it in a while, memory is foggy on it now

#

Just giving you a heads up

#

But thanks for the clarification, makes sense now

hot gale
# unkempt nova Just giving you a heads up

Appreciate it 😄 I'll have a little fiddle around with the different options and see which one works best. Thanks for your help, enjoy the rest of your evening/morning depending on time zone

unkempt nova
#

GL HF

languid scarab
#

Trying to run https://github.com/keijiro/Rcam2 on 2020.3.19f1
Getting this error: Library/PackageCache/com.unity.render-pipelines.high-definition@10.6.0/Runtime/Compositor/CompositionLayer.cs(60,26): error CS1069: The type name 'VideoPlayer' could not be found in the namespace 'UnityEngine.Video'. This type has been forwarded to assembly 'UnityEngine.VideoModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' Enable the built in package 'Video' in the Package Manager window to fix this error.
However the the built in package 'Video' in the Package Manager is non-existant.

unkempt nova
#

Every time I get an error like that, I just reset packages to defaults and they go away

dry yacht
austere jewel
#

That is so damn specific

dry yacht
# austere jewel That is so damn specific

I saw a similar tiling system in the game Dyson Sphere program, so as I searched I came accross this article but I couldn't find any implementation, I guess I should roll my own

unkempt nova
#

I was thinking it looked just like DSP when I saw it heh

#

Sebastian Lague made a video on sphere generation with equally spaced points, I think? Not sure if that'd help you out with a grid though

dry yacht
kindred tusk
bleak edge
#

Guys, I don't get meta files.
I'm doing this internship for a small studio, and they told me to stop committing the meta files that unity automatically adjusts when I for example, open up a scene.
They work on Mac, I work on PC, so a bunch of my meta files get adjusted when I open up the project. Even things that have nothing to do with what I was working on.
I always learned that it doesn't really matter if you commit these. Now I'm being told to stop and stay picky about them. I think that's just going to give me a ton of headache by having to resolve merge conflicts and picking out the right meta files for each commit.
What should I do here? What is the way to go? Are they right in saying that simply opening a project has messed up some of their references in a different scene? Because I hard-doubt that tbh.

#

can't find anything in the docs that says you'd have to do that either.

novel wing
languid scarab
bleak edge
austere jewel
unkempt nova
bleak edge
flint sage
#

What are the actual differences in the meta files

novel wing
flint sage
#

Also, you should really know what files you have changed and only submit those

austere jewel
novel wing
#

Oh yeah actually, it's possible that since you are opening it on Windows you are causing the asset in question to apply some platform specific settings. This can cause a change in meta files, notably importers.

austere jewel
#

Minor version differences can touch up meta files. Selecting assets even when not working on them can do it. When working in a team with version control it's courtesy to not dirty things unnecessarily. Sometimes Unity can fuck up and break things, so looking at changes you've made before you commit them is also a good thing to do.

bleak edge
#

weird

austere jewel
#

Grow up and don't ping me for no reason

#

One's a slur, the other's not

humble leaf
#

Using an ableist slur is not the same as swearing. If you're not here to talk about code, don't talk.

#

!mute 181873334818963457 My perception of the rules: come back tomorrow when you have a code question.

thorn flintBOT
#

dynoSuccess ᲼᲼᲼᲼᲼᲼#3520 was muted

hollow garden
#

If there were children here i assume theyd be banned since thats against Discord TOS but go off ig

mortal glen
#

Hi, I am trying to deserialize this with JsonUtility and now trying with Newtonsoft, but not getting a lot of success.

#
public class TokelToken
{
    public string tokenid;
    public string owner;
    public string name;
    public int supply;
    public string description;
    public string[] data;
    public int version;
    public bool IsMixed;
    public int height;
    public string ownerAddress;
    public int blocktime;
    public string blockheight;
    public int syncedHeight;
}
#
TokelToken tt = JsonConvert.DeserializeObject<TokelToken>(mytokens.downloadHandler.text);
fresh salmon
#

Your root is not your object directly, but rather an object that contains a list of what you want

mortal glen
#

I think I am doing something entirely wrong because my class covers one item

#

@fresh salmon can you help me to get into the right direction, never used lists or json before in unity :S

fresh salmon
#

So

public class Whatever {
  public List<TokelToken> tokens; // { "tokens": [ your items here... ] }
}

Whatever root = JsonSerializer.Deserialize<Whatever>(json_text_here) would do the trick

#

Because you don't have a single token, but a collection of them, and they all are under a key named tokens at the root of the JSON

mortal glen
#

so i need another class to wrap them into?

fresh salmon
#

Yup, as per the example above

#

The Whatever object is the wrapper over it

mortal glen
#

ok, understood

#

how do I deal then with data?

#

its like a nested thing inside token

#
    "data":{
            "raw":"f70101fe65530600021068747470733a2f2f736974652e6f7267030104050202abcdef",
            "decoded":{
               "id":414565,
               "url":"https://site.org",
               "royalty":1,
               "arbitrary":"\u0002\u0002���"
             }
            },
#

does that also needs its own class?

fresh salmon
#

Yup

mortal glen
#

or is string[] good enough

fresh salmon
#

If you don't need it though, no need to create a specific field in your class, the serializer will ignore it

mortal glen
#

noooo this i need

#

thanks a lot ❤️

regal olive
#

hi, how can sop modifying collections while iterating over it in this script? ``` public void Update()
{
t += Time.deltaTime;
if (t > 0.1 && l1.Count >= 1)
{
t = 0;
foreach(helper h in l1)
{
helper2 = h;
helper2.activate = false;
helper2.highlight = false;
l1.Remove(helper2);
}
}
}
private void OnTriggerEnter(Collider col)
{
if (col.gameObject.GetComponent<helper>() != null)
{
helper = col.attachedRigidbody.gameObject.GetComponent<helper>();
helper.activate = true;
helper.highlight = true;
if(l1.Contains(helper)==false)
l1.Add(helper);
}

}
 
   private void OnTriggerExit(Collider col)
{
    if (col.gameObject.GetComponent<helper>() != null)
    {
       helper3 = col.attachedRigidbody.gameObject.GetComponent<helper>();
        helper3.activate = false;
        helper3.highlight=false;
        1.Remove(helper3);
        
    }

}
}```

austere jewel
#

Don't use Remove in a foreach loop

regal olive
kindred tusk
#

You need to move backwards through the list or else you'll skip elements

austere jewel
regal olive
#

because nobody would give answer there

austere jewel
#

where please post in the correct channel next time

unkempt nova
#

Typing "forr" and hitting tab will autocomplete a backward for loop in most IDE btw

regal olive
#

ok thank you guys, i guess i just dont use foreach with lists

#

even if it is possible somehow

#

but i guess this is not for advanced code

austere jewel
#

No, you just don't modify collections while using a foreach

mortal glen
#

@fresh salmon I get

Argument 1: cannot convert from 'string' to 'Newtonsoft.Json.JsonReader'

when using

Tokels tokeltokens = JsonSerializer.Deserialize<Tokels>(mytokens.downloadHandler.text);```
hollow garden
regal olive
#

ok thanks

fresh salmon
foggy elk
#

Good afternoon community.
Question regarding GetField() and there around.

Concider the following elements:
public class Player 
{
public int itemA;
public int itemB;
}

public class PlayerCharacter : Monobehaviour
{
public Player player;
}


I understand I can use GetField to get the hold of itemBs value, but how do I write it?

regal olive
#

but thanks

fresh salmon
foggy elk
#

aye

austere jewel
austere jewel
# foggy elk aye

It has set value and get value functions. Though why you'd need reflection is beyond me

foggy elk
regal olive
austere jewel
#

Still doesn't require reflection as far as I can see

regal olive
austere jewel
foggy elk
austere jewel
#

I have no idea as to the specifics of what you're doing. Why would you need to do string comparison? Enums are just fancy integers. If you use them to index multiple things with dictionaries or lists then you can link them together easily

mortal glen
#

@fresh salmon I got the right method now, but as I thought the data object gives me horror:

ArgumentException: Could not cast or convert from System.String to TokelDataDecoded.
foggy elk
#

and bear in mind another condition may want to search for Hitpoints, intelligence .. or even bools.

austere jewel
mortal glen
#

@fresh salmon I made Tokels, TokelToken, TokenData and TokenDataDecoded

public class TokelData
{
    public string raw;
    public TokelDataDecoded decoded;
}

and

public class TokelDataDecoded
{
    public int id;
    public string url;
    public int royalty;
    public string arbitrary;

}
fresh salmon
#

Then you have a field or property that is of type TokelDataDecoded, but it expected a string.

#

Hm if I remember right that structure is correct

foggy elk
mortal glen
#
    "data":{
            "raw":"f70101fe65530600021068747470733a2f2f736974652e6f7267030104050202abcdef",
            "decoded":{
               "id":414565,
               "url":"https://site.org",
               "royalty":1,
               "arbitrary":"\u0002\u0002���"
             }
            },
radiant wave
#
System.IO.File.WriteAllText(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop) + "\\New Folder\\test.txt", "Test"));```

I probably can't use these File Directory stuff in a WebGL build, correct?
fresh salmon
austere jewel
mortal glen
#

@fresh salmon nope, then no error

fresh salmon
mortal glen
#

Maybe do something inside the class and deserialize the string into the TokelDataDecoded?

#

they are NFT, so they should be all object :S

fresh salmon
#

I have to go, if you have more questions post them here, someone will take the lead

distant gyro
#

Got a question about serialization and reflection

  • I have a ScriptableObject called UpgradeSettings with a serialized List of instances of a plain C# class called Upgrade
  • The Upgrade class is Serializable and contains another List of instances of C# class PowerUp
  • The PowerUp class is also Serializable and has yet another List of instances of C# class PowerUpEffect
  • PowerUpEffect has a variety of derived classes, like HomingBullets, ExplodingBullets and so on
  • I use reflection to create instances of the various derived classes and put them in the List of PowerUpEffect instances in the PowerUp class
  • I then use reflection to get all the values from the instances and display fields for editing them.

So far, so good.

Problem is that once the asset database refreshes, the serializer seems to turn all of the instances of the derived classes into instances of the base class! Is there any way to work around this?

austere jewel
#

That will happen if the types are not UnityEngine.Object types. You can use the SerializeReference attribute to serialise polymorphic data otherwise @distant gyro

distant gyro
#

Ahh.

#

Let's see if that does the trick ...

#

@austere jewel SUCCESS!

#

Thank you! I now also have a really weird feeling of deja vu like I've been here before asking a similar question and gotten the same answer from, uh, you.

pastel garden
#

hay i need help with my code

#

(quite advance)

tropic lake
#

send it and people will see if they can help

pastel garden
#

if anyone can help pls dm me (neural networks)

humble leaf
pastel garden
#

sure

#

here you go

abstract geyser
#

Is there a way to change the way the renderer sees objects from Normal to Wireframe without having to swap out materials or create a custom shader? I am using URP 7.7 and Unity 2019.4 LTS

fast mural
#

what do you mean? runtime? editor? in scene view you can change from shaded to wireframe, if that is what you want....

hybrid ore
elfin tundra
#

i see many potential issues so specify the line that has an error on it

#

for example, you named a variable the same as a type in MenuUIHandlerScript

hybrid ore
#

Okay, I tried to do something in the second script I need to add some code

elfin tundra
#

you also never use your iterator variable in NewColorSelected and you assign to its parameter

#

many many issues so we'll go one step at a time

#

run it and send the first error

hybrid ore
#
    {
        // add code here to handle when a color is selected
        
        ColorPicker.ColorButtonPrefab.onClick.AddListener(() =>
        {
           color = ColorPicker.SelectedColor;
        });
    }```
elfin tundra
#

that's not an error

#

you already sent that code and it has lots of problems which i mentioned earlier

hybrid ore
#

When I start the game I can select one of the colors. I can press start(to move to another scene) and exit

elfin tundra
#

ok but what's the error

#

there are lots of mistakes in your code, i need to know where to start

hybrid ore
#

I don't have any errors.

#

My point is I should handle the color which I selected but I didn't do it correctly

elfin tundra
#

if you don't have any errors you're running it very wrong lmao

#

there are lots of mistakes in your code that should be causing errors

hybrid ore
elfin tundra
#

wtf

#

are you sure those scripts are running? bc maybe they're just never running

#

which might be why they aren't causing any errors

hybrid ore
#

It's my exercise from the course I got to this game with scripts to add some things and optimize the code. Everything works but I don't understand how to do it I checked every forum and yt but I don't know who to handle the color

elfin tundra
#

so you didn't write these scripts? they are someone else's?

hybrid ore
#

Unity

#

This is reason why I don't understand

elfin tundra
#

no, they're not unity's

#

there's no way unity would distribute code with mistakes like that

hybrid ore
#

"project brief"

elfin tundra
#

idk man i don't see anything there about switching colors

#

how did you download those files?

hybrid ore
#

point 5 there is a link

elfin tundra
#

yeah i see that but it doesn't link to the actual cs files

#

where are those am i stupid 😂

frail dock
#

is it possible for the main thread to execute a method the second time simultaneously?

elfin tundra
#

that's kind of the point of threads, they allow you to do more than one thing simultaneously

frail dock
#

i have a situation where a global list is being modified while running the same method multiple times

frail dock
elfin tundra
#

you said that

hybrid ore
#

@elfin tundra I'm sorry there is instruction 😅

frail dock
frail dock
#

cause i'm only using the main thread

elfin tundra
#

you said execute but anyway wdym access?

hybrid ore
#
Unity Learn

In this tutorial, you’ll learn about the basics of Version Control, and the reasons to implement it in your own projects, even if you’re developing applications by yourself. You’ll also learn about the different Version Control options available to use with Unity, and put your new skills into practice by downloading the project that you’ll use t...

frail dock
#

i have a method that modifies a global list

hybrid ore
#

@elfin tundra In materials.

frail dock
#

but if i draw too fast i get errors

#

but not when drawing too slow

shadow seal
#

Provide said errors

frail dock
elfin tundra
frail dock
#

not sure how helpful this is though since a lot of stuff is going on

#

basically the order is this

#

enter method, modify public list, copy public list to internal list, do stuff with internal list, done

shadow seal
#

Do what stuff?

hybrid ore
#

@elfin tundra I really don't know but it's hard to understand 😳

shadow seal
#

Stuff isn't helpful

#

Especially when your internal list, might just be references to things in the public list

frail dock
shadow seal
#

Can you just show us tbh?

#

Might be easier

frail dock
#

can't show the entire code lol, its like 2000 lines, but maybe i'm copying in the internal list wrong? 🤔

#

i'll try posting some stuff

hybrid ore
#

@elfin tundra What do you think about it?

shadow seal
#

The most important part is likely the method where this error occurs

#

That shouldn't be 2k lines

elfin tundra
kindred tusk
elfin tundra
#

yeah

kindred tusk
#

If you don't know how to code you're in the wrong room

elfin tundra
#

def go there now

hybrid ore
#

Okay

kindred tusk
#

They just did...

hybrid ore
#

Thanks, I did it 😉

undone coral
frail dock
# shadow seal Can you just show us tbh?
// global list
private Dictionary<string, Dictionary<string, List<byte>>> blocksWithAllPaths = new Dictionary<string, Dictionary<string, List<byte>>>();

// enter of method

// global list is being modified

var blocksWithPaths = new Dictionary<string, List<byte>>();
        

        // assign values from global list to internal list
        List<byte> bytes = null;

        foreach (KeyValuePair<string, List<byte>> each in blocksWithAllPaths[chunkKey]) {
            bytes = new List<byte>();
            foreach (var each2 in each.Value) {
                bytes.Add(each2);
            }
            blocksWithPaths.Add(each.Key, bytes);
        }

// start of a bunch of while loops scanning around blocks and building the paths

var blockToBeModified = blocksWithPaths[key]; // block to be modified with key being the current block being worked on, this is where error occurs

// end of while loops
#

best i can do

shadow seal
#

Christ, I'm gonna need a minute

frail dock
undone coral
#

are you trying to find a path between two blocks in a 2d or 3d space?

#

what does that mean, generate collisions?

#

anyway, you are adding to a dictionary while enumerating through it

#

you can't do that

#

lemme help you see what's really going on

frail dock
#

best if i just show you

shadow seal
#

He isn't doing that

frail dock
#

i'm not adding while enumerating

undone coral
shadow seal
#

He enumerates through blocksWithAllPaths and modifies blocksWithPaths

undone coral
#

it looks like it's not being enumerated

shadow seal
#

Otherwise it would error

#

That isn't the error

undone coral
#

oh it's not concurrentmodificationexception?

#

or whatever it's called in c#

shadow seal
#

It's a key not being present in the dictionary

undone coral
#

oh

#

key exception

#

yeah

#

i don't know this is a mess

#

what are you trying to do? @frail dock express in words

#

don't send a video

frail dock
undone coral
#

lol

#

it's okay

#

you will improve it 🙂

frail dock
#

ergo the global list

shadow seal
#

I don't think this is complete code

#

Where is key?

frail dock
#

as i said, it's not, the everything is spread, you can't possibly understand any of it unless i post the whole thing

shadow seal
#

Paste sites exist you know

frail dock
#

ahh, i'm a bit worried of code snatchers tbh

shadow seal
#

There must be an easier way than a Dict of string, Dict of string, List bytes

undone coral
#

it's okay

#

you don't have to

shadow seal
#

Nobody will steal this code...

undone coral
#

just express in words what the goal is

#

oh i've seen part of your video before

#

you're trying to generate a collider for a tile map that gets modified?

frail dock
#

well it's not tile map, it's a mesh

undone coral
#

yeah

#

like modify a grid, and optimized modify a mesh?

frail dock
#

it goes modify block list, modify mesh, generate colliders

undone coral
#

usually if you try to use the fewest colliders or whatever, it performs worst in the most common case

frail dock
#

but the colliders part took a shitload of time to optimize for performance

undone coral
#

yeah

frail dock
#

i got it down to 10ms

#

but this last part would get it down to 6

#

i just don't get how the list is being modified simultaneously

undone coral
#

it looks like you probably just accidentally deleted the key before you use it again

frail dock
#

unless i'm missing something

undone coral
#

or you're visiting the same key "twice"

#

if that makes sense

frail dock
#

well, what's I think happening is the internal list is being modified with outdated information

frail dock
#

that's what that list of bytes is

#

so if any empty sides are detected the while loops keeps going until all sides are covered

abstract geyser
frail dock
#

i'm guessing if it's going too fast one of the maps is wrong and ergo the key error

#

but how can the list be modified twice if it's only on the main thread 🤔

undone coral
#

it wouldn't be going too fast or anything like that