#archived-code-advanced

1 messages · Page 99 of 1

half swan
#

Have the script register itself to where it is needed?

lofty inlet
#
X.onClick.AddListener(
        () =>
        {
            Method();
            X.onClick.RemoveListener(Y);
        }
);

what would I put as Y to remove the addlistener? or is this not possible

long ivy
#

store Y before adding it as a listener, then you can have it reference itself

lofty inlet
#

also I realize Y may be misleading
it's not a separate function, but just a placeholder for what the actual code would be

long ivy
#

I assumed you wanted a listener that removed itself from the click event when invoked. If that's not the case, maybe you can describe what you want a little more

lofty inlet
#

yeah

#

basically I want the button to do the thing, then remove the lambda expression

#

another way I was trying to go about it was somehow naming the lamba expression which I don't think I can do after some googling

long ivy
#

you just need to have something your delegate can use to reference itself

   UnityAction listener = default;
    
    listener = () => {
        Debug.Log("Button clicked!");
        button.onClick.RemoveListener(listener);
    };
    
    button.onClick.AddListener(listener);
    
    button.onClick.Invoke();
    button.onClick.Invoke();
lofty inlet
#

rip
I was trying to do that without having an external function/action

tall ferry
worldly pecan
#

I haven't really worked with native memory before and I was wondering if anyone experienced in it could offer guidance on how to properly do something.

I have some map data that is created and managed on the GPU, however I need to read it back to the CPU. To do this, I make an async readback call like this. However the native array returned by "request.GetData<TerrainChunk.MapData>()" is readonly, so I cannot edit it.

For the time being I'm doing this to get around it
if(storedMap.IsCreated) storedMap.Dispose();
storedMap = new NativeArray<TerrainChunk.MapData>(mapData.Length, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
storedMap.CopyFrom(mapData); //Copy so we can edit it
mapData.Dispose();

But this is pretty wasteful, is there a better way to do this?

rugged radish
#

I'm pretty sure you have to copy the readback results either way, because they are valid for the current frame only. I researched the topic quite a while ago though.

worldly pecan
rugged radish
sly flower
#

hey devs!! I am looking for some suggestions. Now I have a project where I want to have a UI Manager to handle all the UIs in the game regardless of which level you are in. Now the thing is I dont want to manually place this manager in every level.

I have seen suggestions where they uses an additive scene which stores all the persistent objects and take the rest of the things from there... now the problem is with this approach, everytime I spawn an object onto the scene, it spawns in the root level. And then I have to use the Move() method to bring them to the scene they are expected to be.

Now I want to know if this is an expensive call because if I had something like projectiles or something that needs to be created frequently... wont it be expensive to bring them to the current scene...

Or is there a better way to handle this thing

worldly pecan
rugged radish
#

yeah, I meant native arrays
I need results to be persistent and pass to jobs, so storing in native arrays is convenient for me

#

it's just that copying is a mandatory step

#

unless results are to be discarded immediatly I guess

worldly pecan
upbeat path
sage radish
worldly pecan
worldly pecan
#

Problem is it might be disposed of already

upbeat path
worldly pecan
rugged radish
#

IntoNativeArray seem to be working with textures only ?

#

nvm, there're compute buffer overloads as well

#

wonder when those were added, might update my readback wrapper to this too

worldly pecan
#

Seems to work, except I'm passing the NativeArray normally, and it's being copied as it's a struct. I can't use ref because I'm capturing the values with a lambda, should I use a delegate(I'm not that familiar with it)

#

I can wrap it in a class lol

void oasis
#

Hey guys I'm a developer for career but getting into Unity because I want to make games as a passion of mine. I'm trying to understand what is that best way nowadays to structure objects?

Right now let's say I have an Enemy prefab.
That Enemy prefab has different components:
Health
Damage
Movement
So on and so forth. All different scripts that that handle different things but the Enemy itself is never really a script or class itself that inherits from some base class.

My question is, is this a good way to approach game development? Some component based system? I was thinking of inheritance also but just wanted to know what is everyone's thoughts.

rugged radish
#

the callback argument is optional, I had to use it in the old wrapper to copy, but now it just writes directly to native array

worldly pecan
worldly pecan
upbeat path
void oasis
void oasis
orchid marsh
worldly pecan
#

Also the more objects means more for your GC to do

void oasis
upbeat path
void oasis
#

Ahh that makes a sense. Yea this will be officially my first game I plan to release so maybe I shouldn't overthink / overengineer something smaller scale.

upbeat path
thorn flintBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

worldly pecan
wet sail
#

hello. need help. i have a class "EventsEmitter" and many scripts that use one or two emitters (for eg. ontriggerenter, a box would inform that emitter that a collision happened and the emitter will do stuff to it)
problem is when i have a script like this, i cannot drag/drop in the inspector the Emitter. im not sure how to do it?

public class BoxEmitsTriggerEvents : MonoBehaviour
{
    public EventEmitter evt; // i need to drag/drop this between scripts in inspector.. how do i do this?
    public string eventName;

    private void OnTriggerEnter(Collider other)
    {
        evt.SetTriggerForEvent(eventName, true);
        evt.GetEventArgs(eventName)["collider"] = other;
    }
    private void OnTriggerExit(Collider other)
    {
        evt.SetTriggerForEvent(eventName, false);
        evt.GetEventArgs(eventName)["collider"] = other;
    }
}
#

i guess the best way is a wrapper like a "EventSystemHolder" monobehavior class?

paper coral
#

Someone made a script for me that I can use in my game. They put it into a .unitypackage file. Has there been any cases of viruses being spread this way or is it generally safe? Just want to be extra safe. Google isn't giving reliable answers.

wet sail
#

can be a virus yes

paper coral
#

Alright, opening it on my virus pc then and i'll just type over the script if it's there

#

Thanks

wet sail
#

not unity related. c# only lib

regal lava
#

Well, it needs to either inherit from Mono or be tagged as Serializable to be configured in the editor

worldly pecan
#

I've been experimenting with ComputeBuffer.BeginWrite(), and idk why but it seems I'm handling something wrong.

#

I checked at the end and writeDest does have all the correct data, however when I run this actual code, Unity crashes inexplicably leading me to believe this is not how to actually use .BeginWrite(), does anyone have an idea on what I could be doing wrong?

#

*GenerationBuffer is a static computebuffer initialized with a stride of 4(I reinterpret the data whenever I use it)

worldly pecan
#

Edit: When I switch the copy to a temporary buffer with exactly the size of(numPoints) and the stride of the struct it works--maybe it has something to do with the stride or it being persistant?

sage radish
glossy cargo
#

hey guys so ive made a rigidbody based character controller and a slide mechanic. for some reason tho when I slide and then stop sliding the momentum isnt conserved. for example i would slide and then jump and the slide momentum isnt conserved and im not sure why.

#

here is the movement, ground check and slide code

quartz stratus
untold moth
thorn flintBOT
livid kraken
#

Just a small update on this. First of all it happens only in the editor. Also it seems to happen randomly. Sometimes it would be the audio, sometimes it would be loading textures into memory. Now textures I can get, but audio is only a 4mb diff between not loading and loading the mentioned scene.

timber flame
#

Which one do you prefer to send and pass arguments to parent and child init method (zenject)?

//mono parent
[Inject]
private void Init(SomeTypeA typeA){}

//mono child
[Inject]
private void Init(SomeTypeB typeB){}

or


//mono parent
public void Init(SomeTypeA typeA){}

//mono child
[Inject]
private void Init(SomeTypeA typeA,SomeTypeB typeB){
   base.Init(typeA);
   //...
}
timber flame
#

I like the second one like pure ctor

#

because I have more control to pass data or use it in the child. Suppose, there are some data arguments as well

stray bridge
#

https://gdl.space/ugihivoteg.cs

I'm trying to generate a navmesh in realtime, however the game still freezes for a few seconds when this code is called, even though it should be executed asynchronously (on line 42). The deep profiler returns those tasks as the most expensive: NavMesh.Recast.RasterizeTriangles, NavMesh.Recast.FilterBorder, NavMesh.Recast.BuildCompactHeightField and NavMesh.Recast.ErodeArea.

Any idea why?

rugged radish
#

I'd look into NavMeshBuildSettings
I remember that reducing some of the parameters made it run for a few more frames but making less of an impact on fps, to the point where it wasn't noticeable at all

#

also, in my case, writing a custom async collect sources routine helped the most, but looks like it's not an issue for you according to profiler

stray bridge
#

thanks for the reply, thats what it was. setting the maxjobworkers to 1 fixed it. im gonna further test it now in a build but i think it works

visual shard
#

Hi there Can some One help me with integrating Ads if they have done it before please provide the script and the method to do so i have tried unity doc's and youtube but wasn't able to do it succesfully

#

also i need Help with NavMesh it is not there in the designated place like with the physics and all that stuff

upbeat path
gusty socket
#

Hey there,

I'm experiencing a persistent issue where the Vuforia database is not recognized when I build my app as an Android App Bundle (AAB) with split binary options. However, when I build the project as an APK or < 150MB, everything functions correctly.

Here's what I've explored so far:

I understand that there are specific considerations with the StreamingAssets folder in AAB, such as potential delays in downloading contents. I attempted to package the Vuforia database using AssetBundles. Unfortunately, it seems that the .dat file cannot be included in an AssetBundle. For reference, the app does upload and I can open it. It is just Vuforia which doesnt work!

I have a loading scene in Unity and my main Scene which gets loaded after

Setup Details:

Unity 2022.3.25f1
Vuforia 10.22.5
Build App Bundle (Google Play) [Check]
Split Application Binary [Check]

Base Scene Size: ~50MB
Main Scene Size: ~1.5GB

I've spent numerous hours over several nights trying to resolve this without success. Does anyone have suggestions on how to ensure the Vuforia database is properly recognized and loaded in an AAB format? Any insights or fixes would be greatly appreciated.

My Question at the unity forum
https://forum.unity.com/threads/how-to-make-vuforia-with-aab-and-split-binary-work.1582065/

Thank you

upbeat path
gusty socket
upbeat path
gusty socket
glossy cargo
#

hey guys so ive made a rigidbody based character controller and a slide mechanic. for some reason tho when I slide and then stop sliding the momentum isnt conserved. for example i would slide and then jump and the slide momentum isnt conserved and im not sure why. here is code:

compact ingot
sly grove
#

VelocityChange won't overwrite the velocity

upbeat path
gusty socket
#

I think this is just for saving scenes, or Am i wrong? My problem is more Streaming Asset Folder related and that aab plus binary split separates the vuforia files. But thank you

upbeat path
gusty socket
upbeat path
gusty socket
woven marsh
#

Sorry I couldn't find a Burst or DOTS related channel so I'm asking this here:
I'm very confused about something I learned about Burst today and asked it in the forums. Can anyone who knows the answer take a look at it please?
https://forum.unity.com/threads/what-are-the-optimizations-that-burst-compiler-do.1208473/#post-9788790

stuck plinth
delicate grotto
#

hello, i'm using OverlapCollider function for a collider2d component. It requires a ContactFilter2D which i create, and add filter for player layer

_cf.SetLayerMask(Physics2D.GetLayerCollisionMask(i)); //neither of these work btw
_cf.SetLayerMask(LayerMask.GetMask(LayerMask.LayerToName(i)));

when i brute force all of the possible layers and check for collisions with player gameobject it gives different results (some collide some not)

despite that, when i include said ContactFilter2D in OverlapCollider function, it adds to its output absolutely everything that it touches no matter what layer it is on (even the UI which is on layer that collides with literally nothing lol)

