#archived-code-advanced
1 messages · Page 99 of 1
X.onClick.AddListener(
() =>
{
Method();
X.onClick.RemoveListener(Y);
}
);
what would I put as Y to remove the addlistener? or is this not possible
store Y before adding it as a listener, then you can have it reference itself
I was kinda trying to remove the addlistener without making a separate function
is there a "this" but for the addlistener?
also I realize Y may be misleading
it's not a separate function, but just a placeholder for what the actual code would be
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
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
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();
rip
I was trying to do that without having an external function/action
you should stop worrying about extra lines, extra functions, or anything like this. its silly
referring to this and also above about trying to null check on 1 line
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?
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.
is it automatically disposed by the system?
iirc they are
I looked up my code that performs readbacks and I don't dispose the GetData results
only the arrays that are being copied to
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
Ah that's unfortunate--the performance I'm getting with copying to another native array is still an order of magnitude better than an array though, so I guess I'll keep doing this
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
I understand on a general level that the architecture is built this way, but fundamentally I don't see why they can't entrust us the responsibility for the readback nativarray
it's simple, a native array is just a pointer into unamanaged memory and once you have one of those and can write to it you can cause havoc
Have you tried using AsyncGPUReadback.RequestIntoNativeArray? I assume that will write the results directly into a NativeArray which you provide, avoiding the need to copy.
I mean as long as you know what you’re doing and don’t access out of the memory block, there shouldn’t be any havoc.
Hmm I can try that
Problem is it might be disposed of already
Yep, and that is the thinking behind evry known C and C++ bug. You lot are just not to be trusted
😭
Actually that may be what I'm looking for thx
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
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
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.
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
Yeah, but my readback is multiple steps, because the address is also on the gpu, so I need to pass the first one through a callback argument
I'd say anything related to the "Enemy" should be part of the class object and any temporary objects used for calculations are structs.
the enemy prefab will be a class, in fact it will consist of 2 classes, GameObject and Transform. with those you can use the rest of the components, this is the Unity way of object design
Sorry I didn't mean objects as the type I just mean like architecture design wise
Right but I'm saying what is the norm? to have base classes? Do I reuse components such as Health, Damage and such or inherit from some base class?
It'd just depend on your needs but having those scripts as non-monobehaviours would work as well - they'd be associated with an enemy component instead of being components associated with an enemy object. It merely depends on what features you're needing from mono behavior, component etc (not sure why the message was moved from another channel)
Depends on the type of game, if it's pretty simple or the objects are pretty similar you can inherit, but if they're very different it's better to make different objects entirely
Also the more objects means more for your GC to do
Interesting so one of those, there's no real answer kind of questions? Also I moved it sorry. I thought code-beginner was more of a learning to code kind of channel
Generally you would want to reuse or if not inherit. If you can do neither then use interfaces. A lot will depend on the complexity of what you want to achieve and how good a designer you are
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.
tbh, if this is your first game, do not start with 'my game' do some basic stuff first. !learn is the best place to start
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Ayy I got it to work, just passed a wrapper class lol
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?
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.
can be a virus yes
Alright, opening it on my virus pc then and i'll just type over the script if it's there
Thanks
Show the EventEmitter class
its from a plugin
not unity related. c# only lib
Well, it needs to either inherit from Mono or be tagged as Serializable to be configured in the editor
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)
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?
It might be safer to call BeginWrite with a type of the same stride as the buffer and then reinterpret the array afterwards.
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
might be worth asking in #⚛️┃physics if you haven't already
ye i did as well
Can you share the !code properly?
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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.
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);
//...
}
The first one
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
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?
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
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
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
do not cross post, also this is in no way an advanced topic
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
not quite sure how Vuforia works but for my RDBMS system I include the database file in the streamingAssetsPath and for android I use UnityWebRequest to read that file and write it to persistentDataPath, from there I can access it without any problems
I tried that as well, I placed my Vuforia .dat and .xml files on web server and downloaded it. But Vuforia wont initialize or load the database. I checked the Vuforia API but nothing.
My last hope would be, to fully download my main scene as an assetbundle and load it into the app when starting.
Any information on a good asset to load a ~1.5gb scene as an assetbundle?
not as an assetbundle but my Save for Unity System could cetainly handle that
Unfortunately my Vuforia Database won't load anything if the app is bigger than 150MB 😦 ... Therefore I have to unload and download some stuff..
What do you mean with save for Unity system ?
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:
Your move overwrites the velocity.
VelocityChange won't overwrite the velocity
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
you are very wrong, but you mentioned scenes specifically which this can do. I honestly cannot see how you are equating the Vuforia problem with it being a .aab build
Im gonna have a closer look. When building aab + binary split the files from vuforia are getting separated or vuforia cant load them i dont know... with .apk and oob I didnt have the problem.
the only difference between a .aab and a .apk build is that the .aab contains multiple versions of the code. It has no impact on the data
Reproduction steps: 1. Open the attached project "ReproProj" with Android Platform 2. In Edit > Project Settings > Player Sett...
with apk and obb there was an obbextractor script from vuforia. But this doenst work with aab 😦 ...
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
into lib_burst_generated.dll or your platform equivalent, which can be loaded by unity like any native library
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
SetLayerMask works fine. Can you show the rest of the code?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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)
BTW you know you can do cs [SerializeField] private ContactFilter2D _cf;
and you can set the contact filter up in the inspector
does it work that way?
of course
it works both ways
im so upset
no i mean, does it actually filter things out if setup through inspector
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
does not work for me when through code lemme check inspector way
Well for one you aren't using OverlapCollider properly
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
_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
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
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
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
show me
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
How
even regardless, if I dont move after the slide and just jump, momentum still isnt conserved
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
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?
Found an article:
https://www.researchgate.net/figure/Optimal-coloring-obtained-by-the-Grid-6-L2-1-coloring-algorithm_fig3_221406564
Unfortunately I need upwards of 8 colors and it's a very expensive coloring algorithm, prob will just use interlocked operations
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
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
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
yes just wrap around the obtacle let me share a screenshot from the game
The red line is what i want connect from the start point to the end
gift wrapping is the name of algorithm (though it formal name is convex hull)
google gift wrapping algorithm
alright thanks
btw if it is logical graph (your grid) you can use shortest path
its a logical graph and i have astar in the project but astar is too performance intensive
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
the first line of that file is using System, did that go missing in your copy somehow?
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
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
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 ?
are you using any plugins that might contain Microsoft.Bcl.AsyncInterfaces?
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
the reflection....
please at least make your screen brighter
Don't encourage him, you know as well as I do that posting photos is not acceptable here
Oh
Why do you need to smoothen an SDF? It's trivial to sample a "sharp" SDF and apply smoothing afterwards.
Well the two issues with it is that the state machine doesn’t seem to work and it doesn’t abide by the speed value I put in the NavMeshAgent component
to gradually zero out a function based on sdf value
straight sdf creates very noticeable edges
while blur is an option, it makes a lot of other parts of my compute pipeline problematic because it becomes impossible to evaluate functions at any given point
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
It's a bit strange to me that you don't want straight edges. What are you using this SDF for?
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)
landscape generation, it blocks in main elevation changes, so it looks very unnatural and persists through all the other steps of the pipeline
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
you should take a look at the code sharing section of https://discord.com/channels/489222168727519232/854851968446365696
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
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
#💻┃code-beginner and !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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)
Is there anyone can enlight me with UniTask?
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.
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.
Is "fire and forget" the term to describe calling something looking as asynchronous synchronously?
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)
it's pretty easy to shoot yourself in a foot with async void calls
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
because of exceptions?
Yeah, you can also just always use UniTask if you don't care about that guarantee/performance benefits.
because it's a very easy way to get a bunch of race conditions in your code that way
multiple async functions modifying collections in unexpected ways, for example
I thought UniTask runs all in main thread as unity does if you don't switch threads manually
it still doesn't guarantee any order of exection
wait, actually that's async in general, maybe UniTask does 🤔
I mean how is it possible while all happens on main thread
async tasks also run on the main unity thread
I think it is case for async / await in general in c#
and they sure cause race conditions
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.
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
My wording wasn't clear, "race condition shouldn't have anything to do with it" the it being "why async void is considered bad."
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
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
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
I'm a little confused - if you're saving and loading as json, why does it need to be a ScriptableObject?
Also are you expecting this to change a ScriptableObject asset in your Assets folder?
It seems like you're initially loading them from Resources, then saving the new value in persistentDataPath?
jep
So how does this code in particular reconcile that?
But also - you said "why cant i load this Scriptable object in build"
What exactly is happening when you try to?
Can you explain what's going wrong though?
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
Isn't it problematic to try to directly use JsonUtility with ScriptableObjects?
Won't you just get the instance id?
(same as MonoBehaviour)
so i have GUIDS in the scriptable objects
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
so i want to search my type with that
for the second time today you're my hero simonp thank you ❤️
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)
Are you scripts in the project using an assembly definition?
(not the scripts in the package)
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?
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?
darn! totalled missed that @sly grove and I was LOOKING for it.. that's prolly it.. thank you!
If your package has a non-auto-referenced asmdef, then you must use an assembly definition in your project to reference it
@bleak citrus @sly grove 💯 🎆 🥇
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
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
no one is entitled to help here and if you actually tried to debug your code and showed some more information someone may help\
could u help me then?
probably not, I'm off for dinner
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
this probably belongs also in #archived-networking and #⚛️┃physics i imagine
it would need a minecraft-like server-client model where the server (or internal server) does all the world saving and loading
what? I meant I was interested in talking to others about this
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.
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?
It does not render the world as voxel but as cube.
Not voxel rendering, simple mesh rendering
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
Minecraft does not use that either.
oh my bad what technique does it use for rendering the chunks efficiently
Regular triangle meshes
So every block is at least 2 tris?
Welp, if it's good enough for Minecraft it's good enough for me I suppose
Every cube face is 2 triangles. No optimization like greedy meshing
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
Fair enough. Optimisation shouldn't be my first concern anyway, I just wanted to look into it as a cool project but am now realising it would be a waste of time to optimise from the get go
Yes, if you pick your style appropriately you can get away without any optimization
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
Make a 320x240 pixel art game and you can software raytrace that game at 30 fps
👀
As much as I love the pixel aesthetic I also somehow hate low resolution
But it is an intriguing idea
use dlss to upscale it to 4K
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

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
@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?
is your lambda async void? it's not particularly worse than any other async void method, it can be poor style if it makes it hard to tell at a glance that async is being used, but i'd say it's fine in some cases
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
Can you show your code?
Have you seen John Carmack's talk on YouTube where he goes over raytracing
Good video
yes, I see now way to use UniTask return type in this case
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;
}
}
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.
what is it?
You would just do async UniTaskVoid cardsToSelect => ....
Like this?
public static Action<T> Action<T>(Func<T, UniTaskVoid> asyncAction)
=> value => asyncAction(value).Forget();
Looks good to me.
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.
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();
I didn't but this sounds very interesting
seems the problem is in async UniTask<int> SelectCard function, because awaiting UniTask.Delay works normally.
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?
You're using some third party editor gui, probably NaughtyAttributes, with that [Button] attribute. Probably not a Unity bug if that property drawer behaves strangely.
Thet works when I hide my list from inspector 🥹🥹
I think that assignment to array redraw editor inspector and flags break
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.
Sorry, what are you trying to drag into a public field?
Also, I feel like this is not really an advanced question.
SerializeReference is usually the go to solution. You can also use ScriptableObject.
Hey sorry if this was not an advanced topic.
i just want to create a script called WeaponFiringLogic that i can use to derive other scripts from to create new firing logics..
I want to be able to make a public reference to the base class , allowing me to drag in or assign any scripts that dervive from the base class.
will look more into SerializeReference , I am currently using ScriptableObjects as data containers.... i am trying to assign a WeaponFiringLogic within a scriptableObject called WeaponData
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
If you're starting out and your code requires SerializeReference I'd reconsider your structure of how you're doing things
Ive been coding for the last 2 years but am self taught!
I mean the project itself. Usually SerializeReference is something to bandaid up my misjudgenment of how I am to serialize things haha
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.
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
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
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
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
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
try some paste sites
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
IWeaponFiringLogic would need some SerializeReference to work with the editor
ahh so it is a polymorphisim issue
consider just doing SOs inside of SOs like reaper mentioned
A scriptable object cant contain methods can it?
it can, sure
i thought it was just a container for references
ohhhh
shiii
I dont know how ive never tried that
😂
ScriptableObjects are just c# classes at core, but they are helpful such that you can reuse those instances throughout your other objects
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
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
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
your code suggests these should not be SOs at all, but instead MonoBehaviors
To me it seems like you just want some composite logic
Look at WeaponData script
Could be!
Honestly i dont know what i need , and thats why i came here , i stuggle this part with game development everytime , i have no problem with anything except this
you aren't passing any data into your weapon firing logic, so you have a design problem as-is
im not sure what you mean?
thats what an example weapon data looks like
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
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
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
are you saying to do this?
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?
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!
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) { }
}```
I have already set up Steamworks but don't know exactly how to connect items in steam inventory to unity, are there any good tutorials out there?
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.
umm i dont know specifically of any tutorials as i haven't gotten that far , Have you looked at the steamworks documentation?
i can look around for some tutorials for you but i doubt id find anything you havent already searched for
All good thank you for your help i will probably try ask ChatGPT xd
Thank you for this!
Got everything switched around but im still running into the issue where i cannot assign the DumbFireRocketLogic to a reference of WeaponFiringLogic!
I guess ima have to go learn more about the serialization so that it can be assigned to reference within inspector..
Trying to drag the DumbFireRocket script into the WeaponFiringLogic reference within a WeaponData SO
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
right so with mono it would require another gameobject with a component of WeaponFiringLogic
oh the issues that its just not attached to a gameobject within the scene
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
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.
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
lol its so hard to forumalte my thoughts into words
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
ScriptableObjects don't exist in the scene and don't contain MonoBehaviours
so what you are saying is that i will still have to hard code the type and i cant just make it modular
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
the weaponData is used to fill out a Weapon script that is attached to each weapon
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
see thats what ive been getting at....
I am trying to avoid explicity coding a logic to each weapon , i am trying to make it so any logic can be used with any weapon
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
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
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
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
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
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
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
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
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
you say this but even if i attach the dumbfirerocket script to an empty gameobject im still not able to drag it in
in your video, you're dragging your script (a text asset) into the slot
that is not a textAsset
it's a script asset, you know what i mean haha
is it a prefab or a scene object
it was just an empty gameobject with the script attached to it
make it into a prefab then drag it onto the SO
now i do lol
lemme try that
damn channel wont let me put gifs , jesus christ so all i had to do was make it a prefab
Thank you
so much!
well, it's better to understand why you need to make it a prefab in the first place
i just wasnt connecting the dots
but SOs would work too in this case if you don't need the scene presence of a mono
i may try to mess around with using SO for it , they are super easy to work with imo , i dont mind having a bunch of prefabs to contain the logics aslong as it works thats all i care about
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!
ye np, fighting with unity's editor is part of the experience of making a game
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
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.
When you say text asset I immediately think of a string or a TMP asset
Never heard someone refer to a script as a text asset
It is a string. A file that has a string in it.
Scripts are just text after all. What makes them into something meaningful is compiling them.
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.
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.
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.
whats poco?
plain ol c# object
oh lol i was thinking property oriented class object XD
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
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
Another idea if you dont want to create editor assets is to map your types to enums/structs to initialize those instances
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
sounds good. Enums are great for reducing assets and classes in general
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 💀
anyone have experience with splines?
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
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?
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
when you rotate the child do you increase the size of the parent cube?
is there a way to convert a gameobjet to entity without subscene
I would ask in #1062393052863414313
Here is the 2D view, the collider (green) is perfectly in the parent object, the renderer is in this awkward state where it does not fit the collider.
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
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.
Is your parent object uniformly scaled?
What do you mean by that?
Is the scale of the object (and all its parent objects) uniform?
Ideally, 1 : 1 : 1
but technically - as long as all the axes of scale are identical, it is uniformly scaled
that is why I asked for the inspectors as well
If you have scale that is different on any of the axes, it is not uniformly scaled
No its is not, it just fits in based on the collider of the blue child object beforehand.
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
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.
fix your scaling
But maybe a better question is - what is the goal of this thing?
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.
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
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?
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)
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...
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
that's actually not completely correct.
'\r',''
you should also use the SplitString.RemoveEmpty option
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 ?)
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
well, in my game each voxel is only one color, i though i could use the color system so i need multiple material i think, in other case i should create a png texture with everything inside ?
Actually i'm using code to create the meshes, so i would like to combine them before creating each game object, like having only one game object for the whole chunk
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 ;)
i could swap things if needed, actually i have an array of materials but i could rework my code to change it to use another method
i don't understand
i'm not currently into the shaders, idk what it will change
read up on how minecraft samples a texture atlas, there's quite a few tutorials for unity on it too
well i though because i'm not using texture and just a plain color, it would be easier xD
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
Okay i'll look into it
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
thanks
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));
Look up closures, you just need to assign the value to a local variable first then use that instead of i
Thanks, I see Lambdas link to variables and not values given their special scope 🙂
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
you might want to look into AssemblyReloadEvents.beforeAssemblyReload
love you
Calm down, simple worship is sufficient, lol
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.
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
My bad
yes, it's there
Its Y is 0.0
But IsGrounded starts as false
Are you perhaps starting INSIDE the ground?
And is the a CharacterController?
By looking at it closely
Are the feet or whatever intersecting the ground?
Then that is an issue. Raise it up a little
Let's move this to #💻┃code-beginner
Send a screenshot of the WHOLE editor, with the character selected
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?
Hey, what do you think? in the game Timberborn, they have used cellular automata for water simulation?
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.
Each piece of Equipment is actually made up of multiple items, is the thing. So there's "Loose items" which take up a slot, and Equipment, which takes up a slot.
So one slot might hold "Swords" and hold Copper, Iron, and Steel swords, while another slot might hold "The Triplesword of Doom" which is a slot that contains all the items comprising it and variables relating to them
If it works, it works. A simple breath first fill can work.
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
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?
This is a way of doing it. Not one that would suggest.
So how would you suggest handling that specific situation? (Having Equipment made of multiple items, and Items in the same inventory)
I already shown you 3 ways to make it.
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.
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
It is bad, but it works. So why not.
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?
It can work. But as stated, you would want to do:
public class Item
{
private Slot equippedSlot;
private List<Item> subItems = new List<Item>();
}
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!
Yeah, that is why I suggest you go the "God Class" way.
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.
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
Read on God Class and why they are consider an "anti-pattern".
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"
First two avoid God Class. But as I stated maybe 5 times, you should go for the God Class instead of trying to avoid it.
Ahh
No. Taking in consideration your skill it is better to make something simplier.
Sorry if I'm being annoying, I'm just trying to learn and do things right.
It is alright. Take your time to learn. Just mindful that you are currently learning and what others might call anti-pattern might actually the best way for you, as you are starting, to implement something.
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.
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?
As your class grow, you are going to have more and more issue with understanding it. It is not usually for God class to get as long as 2k lines of code.
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.
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)
But, obviously, it depends on how much your God Class is big which is also directly dependent on how much your project is big.
It is an example. What you plan and what you will have is also different. There is a high chance you have something more than simply what you are planning for at the moment. At least, I hope for you because it would mean that your project is progressing.
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
Whatever suit your boat.
Scriptable Object should be immutable though.
It is immutable, it only holds the base item data, and the inventory will only recieve base values from it
Then how will you handle case such as the quest item being chargable ?
Or, having stacks of quest item.
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
Yes, you will need at some point to associate instance specific data to a ScriptableOBject.
Such as
- The amount of use remaining
- The current percentage charged
- The amount of stacks
- etc.
None of those are a factor for my game's design, though.
For now.
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
In other words, the Item. Hence, the item would then be a "Quest Item".
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.
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?
Yes, if you do not use a God Class. If you use a God Class you can simply add directly the field into the Item class.
But at the end, you do you.
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?
Because you do not have enough experience to understand and navigate the subject. If you are more interested in learning than making your game then by all means go ahead.
The subject of... abstract classes?
No. The subject of Polymorphism in Unity.
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 ?
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.
can anyone good with unity help me fix a bug in my game
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
Just making sure I understand here, are you saying that given a plane defined by a 2D polygon, you want to generate an array of objects along the sides of the polygon (case 1)? Or are you looping through a 2D array over a mesh, and only instantiating the objects that fall onto the plane (case 2)?
I want to do case 1
How would you do It?
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
depends on what your wrap settings are
because then a Texture of width lets say 512, would be 513, given that 0,0 is not accounted for
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)
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
it seems to still return a colour from pixel -1, -1
why wouldn't it
the wrap mode only detemines what color
the texture always starts at 0,0
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
I'm not sure the tiling/wrapping settings affect the CPU side pixel access
This is mostly for sampling on the GPU
alright, thanks
it just picks a color based on the wrapping mode
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
As per the docs:
https://docs.unity3d.com/ScriptReference/Texture2D.GetPixel.html
The lower left corner is (0, 0). If the pixel coordinate is outside the texture's dimensions, Unity clamps or repeats it, depending on the texture's TextureWrapMode.
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
That's exactly the behaviour that Praetor quoted from the docs. So it's all by design.
err that is the one part I didn't read lol
mb
does "clamps it" means it returns the nearest pixel?
Yes. The nearest valid.
"the last pixel at the border will be used." got it
thank you
@clear shard
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.
many thanks for your detailed response
I understand your equation but I don't know how to actually do that in code
No worries, I made a prototype that demonstrates the concept by drawing Gizmos. Just attach this to an empty object and you should see it
https://pastebin.com/3kf5jHii
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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.
Wow, aren't you overthinking it?
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
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
how is it broken? is it because of the sensitivity?
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)
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
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
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?
mostly effort and knowledge of how
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.
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
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.
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.
true, but those would be the fringe cases
Depends on how you convert them, to a string there should be no issue.
Note that when converting these to strings, the local culture is applied to the number, which means the number will be formatted differently depending on the user's computer language.
3.14 on an English locale
3,14 on a French locale
This can mess up the hash, as one character changes
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
You can specify the invariant culture yep, which formats everything independently of the locale
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.
it is for pc
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)
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
True, I guess im just pointing out that it is impossible to make this hard for smart attackers.
I dont see the point of this 2nd hash, is it not just gonna compare to a value that the user sends?
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
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
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
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.
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
@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
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
What is suppose to happen when the source is destroyed ? Is the debuff suppose to still be alive ?
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
The % would be the last available stat ?
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)
Usually, I implement debuff as a copy of the stats.
which is basically a trigger recursive spell I've tied to these debuffs
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.
That would be snapshotting in this case and it is something I am considering
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.
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
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.
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
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.
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
By hybrid, I mean by having a "Refresh" function.
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
It seem to be a reasonable approach.
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.
More than a copy I would do a caching.
The hashing is to prevent someone from editing the desktop file, since the hash is only for the number the game gave out, any changes to the file itself would make it generate an incorrect hash when verifying
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
You said "on my end I get..." then people can always just edit it during the process of giving those score to you.
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."
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
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."
assuming asymmetric encryption, the only way to know the plaintext is if they look at the code where it happens
And any code running on client side is always naked code.
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
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.
^ 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
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.
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.
The hash prevents them changing the score, since it won't match up
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
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.
It was mostly to learn save/load, which I did so not really
why Unity show error missing dll when importing onnx runtime
https://github.com/microsoft/onnxruntime-genai
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
It seems Physics2D.GetRayIntersection does not return the top sprite with collider2d
I want it to return the top sprite
:/ I want to know the exact algorithm used in this game. I know there are a bunch of approaches
What do you mean by "top"?
It should iirc
Wups! :)
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)
I have decided to test it out and the objects are spawned outside of the shape. Am I doing something wrong?
Oh, got it working. The planeNormal was set to (0, 0, -1) by default.Now they're spawned perfectly inside of the perimeter
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
So.... is EACH ring still doing this?
Instead of just 1000 Updates you now have 1000 updates running 1000 jobs?
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
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
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.
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
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Hm. Weird. I moved some code around and don't think I changed anything related to this and now it works. 🤷♂️
Hate that.
I was going to suggest trying:
https://docs.unity3d.com/2018.3/Documentation/ScriptReference/EventSystems.EventSystem.SetSelectedGameObject.html
And maybe a raycastall method to grab as many elements that may be behind
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
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?
Yes. Use Time.deltaTime. That's also a beginner question, which should be asked in #💻┃code-beginner, in case you want to continue this conversation
I'm using Time.deltaTime but I still get this issue
Please, show the code in #💻┃code-beginner
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
If you want to do this with a job, you should have a manager run one job over a native array of all of your objects. To keep a list of your objects, probably easiest to add them to a managers list in the start function of each ring (or some better solution)
This post seems to be trying to do somethign similar
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
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?
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)
GPU instancing is a graphics technique available in Unity to draw lots of the same mesh and material quickly. In the right circumstances, GPU instancing can allow you to feasibly draw even millions of meshes. Unity tries to make this work automatically for you if it can. If all your meshes use the same material, ‘GPU Instancing’ is ticked, your ...
I made a final version with what you said and what Bulbus sent yesterday
If you want I can share
Sure, go ahead
rendered on top, the highest order I mean
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.
I think I figured out a better way
public PatrolTask(EnemyTree ctx) {
Trees have to pass themselves in to create a new node
well, this is cool, but how do i apply a texture instead of color
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
Tutorials for Unity Shader Graph and Universal Render Pipeline
Also, earlier I did post a shader graph I've made that uses texture arrays to render via fragment using uv coordinates
#archived-code-advanced message
is there any direct link to what i should look at
for my grass problem
Are you not chunking your meshes? If you're making 100k meshes without any combining of course you're going to run into drawcall problems
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
I'd profile and see if it's a vert problem or a drawcall problem
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
Could be a problem such that you're updating a buffer every frame with 100k units
there is no buffer tho
in this code version at least
RenderMeshInstanced operates with Matrix4x4[]
so well, using compute shader, I place the buffer of all positions in the beginning, and each frame I get distance from camera to each instance, and if it's lower than 50, add it to a second buffer which is like "instancesToRender", and then each frame i read the second buffer into a Matrix4x4[] and call rendermeshinstanced
and well, it gives less fps of course since there are too many operations ig
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
haven't you rendered grass fields before?
so well, 100k meshes was never a thing you tried to do?
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
so 1.6m verts? That's not much of a problem
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
maybe i'm dumb but
there are 3.2M verts
how
1.6m tris
oh, right you have double than expected eh
maybe that's cuz material is double sided
still, 3.2M shouldnt be tanking your fps that hard
and 450 batches isn't fps heavy either
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
says you're rendering 200000 instances which is probably why you've double verts
sadly it's 100k
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
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
how
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
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
do i need to place 100k meshes by hand and the run combine at runtime?
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
one sec
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
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
fps is same no matter where you look or where camera is
but culling individual grasses using bound/positions won't rly work this way
i guess
since it's just 1 giant mesh
if it's a single mesh you have to cull it through manual methods
and it means i need to code again
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
what is a static batching tho
this way i don't need the script to make combined mesh right?