how do i make ContactFilter2D actually filter out layers in OverlapCollider

upd: changing collider components properties to ignore everything does not work either so i guess it gathers only pos from the collider and not its settings

sly grove
delicate grotto
#

debug draws out rays to everything which if i understand correctly, the "everything" should be filtered out by the contactfilter but it does nothing no matter the layermask i use

#

colliders gameobject set to a layer which does not include everything in collision matrix
collider component has istrigger tickbox on (same result with or without so does not matter i think)

sly grove
#

BTW you know you can do cs [SerializeField] private ContactFilter2D _cf;

#

and you can set the contact filter up in the inspector

delicate grotto
#

does it work that way?

sly grove
#

of course

delicate grotto
#

so not through code

#

nice

sly grove
#

it works both ways

delicate grotto
#

im so upset

#

no i mean, does it actually filter things out if setup through inspector

sly grove
#

of course

#

what would be the point of it otherwise

#

It works both when set up through the inspector and when set up in code

delicate grotto
#

does not work for me when through code lemme check inspector way

sly grove
#

Well for one you aren't using OverlapCollider properly

delicate grotto
#

did i mention that the mask itself reports (i forgor the function) that it will ignore a certain gameobject when i iterate through layermasks
yet the OverlapCollider collides with anything anyway

sly grove
#
        _collider.OverlapCollider(_cf,targetsArr);
 
        foreach (Collider2D collision in targetsArr)```
This is not right
#
int objectsHit = _collider.OverlapCollider(_cf,targetsArr);
for (int i = 0; i < objectsHit; i++) {
  Collider2D collider = targetsArr[i];
  Debug.Log($"Hit {collider}");
}```
#

this is how it works^

#

you were ignoring the return value

delicate grotto
#

pretty sure that array that it returns does not depend on whether i use the return value or not

#

one way or another i iterate through its elements

#

just slightly less performant way using enumerator

sly grove
#

Yes but the return value tells you how many to iterate over. I suppose in this case since you're making a brand new array each time (which is quite inefficient) it won't matter, but it's still wasteful

#

if and when you reuse the array, it will be downright incorrect to ignore the return value

#

Anyway show me some object it's hitting that you don't expect it to hit

#

and show what layer mask you used

delicate grotto
#

yeah efficiency is not the point though
also just checked it through the inspector, does not matter the overlapcollider returns anything regardless of the layer mask

sly grove
#

show me

delicate grotto
#

1 sec

#

oh my god it works if you check use layer mask in the editor

#

docs say SetLayerMask automatically sets that propery to true though why that didnt work

#

mystery solved, set up the contactfilter through editor dont forget the checkbox, setting up through code didnt work (for me :( )

#

@sly grove thanks for the help

#

oh

#

ContactFilter2D is a struct

#

no wonder me creating a new one then changing it using its methods while not returning the result to contactfilter variable didnt work
that wouldnt actually work since it returns void, im confused now
what a waste of an hour an a half

glossy cargo
#

even regardless, if I dont move after the slide and just jump, momentum still isnt conserved

verbal yarrow
#

I'm trying to implement custom Bloom effect in Custom Render Feature, totally bypassing URP's post-processing stack. I've started from the end of pipeline - from tonemapping.
So I've created simple render pass that grabs _CameraColorAttachmentA (HDR buffer) and tonemaps it into camera color target through custom shader. But I've encountered couple problems.
Hardcoding _CameraColorAttachmentA does not seem reliable, but I can't find a workaround. UniversalRenderer has RTHandle for it, but it is internal and not acessible from custom render pass.
I see results of my render pass in frame debugger, but UPR's FinalBlit pass always overwrites it in the end. I needed to push RenderPassEvent to AfterRendering+500, but I'd like to get rid of FinalBlit totally as my tonemapping fulfills all it functions anyway

worldly pecan
#

To resolve some racing issues, I'm thinking of creating different groups that cannot read & write to the same grid location.

Does anyone know an algorithm to color a 3d grid(each node connected to 2 nodes in every axis) to 2 degrees of seperation? Such that one color cannot be adjacent to a node adjacent to the same color?

tiny pewter
#

isnt the problem is equivalent to separate the graph into three subgraphs?
btw coloring a graph using n colors for n>2 is np problem

#

but i think there should be some patterns for grid then you just need to copy and paste the pattern to apply to whole grid

outer barn
#

Hey guys , I am trying to create connected walls in a game, currently when there is an obstacle in the path of the walls they do not re-adjust their position to avoid the obstacle and create the wall by being connected to start and end point of the wall.
red is obstacle green is wall, i want the wall to wrap aroudn the obstacle like this.

any algorithm I can use

tiny pewter
#

gift wrapping, but dont wrapping the whole obstacle, start from the point than closest to one end, then wrapping in anti clockwise/clockwise until meeting the closest point to another end

outer barn
#

The red line is what i want connect from the start point to the end

tiny pewter
#

gift wrapping is the name of algorithm (though it formal name is convex hull)
google gift wrapping algorithm

outer barn
#

alright thanks

tiny pewter
#

btw if it is logical graph (your grid) you can use shortest path

outer barn
#

its a logical graph and i have astar in the project but astar is too performance intensive

stoic otter
#

i suddently get a error with fmod on the platform appletv i dont have even apple tv in the build settings i dont get it

stuck plinth
stoic otter
#

wth yeah it does

#

but why haha

stuck plinth
#

did you run an auto cleanup in your IDE or something? it's only used in conditional code

#

so it's normally flagged as unused

stoic otter
#

aa yeah i did a few days ago

#

if i save now the unused library disapear

#

i hate code cleanups haha

#

your a life saver @stuck plinth

haughty forum
#

error CS0433: The type 'IAsyncEnumerable<T>' exists in both 'Microsoft.Bcl.AsyncInterfaces, Version=6.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' and 'netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'
anyone know abt this ?

stuck plinth
rugged radish
#

I solved my problem of smoothing polygon sdf fields (shortest distance from) for small to medium sized polygons
but now I bumped into this problem again when I tried to apply that pretty expensive algorithm to a very large polygon (it uses 2 nearest point look ups and 2 ray polygon intersection tests for every point)
so I'm trying to find a better solution again, any ideas ?

#

just some keywords to research would be helpful

tiny pewter
#

the reflection....
please at least make your screen brighter

upbeat path
sage radish
hollow wraith
rugged radish
#

blur is still a consideration, I tested it and it does the job well, but I want to try and find a solution that doesn't rely on filters

sage radish
hollow wraith
#

I got the AI script from my school computer, I can post it here now, I just need to figure out how to do that (It’s currently in a google doc)

rugged radish
#

I use a lot of sharp sdf actually, it can work in most cases, but looks pretty bad for some of them

#

mainly, when transition threshold is too small

hollow wraith
#

Ok, current issues: the AI is stuck on the hunt mode, AI movement does not abide by the speed and other movement values in the Nav Mesh Agent component. Script: https://hastebin.com/share/didaheqali.csharp

sly grove
thorn flintBOT
winged shoal
#

If anyone here knows how to work with unitys NavMesh system and can help me make a good fnaf animatronic ai then please dm me (I got some code ready)

austere summit
#

Is there anyone can enlight me with UniTask?

stuck plinth
austere summit
# stuck plinth what about it?

I'm developing card game. Some of card effects completely synchronous but others want to await something. To not make things complex I want to keep effect execution code in single form. So I want all my effect Execute method to be possible to run asynchronously.

I wonder what type should those methods return. I've started from UniTaskVoid but it seems this type isn't awaitable. I'm consfused what then UniTaskVoid is for? Or maybe there is a way to use it with await. However I've ended up all methods use UniTask and synchronous return UniTask.CompletedTask instead of awaiting anything.

scenic forge
#

UniTaskVoid is just a "fire and forget" version of UniTask where you get some performance benefits at the cost of not being able to await it, hence fire and forget is the primary use case.

#

If you need to await then yes, UniTask is the correct return type.

austere summit
#

Is "fire and forget" the term to describe calling something looking as asynchronous synchronously?

scenic forge
#

No, it just means you start an asynchronous task but you don't care about its execution at all (eg whether it completes or not, what it returns, if it throws, etc)

rugged radish
#

it's pretty easy to shoot yourself in a foot with async void calls

austere summit
#

And UniTaskVoid is just special case where I want my code to be consistent to UniTask framework but I guarantee that i don't await it anywhere

austere summit
scenic forge
#

Yeah, you can also just always use UniTask if you don't care about that guarantee/performance benefits.

rugged radish
#

multiple async functions modifying collections in unexpected ways, for example

austere summit
rugged radish
#

it still doesn't guarantee any order of exection

#

wait, actually that's async in general, maybe UniTask does 🤔

austere summit
#

I mean how is it possible while all happens on main thread

rugged radish
#

async tasks also run on the main unity thread

austere summit
#

I think it is case for async / await in general in c#

rugged radish
#

and they sure cause race conditions

scenic forge
#

Race conditions shouldn't have anything to do with it.

#

async void is considered bad mostly because of error handling, and the cons of not being able to await.

#

It really exists so that you can use async methods in places where a regular method is expected, without forcing existing code to add an overload to also accept a task returning handler.

stuck plinth
#

sure you can get race conditions with async methods, just like you can with coroutines or update methods on different objects

#

async in unity is part of the good old player loop like everything else

scenic forge
#

My wording wasn't clear, "race condition shouldn't have anything to do with it" the it being "why async void is considered bad."

rugged radish
#

it was about async void specifically for me
after spending few hours debugging that code, I moved everything to awaitable code and it solved everything for me

stuck plinth
#

yeah, it's the same as StartCoroutine except you can't tell from the caller end if it continues running async

#

the context where i'd say you should 100% avoid async void is virtual methods, that can cause a huge headache

stoic otter
#

I cant figure out why cant i load this Scriptable object in build?

#

im having a few sharedvariables in scriptable obkjects

#

some of them need to save in build mode

#

at the quit function i use the save function

sly grove
#

Also are you expecting this to change a ScriptableObject asset in your Assets folder?

stoic otter
#

well some are the sound settings

#

like sfx volume and such

sly grove
#

It seems like you're initially loading them from Resources, then saving the new value in persistentDataPath?

stoic otter
#

jep

sly grove
#

But also - you said "why cant i load this Scriptable object in build"
What exactly is happening when you try to?

stoic otter
#

well it looks like it just doesnt load it while in my appdata folder it is there

sly grove
#

Can you explain what's going wrong though?

stoic otter
#

i have tried to edit it now and it almost working

#

ArgumentException: Cannot deserialize JSON to new instances of type 'SharedVariable.'

#

aa i ge tit

#

jsonoverwrite

sly grove
#

Isn't it problematic to try to directly use JsonUtility with ScriptableObjects?

#

Won't you just get the instance id?

#

(same as MonoBehaviour)

stoic otter
#

so i have GUIDS in the scriptable objects

stuck plinth
#

yeah, if you try to load it into a new object, it'll try to instantiate the scriptable object which isn't allowed, but overwriting the fields should be fine

stoic otter
#

so i want to search my type with that

stoic otter
abstract folio
#

I’ve got a new git package I made that I can’t seem to get working right. It just contains a couple simple classes, but visual studio won’t recognize them, or the namespace they rode in on. I have an older git package that works just fine, but I can’t see to find the difference between the two.
Package Manager installs it properly, and do I see the imported files in the package section of the project view.

But I get: namespace not found in visual studio

Not Working: https://github.com/glurth/Pool
To Compare I used this working version, working: https://github.com/glurth/SerializableDictionary
Once this package was added to the project, all is good: namespace found fine

I’ve double checked the package.json file, and I THINK it’s good. I’ve tried deleting and rebuilding the library folder. Folder pattern looks the same as working version (minus editor folder). Classes in the package are indeed public. Test with second package working confirm Visual Studio/ Intellisense integration is setup properly. Confirmed no compiler nor other console errors present after import. GitHub repo is public.
And Idea on what else I should check/try?

#

(ugh- sorry about that image formatting.. not sure what happened there- bottom right is after installing known-good package)

bleak citrus
#

Are you scripts in the project using an assembly definition?

#

(not the scripts in the package)

sly grove
#

Yeah it looks like the one you said is "working" is using an asmdef. Did you happen to reference that asmdef from your own asmdef?

abstract folio
#

I do not have such a file in either repo, if thats what you mean.

#

waiot what

sly grove
#

the second repo you linked has an asmdef.

Are your scripts in the project using one?

#

The ones in Assets/Scripts

#

also are you having an issue in Unity as well, or only in VS?

abstract folio
#

darn! totalled missed that @sly grove and I was LOOKING for it.. that's prolly it.. thank you!

bleak citrus
#

If your package has a non-auto-referenced asmdef, then you must use an assembly definition in your project to reference it

abstract folio
#

@bleak citrus @sly grove 💯 🎆 🥇

zinc laurel
#

https://gdl.space/tadiwavuse.cpp
i dont know why this isnt working. i want the xp that is too much after the level up to be added to the next level
i think the actuall problem is with the velocity but i dont know why

upbeat path
# zinc laurel

Will you please stop cross posting, this belongs in #💻┃code-beginner so stay there.
Looking at your code you have made no attempt to debug it, so start there

zinc laurel
#

i did man

#

but no one is helping me

upbeat path
#

no one is entitled to help here and if you actually tried to debug your code and showed some more information someone may help\

zinc laurel
#

could u help me then?

upbeat path
#

probably not, I'm off for dinner

shadow shore
#

I've asked this question in some unreal-related channels but I'm curious to see if/how it can be done in unity with netcode.
has anyone been able to create a movable, editable and network replicated voxel cluster? I want to look into making a game where you and friends can build a minecraft-like voxel space ship and walk around in it, fly it...
there are tutorials on voxel rendering in general, but not any for replication and seamless (non axis aligned) movement of clusters of voxels
also most voxel tutorials focus on worldgen and chunks, whereas in this situation I would not want to use "chunks" as such at all

#

rather than using chunks I would want to allow a cluser of arbitrary voxels to move as if it's one gameobject, then if i wanna do traditional MC worldgen later on (for planets for example) i could inherit from the arbitrary voxel cluster but disable movement replication

#

if anyone is interested in coding something like this lmk

#

it would need a minecraft-like server-client model where the server (or internal server) does all the world saving and loading

shadow shore
#

what? I meant I was interested in talking to others about this

dusty wigeon
# shadow shore I've asked this question in some unreal-related channels but I'm curious to see ...

If you have followed a tutorial on Voxel you should be more than able to make it non-aligned and networked. It is a simple as generating a voxel volume in local space than using a transform to modify the rotation and position. The network part could be as easily as generating both the voxel on all client and server. In fact, that would probably be the best method given that you might want to modify the voxel in real-time and it would demand a tremendous amount of data to pass through the network each time you modify a new cluster of voxel.

Also, note that minecraft does not use voxel rendering.

shadow shore
#

so you mean it would be best to replicate the actions (break block, place block) to the server and clients, which have independent copies? makes perfect sense to me

#

because the client shouldnt even have all the world loaded at once voxel-wise, it should stream it in when needed like minecraft does and keep its own copy clientside

#

minecraft does not use voxel rendering.
wdym by this?

dusty wigeon
#

Not voxel rendering, simple mesh rendering

shadow shore
#

let me clarify what i mean in case "voxel rendering" means something other than what i thought,
I want to use greedy meshing similar to how TanTan demonstrates in his Rust/bevy implementation to render voxels in the world

dusty wigeon
shadow shore
#

oh my bad what technique does it use for rendering the chunks efficiently

compact ingot
shadow shore
#

So every block is at least 2 tris?

#

Welp, if it's good enough for Minecraft it's good enough for me I suppose

compact ingot
#

the performance issue in voxel worlds is entirely derived from the amount of data that’s required to store such worlds.

#

And ofc if you want to use expensive meshing algorithms like accurate dual contouring etc for smooth surfaces that can still have sharp features

shadow shore
compact ingot
#

Yes, if you pick your style appropriately you can get away without any optimization

shadow shore
#

I was actually thinking about trying out ray traced lighting anyway lol

#

Optimisation be damned if it looks cool

#

Not that I'm sure of how to do that in unity specifically, I'm weighing up whether this would make more sense as an unreal project

compact ingot
shadow shore
#

As much as I love the pixel aesthetic I also somehow hate low resolution

#

But it is an intriguing idea

compact ingot
#

use dlss to upscale it to 4K

shadow shore
#

GPU "software" RT is good enough for Fortnite to run as well as it does so I could try that.. but that would require knowing how to write GPU code lol

shadow shore
#

Dlss can do surprisingly low resolutions actually, 3kliks video on it was wild

#

I think it got as low as 360p base -> 1080p out before things started being unplayable

#

It would be funny

#

Anyway the reason I'm inspired to do something like this is I thought it would be cool to not only make a little game where you could build ships and fly them around but also one that's super moddable and reads in and registers blocks based on config files

austere summit
#

@scenic forge I use UniTask and R3 together. So I have some subscription and I want to callback with async method returning UniTask<int>. When use async lambda rider says that it is bad case with async avoid stuff but worse. Is there a way to subscribe to Observable<T> and react with UniTask async method?

stuck plinth
#

if you mean the event delegate type is returning a Task, that's usually to be avoided, there's a lot of ways for that to go badly and it's why event handlers are generally the one place async void is better

regal olive
#

Good video

austere summit
austere summit
# scenic forge Can you show your code?

Here I subscribe to some ICardSelector which request some index to be selected and awaits it. When ICardSelector do request in that case I want to subscribe to any numeric button pressed for in editor test purposes. The main pain point in that code for me is that I forced to use async void lamda for SelectionRequested as callback.

public class CardSelectionInEditorProviderTest : IInitializable
{
    [Inject] private readonly ICardSelector _cardSelector;
    
    public void Initialize()
    {
        _cardSelector.SelectionRequested.Subscribe(async cardsToSelect => 
        {
            _cardSelector.SelectCard(await SelectCard(cardsToSelect));
        });
    }

    // TODO: add clamp to [0, cardsLength)
    private async UniTask<int> SelectCard(IReadOnlyList<ICard> cards) 
        => await Observable.EveryUpdate()
            .Select(_ => GetNumberKeyPressed())
            .Where(numberKey => numberKey != -1)
            .AsSystemObservable()
            .ToUniTask();

    private int GetNumberKeyPressed()
    {
        for (int i = 0; i <= 9; i++)
            if (Input.GetKeyDown(KeyCode.Alpha0 + i) || Input.GetKeyDown(KeyCode.Keypad0 + i))
                return i;
        return -1;
    }
}
scenic forge
#

Try wrapping it in UniTask.Action(async ... => ...).

#

Ah, doesn't seem like UniTask.Action has overloads to accept things with arguments, unfortunate.

#

If Unity supported C# 10 you could use explicit return type, but well we are stuck on C# 9.

#

Welp, you can always make your own util wrapper method like UniTask.Action but allow more parameters.

scenic forge
#

You would just do async UniTaskVoid cardsToSelect => ....

austere summit
scenic forge
#

If you don't want to use a wrapper you can also just inline what the wrapper does into the call site.

#

Or if you have the ability to modify the method signature, adding an overload would also solve it.

austere summit
#

I've tested this approach and it seems that when .Forget() used await just get lost and never happens.

public void Initialize()
{
  Action<IReadOnlyList<ICard>>(async cardsToSelect =>
  {
      UnityEngine.Debug.Log($"start to await num selection"); // this log happens
      var num = await SelectCard(cardsToSelect); // this never happens
      UnityEngine.Debug.Log($"num selected: {num}"); // this never happens
  }).Invoke(null);
}

public static Action<T> Action<T>(Func<T, UniTask> asyncAction) 
    => value => asyncAction(value).Forget();

// awaiting this works fine
private static UniTask<int> SelectCard(IReadOnlyList<ICard> cards) 
  => Observable.EveryUpdate()
      .Select(_ => GetNumberKeyPressed())
      .Where(numberKey => numberKey != -1)
      .AsSystemObservable()
      .ToUniTask();
shadow shore
austere summit
#

seems the problem is in async UniTask<int> SelectCard function, because awaiting UniTask.Delay works normally.

elfin bane
#

Good night

what is this cool bug in Unity?

I call set on flags only if I open the dropout again and select another flag

if you select several flags in a row in a dropdown, only the first one calls set

this only happens if you assign values to an array; if you remove the assignment, then everything starts to appear normally every time you click on the flag

is there a way to fix this?

sage radish
elfin bane
#

I think that assignment to array redraw editor inspector and flags break

edgy zealot
#

Hey can someone point me in the right direction with this?

Ill explain a bit about what im trying to achieve and what I've already done.

I am trying to create a drag and drop WeaponFiringLogic base class that other classes can derive from allowing me to create many firing logics that all must implement the same 3 methods , start , update , OnTriggerEnter2D

What i have done. I have created the base script and i have created a firing logic variation.

What the problem is... The issue is that i am not able to drag a class that derives from the base class into a public reference within the inspector.

Why do i want to do this..

I want to do this so that i can make different firing logics and then drag the one i want into the public reference contained within a scriptableObject called WeaponData to assign the firinglogic that should be used.

I cant seem to find an easy way to do this.

untold moth
dusty wigeon
edgy zealot
edgy zealot
#

The problem is that unity does not allow for polymorphisim (thats what chat gpt told me) I cannot drag a WeaponFiringLogic into a public reference because unity does not understand how to serialize the properties.

If this is the case then i feel as if i am forced to just code specific firing logics and will need to be hard coded instead of just being able to assign a firingLogic to the weaponsData

regal lava
edgy zealot
regal lava
#

I mean the project itself. Usually SerializeReference is something to bandaid up my misjudgenment of how I am to serialize things haha

edgy zealot
#

ahh, Yeah i dont even know what you mean in regards to SerializeReference other than using the [SerializeField] attribute

#

The issue is i cant find any tutorials that go the route im trying to go , they all just show basic stuff.

regal lava
#

One problem with the editor is that it's not good at ambiguous types like interfaces or generic classes without defined* constraints

#

because there's not really enough information to tell it by simply dragging an asset onto it, but SerializeReferences do provide ways to give it an idea what these types would be

edgy zealot
#

is this why chat gpt was trying to get me to create an interface for the FiringLogic?

#

sorry im trying to provide relevant information without just posting everything lol

#

i think i understand what you are trying to say and will look more into SerualizeReferences

regal lava
#

Probably post the code to give me an idea what you're trying to do

#

for all I know you're not adding [Serializeable] to some c# class

edgy zealot
long ivy
#

the simplest way to do what you want is to make WeaponFiringLogic into an abstract SO and create your implementations as more SOs. Polymorphism will work that way and let you drag n drop your implementations to a standard serialized field on WeaponData. SerializeReference is a cleaner way to do it, but much trickier to use and has a bunch of its own caveats that I think you are not ready for if you're trying to have chatgpt explain things to you

regal lava
#

!code

thorn flintBOT
regal lava
#

try some paste sites

edgy zealot
#

weird its not letting me post the photos

#

Weapon Data 1/ 3

#

Interface

#

Test firing logic

#

i want to assign the test firing logic to the weaponFiringLogic reference in the EnemyWeaponData

regal lava
#

IWeaponFiringLogic would need some SerializeReference to work with the editor

edgy zealot
#

ahh so it is a polymorphisim issue

regal lava
#

consider just doing SOs inside of SOs like reaper mentioned

edgy zealot
#

A scriptable object cant contain methods can it?

regal lava
#

it can, sure

edgy zealot
#

i thought it was just a container for references

#

ohhhh

#

shiii

#

I dont know how ive never tried that

#

😂

regal lava
#

ScriptableObjects are just c# classes at core, but they are helpful such that you can reuse those instances throughout your other objects

edgy zealot
#

i mean i know how to do it i just had never attmepted it before , i just assumed it was only for holding things

#

So i should just create a ScriptableObject of type FiringLogic and then use the createAssetMenu attribute to create new ones

regal lava
#

Right, but the logic between each instance would be the same. But the idea with ScriptableObjects is you can set different default values for each instance and share them between multiple classes

edgy zealot
#

ahh so that isnt what i want then

#

i need to switch the entire code

#

cant just fill in different values for things like speed

long ivy
#

your code suggests these should not be SOs at all, but instead MonoBehaviors

regal lava
#

To me it seems like you just want some composite logic

edgy zealot
edgy zealot
long ivy
#

you aren't passing any data into your weapon firing logic, so you have a design problem as-is

edgy zealot
#

thats what an example weapon data looks like

regal lava
#

You do have the idea there, but the problem is that you're using interfaces in place of abstract classes which unfortunately doesnt work that well with the editor

#

they are useful in other situations with unity, but for serialization purposes you should avoid them

edgy zealot
#

any way you can easily explain the difference between abstract and non abstract?

#

i thought abstract was a way to make it so any class that dervies from it must implement its methods

regal lava
#

abstract would be IWeaponFiringLogic as public abstract class WeaponFiringLogic, that's really it lol

#

instead of by how you've got it set up in the interface there, then you can extend your dumbfirerocketlogic class from it

edgy zealot
#

are you saying to do this?

warm whale
#

Hey,
I dont know if it fits here but how can i connect my Unity Game Skins with a Steam inventory so players can trade Cosmetics?
And do i need any own Dedicated server for it?

edgy zealot
#

youd need steamworks setup if you dont already

#

lmao i feel stupid asking the same question over and over... Appreciate all you for the help!

regal lava
#
public abstract class WeaponFiringLogic : Monobehaviour
{
  private abstract void StartLogic();
  private abstract void UpdateLogic();
  private abstract void OnTriggerEnter2DLogic(Collider2D other);
}

public class DumbFireRocketLogic : WeaponFiringLogic
{
  private override void StartLogic() { }
  private override void UpdateLogic() { }
  private override void OnTriggerEnter2DLogic(Collider2D other) { }
}```
edgy zealot
#

ohhhhh

#

i see

warm whale
edgy zealot
#

thats my issue is that everything ive learned is trial and error using chat gpt as an assistant. I just dont have the knowledge that some of you who may have studied it have.

edgy zealot
#

i can look around for some tutorials for you but i doubt id find anything you havent already searched for

warm whale
#

All good thank you for your help i will probably try ask ChatGPT xd

edgy zealot
long ivy
#

those are MonoScripts, wrong type. You need an instance of WeaponFiringLogic. If it's a SO, create it via asset menu. Otherwise you need to create a prefab that contains it

regal lava
#

right so with mono it would require another gameobject with a component of WeaponFiringLogic

edgy zealot
long ivy
#

no, you can't reference scene objects from a SO so that will also not work

#

that's why I said you have a design problem

edgy zealot
#

hmm maybe im not grasping something here

#

ima take a min to think about what you guys are saying

#

i mean ive been using unity for 2 years , what you are saying to me makes 0 sense

#

Are you saying that a ScriptableObject cannot have references to a monobehaviour script stored within it?

#

i guess im really just not grasping the key points of what you are trying to explain.

regal lava
#

so here's some things. If you were to remove mono from it, and added [Serializable] to the class. Then you have to be explicit on the type that you want, but this is where serialize references do help as then you can be more specific to the type you want

#

but in this situation you can go about it two ways, either do it by prefab instances or by SO instances

#

I say the real benefit of serialize references here is reduction of asset bloat haha

edgy zealot
#

lol its so hard to forumalte my thoughts into words

regal lava
#

for the sake of understanding, remove mono from the abstraction and make your derived class [Serializable] then inside of your SO class specifically define the type as the derived

long ivy
edgy zealot
long ivy
#

I think you are going about this wrongly. Your weapon logic should be a MonoBehaviour that contains a serialized field to your WeaponData. Then your weapons are all going to be prefabs

edgy zealot
regal lava
#

if you were to do it by c# serializable classes you usually need to be explicit on the type outside of a few patterns or serialize references

#

one pattern includes new-ing the class at runtime using a struct of info

edgy zealot
#

maybe its just not possible the way im going about it.

Thanks all for your help!

Im sure ive been a pain to deal with lol

regal lava
#

the easiest solution I believe is just do SOs and extend those out with different derived classes

#

I'm not a big fan of SOs like this, because it can create asset bloat, but that's pretty common to do if you want this modular behaviour

edgy zealot
#

i need to look more into what scriptable objects can do as ive only been using them to hold things like images , floats , bools , ints , lists , dictionary's

#

if its possible to store methods within one then that might be easier

regal lava
#

the overall problem is you want a specific type instance but the editor doesn't know the exact type you want, and unfortunately your way of thinking of dropping the script into the field is not a viable solution with unity (it's also an issue for serialization as it would need to be serialized as this more derived type despite the field being its abstract base type... but again, serialize references do fix this issue)

#

so the fix to it is create the specific instance elsewhere and insert it into that field

edgy zealot
#

what im having a hard time with is that im just wanting to be able to use any script that derives from the base , is the issue that its expecting the actual base class and not one that dervies from it

#

i was under the impression that if i make a reference to a baseclass then i should be able to use any class that derives from the base

#

if this is not the case then i really do need to go and learn more

regal lava
#

you can absolutely insert any class that derives from WeaponFiringLogic in that field you delcared, it's just telling the editor you want to use a specific derived type of it is the problem

edgy zealot
#

ohhhh

#

its just the editor cant serialize it

#

thats what chat gpt was telling me and thats why it made me make the interface

#

clearly chat gpt doesnt know everything

#

ive just been getting thrown in a loop

stuck plinth
#

the editor can handle this just fine with scriptable objects or monobehaviours, you just have to give it an instance not a reference to the script asset

regal lava
#

it's a pain in a butt but yeah, this is where serialize references do kind bandaid all of this, but for the past decade before serialize references were a thing people just made prefabs to overcome this problem

edgy zealot
stuck plinth
#

in your video, you're dragging your script (a text asset) into the slot

edgy zealot
stuck plinth
#

it's a script asset, you know what i mean haha

edgy zealot
#

i was dragging this into the SO

regal lava
#

is it a prefab or a scene object

edgy zealot
regal lava
#

make it into a prefab then drag it onto the SO

edgy zealot
edgy zealot
#

damn channel wont let me put gifs , jesus christ so all i had to do was make it a prefab

#

Thank you

#

so much!

regal lava
#

well, it's better to understand why you need to make it a prefab in the first place

edgy zealot
#

i just wasnt connecting the dots

regal lava
#

but SOs would work too in this case if you don't need the scene presence of a mono

edgy zealot
#

ive struggled with this for a good year now , i just couldnt figure out how to switch logic beyond using stuff like state machines

#

but im not making a state machine for each firing behaviour you know ....😂

#

Lol thanks again... ive been trying to figure this out for a long time!

regal lava
#

ye np, fighting with unity's editor is part of the experience of making a game

edgy zealot
#

i figured i was gonna end up having to make my own editor tool 😭

#

Seriously though i do appreciate all of you guy's help!

think i may finally be un stuck

untold moth
# edgy zealot i was dragging this into the SO

This is a text asset from unity's perspective. It doesn't give shit that the text is compiled into a type that you're interested in at some point. It's like you write "money" on paper and try to buy something in a store with it.

edgy zealot
untold moth
untold moth
edgy zealot
#

correct in the end it is all just text.

#

or rather numbers

untold moth
#

Point is, that text is not associated with anything at that point.

#

Definitely not any types or instances

#

That's why SOs are a thing, they allow you to create instances of classes as assets.

edgy zealot
#

I def got some more learning to do!

I have not explored all the possibilites with scriptable objects and have only been using them as containers for things like floats , lists

#

Im happy with the current outcome of using prefabs to contain the firingLogics but would like to move it to scriptable objects in the future.

regal lava
#

honestly, dragging a poco onto a field seems reasonable but unity's serialization isn't the greatest. The release of serialize reference was useful but I feel like they should have integrated them more into the editor and the UI. There are libraries around that do pick up unity's slack, but still it stinks to be relying on these independent developers for stuff that should just be features.

edgy zealot
#

whats poco?

regal lava
#

plain ol c# object

edgy zealot
#

oh lol i was thinking property oriented class object XD

regal lava
#

In software engineering, a plain old CLR object, or plain old class object (POCO) is a simple object created in the .NET Common Language Runtime (CLR) that is unencumbered by inheritance or attributes. This is often used in opposition to the complex or specialized objects that object-relational mapping frameworks often require. In essence, a POC...

#

CLR object rather

edgy zealot
#

Yeah honestly it seems like it should just work lol like it has no problem showing public references within a SO so why does it have such an issue showing them when the poco is wanting to be assigned as a ref , youd think id just look at the public properties and show them in addition

regal lava
#

Another idea if you dont want to create editor assets is to map your types to enums/structs to initialize those instances

edgy zealot
#

im doing something like that but im just using the enums as a way to decide between things

#

like this enum is within each WeaponData scriptableObject so i can switch the weapons type from within the weaponData

regal lava
#

sounds good. Enums are great for reducing assets and classes in general

edgy zealot
#

lol honestly ive just been learning through trial and error , occasional tutorial and lots of chat gpt

#

finally had to get on the unity discord and get some real help 😂 ♥️

#

its sad ive managed to figure out A* and XOR encryption with data handling before i figured out how to do firing logic 💀

lethal bloom
#

anyone have experience with splines?

sly grove
lethal bloom
#

I've got a spline, but my code to have an enemy looking towards where its going it producing some weird angles, meaning its constantly looking somewhat upwards. I have a clip to demonstrate if needed

open haven
#

Hey guys, I don't know if this question deserves to be in this channel but here is my issue:
I have made it so that I have a parent cube with fixed rotation (0, 0, 0) that will surround a child object perfectly with a side touching the outer-most points of the object in 6 default direction.
So far, it works well. Now I want to make this blue object the child object so when I scale the parent cube, the child object will scale up accordingly.
This works well when the child object is not rotated. However, when the child object is rotated, it always pokes outside the parent cube. I am guessing that this is an issue with Unity's scaling and I should not make the blue object the child of the parent object at the first place. Any suggestions to what can be done in this situation?

tiny pewter
#

is the child object really child in the hierarchy?

#

mb, didnt read your question clearly

#

is the child initial scale < parent in all dimension?

#

btw i dont think it is code question at all

upbeat path
# open haven

when you rotate the child do you increase the size of the parent cube?

real slate
#

is there a way to convert a gameobjet to entity without subscene

sly grove
open haven
upbeat path
#

does not look 'perfectly' aligned to me

#

can you show a before and after pic and show your hierarchy and the inspectors

#

Also not really a code question

open haven
#

When it is not a child object, it is normal. When it is selected and become the child object of the parent (white) it gets stretched for some reason even though its collider stays the same.

#

In before there is no parent-child relation.

sly grove
open haven
sly grove
#

but technically - as long as all the axes of scale are identical, it is uniformly scaled

upbeat path
#

that is why I asked for the inspectors as well

sly grove
#

If you have scale that is different on any of the axes, it is not uniformly scaled

open haven
#

No its is not, it just fits in based on the collider of the blue child object beforehand.

sly grove
#

That's your issue then

#

you are getting skewing

#

whenever you have an object that has children in Unity, it's best practice to only have uniform scaling on that object

#

Unless you are trying intentionally to skew your objects

#

Note that box colliders are always box shaped

#

So when you skew your renderers with non-uniform scaling, the renderer will no longer match the collider

#

the collider will always be a perfect mathematical rectangle

open haven
#

Okay, I understood. Then what would you suggest so that I dont get this.

#

My main goal is to be able to make it so that the child object always fits in the parent rectangle perfectly. And the main reason I am making it the parent is so that I want this parent (object manipulation tool) to be able to rescale this child object.

sly grove
#

But maybe a better question is - what is the goal of this thing?

open haven
#

3D VR scaler whrere by moving the spheres at the corner of the parent we scale the parent up, hence scaling its child object accordingly.

austere summit
#

why can't I create test assembly folder. This option is inactive in some folders and active in some others

#

ended up creating test assembly manually

timber flame
#

Have you used behaviour trees? In behaviour trees, there is something called blackboard to keep some variables and share them to different actions/tasks, we can read them and write into.
My problem is that blackboard in my view is hell because it can contain many irrelevant variables, managing them is really hard, what is your opinion?

wet sail
#

hello. i need some math help. i have a custom character controller with this velocity calc code (per frame)

Vector3 targetMovementVelocity = Vector3.zero;
if (Motor.GroundingStatus.IsStableOnGround)
{
    // Reorient velocity on slope
    currentVelocity = Motor.GetDirectionTangentToSurface(currentVelocity, Motor.GroundingStatus.GroundNormal) * currentVelocity.magnitude;

    // Calculate target velocity
    Vector3 inputRight = Vector3.Cross(_moveInputVector, Motor.CharacterUp);
    Vector3 reorientedInput = Vector3.Cross(Motor.GroundingStatus.GroundNormal, inputRight).normalized * _moveInputVector.magnitude;
    targetMovementVelocity = reorientedInput * MaxStableMoveSpeed;

    // Smooth movement Velocity
    currentVelocity = Vector3.Lerp(currentVelocity, targetMovementVelocity, 1 - Mathf.Exp(-StableMovementSharpness * deltaTime));
}
else
{
    // Add move input
    if (_moveInputVector.sqrMagnitude > 0f)
    {
        targetMovementVelocity = _moveInputVector * MaxAirMoveSpeed;

        // Prevent climbing on un-stable slopes with air movement
        if (Motor.GroundingStatus.FoundAnyGround)
        {
            Vector3 perpenticularObstructionNormal = Vector3.Cross(Vector3.Cross(Motor.CharacterUp, Motor.GroundingStatus.GroundNormal), Motor.CharacterUp).normalized;
            targetMovementVelocity = Vector3.ProjectOnPlane(targetMovementVelocity, perpenticularObstructionNormal);
        }

        Vector3 velocityDiff = Vector3.ProjectOnPlane(targetMovementVelocity - currentVelocity, Gravity);
        currentVelocity += velocityDiff * AirAccelerationSpeed * deltaTime;
    }

    // Gravity
    currentVelocity += Gravity * deltaTime;

    // Drag
    currentVelocity *= (1f / (1f + (Drag * deltaTime)));
}
if (_internalVelocityAdd.sqrMagnitude > 0f)
{
    currentVelocity += _internalVelocityAdd;
    _internalVelocityAdd = Vector3.zero;
}

now, if you can see, _internalVelocityAdd would lunch the character so high when in air compared to ground

#

now this is the add velocity method

        public void AddVelocity(Vector3 velocity)
        {
            _internalVelocityAdd += velocity;
        }
#

i dont want the character to be launching faster in air. im not sure to fix that.
basically i tried to modify the AddVelocity function into this

_internalVelocityAdd += Motor.GroundingStatus.IsStableOnGround ? velocity 
    : (velocity.magnitude > MaxAirMoveSpeed - Motor.BaseVelocity.magnitude ? Vector3.zero : velocity);

but im not sure if its correct (most likely not)

compact ingot
# timber flame Have you used behaviour trees? In behaviour trees, there is something called bla...

It’s a well established design pattern that solves a recurring problem. It is generally a good idea to curate exactly what variables are exposed to the behavior design space. With all access behavior trees (not using a blackboard) you typically get tons of hacks and convoluted deep-links that are unmaintainable https://en.m.wikipedia.org/wiki/Blackboard_(design_pattern)

In software engineering, the blackboard pattern is a behavioral design pattern that provides a computational framework for the design and implementation of systems that integrate large and diverse specialized modules, and implement complex, non-deterministic control strategies.
This pattern was identified by the members of the Hearsay-II projec...

spare creek
#

has anyone ever seen this happening before with debug logs?

#

all im doing is debug logging a string and for some reason its not logging the last part of the text and instead is overlaying it over the first part

#

this is my debug log

#

newItem.isPotion should just be a string that says true as is definied in this csv thats imported

#

this is how im loading the csv

#

and this is how im parsing it

#

i dont see any obvious issue here

#

and ive never seen anything like this befire

#

ah its this which is a classic windows moment

#

fixed by just removing all \r if anyone comes accross this

upbeat path
#

you should also use the SplitString.RemoveEmpty option

pallid glacier
#

Do you know some intresting tutorials for submeshes ? (with multiple materials) because those i find are litterally 10 years old, so i hoped i could have some help here...

I am working on a voxel engine and i want to display a chunk, so i made something to merge the vertices that have the same colors in a chunk, but now it creates a game object for each mesh (one mesh being 2 triangles that makes a rectangle of various size being the merged voxels)
this is what i have (the merges are not perfect, but at least its fast)

#

Here all pair of triangles is a game object with a mesh, how can i do only one game object with all meshes (to have only one draw call ?)

regal lava
#

if you want different textures (one material) you use a texture atlas/texture array and just change the UV values on the mesh itself

#

if you're merging different gameobjects via mesh combine method I think it creates a submesh for each material

pallid glacier
pallid glacier
regal lava
#

you want to use a single material, but your choice of the color/texture depends on the vertex data

#

technically you can just do it with vertex data, but ideally you want to do it inside of the shader cause then you can do more with it using the shader graph

#

or just use world UVs with triplanar ;)

pallid glacier
pallid glacier
pallid glacier
regal lava
#

read up on how minecraft samples a texture atlas, there's quite a few tutorials for unity on it too

pallid glacier
regal lava
#

well, the difference there is you're changing the color vertex data and not the uvs

#

but like I was saying, if you just focus on the UVs, you can just sample a color/texture sheet

#

can do both it doesn't matter

#

my setup for my voxel stuff

#

doing it in shader graph allows me access to unity's shader functionality while also letting me to expand onto it

#

of course you can just do it in hlsl if you wanted to

pallid glacier
#

Okay i'll look into it

regal lava
#

https://www.youtube.com/watch?v=Q60cdwZDyjE
good overview how it works, but the video changes the uvs via gameobject, but you want to change the uvs as you create the mesh yourself (or make a painting tool utility to change the uvs after making the mesh)

Wondering how to implement a texture array in Unity? Want to know how they differ from Texture Atlases? Then this video is for you. A quick explanation of the differences with some hands on c# and shader code to get your own texture atlas up and running in Unity

▶ Play video
hybrid belfry
#

Hello, I am trying to understand why my lambda function does not work as expected. The lambda version of my code assigns the same integer for each looped item and it's always the last item index. The working code works as expected. Can anyone tell me why?

Lambda

for (int i = 0; i < playerUnlockables.Count; i++)
{
    InstanceIDtoAction.Add(playerUnlockables[i].selectableImage.transform.GetInstanceID(), () => { 
        isTouchingUIElement = HighlightOnUnlockableSelected(i);
    });
    Debug.Log($"Using {i} for HighlightOnUnlockableSelected");
}

Working

InstanceIDtoAction.Add(playerUnlockables[0].selectableImage.transform.GetInstanceID(), () => isTouchingUIElement = HighlightOnUnlockableSelected(0));
tall ferry
hybrid belfry
tired fog
#

Is there any way to complete all the existing jobs used by unity regardless if i have the handles or not?

#

And note, I don't use Entities, so I don't have the method CompleteAllJobs() to use

#

Only Jobs and Burst compiler

#

This is a solution to a problem I have when schedulling a job in OnValidate, where when I enter play mode and the game gets recompiled, it loses reference to all handles and the jobs cannot properly complete

upbeat path
tired fog
#

love you

upbeat path
#

Calm down, simple worship is sufficient, lol

clear shard
# wet sail hello. i need some math help. i have a custom character controller with this vel...

I'm not entirely sure I understand how _internalVelocityAdd would be launching the character higher in air than in ground when the if-else clause shown here is only covering lateral/ground-constrained movement. But I think what you're getting at is that _internalVelocityAdd may launch the player too high if the player is already travelling upwards (e.g. just after a jump), is that right? In that case I'm assuming you have some sort of double jump mechanic?
Looking at last message you posted, it looks like you want to limit the magnitude of velocity in your AddVelocity() function to MaxAirMoveSpeed - Motor.BaseVelocity.magnitude to avoid this happening, so I reckon just adding something like velocity.normalized * Mathf.Min(velocity.magnitude, MaxAirMoveSpeed - Motor.BaseVelocity.magnitude) in AddVelocity() should cover all use-cases.

viscid bramble
#

How do I start my character grounded?

half swan
# viscid bramble How do I start my character grounded?

This is not an advanced code question
But it depends on how you start the game. Is the character there already? Then simply position it in the inspector
If you instantiate it, and there is complex ground, consider raycasting downwards and using the hit point as the position for your players pivot

viscid bramble
#

yes, it's there

#

Its Y is 0.0

#

But IsGrounded starts as false

half swan
#

Are you perhaps starting INSIDE the ground?
And is the a CharacterController?

viscid bramble
#

Well

#

How could I know

half swan
#

Are the feet or whatever intersecting the ground?

viscid bramble
#

Well

#

kind of, yes

half swan
#

Then that is an issue. Raise it up a little

viscid bramble
#

doesn't work either

#

I set it the same value as when the character touches ground

half swan
humble walrus
#

I need some advise. My game is going to have extremely complex items, with the following data structure;

Equipment
  List of Items
    Item
      List of Materials
      List of Shapes

I know how I want to set it up, generally speaking, but organizing these items into a proper inventory is something I've been struggling with, on both the coding and game design side. Does anyone have any examples, resources, or just plain advise on how to stack, organize, and display an inventory of Items and Equipment where each one can have complex data associated with it, and can end up fairly flooded with semi-unique items?

I know the hypothetical inventory will need to have at least two types of slots, one which holds single pieces of Equipment, and one that holds a sub-inventory of Items, but how can you have a List which can have two different types of slot, which hold completely different data structures?

timber flame
#

Hey, what do you think? in the game Timberborn, they have used cellular automata for water simulation?

dusty wigeon
# humble walrus I need some advise. My game is going to have extremely complex items, with the ...

Not sure what is complicated here ? Personally, I prefer to keep equipment in the inventory as well and not have two distinct "inventory" system. This way you can easily have things like equipable quest item without really having to make two distinct check for it. If you do not want to show the equipment in the inventory, simply do not show them if they are equipped.

In code, it is as simple as creating a data structure that is polymorphic.

public abstract class Item {}
public class EquipmentItem : Item {}
public class Weapon : EquipmentItem {}

private List<Item> items = new List<Item>();

Note that I would advise to create something like EquipmentItem and instead use Interface (or even better, composition) because otherwise you are going to quickly run in multiple inheritance issues.

I prefer something like that:

public abstract class ItemData {}
public class EquipmentData : ItemData {}
public class QuestData : ItemData {}

public class Item
{
  private List<ItemData> datas = new List<ItemData>();

  public bool TryGetData(out ItemData data);
}

However, as a beginner, you should be more direct and simply have:

public class Item 
{
  #region Equipment
  public int Armor { get; }
  public int AttackPower { get; }
  ...
  #endregion

  #region Source
  public enum SourceType { get; }
  public List<Material> CreatedFrom { get; }
  ...
  #endregion
}

At the end of the day, you choose whatever you prefer, but the obvious choice in my eyes for a beginner, if you only want to make the game and are not really interested in coding part, is the 3rd one. It is straight forward, if the game is simple it is also the one that would make the more sense independent of your experience.

humble walrus
dusty wigeon
humble walrus
#

I basically want my players to be able to craft equipment out of multiple items, so there's a need for a structure that can support slots that contain items, and slots that contain "Equipment" blocks

dusty wigeon
humble walrus
# dusty wigeon Why ? Just make the composant equippable ?

Yeah, that's the idea.

So there would be two slot types,

Equipment
  Items that are part of that equipment block
    Blah blah blah

Pile of Items
   Items that are in the pile
      Blah blah blah

So I would want to make an abstract class for slots, and then two derived classes, one for Equipment, and one for Piles?

dusty wigeon
humble walrus
#

So how would you suggest handling that specific situation? (Having Equipment made of multiple items, and Items in the same inventory)

dusty wigeon
#

I believe that you are adding too much abstracting already and instead should try to use a more simple approach such as a "god class" item.

#

It would align more with your level of experience and aptitude.

regal lava
#

Yeah, my attempts at an inventory eventually boil down to just doing type comparisons

#

unless you've multiple types, which then means to group your types a bit more

dusty wigeon
humble walrus
#

One way or another, the inventory system has to be able to handle discrete lumps of items, since it'll be using a spore-esque item builder.

So, in short, if I used method two, the structure would look something like...

#
Slot (With a variable for whether it's a Pile or Equipment
  Item Collection
    Item Data (which can contain either Equipment-specific Data, or just the individual Item Data)

Is this right?

dusty wigeon
humble walrus
#

So the Item class would itself contain a list of Items? I wasn't aware recursion like that could work

#

That's actually much simpler!

dusty wigeon
#

Usually, it is not something you should do, however because you do not understand correctly how everything works in coding you will have a lot more success in going this path.

humble walrus
#
Slot
  Items
    Item Data
    SubItems
      ect ect

So something like this, then? What is the issues with doing it this way?

#

You say it's usually not something that should be done

dusty wigeon
humble walrus
#

So which method from the ones up above avoids using a god item? You said I should use an interface or composition, are there some good resources for how I can use that instead?

#

It's better that I do it right, even if it's "above my skill level"

dusty wigeon
humble walrus
#

Ahh

dusty wigeon
humble walrus
#

Sorry if I'm being annoying, I'm just trying to learn and do things right.

dusty wigeon
#

In other words, accept that your code will have flaw.

#

This way, you are going to progress towards your goal instead of getting stuck at the starting line.

humble walrus
#

What are some roadblocks I'm going to run into as a result of using a "God Class" for my item data structure, so I know what to look out for in advance?

dusty wigeon
#

Usually, it is due to how some item will only use a part of the class.

#

By example, in case of a "Quest Item", you might have something such as what quest the item is associated with. However, not every item are going to be "Quest Item", hence your field is going to be empty.

#

This will happens for many and many more case inside your class.

#

Nothing you cannot deal with, it just will cripple you in your ability to make code faster and more robust.

humble walrus
#

I don't plan on having something like a "Quest Item", however. This system is purely and hyperfocused for holding two sets of values-

Base Item Stats
Equipment Specific Construction data for spawning item collections (I.E, it'll store Transforms and Parent Index so I can instantiate them all for setup during combat)

dusty wigeon
#

But, obviously, it depends on how much your God Class is big which is also directly dependent on how much your project is big.

dusty wigeon
humble walrus
#

Also, I have a seperate system with a database for holding base-items already, so something like "Quest Item" data is already handled

#

I use a system of Scriptable Objects to hold core item data currently

dusty wigeon
humble walrus
#

It is immutable, it only holds the base item data, and the inventory will only recieve base values from it

dusty wigeon
#

Or, having stacks of quest item.

humble walrus
#

It won't be, if I need specific items for a quest, I have a database with every item indexed into it, and can just flag for a specific item index. Are there any issues with that specific approach?

#

I won't ever need to change base item values, only store collections of them

dusty wigeon
#

Such as

  • The amount of use remaining
  • The current percentage charged
  • The amount of stacks
  • etc.
humble walrus
#

None of those are a factor for my game's design, though.

humble walrus
#

Yes, but even if I did, I wouldn't store that data in the base item scriptable objects. Those are purely for reading from. If I needed to track Stats, Stacks, and the like, those would be in a class which only holds a referennce to the base items.

So the Base Items just hold stuff like attack power, weight, and value, and things read from that class to know what the item's default values are.

#

I'm basically just using them to store templates, not in-game items

dusty wigeon
#

Almost every object in a Video Game has "Share Data" and "Instance Data". Usually, I make a scriptable object that I call "Definition" for each type of object. Quest, Character, Item, Abilities, etc.

#

And, the same way your Item would be a God Class, you can have a Definition that is a God Class.

humble walrus
#

Yeah, but I don't need multiple types of Item, just two ways of storing it, one with base data, and one with construction data like transforms. If I needed additional functionality, such as a hypothetical quest item definition, wouldn't I just use an Abstract ItemData class, like in example two, and derive from that class to create QuestItemData and WeaponItemData, one of which holds extra variables associated with quest items?

dusty wigeon
#

But at the end, you do you.

humble walrus
#

What makes using an Abstract ItemData class the wrong call? It seems fairly straightforward to me, but it sounds like there's some sort of pitfall that would require more research on my part.

I have Abstract ItemData, then I have derived ItemData classes from it, and a function that attempts to retrieve that data and output it for function purposes, right?

dusty wigeon
humble walrus
#

The subject of... abstract classes?

dusty wigeon
#

Things like Serialization is also important to understand.

#

Abstract Class is only a way to make Polymorphism.

#

There is a considerable amount of things to understand to be able to make clean code. From my experience, if you attempt to use pattern and feature that you do not know you find yourself in a worst situation. I suggest that you tackle a bit at a time and do not try to implement a "generic" system ahead.

#

You will most likely struggle with just that.

#

But, obviously, this is your choice and depends on what you want to do. Is your game more important than your learning experience ?

humble walrus
#

Well, I'm already going to need polymorphism for other stuff anyway, and am already in the process of working on that for implementing unique on-hit and on-contact effects for items.

#

I suppose it'd be better to just make something and return here with it later for review and refactoring.

arctic drum
#

can anyone good with unity help me fix a bug in my game

elfin salmon
#

Hey all, I'm trying to instantiate objects on a plane defined by vertices (Vector3 array) the picture below is a top view sketch of the problem. I want to instantiate a series of objects along the edges of the plane but sometimes it can have irregular shapes such as the one below, and then the objects would be also outside the plane which I don't want. How can I make sure the objects are not instantiated if they appear outside the boundary? My initial thoughts would be handle the generation of objects differently if the angle between edge 1 and 2 is below 90 degrees but I don't know how to proceed for the rest

#

this image is more clear

clear shard
elfin salmon
#

How would you do It?

jaunty swallow
#

Quick question, what pixel do Texture2Ds start at? Logging the colour of pixel -1, -1 returns a colour instead of an error...

#

start and end at*

#

Since it returns a colour, I'm assuming it loops the texture, if that's the case then does the texture start at 0,0 or 1,1

sly grove
jaunty swallow
#

because then a Texture of width lets say 512, would be 513, given that 0,0 is not accounted for

sly grove
#

obviously it "starts" at (0,0)

#

0,0 is indeed one of the pixels in the 512 width

#

the last one would be (511,0)

jaunty swallow
#

yeah that would've been it, couldn't check it since it was wrapping

#

and I'm making the texture through code so forgot that was even a thing, thanks

jaunty swallow
sly grove
#

the wrap mode only detemines what color

#

the texture always starts at 0,0

jaunty swallow
#

yeah so how can it return a colour outside of its boundary

#

I thought the whole point of clamping it is to prevent it tiling

#

but that's what it seems like it's doing

untold moth
#

I'm not sure the tiling/wrapping settings affect the CPU side pixel access

#

This is mostly for sampling on the GPU

jaunty swallow
#

alright, thanks

sly grove
#

i don't really see why it matters

#

the size of the texture are determined by its width/height

#

If you don't want to go outside of that, don't

jaunty swallow
#

well tbh I only needed it because I thought that the texture possibly not starting from 0,0 might be what's messing up my generation, it was more for testing rather than actually needing it

#

yeah I read the docs but it was returning me when queried for -1, -1, that's why I was confused

untold moth
jaunty swallow
#

mb

jaunty swallow
untold moth
jaunty swallow
#

"the last pixel at the border will be used." got it

jaunty swallow
elfin salmon
clear shard
# elfin salmon <@272729420173672448>

My current idea is that you could define a radius that an object should be from each line and from each adjacent object, and then before you instantiate each object, you calculate the distance between the instantiation point and any line that's near it using the equation in the pic. If it fails the check then you move on to the next candidate position and try again. You keep going until you cover the whole perimeter of the plane.
I'm trying to figure out exactly how to implement it though.

elfin salmon
#

many thanks for your detailed response

#

I understand your equation but I don't know how to actually do that in code

clear shard
#

This is an example of a perimeter with acute angles. It's not perfect, as you still get objects that are close to each other, but they all remain within a set distance of the plane perimeter

#

To account for object overlap, you would have to compare the distance between all the previous objects, which would have muddied the code quite a bit. I'm sure there's a clean way to do it so that you don't have to compare distances with every object, but I kept it simple for now.

compact ingot
# elfin salmon I understand your equation but I don't know how to actually do that in code

#UnityTips Here is a little gist to find the closest point on a ray to a given point.

It also gives you the the distance in an out parameter without any square roots!

If the point is "behind" the ray's origin the closest point is the origin!

#math #gamedev #indiedev

soft moon
#

Didn't they want to simply spawn an object between the 2 lines, coming from a single point, with an angle between them?

#

I would do it this way

#

P is the 1st object's new position. Other objects may be calculated by adding their and the previous object's half widths to it

prevPos + (prevObject.localScale.x + currObject.localScale.x) * .5f
lavish wyvern
#

im wanting to make a secure system to store highscores, and make it so that its impossible or at least extremely hard to fake, so im using MD5 to generate a hash code form the score number, and write that to a file on the desktop, then when submitting scores you put your name, the score, and the hash, moderators can then take these, and plug it into a sperate app that will generate a second hash from the score provided and check to see if it matches the provided hash

#

im just unsure of exactly how secure this is, or how hard to fake it is, i did take a couple hours to get the app and the game to generate the same hash for the same number, so its super sensitive to any changes in the way a hash is generated

fresh salmon
#

MD5 is a broken hashing algorithm

#

Use SHA-256 or better

lavish wyvern
#

how is it broken? is it because of the sensitivity?

fresh salmon
#

It can be reversed, allowing plaintext to be retrieved from the hash. Which is what hashed must NOT do usually

#

It's still fine to use it for data validation (checking if data was not altered by a third-party)

lavish wyvern
#

well all the would get from reversing the hash is their highscore

#

just keep in mind never to use it for sensitive or vital functions

fresh salmon
#

Right, so you can keep MD5, it's fine. As you noted that's normal the hash changes a lot even if the plaintext message changes a little, so before hashing you might want to format it in a way that prevent these issues, by removing spaces at the beginning/end of the message, etc.

#

For secure communications with sensitive data, you could use an asymmetric algorithm like RSA, where only the receiver has the decryption key

tall ferry
#

Public key crypto definitely makes more sense here than a hash. What's to stop someone from just generating a hash themselves for the score and submitting that?

lavish wyvern
#

mostly effort and knowledge of how

fresh salmon
#

Note that C# has deprecated MD5 though I think (it throws exceptions or reports compiler errors), so once Unity switches to modern .NET you won't be able to use it anymore.

lavish wyvern
#

and also the system is super sensitive to how a hash gets generated

#

an int and a float can be the same number but generate completely different hashes

tall ferry
# lavish wyvern mostly effort and knowledge of how

Even then, anyone can open up the game and look at the algorithm used.
But at the same time, anyone can open the game and mod it so their score is higher before any of the encryption stuff happens. Almost nothing you can do about that, and realistically this is where most people would attack if they wanted.

clear shard
# soft moon Wow, aren't you overthinking it?

Just trying to generalise as much as possible. I'm assuming that the objects will be spawned along the entire perimeter, so I have to account for edges of any rotation, hence why I'm using normalized directions between vertices to calculate the next object position, and also perpendicular directions from the boundaries to move the objects a set distance inside the perimeter. In your implementation, you would still need to do the same to keep it orientation-agnostic.
As for checking distances, your implementation is also a good alternative. Instead of checking the distances from adjacent edges on each iteration as I have, I'd imagine you could calculate the start and end points, and only iterate in that range for each edge.

lavish wyvern
#

true, but those would be the fringe cases

fresh salmon
#

3.14 on an English locale
3,14 on a French locale

#

This can mess up the hash, as one character changes

lavish wyvern
#

then couldnt i set up a way to change the way the verify app generates its hash then? so you can choose a local culture format

fresh salmon
#

You can specify the invariant culture yep, which formats everything independently of the locale

tall ferry
# lavish wyvern true, but those would be the fringe cases

I dont think it would be. I assume this is like built for pc. Let me know if otherwise.
First thing people would try to edit that local file, when that doesnt work then more advanced attackers would likely open up the game to either just insert a quick script which modifies the score or look for how the file is written.

lavish wyvern
#

it is for pc

fresh salmon
#

Yep a "checksum" does not prevent me from decompiling the game, crafting a correctly-formatted score payload, hashing it, and sending both to your server

#

Neither does cryptography honestly, you could still get the public key from decompilation

#

(unless the server sends you a new one for each request)

lavish wyvern
#

its a manual system, the hash is the key, so format of a score submission is "Name,score,hash"

#

then the verification app that only mods have you plug that in and it takes the score and generates it's own hash, and checks to make sure the two hashes match

tall ferry
#

True, I guess im just pointing out that it is impossible to make this hard for smart attackers.

tall ferry
fresh salmon
#

Better have an automated system server-side that rejects the request if the provided sore is an outlier (too low, too high) compared to others

lavish wyvern
#

in order to fake a score theyd need to generate the hash for the score they want, and doing that would also generate a lot of false positives, especially since the game scoring itself has a lot of room to pull far ahead the longer a game goes

fresh salmon
#

It's easy given that you know how the code works.

string payload = "SPR2,5456485348464";
string hash = Convert.ToHexString(MD5.HashData(payload));
payload += "," + hash;

There you go

#

I send this to the server and it works

tall ferry
#

If we're assuming that players wont open up the game, you could go with public key crypto and insert some dummy data in the score like maybe the current time or other information in the game. Only you can decrypt it so when it's taken back, if that data isn't there then you know it was messed with

#

Players would still only send name, score, and the ciphertext.

lavish wyvern
#

sp i set a key and it needs it to decrypt properly in the verify app

#

basically its two seperate applications, the game itself, and the verification widget thing

#

that way i have an easy tool i can give to the moderators to check scores in two or three seconds

#

the game itself has no connection to the internet so im not worried there, the leaderboard and scoring is discord side and moderated

misty glade
#

@lavish wyvern Is there a better way to boil your score down to something that couldn't be hacked? Like a seed and string of moves that could be used to calculate the score on the server?

#

Having a single "score" data point that you're encrypting and sending up to the server could still be modified client side prior to "encryption" which obviously skirts the reason for doing it.. encryption as a tool as you've described is more designed to prevent someone in the middle from doing something with it (reading it, changing it, etc)

#

in other words - if your app contains the logic to generate a hash based on the data of the score; so does the cheating user - they just might need to change it in memory before the hash is generated.. maybe that's a step up from just editing the file on the desktop, but it's still pretty trivial for someone who wants to cheat

regal lava
#

Looking for some ideas how to handle cleaning up references that are owned by objects that were previously removed from the scene (or placed back into an object pool). For example, let's say some enemy throws some damage over time effect onto your guy, but you manage to kill them. Now, if you were caching a lot of your combat logic, this effect's stats would be tied greatly to the enemy object, creating a null exception error if you were to remove the container that this effect was referencing. One way to combat this I'd imagine is just detaching the stat container from the enemy when they die, and let all object referencing it clean themselves up.

Another idea is to just snapshot/copy construct your stat container, but the problem with this is that I see myself making multiple copies per action ability for how component heavy I've made my systems. Also, since I'm dealing with a large amount of enemies, this seems like the less ideal solution for performance.

#

I guess the answer I am looking for is if anyone has experience detaching object data and cleaning it up later

dusty wigeon
regal lava
#

Right, if let's say this burning effect is dealing a % of the caster's fire damage stat, it should be constantly reading it as they are alive

dusty wigeon
regal lava
#

Right, in that case it would just be an int, but I do have some more information tied to it like trigger abilities (target explodes with burning debuff on death)

dusty wigeon
#

Usually, I implement debuff as a copy of the stats.

regal lava
#

which is basically a trigger recursive spell I've tied to these debuffs

dusty wigeon
#

Could you not remove the reference to the % of the caster and instead only use the % at launch ?

#

It would simplify a lot the issue you have at hand.

regal lava
#

That would be snapshotting in this case and it is something I am considering

dusty wigeon
#

You should do it if you have nothing prevent you from doing it.

#

You are going to remove a lot of potential issues.

#

In fact, whenever you implement a debuff, you should always consider that the source might disappear.

regal lava
#

It would be a copy construct of a caster's stat for each of these triggers I believe, but I guess it's probably the most managable without a lot more cleanup logic

dusty wigeon
#

Alternatively, because you might find yourself in situation where you absolutely need a reference to the source, you can simply use events.

#

Whenever the debuff is created, you register to the OnDeath of the source.

#

Handle whatever needs to be handle when the source is no longer available.

regal lava
#

Yeah, having sources out on the field and stuff seems quite complicated to deal without unless I am using a new/copy reference, but games like Path of Exile did change their way they do things. Majority of thier logic was snap shotted, but they did a 360 and made it so that equipping/unequipping items would update abilities instantly

dusty wigeon
#

You can have an hybrid. In the case of PoE, they might have a reason to update it while in your case it is not the case.

#

Always use the appropriate solution for your problem at hand.

regal lava
#

I'll probably stick with the snapshot idea for now as it does seem like the easiest. For one, I can't be bothered to profile that I'm cleaning up everything correctly otherwise haha

dusty wigeon
#

By hybrid, I mean by having a "Refresh" function.

regal lava
#

Right now I do have it so if I did change a piece of gear it would update everything out on the field, as if it all were being refreshed

#

but that's because it just reads from that one source

dusty wigeon
regal lava
#

and ideally I'd probably want to use it for performance reasons, but that's some extra logic I need to figure out to handle with these lingering references

#

probably comes down to a hybrid idea such that I do copy construct the stats if the target is removed, or detach the reference.

dusty wigeon
lavish wyvern
#

So on my end I get two strings and a hash, Name, Score unencrypted, and The encrypted score

#

Keeping the score unencrypted is intended since I don't have means to decrypt a hash code after its generated

#

The score would have to be edited during runtime, since the hash is generated when closing the game

#

The game has only one button, since it's purely time based, you just tap to a rhythm set randomly, and score is only updated when space is pressed

#

Plus the game doesn't connect to the internet, so they can't send any code to or from the validator, it's an offline game so sending code to a server wouldn't work since their isn't one

scenic forge
#

The thing with this kind of protection is that, you always know someone can just look at your code and figure out what hashing/encryption algorithm you use, and they can just make up a score they want then apply that algorithm, and it would be indistinguishable.

#

Because of that possibility of always existing, it's just a fake protection. A score having a valid hash no longer means "that score must be legit" it merely means "it could be legit or it could be a smart cheater."

tall ferry
#

this is partly why i suggested using encryption and adding more information, so that information can be decrypted and checked. wont stop someone from opening the game, but its a lot better than having a hash where you have both the value and hash of the value visible.
For something like this, it has to be assumed that attackers arent gonna open the game up

#

still fake protection, but more of a deterrent which is really what cryptography is about

scenic forge
#

Encrypting is useless too, instead of "oh look the hash matches" it would be "oh look I can decrypt correctly" and the only conclusion you can reach is that "the score might still be cheated it's just the cheater is smart enough to at least figure out the protection scheme."

tall ferry
scenic forge
#

And any code running on client side is always naked code.

tall ferry
#

agreed, and i still think the only option is to just let it be encrypted unless they change the whole game to only run on some server. if the user mods the game or looks at the algorithm used, theres nothing that can be done. So it has to be assumed the game wont be modded.
With a simple hash, the user can still just cheat without looking at the game. They just copy someone elses score and hash. With encrypting data, at least they can be verified by adding data in like the current time or other information that'll be very specific to a user

scenic forge
#

I mean, you can also just add the same specific data to be part of the hash and that would also prevent someone copying over another person's high score, but I digress.

#

I suppose the point I'm trying to make is that, this is a bunch of wasted effort.
Let's imagine if you go through with a hash protection scheme. So now every time a player submits a score to you, you can use a software to check the hash and reach a conclusion of... "if they cheated then they are at least a smart cheater." And if someone posts a cheating tool that generates the hash? Then there's practically no point in even spending time to check the hash anymore. Both your effort of implementing such a scheme and the usage of it is just wasted.
If your game is popular enough, important enough, for people to start cheating, they will figure it out.

terse inlet
#

^ it’s the same as multiplayer programming. You have to assume any data coming from your client is faked. Because it can all be faked. They have your code

scenic forge
#

There are better protections you can do though, for example includes more data than just a score (eg player inputs like @misty glade suggested). Even if you can't use the inputs to perfectly reproduce the original gameplay to prove the score to be at least possible (keep in mind, the inputs can still be made up), you can still use some statistical methods to detect fake data. But even this is only to a certain degree of protection, it's just a rat race between you finding more methods to detect cheating and cheaters figuring out your method and making the fake data look more convincing.

slate spoke
#

I wasn't sure where to put it, but I have a shader coding problem posted in #archived-shaders if anyone can help with it. Bonus points if you have experience with VRSL or DMX.

lavish wyvern
#

And on top of that this isn't really a game I expect to have people cheat anyway

#

Like woop de do you cheated at a game where you press spacebar to music

#

Plus I know what scores are possible anyway, so people sending me a score I know isn't possible is already out

scenic forge
#

People can just look at your code and figure out the hashing algorithm and generate the hash themselves. But that's kind of my point: if your game is popular enough that people take it seriously and want to cheat, they will figure it out so your hash protection is useless; if your game isn't, then no one cheats and your hash isn't protecting anything. Either way it's wasted effort.

lavish wyvern
#

It was mostly to learn save/load, which I did so not really

trail spoke
pallid glacier
#

For those who are using Unity tests, the code coverage package's last update is 2019, it seems to be a bit abandonned isn't it ?

#

oh well no mb, it has later updates

timber flame
#

It seems Physics2D.GetRayIntersection does not return the top sprite with collider2d
I want it to return the top sprite

timber flame
sly grove
#

It should iirc

bold mountain
cedar cradle
#

How can i move two rigidbody objects that are connected via a fixed joint without breaking them appart(the fixed joint has a breake force)

soft moon
#

Oh, got it working. The planeNormal was set to (0, 0, -1) by default.Now they're spawned perfectly inside of the perimeter

cold canyon
#

Hi. I have a ring that rotates in the update method, but there can be 1000 rings in a level which is a problem for the CPU. To solve this i came up with the idea of using a job system. I wrote a job that does exactly what i want. It works, but for some reason my fps dropped by 2x. Anyone knows why? Here's the code:
Ring: https://pastebin.com/dhHS3tvq
Job: https://pastebin.com/GqT55psz

sly grove
#

Instead of just 1000 Updates you now have 1000 updates running 1000 jobs?

cold canyon
#

yes?

sly grove
#

THat seems useless and counterproductive

#

YOu would want one central manager adding all the transforms to a single TransformAccessArray and scheduling ONE job to move all the rings

#

And get rid of the Update for the individual Ring script

cold canyon
#

but what is the best way to find all the rings, because some of the rings are already in the scene and the other part creates from the Unity's spline

cold canyon
#

i got the better results but still performance is worse compared to the rotation in the update (left screenshot is no jobs, right screenshot is jobs)
https://pastebin.com/5T6GTx5V

#

i got the screenshots wrong.

misty glade
#

I have a click problem.

I'm using UGUI and implementing IPointerDownHandler, IPointerDragHandler, IPointerUpHandler, IPointerClickHandler in various components. I have a popup that catches clicks with another component underneath (that also catches clicks, but obviously can't if the popup is a raycast target). I want the popup to disappear on Down and "pass the click" through to the component underneath - so I pass the PointerEventData and call OnPointerDown directly.. but the drag doesn't seem to work - ie, the click is a "different" click.

Any ideas on how I can make this work?

#

I'll .. simplify my code and paste

#

Hm. Weird. I moved some code around and don't think I changed anything related to this and now it works. 🤷‍♂️

#

Hate that.

regal lava
#

And maybe a raycastall method to grab as many elements that may be behind

misty glade
#

This is in UGUI-land, not physics and real world space land.. I can't write real games 😉

#

It doesn't work reliably unfortunately; but after some googling I found a ten (!) year old thread that recommends sending the event with SendMessage() instead of calling OnPointerDown

rose stump
#

So in my shooter game I'm using an Invoke function to manage the fire rate of my gun, the problem is that I noticed that in the build if I run the game at 144fps the fire rate is a bit faster than when I run the game at 60 fps. Is there a way to fix this?

soft moon
rose stump
#

I'm using Time.deltaTime but I still get this issue

soft moon
deep jasper
#

how do i render 100k grass meshes on random positions inside the box each frame? :0

#

rn i build up matrix4x4[] on start and then use RenderMeshInstanced() on it each frame

clear brook
deep jasper
#

and it's already killing fps cuz like all grass meshes are rendered equally with no culling or lod

#

and taking time to process the placement because it's literally 100k operations with randoms and matrix translations, and I would need to instantiate or disable grass zones at runtime because player would be moving from one part of world to other

delicate mural
#

I'm currently designing a behaviour tree AI system, and am having trouble with information sharing between nodes

#

Soo say a child needs to access some data from higher up in the tree. Nodes are a generic class that are meant to be inherited.

#

The tutorial I'm watching uses a string based data request which I REALLY don't like

#

Any ideas?

clear brook
# deep jasper and it's already killing fps cuz like all grass meshes are rendered equally with...

It looks like RenderMeshInstanced() does consider all of the meshes as one for culling, which is pretty rough. You could divide your map into patches of less grass (say 9 in a grid loaded at a time around the player), and have each patch do its own call.

Also, probably a lot of easy performance gain by doing DrawMeshInstancedIndirect, and only sending all the position data to the gpu once, if you are not already doing that (see https://toqoz.fyi/thousands-of-meshes.html or similar)

elfin salmon
#

If you want I can share

soft moon
timber flame
proud sable
# delicate mural Any ideas?

Allow nodes to store data in the tree, using a dictionary to do this is usually the way most (including my own tools) go, simply store a dictionary <string, object> at your tree root and allow nodes to store to this 'blackboard', then your nodes could simply do tree.Get<Transform>("target") or something.

If you're worried about performance don't be, dictionaries as you should know are fast enough for something like this and most tools use this method anyway.

#

Without strings only thing that comes to mind is a predetermined array of data the child can access on the parent with a hard index for what it needs, it's hacky and I can't say it'd be better than using a dict but it wouldn't require strings at least.

delicate mural
#

public PatrolTask(EnemyTree ctx) {

#

Trees have to pass themselves in to create a new node

deep jasper
#

i copied the code and played around with it, so i was able to render 1m meshes with those random colors across 100x100x100 cube

#

but well, shader doesn't rly support texture and i never really coded custom shaders

#

only worked with ShaderGraph

#

is there any like guide to writing custom shaders

regal lava
deep jasper
#

for my grass problem

regal lava
regal lava
deep jasper
#

i mean i just build up a matrix in the beginning

#

and then call RenderMeshInstanced each frame

#

So well, they just get placed on their coords but fps goes down to 60

regal lava
#

I'd profile and see if it's a vert problem or a drawcall problem

deep jasper
#

i don't think it's a vert problem since it's just 2/4 planes crossed

#

With a grass texture applied

#

and the code is just


RenderProperties rp // material's rp
Mesh mesh // 4 planes or 2 planes crossed
Matrix4x4[] matrixArray // all positions 

void Update() {
    Graphics.RenderMeshInstanced(rp, mesh, 0, matrixArray);
}```
#

and i don't rly know way to optimize it

#

last thing i tried was compute shader which calculated LOD's and cutoff

regal lava
#

Could be a problem such that you're updating a buffer every frame with 100k units

deep jasper
#

there is no buffer tho

#

in this code version at least

#

RenderMeshInstanced operates with Matrix4x4[]

deep jasper
#

and well, it gives less fps of course since there are too many operations ig

regal lava
#

honestly this is something I'd do with compute shader over this API, but I've not really played around with this beyond messing around with spawning some primitives

deep jasper
#

haven't you rendered grass fields before?

regal lava
#

using vertex shaders yeah

#

and vfx graph (also compute shader)

deep jasper
#

so well, 100k meshes was never a thing you tried to do?

regal lava
#

Not with this API, I've not tried making any amount of grass, and it does seem to render it as a single draw call. So if you're saying it's not a vertice problem then culling isn't the issue either.

#

The only thing I can think of without doing some testing is that creating these many meshes with this API call every frame could be the problem

deep jasper
#

it's not like im sure

#

if mesh is 4 planes crossed, then it has 16 verticies

regal lava
#

so 1.6m verts? That's not much of a problem

deep jasper
#

Well, should be 1.6m verts yeah

#

i mean lemme switch to old code and see

clear brook
# deep jasper is there any direct link to what i should look at

There is probably not going to be any 1 to 1 off the shelf solution. I would recommend going through tutorials to build the background knowledge you need.
If you wanted to adapt the StructuredBuffer/DrawMeshInstancedIndirect solution, the way forward would be to modify a standard shader (that can handle textures), and add in the code from their example to use the _Properties buffer to gather the location. This will be easier if you take some time to get familiar with less complicated shader coding

deep jasper
#

there are 3.2M verts

#

how

regal lava
#

1.6m tris

deep jasper
#

i'm about verts rn

#

each quad is 4 verts

#

if there are 4 quads, then it's 16 verts

regal lava
#

oh, right you have double than expected eh

deep jasper
#

maybe that's cuz material is double sided

regal lava
#

still, 3.2M shouldnt be tanking your fps that hard

deep jasper
#

to like see grass from behind

#

i don't rly get higher than 40fps rn

regal lava
#

and 450 batches isn't fps heavy either

deep jasper
#

i mean it might be cuz i have gtx 1650 but it's not that bad

#

when i don't look at the grass, i get 60 fps

regal lava
#

says you're rendering 200000 instances which is probably why you've double verts

deep jasper
deep jasper
#

might be even less

#

cuz density doesn't show real grass number

#

for each grass blade i check if it's not floating in air

#

so real number might be like 99977 or smth similar

#

waaaaait

#

what the hell

#

they are really doubling for no reason xD

regal lava
#

if you want to try something out, bake the mesh and try rendering it as a single drawcall

#

see how performant that is compared to this API

deep jasper
#

you mean 100k objects as one prefab/fbx or smth

#

well

#

it wasn't rly doubling

#

more like my script was doing a bit cringy

#

rn it's exactly ten meshes

deep jasper
#

and it's adding 320 verticies anyways

#

lemme turn off double sided mode

#

nah still

#

it shows that vertex count is 16

#

and matrix length it 10

#

so it should be 1.6M verticies

#

but it's showing 3.2 xD

#

well, vertex cound doesn't change if i play with material, but fps doubles when i render only one side of the mesh

deep jasper
regal lava
#

Right, you need the component instances to actually combine so that is one way. Another is just generate the mesh data from scratch using the mesh library

#

You could even try static batching as an alternative as that does have culling integration

#

Best way imo is just chunk it enough

deep jasper
#

well

#

combining has a limit of 65535 verticies

#

so well, 4k instances for each combine object if grass is just 4 planes

#

and well, total chaos and lags in hierarchy

#

and well, no culling

regal lava
#

Yeah, I was suggesting to chunk it a bit. If you do want it as a single mesh you'd have to probably generate the vertex data directly

deep jasper
#

fps is same no matter where you look or where camera is

deep jasper
#

i guess

#

since it's just 1 giant mesh

regal lava
#

if it's a single mesh you have to cull it through manual methods

deep jasper
#

and it means i need to code again

regal lava
#

if you chunk it, you get the benefit of frustum culling

#

static batching -> more loose chunking option if you want to cough up some extra mem locations

deep jasper
#

what is a static batching tho

deep jasper
#

this way i don't need the script to make combined mesh right?