#archived-code-advanced
1 messages ยท Page 15 of 1
you should confirm hardware decoding is used for 4k. the sending server has to use the correct SDP for it
there's a level limit for it
did you author the webrtc signaling yourself?
@hushed moth
or are you using a pre-existing relay of some kind?
or hwat is it?
lets say half-half
I had a problem with the encoder, in obs, if the encoder is nvidia nvec x264 then google blocks it, it only works with x264 encoder + profiler = baseline
looks like the ffmpeg recode solved the problem, but still, I dont think that setting the texture in each receive is a good solution
okay i really want to help you
but all your answers have been like this
you have to just say it what it is or that's it
i can't help you if you don't tell me straight clear answers with truth
thanks for the tip, i will try it in the future
i will also look into the suggested branch
okay, i think i can't help you anymore i'm sorry
Hey guys, is it possible to clone a prefab and make changes to it before instantiating it?
Why not create a prefab variant, if your changes are that significant? Otherwise, making changes immediately after instantiating should get the job done. I would argue that if you have to change so much about the prefab that that solution is not viable, it should be a variant.
You can't make a prefab on runtime.
However you can instantiate a inactive game object and use it as prefab ๐
It's a small change, but this change is always different, which is decided at runtime. Alright, I guess there's no other way besides instantiating it first in a way that allows me to do the changes afterwards. Cheers :)
damn a real discord mod uh oh
Good point my friend thank yoh
Hello all, I am working on a particularly mathematic game in Unity and I need to write some tests, I wasted far too much time tracking a math mistake through the grapevine.
I want to ask if it's possible to add each MyClassTest next to MyClass so that I have them together at all times, regardless on how I choose to refactor the folder structure.
I saw some asmdef shenanigans are required so I am thinking perhaps it's impossible. But I still want to have it like this as my scripts hug my prefabs where I use them 1:1.
Thank you!
Sup room
You need to, and would want to separate assembly for Runtime and Test. Test classes tends to not exactly match with runtime classes anyways. I recommend you to use Test Framework package, if you're not using it.
Heyas. So wondering if anyone has had an issues with using Unity's Device Unique Identifier (UnityEngine.SystemInfo.deviceUniqueIdentifier). This is supposed to give a unique HASH from their device hardware (except for iOS), but I'm starting to think that it's maybe not unique as the documentation does not mention anything for Linux based platforms (https://docs.unity3d.com/ScriptReference/SystemInfo-deviceUniqueIdentifier.html)
I have implemented an auto login system based off their device Id for the game I'm working on (using PlayFab), but now that we have a higher influx of players after going public free-to-play, I'm noticing some players can login to another players account due to possibly having same deviceId, so if anyone has a better understanding on how this device Id works, that'd be appreciated.
why not just instead of using a gimmick like this
just have a token
It is not good idea to use something that user can easily fake like deviceUniqueIdentifier to authentication. Even if it is guaranteed to be unique, that does not mean it's going to be secure.
Anyways, the doc says it will return unsupportedIdentifier if not supported, so you should check the value on Linux.
Convention-wise I like this better
other.TryGetComponent(out ISomeInterestingInterface interfaceCommonName)
Anyways of course, that's good way of abstract components ๐
from a C# standpoint always use the generic method if you can
It is generic method
thats not what generic means thou
๐
you are using the literal definition i'm assuming
yeah this sounds good in theory
eventually you hit inheritance hell
and go there must be a better way
and thats where entities come in
with the whole ECS pattern
yeah i understood your intention
the main problem with inheritance is, its really hard to build an object dynamically
you can't create classes dynamically thou?
unless you pre create all combinations of them
of course
yeah but thats no longer inheritance
so if you wanted a collision handler on your object now
you have to go through components
i'm just referencing this
on collision grab the ICollision handler which you can't dynamically add to your object
Inheritance is one of tools to abstract things
unless you add the component
There is no silver bullet ๐ค
what do you mean who cares about dynamic lol
i'm not talking about literal dynamic keyword
i mean like if you had a rpg player who suddenly got a shield
you can just add IShield or something
but only as a component
shrugs does it matter?
yeah but what i'm saying is you are already using the C in ECS
I contribute to Svelto.ECS and there we don't allow dynamically adding component
It's not really ECS thing, it's just different pattern
If you need to add or remove some feature dynamically, you need different approach
wait just to confirm
you have an entity and it must be created with all components
so you can't add or remove components from that entities life time?
It needs to build with pre-defined entity descriptor.
Yes you can't add or remove components
It's for performance, To optimize memory structure
but shouldn't that be left up to the consumer to decide
whether or not they want that particular entity to be optimized or not? (in that way)
But by supporting it we'd have to support different type of memory layout ๐ค
well yes true in your case
I'm thinking it as characteristic of Svelto.ECS
how do you add or remove functionality from an entity - unless you have to destroy it and recreate it?
and if you have to destroy it and recreate it how does caching work
cause alot of ecs is reusing memory space
Have flag in component, or put it in filters, or change groups that can be queried from
so that means every single functionality possible must be attached to the entity
and just have something to disable it (flag)
If you're curious, see articles linked, it may make more sense https://github.com/sebas77/Svelto.ECS
Yes
i guess its just a different way of thinking
not a fan of it however
i could see the benefits for extreme performance
Yeah you can get very optimized memory layout if everything is statically determined
It may cost your productivity, yes ๐
also costs query time
if there are lets say 100,000 units with some sort of "debuff" component even thou they aren't active
you'd have to find the active ones
unless you track that real time
but then that costs you space
Depends, user can move entities between query groups.
So user can have debuff-active group and only query from there
Kinda. It still supports indexing feature separately to support some less optimal cases
But yeah always have trade off
deviceUniqueIdentifier on iOS by default will be unique per installation of the app
if you uninstall and reinstall it on iOS, it will not be the same
unless you obtain the right entitlements
you are better off generating an ID and storing it in the app's documents for it to persist
you should probably use an identity service's pre-existing guest or device accounts. for mobile users this is usually centered around a message to their phone number
i wouldn't overthink it. you don't have to use unity testing framework as your testing approach
you can also write whatever you want wherever you want, and call it wherever you want
if you want the tests in the script, go for it
Yeah for iOS I'd use the user's App Store I'd, as that seems to be the safest way
I'm thinking that I should also get the users MAC address, add it to their unique device ID string, and re hash it to use that as the auto login key. But yeah, not sure if that's really that secure still
But it would mean that users on a platform that does not support unique identifier would mean it is now unique
this seems overly complicated
for no reason
just given them a login token and save it to their system if they want to remember me (after successful login)
cause what happens if they do this on a public device
kinda stupid
Right yeah good point, like at a cafe.
I kinda wouldn't just thought that storing their login token in their options file for example would be bad as well, incase someone else gets their hand on options file and just copies the key
if you hit remember me
on a device someone can steal
thats kinda on you
but thats true for any login token right now
like i could ask for or steal your discord token
and just pretend to be you
(just to clarify this is hypothetical and i in no way want it)
Yeah fair enough. Good point.
the good thing about tokens is you can have expiry dates and people can invalidate them
cause you can just generate a new one every x days
So you'd recommend generating a token separate from any device identifiers, and just storing that if they hit remember me
yeah
this way you can handle collision server side as well
(in the rare case it does)
Yeah makes sense.
Do you have a recommendation for how I should generate that token? (C#) Like basing it off certain hardware serial numbers, or something like the current date where it's a one-time creation that will be completely unique?
eh
just generate a guid
Yeah had a feeling youd say that haha
is DrawInstanceMesh still the fastest way to display many times the same thing or is there a faster way now in 2021?
So lets say I want to pass a NativeArray<uint> to a c++ funtions that has unsigned int* destination as the parameter. What I have to do is (IntPtr)NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks ( myArray ) ; Is this correct ?
how do I declare the function on the c# side? I dont want to wrap everything in unsafe, passing the IntPtr results in a sigsev. Not using NativeArrays and simply passing a uint[] works fine
Idk what I'm doing wrong with the nativearrays
probably make a couple of adapters for the functions that you need, taking in native arrays
or use unsafe
Hi guys, I'm making a unity project that requires external dependencies aka plugins. I would like to know what is a way in unity to deal with external dependencies. Is there a some kind of package manager as npm for unity? So any new developer, who clones my project can install all required dependencies with a single command. Because now I'm forced to install all dependencies manually by clicking on unity package files and importing it.
afaik no, you have to add them to source control
and what if my packages are like hundreds of megabytes?
git lfs
Got it, thanks
Unity does have a package manager, it's somewhat new and less feature rich than npm but it's viable.
If you install any packages via it then they will be cached in your "Library" folder and added to a JSON file in the "Packages" folder.
https://docs.unity3d.com/Manual/Packages.html
as far as I see not all packages support it, right?
For example Zenject doesn't or does partially
Thats the problem if I pass a NativeArray instead of a simple uint[] the data on c++ side gets jumbled idk why. So I think Im forced to pass in the pointers explicitly
show more code
maybe you don't convert the length right or something
you can pass the pointers, just make a wrapper function that encapsulates the pointer business so that you don't have to put unsafe everywhere but just in that function
make the function take a native array
and do the pointer business there
if it's just code, consider forks + git submodules
good point
if it's nugets, I'd suggest managing them with a custom script
nugetforunity exists, bit it's meh in my experience
so I can just add zenject git repo as submodule to plugins folder
and whenever I clone project again, I'll just go git submodule update
basically yeah
and it will fetch it for me
if it's possible, it's usually a good approach
but what about building library?
Give me a min I will show you the exact code I was away for lunch
Are there any pitfalls with that?
what's that?
DrawMeshInstancedIndirect could be even faster
well, if I install library from unity asset store / or by downloading it manually, it comes like a built binary, no?
oh you mean restoring the cache
while in gitsubmodule it's just a code
so what? is that bad?
if it's in a separate asmdef, it would get cached and only build once anyway
I mean that code would be build on my local machine and there might be problems with environment or no?
i guess it depends on the project, but I'd expect it to just work
okay
@maiden turtle so this is the function on the c++ side c++ size_t meshopt_simplify(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, unsigned int options, float* result_error); I have it wrapped like this cs [DllImport("meshoptimizer.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)] private static extern UInt64 meshopt_simplify(NativeArray<uint> destination, NativeArray<uint> indices, UInt64 indexCount, NativeArray<float3>[] vertex_positions_data, UInt64 vertex_count,UInt64 vertex_positions_stride,UInt64 target_index_count, float target_error, uint options,float[] out_result_error); if I use a simple uint[] instead of the native array stuff it works as expected so I'm guessing the pointer passed to the native array does not point directly to the data
is it extern(C) on the c++ side?
yes
it's weird to me that it works at all. I'm not sure on the details of function signature mapping, but to me these two look completely different. an int* is not the same as a NativeArray<int>. let me consult the docs
a native array is pointer + length
afaik
well the function itself is made to take the pointer of the first element and the size of the collection and iterate over that
so it works exactly as expected when passing in a uint[] is it's a pointer to the first element anyways( I think) not sure what NativeArray points to
I want to get the NativeArray part down since I'm going to have to spin up jobs calling this dll in the future
and I have to use this new mesh API
it would appear to me it passes the pointer to the array object, not the array data. have you actually tried iterating over data and confirm it works?
iterating over what data ?
if you pass a uint[], you say it works. by that you mean the code on the other side gets a valid pointer?
yes it also returns valid indicies that build a valid mesh
so I can confirm that passing uint[] works fine
also it seems I cant pass a IntPtr struct to a int* in c++
again, idk the details. ehat I'd do is I'd replicate the signature perfectly, make it unsafe, and write out a bunch of adapters for native arrays, then it would work for sure
I can't find the relevant docs on this marshalling, i think it's called, rules right now
the adapter would just call the actual binding, having extracted the pointer from the native array that was passed in
I wanted to somehow avoid using a unsafe context but looks like it cant be avoided
just use it in the wrapper function
you can call it normally in a safe context even if the function is unsafe
unsafe doesn't mean you can't use it in safe code
Yes, most people don't support it
get_gameObject and get_transform allocate 40 B, is that a recent regression?
I have also noticed 40 B GC in OnTriggerEnterExit events when calling collider.TryGetComponent. Its get_gameObject that allocs 40 B
hmm, is this related to my question?
you would need to declare ref NativeArray...
then it iwll work
the correct way to use a nativearray in your extern is
I just did a test with ``` [DllImport("meshoptimizer.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]
private static extern void myTest(uint* destination, uint count);
public static void NativeArrayTest(NativeArray<uint> data, uint count)
{
uint* ptr = (uint*)NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(data);
myTest(ptr, count);
}```
and this works
it adds 1 to the native array and prints it out from unity
i was writing the declaration
your telling me that if I do ``` private static extern void myTest(ref NativeArray<uint> destination, uint count);
it's nuanced
i wouldn't use the ref keyword at all here
what I did in my test is what you suggest right ?
yes but i would use intptr
let me test with intptr
because that's the actual type that is passed to your extern
should be UIntPtr right ?
cause the c++ side expects unsigned int*
Good day all! I am attempting to automate a build process for hundreds of webgl mini builds. Its a single scene. Set up the decorations, build, new decoration layout, build, repeat. Using the official documentation and each time I get error CS0234: The type or namespace 'Build' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)
Any ideas on how to overcome this? Is this a known issue? So far my reseach has not returned much.
Link to the doc:
https://docs.unity3d.com/2020.3/Documentation/ScriptReference/BuildPipeline.BuildPlayer.html
My code:
using UnityEditor;
using UnityEditor.Build.Reporting;
...
[Button]
public static void TestBuild()
{
BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions();
buildPlayerOptions.scenes = new[] {"Assets/Scenes/Dev.unity"};
buildPlayerOptions.locationPathName = "Assets/Builds";
buildPlayerOptions.target = BuildTarget.WebGL;
buildPlayerOptions.options = BuildOptions.None;
BuildReport report = BuildPipeline.BuildPlayer(buildPlayerOptions);
BuildSummary summary = report.summary;
if (summary.result == BuildResult.Succeeded)
{
Debug.Log("Build succeeded: " + summary.totalSize + " bytes");
}
if (summary.result == BuildResult.Failed)
{
Debug.Log("Build failed");
}
}
Any help would be greatly appreciated!
intptr is just void*
as a value
since structs are passed by value in c#
so then who will do the vast from void* to unsigned int* ?
it is a static cast, they are the same ๐
x-files music
you've basically figured it out
try putting your script inside folder named "Editor"
the only reason to do this is to make it bulletproof
this is the example in the unity source i found
it's actually very rare to pass native arrays to extern declared methods
in their bindings
they usually package it all in a struct as with the async readback api
using IntPtr means it's unambiguous how C# should marshal i think
Its not an editor script, it has object references in the scene
then wrap all editor related code with #if UNITY_EDITOR and #endif
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.Build.Reporting;
#endif
...
#if UNITY_EDITOR
[Button]
public static void TestBuild()
{
BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions();
buildPlayerOptions.scenes = new[] {"Assets/Scenes/Dev.unity"};
buildPlayerOptions.locationPathName = "Assets/Builds";
buildPlayerOptions.target = BuildTarget.WebGL;
buildPlayerOptions.options = BuildOptions.None;
BuildReport report = BuildPipeline.BuildPlayer(buildPlayerOptions);
BuildSummary summary = report.summary;
if (summary.result == BuildResult.Succeeded)
{
Debug.Log("Build succeeded: " + summary.totalSize + " bytes");
}
if (summary.result == BuildResult.Failed)
{
Debug.Log("Build failed");
}
}
#endif
Gotcha. Thank you I will try that now
Thanks doc if anything this will make the code cleaner
what's the game?
are you trying to turn N assets inside a viewer into N webgl builds?
hi all, does anyone have any pointers to making a good pre commit hook for c#? I'm trying to stop my devs from committing if there are any stylistic or typo errors in their code
Creating mini scenes for a client. Using an algorithm to create all possible combinations and spit them out as webgl builds little dioramas
@abstract root Thank you but wrapping the editor bits did not work
any specific errors?
The same, claiming I am not using UnityEditor.Build, which I am
is the script inside a separate assembly?
You can't have any references to UnityEditor outside of Editor assemblies, the error says that you are and thus you need to exclude those from builds
No, It is in the scripts folder
Ok, I'm sorry a bit lost on how to resolve that
Nixa gave you a good example on how to exclude things, you should do that for everything that uses UnityEditor
Or move your editor only code to an editor assembly, either a folder named Editor or if you're using AsmDef files then you need to create an asmdef and mark it as editor only
Yes you probably missed something
the error will point to where it found an issue
This is where it says the issue is:
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
Not sure how I could have possibly messed that up
Looks like it's not wrapped in an #if
The include lines need to be wrapped as well?
Yes
It's in Nixa's example ๐คทโโ๏ธ
I see, I just missed that is all
yeah, this is what I meant, that can never go wrong
yeah thanks for the help. I think I have it figured out now
now to continue restling with the unity api
btw what the doc suggested for IntPtr also works fine at least in the test, hope so with the actual codebase as well
yeah since all pointers are the same size, it only matters from the type safety standpoint which type of pointer gets passed
and if you made adapters, you wouldn't care about that anyway
so what is "safer" ? IntPtr or explicitly using the same pointer type as the c++ code ?
Neither one ensures you got the function signature right, I think.
using the same pointer type, well, reflects the type
so imo that's better
but make the wrapper functions anyway
in the context of what you are talking about is this ``` public static void NativeArrayTest(NativeArray<uint> data, uint count)
{
IntPtr ptr = (IntPtr)data.GetUnsafePtr();
myTest(ptr, count);
}``` the adapter ?
yeah
cool we are on the same page then ๐
that was how I'm making it anyways. I'm not calling the extern directly
does anyone have any pointers to making a good pre commit hook for c#?
you probably want to use something that can compile into a single binary for all platforms, like golang or zig
then, author it as a plugin for pre-commit
however i will warn you... this is a colossal waste of time
in my experience, it's best to have a custom cli tool for all CI stuff. you could try Nuke maybe, I didn't like it much but it does a lot of stuff for you.
hello, i'm wondering does anybody know of a way i could acquire names of the files that a folder holds? for example if i go to a special directory i can create files File1.txt File2.ogg File3.exe and so the game acquires the names and creates strings so now i have 3 strings each one named that (order doesn't matter) and if there's only one file it only acquires a single string etc.
thanks, but how does it work by the way?
it's a function
I'd forgotten about this one. Cheers.
That requires some shader knowledge but should be super fast
Also because you have to give the object positions etc. as buffers, its really easy and fast to modify them using compute shaders
Should I always declare my classes as sealed when posible?
No
it's just noise
I'd say only bother with sealed if you're making a library for other developers to consume.
Well, bother with sealed is good practice and in some cases you can gain a little bit of performance
Not sure if I am asking in the wrong channel but I ran across something and can't figure out why. I am raycasting to an inverted cube and its not returning the correct normals. A basic cube returns the correct normals but not an inverted one. The player is inside of a box
You have taken into account that inverted faces also have inverted normals?
I tried using the inverse but it still hasn't returned the correct normal
this is what I am using
{
Debug.Log(normal);
switch (normal)
{
case Vector3 v when v.Equals(selectedObject.transform.forward):
_surfaceDirection = SurfaceDirection.Front;
break;
case Vector3 v when v.Equals(-selectedObject.transform.forward):
_surfaceDirection = SurfaceDirection.Back;
break;
case Vector3 v when v.Equals(-selectedObject.transform.right):
_surfaceDirection = SurfaceDirection.Left;
break;
case Vector3 v when v.Equals(selectedObject.transform.right):
_surfaceDirection = SurfaceDirection.Right;
break;
case Vector3 v when v.Equals(selectedObject.transform.up):
_surfaceDirection = SurfaceDirection.Top;
break;
case Vector3 v when v.Equals(-selectedObject.transform.up):
_surfaceDirection = SurfaceDirection.Bottom;
break;
}
return _surfaceDirection;
}```
damn haha. Why would it be a waste of time?
Hmm you could use dotnet format..
Yeah, I'm thinking of enforcing dotnet format, but the goal of the pre commit hook is just to stop devs from committing if there's anything we don't allow style-wise
I dont have enough information to go with "what I want". I don't know what are the proper options to form an opinion or decision.
Hey, should I use DrawMeshInstancedIndirect for a custom detail renderer? I'm using DrawMeshInstanced at the moment, but noticed that a lot of other solutions use the indirect method.
indirect has the potential for better performance - but is also a bit more complex to set up
what exactly are you testing? what is the game?
?
Yes
I have some spreadsheets that dictate the proper loot and progression rate but my actual Unity-based generation is giving me buggy results
okay
that makes a lot of sense
So my need is straightforward, I can either put Generate.cs and GenerateTest.cs in the same folder, or I can mirror my Scripts folder with a Tests folder
yeah
I would prefer pairing the classes together Generate.cs and GenerateTest.cs
otherwise I have to sync the Tests and Scripts all the time
besides the aesthetics of it, why is it essential that the files be side by side
and why do you use the word sync? you could, or could not, write tests for any code, or no code
The asmfdef is my blocker because I see everybody put all tests in a single folder
what about it exactly is blocking you?
If I put all the tests in individual folders sprinkled around, I have to make an asdmfdef for each, right?
no
An asmdef takes the folder it's in and the subfolders and turns it into a dll yes?
yes
you're a very experienced developer so i hear you
there's a particular way you want to organize the files
which, it sounds like it's the golang pattern to me
i just have to understand if this is essential
like besides the aesthetics of it
why does a ClassNameTest have to exist for every ClassName
and why does it have to be side by side in the file system?
I restructure my project shape frequently and recently I split the code in several submodules / git projects to reuse in other projects
Thus I wanted the class and the test class to stay together
Unity testing definitely kinda forces you into having parallel folder structures, due to the way asmdef works
okay but
@sly grove I was afraid of this, but tutorials are kinda all identical and I hoped to find a solution
what if you just had a file called GeneratorTests that tests all of your generation code?
and it's just 1 file for "all" your classes
And have a 5000 line code omega class? sounds painful to update it
you have a working game, usually for a less experienced programmer i would tell them that these aesthetic constraints are getting in the way of things
but if it's important to you to organize something in a very specific way
you can have the files side by side, and each their own named thing or whatever
it just depends do you really need Tests or tests?
are you going to run these automatically in a build server?
do you need them to correctly respect accessor visibility?
I like single-responsibility classes and I structured my features in the form of:
Feature
-FeaturePrefab
-FeatureView
-FeatureViewTest (this is what I gravitate to add everywhere)
I will do them manually, or make a local script before doing git commit
do you need a testing framework is really the question
do you care for any of the value that XUnit / NUnit (peer of unity's testing framework) gives you?
Well, I want to do Asserts and I like the UI panel that shows me what's failed and what's succeeded
okay
I don't really care about the tool, just the results (painless as possible)
does it matter to you if your build ships with the small testing framework dll?
included inside the export?
yes
I guess it's fine
okay
then you can just reference the testing framework package in your Scripts asmdef (or however you have it organized) and you're good to go
you can declare the tests
side by side
how small is the testing dll
Then problem solved! I get to have my cake and eat it too
lol
thank you @undone coral
basically you're making your player assembly contain the tests
which are just methods with the annotation [Test] or whatever
in principle, it will all get stripped out in il2cpp anyway, since nothing references it
I will put the contents of my Test.cs classes inside #if UNITY_EDITOR anway
yeah i think it will all be fine
for future reference a NativeArray has a bunch of fields, the first field happens to be a pointer to its malloc'd buffer. declaring NativeArray in the extern statement incorrectly sizes the function call, because NativeArray is a struct and C# passes structs by value (copies them)
an unsafe cast of nativearray to a void* happens to work because the first field is indeed a pointer to a buffer
so if you interpreted the nativearray as an IntPtr or void* unsafely, Things Would Work
that wouldn't be true if the declaration of NativeArray ever changed
if you did ref NativeArray, the method would receive a pointer to the struct, whose first field is happens to be a buffer point. so the receiving method would actually get a void**
no good.
Can I make 'nested' class as MonoBehaviour/ScriptableObject?
How do I match the filename?
1 mono per .cs
you mean derive a class which itself derives from monobehaviour ?
public class OuterClass
{
public class TempBehaviour : MonoBehaviour { }
}
Outer class is not MonoBehaviour
you can but you won't be able to add those components in the editor or really see them properly in the inspector. You can only interact with it via AddComponent etc..
I don't recommend it
basically the editor doesn't know how to handle it if it's not 1:1
why would you want to use such a construction?
It's related to convention of my package
I use generic outer class so it's gonna be extra challenging ๐
Well, it's actually gonna be SO and user will not directly change content of it
So imma give it a try...
I cannot see that working
you won't be able to create Assets of the SO, only instances in memory
which defeats the purpose, right?
the SO asset needs a file GUID to point at for the script. It won't have such a thing if the class is not 1:1 with a file unfortunately
Hmmm yeah that will be shame
I can just go with interface ๐
Though It will be still 1:1 match
Outer class is not Mono or SO
That is the problem
It won't be able to detect that sadly ๐ข
public class OuterClass
{
public interface ITempBehaviour { }
}
public class TempBehaviour : MonoBehaviour, OuterClass.ITempBehaviour { }
I might end up doing like this, it's also fine ๐
that will work
But it's still gonna need generic ๐
I'll post here when I sort this out
generic on the interface or on outerclass?
It's gonna be on outer class and SO
I saw this repo and pretty interesting https://github.com/SolidAlloy/GenericUnityObjects
So I probably can create asset with generic args same way
be careful with builds, a lot of generics will work in Editor but get removed from a build
Yeah, as long as they are being used it should be fine, but I'll make sure test them
code stripping can be an absolute bitch
This repo turned out it's codegen solution with Reflection.Emit
That automatically generate empty child class lol
Interesting but I'll have to find out a better way
DrawMeshInstancedIndirect could be even
The unity API is mostly just a wrapper for those systems to interact with GO's yes, but there's also other things like sound, UI, inputs.
80% of the time you don't need a Mono class.
is the goal to have a script that "holds" a data class or something
for the spreadsheet thing?
you can use the approach addressables does
Yup it is
Do you mean AssetReference thing?
yes one perspective is that the end user knows exactly what type they will need
they are never going to make the error, oh no i forgot what type this is
they can handle CatheiReference ref; ref.AsRow<RowType>()
otherwise code generation is unavoidable. you would probably want to create an IDL, and then generate the types from that using someone else's tool.
Yeah actually I pretty much settled with same conclusion
So my SO will only hold JSON serialized string that can be used for any row
With a type metadata for editor script to filter them
i also do not find it that burdensome, in general, to declare the class MyClass : BaseClass<RowType> {} myself
if i am using your sophisticated thing, i can handle creating that file
i wouldn't be bummed you didn't make that for me
however... how are you generating RowType?
that's still codegen
tricky codegen at that
i've seen JOOQ's code it's nuts
gotchyu fam
Then I parse spreadsheet by that type user defined
gotchyu famalam
i would suggest doing the hdrp config package approach
where you get a copy of a bunch of things you can customize
then you can give the end user the file
[Serializable]
public partial class DefaultRowType : IRowType {
}
that they can edit... they're going ot have 1 row type most of the time
then include a file ```cs
public partial class DefaultDataHolder : DataHolder<DefaultRowType> {}
in your package
Hmmm how will it help :0
DataHolder would be a monobehaviour*
public abstract class DataHolder<TRow> : MonoBehaviour where TRow : IRowType { ... }
you can actually just put both partials in your package
and then build your docs around filling out the partial
on their side, in their own space
since most people will have 1 row type they'll at least be able to get started easily
you just can't easily rename / upgrade this stuff, but that's a problem with all serialization libraries
Ah that kinda thing ๐ค Isn't it basically codegen without 'gen' but manual copy
or no copy
it's a low ask
protobufs ships all its classes as partial for C#
in case you wanna add stuff
public class ItemSheet : Sheet<ItemSheet.Row>
{
public class Row : SheetRow
{
// use name of matching column
public string Name { get; private set; }
public int Price { get; private set; }
}
}
This is how it looks like rn
The thing is I'm supporting multiple importer/exporter with same object
public abstract class SheetScriptableObject : ScriptableObject, ISerializationCallbackReceiver
{
[SerializeField]
private string _serializedRow;
[SerializeField]
private List<UnityEngine.Object> _references = new List<UnityEngine.Object>();
private ISheetRow _row;
}
SO's gonna look like this, I'm happy with the format itself
User can use ItemSheet.ScriptableObject type to filtered reference of SheetScriptableObject and get ItemSheet.Row through it
Which I'd provide with PropertyDrawer
So that one is pretty much settled, I have another problem, though
About how to support column referencing specific asset, while supporting server side assembly
Something like AssetPath<GameObject> is not going to work in non-Unity env ๐ค
you can use unity stubs
they exist
they're alright
What is that?
hmm
there used to be a github repo
with unityengine.dll and unityeditor.dll
stripped of externs
so it's just the types
Sounds useful for this purpose
Setting looks like requiring some complex work but very interesting, thank you
I'll either go with using mock classes for Unity, or just use generic AssetPath
it is pretty painful to install the unity editor into a container btw
could be a huge distraction for you
Exactly. ๐ข
although i think most innovation lies there
it's very tough
i pitched trilib guy on it too
Only if there was [Conditional] for generic parameter lol
Is there a reason?
I do use codegen in my own projects, roslyn generator is cool, just I don't need codegen for this library
Ah was wondering if there was hate against it.
Plus making codegen configuration generic is messy XD
I want my libraries Vanilla as possible so it can be easily maintained
should the UserSettings directory be gitignored?
When you make your repo on github, add the default ignore file.
I don't use GH unfortunately
and the project is already made
If you have your .gitignore handy, could you please tell me if UserSettings is included in it?
no worries if not
ah yeah that's a good point -- id already done that, and am using a template, but i guess the update to 2021 added this directory. mine didnt have that. thanks
looks like UserSettings is indeed included in 2021
They should be ignored
It's personal settings per user
Thanks!
ComputeBuffer.GetData, is there something faster and non blocking?
When you initialize an object you have control over what it can reference as well, as oppose to having to resort to using the api to pull a reference.
SomeRegisterService(this);```
ComputeBuffer.GetData is the fastest way. AsyncGPUReadback gives you non-blocking, but is a bit slower.
In theory, you should not create GameObject if it doesn't have "view"
Which would be physics collider or rendering component, they would only interact with physics
But if you count logical case like "Player HP went down so HP bar should decrease" as interaction then there is much more way to interact
Do you know how much slower Async is?
Documentation says:
adds a few frames of latency
Sure, if your system doesn't need to do that. But relying on (for an example) like a health system mentioned above you shouldn't have a GO health (just a health bar) you shouldn't be using any API calls to get a reference to anything.
HealthBarUI.Set(Player.Health) There's no API calls to unity, you have all direct references so I don't know why you don't think it's a good idea to "couple" one Mono to another when you can have managers / controllers.
I'll take that, thx
"That game object would have something that represents the health system" You're saying you would put the player health on a healthbar UI?
Why would you have health data on a GO?
public uint health;```
You would pass your view a value and it would render it, right?
An observer doesn't need to be a GO
"That game object would have something that represents the health system" You are saying that it represents a health system, not the health value.
how are you using it? usually for low latency stuff you want to keep it on the GPU
I'm trying to explain that 80% of the time you don't need to interact through game objects (and you shouldn't). For the above example your game objects should only receive and render the value of health, there shouldn't be health anywhere in the scene as you don't need it.
For things like a player attacking enemies, yes that's a system that needs colliders, and you would have to use the API.
For a system that has only ONE enemy you wouldn't use colliders unless it was physics based and you would directly call Enemy.Hit(damage) from your Player.Attack(), or even a observer.
You wouldn't want to rely on another layer of interface if you can just do it by directly referencing.
I'm adding to your central point by saying most of the time a system doesn't need to rely on the API to get references, you can arcetect it around direct references when you can.
it needs to come back to the cpu to get mesh colliders
what exactly is the cause of your in game interactions that isn't a raycast I literally just showed you Enemy.Hit(damage) from your Player.Attack(),
that's tough
imo you should do a rough simulation in CPU first
void IsAttackButtonPressed(){ Player.Attack(Enemy, damage)
Mate you have inputs.
Instantiation is also interaction ๐
on modern AMD and NVIDIA gpus, compute can run parallel to graphics, and in principle you can get your data same frame
Player.CurrentEnemy(this)```
The spawner and instance
it's not sim, it's marchingcube to mesh a voxel volume
I think we're trying to explain that you don't need to use the API in most cases.
From a manager.
Static.
Singlton.
Where would you like to get it?
have you looked how mudbun does it
And relying on a raycast is better?
You're free to do what you want. I'm trying to argue that having a direct reference as opposed to relying on a API interface is better.
I disagree 100%.
But you're free to do it your way.
You know that relying on the API is "Middle management" too right?
does what?
marching cube to mesh a voxel volume
they keep it on the gpu
I understand it, but your only argument as to why you prefer using the API is that "managers suck" When you're using managers.
it has colliders too
i don't know if it's realtime colliders
ok, lemme look
or like if you have to call a method to get the mesh
.Hit(), .Collide(), .Find() pick what you amt.
i don t know if it s realtime colliders
But a raycast (or any other collision) is a lose manager.
You're literally using a manager when you use those.
What do you think .Hit() is?
Then use a Singleton.
Alright mate. You keep using the API.
What do you think Physics. is?
You think it's some magic code? ๐
I don't use managers uses manager.
What is the Physics. lib to you?
How does it exist?
I'm listening, you're "Barfing" at managing references but then don't acknowledge it's a standard across Unity.
Alright, anyways you're free to do what you want.
But you refuse to write one because "Barf"
IMO you're just relying on weaker code and adding smell when you rely on physics when you can easily contain a direct reference where you need it, but you can do what you want.
We don't have to agree, and that's fine.
To be fair your only opinion was "Barf" ๐
why would you have both Instance and Singleton?
I think you're lost mate...
Who... Actually cares?
this whole thread is very childish.
theres no 1 way to do something
Move on
Well you should get it right, SomeManagerManager.Instance().Enemy()
whether you DI or singleton i think his problem is more having to write a manager
sad thing is
this means ECS is out the window
cause S is basically a manager
would be nice if they supported DI out of the box
thats not what DI means
As many as your contexts ๐ค
Call me a sinner
i think most people have something similar
For example each prefab can be each small context if they need dependencies
A combat can be context, a scene can be context
that doesn't really mean anything thou
Singletons are good, if used in moderation Imo.
GameManager is the only singleton here, and it has a reference to the other managers
public AudioManager GetAudioManager() => audioManager;
public SaveManager GetSaveManager() => saveManager;``` and yes, i prefer this, instead of a property
but that's effectively the same thing as a property
we all have our kinks boxfiend
๐ It is not single point of entry if it's getting referenced from all over your code
if its many:1 its single point of entry no?
how else do you define single point of entry otherwise
Single point of entry should not be referenced by other code in that context..
???
It should reference dependencies, not getting referenced
dependencies of what?
this is a wrapper around the resource
to give a single point of entry
what dependency are we talking about here
Composition root is where the dependencies getting injected..
Not the other way around like every other script referencing Composition root
oh if you are referring to push vs pull sure
I'm talking about Dependency Injection
yeah i know
yeah its just DI without a framework. actully prefer it this way
but whos gonna build DI
i was more referring to this is single point of entry
i didn't really care about the CR comment
but i see what you are getting at
Single point of entry is where program or context starts, composition root can be initialized
it just makes it easy to manage dependencies, they can be constructed at different points with the top being main, and passed down to what depends on them
only if we're talking in context of DI sure
Referencing single point of entry is like calling Main from your script, which is nonsense in most of scenario
Y'all want to fight about Scriptable Objects now?
i've still never used an SO before
(โฏยฐโกยฐ๏ผโฏ๏ธต โปโโป
Keep it that way, SO sucks
It's actually funny, on the other discord (GDL) they advocate for SO's.
They're an awesome part of the toolkit that people should consider when implementing anything. Just like almost everything else you can use them inappropriately or wastefully
huh its probably the type of concepts i code, most of it doesn't have (large amounts of) hard coded data
since its mainly roguelike/lite stuff so haven't had a need for a data class
like the test tower defence i'm trying out right now you build your own tower
so there is no definition
Using SO something other than immutable data is basically visual scripting ๐
Don't you build a tower in every tower defense? It's in the name
แดต'แต แถ แตแถแตแถฆโฟแต สทแถฆแตสฐ สธแตแต
Where do you store data like waves, items, initial health, etc?
its all math formulas
there is however a baseline
for the (stats)
and there is no predefined wave
So baseline values are just set in inspector I guess
I see, nothing wrong with that if you don't have to edit or refactor values a lot
oo, a scriptable object gold star
you don't have to start
don't even think about scriptable objects
this is very pleasing and reassuring to me
the comforting, snug feels of the scripts that you finish and don't revisit, and then when you need to write new stuff, it gets added on
the warm fuzzy of a game getting made
this is psychotic and puts me into an emotional tailspin
okay i can think of worse things:
public class managers : ScriptableObjectSingleton<managers> {
public Func<ScriptableObjectSingleton<audioManager>> getAudioManager;
void Start() {
getAudioManager = FindObjectsByTag("audio manager")[0].GetComponent<AudioManagerFinder().audioManager_FindAudioManager_SO().Deserialize();
}
}
Too artificial
Unless you make YT video with lot of tutorial follower
lol
okay i'll work on this bit more
_SO is pretty authentic though
doing it on start is somewhat sane, you've really got to make some basic logic mistake in a property that means it's retrieved via Find every time it's called
Hello, I have a problem with collider and rigidbody. I force my ball with 2000f and it bounce off even dont hit the bound (pic1) - exactly it cant because the ball smaller than empty between two bounds.
When I force my ball with 1000f , it go through normaly.
I had test my Ball with Continous Speculative and Continoues Dynamic but nothing change
Does OnMouseEnter get called for any collider in 2D, or just the first one the raycast hits?
Guys I have weird problem. I have a player object which is always in DontDestoryOnLoad Scene. It is a VR game. It has in Start() SceneManager.sceneLoaded event. But if a new scene is loaded all references in this script gets null. But only in the sceneLoaded assigned event method. I am really confused what is happening. I already checked with Awake and Update but there references are NOT null but in the event method they are null. And the funny part is this happens not always. Even if (gameObject) causes error
looks like PlayerManager isn't DDOL after all
and any other GameObjects it references which aren't also DDOL will be lost when their scene is unloaded
The references are all childs of the main gameobject. Like I wrote I used Update() to print the references and they are never null there and it happens randomly. I also checked OnDestroy.. also not invoked. In the editor I can see the gameobjects all exists and even in the inspector I see them they are assigned.
Ok I tried something else. It has definitely something to do with SceneManager.sceneLoaded. I changed to LoadSceneAsync and used complete event and there gameObject exists but in the event of sceneLoaded it shows still error.. Weird.
public class DDOL : MonoBehaviour
{
void Awake() => DontDestroyOnLoad(this);
}
Also if you can, I would suggest removing your dependency on Unity child / parent. And hold references directly to your instances.
A parent spwans a child, so you have your reference right there.
May fix some of your issues.
void SpawnChild() => new Child(this);
maybe time to show some code. The fact that your OnSceneLoaded takes an extra argument tells me maybe you have a closure over something and are not looking at what you think you're looking at
how are you setting this event up?
This is how it looks like (simplified)
Player (PlayerManager.cs)
-->Camera (CameraFade.cs)
Player has the PlayerManager script.
Camera has the CameraFade script. PlayerManager has a field for CameraFade and I just dragged and dropped dropped it like usually. Its also a prefab. So it cannot lose actually.
But still does not makes sense, why this.gameObject should be null?
But like above I said with AsyncOperation it never shows any errors. Just check the image. Async also uses gameObject and no error while in the SceneLoaded it shows error.
Ok in a sec
@long ivy
void Start()
{
SceneManager.sceneLoaded += OnSceneLoaded;
}
private void OnSceneLoaded(Scene scene, LoadSceneMode mode) {
previousScene = currentScene;
currentScene = scene.name;
Debug.Log("OnSceneLoaded invoked");
Debug.Log(gameObject); // this shows error sometimes
//if (gameObject) // this even cannot work, it shows error
// StartCoroutine(DelayedInvoke());
//else
// Debug.LogError("This gameObject does not exists...");
//IEnumerator DelayedInvoke()
//{
// yield return new WaitForSeconds(1f);
// camFade.SlowFadeIn();
//}
}
// This gets called if I want to change the scene
public void TransitionToScene(string scene) {
sceneName = scene;
camFade.SlowFadeOut();
Invoke("LoadScene", 1.5f);
}
private void LoadScene() {
previousScene = currentScene;
//SceneManager.LoadScene(sceneName);
asyncLoadScene = SceneManager.LoadSceneAsync(sceneName);
asyncLoadScene.completed += (ao) =>
{
Debug.Log("asyncLoadScene.completed invoked");
Debug.Log(gameObject); // NEVER shows error (10x tested).
if (gameObject)
StartCoroutine(DelayedInvoke());
else
Debug.LogError("This gameObject does not exists...");
IEnumerator DelayedInvoke()
{
yield return new WaitForSeconds(1f);
camFade.SlowFadeIn();
}
};
}
And of course this one
void Awake() {
DontDestroyOnLoad(gameObject);
}
The version I am using is 2021.3.4f1
this doesn't match your previous code. Does the PlayerManager GO have a parent? Does PlayerManager exist in the scene as a prefab instance?
I used in OnSceneLoaded PlayerManager argument just to compare the instance. I thought maybe there are two of them and weird things happens. I just changed back to original code.
No, PlayerManager has no parent. PlayerManager is a prefab.
does PlayerManager do anything else? Is it a singleton? Is the AwakeScene ever loaded again?
This is not even my project and not my code. I just got hired to complete some milestones but I couldn't even start because of this error ๐
.
However, as you can see it works with asyncLoadScene.completed event.
But I also noticed if I go into playmode if I don't get error.. so the error never comes. But if I restart and it shows error.. so it happens always. But still does not make sense for me.
Yes but in that time I do nothing else. In AwakeScene is just idled until I call LoadScene (TransitionToScene). AwakeScene is only loaded on gamestart and from there I can switch to another scene which I can choose via the UI or via ContextMenu in the editor (for faster debugging).
The singleton is a good hint. Let me check that
Omg you are right. It is a singleton and they activated the Enter Play Mode without Domain Reload. Now it makes sense.. Holy...
Ok, I finally figured out what's actually happening. The singleton is NOT the problem. Oh dear.. what a headache.
Since this SceneManager.sceneLoaded is a static, it does not gecleared if I replay because Enter Play Mode was activated in the project settings. So it just contains the handler and reference to the gameObject which of course is null when I turn back to editmode.
Now it also makes sense why it happens sometimes. If I change code and compile the domain gets reloaded so the sceneLoaded handler list is cleared. That's why it worked also all the time until I restart it without any code changes because sceneLoaded had one handler in the list not two with null. What a headache. I hope I was able to explain it clearly.
At this point I'm at a total loss. https://pastebin.com/1DyXju4F I know that the data in newIndicies is correct. The triangles get set, the submesh has the correct number of indicies, the bounds are correct etc etc. Yet no mesh is rendered at all. I also know that the vertex data is there and correct since I dont modify the verts at all. Wtf am I doing wrong.
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.
wrong group sorry
If you're going to post elsewhere please at least make the effort of deleting your question here!
effort made
where do you interact with the submesh here?
anyway i think it's just something here that has to actually be called
i am not sure what it is
If something else has to be called Im not sure what it is too since its nowhere in the docs
Hey guys, I'm wondering if anyone has some insight in an algorithm that would create a pattern similar to this? I am planning to use this for a continuous 2d cave system
where did this picture come from?
did you draw it?
Ye I drew it
okay
you can try drawing it again, and write down the decisions you made while you were drawing it. that is the start of your algorithm
there are many approaches to procedural graphics generation, but the real problem is that they are incomprehensible to people who have never done it before
and it wont' be useful to use a preexisting one for you
Ah that makes sense thank you
i would probably use an L-system to generate lines. self closing loops are challenging to express for uh, laypeople
honestly just looks like some modified version of perlin worms
one pass where it mostly moves right, then another pass where it adds offshoots
Can I guarantee that a perlin worm will overall move right?
the biggest part of doing this is the problem solving
if you like math try to express it mathematically
if you like updateloopese
you know, make a character that walks in that path
I am using this method to change the direction of the enemy towards the player in a 2D top-down game. But the animation is flickering do you see any problem in this way of implementation?
Nope not showing the progress. I understand that the channel is for advanced code. forget to write the description. I have edited the post
This is at best #archived-code-general kind of question. @mortal orchid
Don't cross-post.
You'll need to provide more info, like whether you're getting the logs or not. Make a development build if needed. Check the Player logs if needed.
Ask in #archived-networking if the error comes from any networking related method.
sorry, It is a development build which is how I know that the error is nullreference object
You'll need to post the full error message, which contains the stack trace
OK
NullReferenceException: Object reference not set to an instance of an object
at Launcher.OnJoinedRoom () [0x0000c] in C:\Users\fdmcp\Valorant 2d\Assets\Launcher.cs:22
Error onLauncher.cs, line 22.
playerPrefab was null
but how
That's what you're trying to solve
Maybe the PlayerContainer object isn't there at the time the method runs
Try referencing the script in any other ways than drag-drop.
how would I do that if its a prefab
Like any other object. If you're able to drag-drop, you can do all the other ways. This includes using GetComponent<T>, Find, FindObjectOfType<T>
I'm just so confused why it works in the editor and not in the build
That's why I'm telling you to try other ways of referencing that component
It's a networking issue, and I'm not experienced in networking, so we do the regular C# and Unity ways first
If that leads to nothing, ask in #archived-networking
Ok
Hi I have a script that generates a mesh and assigns that mesh to a property. When I try to Apply the overide mesh to the prefab (I want to save it to the prefab) it says that I can't because the mesh is a scene reference. But the mesh is generated by code and assigned as a property to the object. How can I do this? Do I NEED to do an editor script?
I just launched the build agian and it worked idek what was wrong
Hello my Trigger is not working ```csharp
private void OnTriggerEnter2D(Collider2D collision)
{
trsf.position = new Vector3(5, 5, -1);
if (collision.gameObject.tag == "Player")
{
Audio.Instance.PlaySFX(win);
SceneManager.LoadScene("Winning Screen");
}
}```
If I go to that trigger with my Player but it does nothing
You didn't check isTrigger flag. #๐ปโcode-beginner
I tried that but it just dissapeared
how would I change the skybox material in a custom render feature? I tried RenderSettings.skybox = newMaterial, but that set the skybox for the subsequent pass as well, would just like it in my scriptable render feature.
maybe cache the original skybox material and set it back at the end of your feature's pass?
At what point would I reset it?
I haven't done much with custom render features, so I'm just guessing here. But looking at the docs, it seems like doing it at the end of your Execute method would do it. I'm guessing any time after you execute the command buffer
Well, I'll just keep hacking away at it. To be clear I am trying to render the skybox with a unique material only in my render feature.
CRTs are a bit of a nightmare tbh, double buffered CustomRenderTextures only got WebGL support like 6 months ago. Best of luck ๐ช
how do I define a custom LightMode tag in shadergraph?
What disappeared
This is a #๐ปโcode-beginner question BTW
this might be helpful
I have that one - and yes, it is quite helpful.
What I wish to achieve is a "movement" distance outline similar to that of XCOM. Currently I have a bunch of individual planes to represent each "tile". I imagine the way this would be most easily done:
- Grouping all the tiles within range.
- Filtering out all non-edge tiles.
- Then using the edges of the edge tile's meshes to get a series of points with which to procedurally generate a plane that would represent.
- Applying a transparent material with a border shader.
I'm primarily concerned about the opaqueness of step 3 since I don't have a lot of 3D visual programming skills. I was wondering if anyone was aware of any resources that cover similar procedural mesh generation techniques?
I guess related to this, when constructing a mesh. Aside from minor performance hits, can I just ignore some vertices? One approach that comes to mind is to simply create a bunch of vertices to represent a rectangle that would be the max height/length of the movement area, and then simply render each moveable square with 2 triangles and just ignoring any vertices that are not on a corner of a valid tile.
It has to be stored in an asset in order to be serializable. Prefabs cannot hold mesh assets.
you can create a new asset and add the mesh to it
i think this can be solved with just a shader
command buffer at most
maybe, im not sure, some of those corners on the screenshot look sophisticated
I'd probably be even further behidn with that approach. At least when it comes to proc genning a mesh, I understand the theory behind it, but maybe not the best practices.
This can be done easily with custom renderer feature, https://github.com/Unity-Technologies/UniversalRenderingExamples
see the one with hull method....
oh wait, misread, that's not related to yours I think.. scratch that!
there is anyway to setting this by code?
Not able to get any help on that so thought maybe it is an advanced problem. ๐
When changing the gameobject name via code "go.name = 'something'" I don't see it changing in the Hierarchy when the game run
hey im making a sort of prop hunt game and i was wondering how i could make a script that automatically goes on top of the floor instead of floating in air or in ground? sorry if im unclear
It works. You're probably just looking at the wrong object or something
Or your code isn't running
Not at all, they are used a lot
not at all, if anything using MB for literally everything is a code smell
Agreed.
Interfaces have issues in Unity and Abstract classes are preferred where possible for MB.
But when writing any kind of code you should stop and think if it needs to be a MB at all.
You can do a LOT with [SerializeReference]
If you don't try to mix them and use MB only for views (and don't use SO) then you won't have problem
I work on gameplay on days and work on library at night
Well if you want them to be a SO then use abstract classes with <generics> you can accomplish a lot. ๐ค @regal olive Would that not be good enough for your use case?
I think I don't quite get the issue. I am sorry.
It this just not liking that the inspector does not allow you to reference a SO by an interface? @regal olive
You can write your own editor script. Maybe use Odin for that (I think the functionality is there but not 100% sure)
You can also perform checks for interfaces in "OnValidate". I think you can even create your own generic class and your own mono behavior base that checks all of its fields via reflection and runs their "OnValidate" method maybe. But these are workaourds upon workarounds ๐ค I am just brainstorming atm...
Sure ๐ tho its not [ReferenceField] but [SerializeField] ๐
Yeah. As I said. Unity pushes you towards abstract classes. They work much better in the inspector in general
Sure it does. Again. Push your code into an abstract base class and it will work in the inspector.
Unity prefers very flat class structure for most things. Each component should do 1 thing and 1 thing only. Therefore there should be no need to have interfaces on components.
That does not mean you don't use interfaces in Unity. You do. But for non-MB non-SO scripts. You can use interfaces for [SerializeReference] Lists for example (I love this use case. You can easily create a list of conditions and checks that build up into something like a quest/achievement system)
i would actually argue interfaces go very well with components and doing only 1 thing, since it makes swapping of implementations of that 1 thing very easy
though you can still GetComponent by interface type, which is rather helpful for things like raycasts, and taking a action on the hit object
it's in PlayerSettings
think its because i also do server side stuff and work with Go, but composition and interfaces are my default way to handling most things over more OOP style stuff
really the most annoying part, is not being able to drag in UnityEngine.Object based stuff, on a SerilizedField
otherwise it works decent
though the gopher in wishes i had implicit interface implementation
for non UnityEngine.Object based stuff it works great, or if you call GetComponent yourself
like most of my state machines, are regular C# objects, saved with SerilizeReference
and all by interface type
Do I NEED to do an editor script?
the simplest thing to do is to declare a context menu function using[ContextMenu]on your monobehaviour, then click the triple dots icon in the upper right corner of the component's title in the inspector to run the function you annotated with it
#if UNITY_EDITOR
using UnityEditor;
#endif
class MyScript : MonoBehaviour {
public Mesh myMesh;
[ContextMenu("Generate and Save Mesh")]
public void GenerateAndSaveMesh() {
#if UNITY_EDITOR
var mesh = GenerateMesh();
var asset = AssetDatabase...
myMesh = asset;
...
MarkDirty()...
#endif
}
}
yeah can be worked around, issue is for example the faking it with a abstract class, is you can only extend from 1
so kinda interface like, but it pushes you into larger interfaces instead of lots of small tiny 1 or 2 function ones
That is a very nice functionality I agree. BUT
What allright was writing about were local (I assume) children object references. Which... you can totally go without interfaces for that.
No. Why would it. You instead have more components. You can still have tiny classes with a singular purporse.
I ended up finding an answer online. It seems the issue is that meshes are not serialized as they are assets. I ended up serializing the vertices and triangles and it worked like a charm
interfaces for this are good for cases of the interface defines what something can do, but multiple components implement it so the how can be different and the caller does not have to care exactly which component handled it
when you say serializing the vertices and triangles...
you can definitely save a unity mesh as a .asset asset
that is the editor-native mesh representation
To clarify. We are talking about MBs so more than one base class is present for sure.
I am NOT talking about aggregating multiple interfaces into a single base class. And then just saying "f it" and not implementing some of the interfaces methods in the subclasses. (Who would even do that. Creating 0 side effects methods for everything? or throwing exceptions. Thats terrible architecture)
i think what you found online is wrong
Different class for AWeaponEffect ADebuff AUpgrade etc...
here's the head of one such file
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!43 &4300000
Mesh:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
...
it does indeed have vertex and index buffers in it
when i see interfaces in a unity game i see "junior programmer"
you control 100% of the source code in a typical unity game. if you need functionality X in place Y, you can declare it there.
when you author libraries that will be open source, it also makes less sense to create apis that accept interface arguments
exhibit A: cinemachine
the IVirtualCamera interface is implemented by only two classes, and its purpose is to work around the fact that you cannot new an MonoBehaviour but would like to mock the behavior of one, from the point of view of how it implements blending, in a very specific corner case in their implementation
interfaces make sense when you cannot possibly know all the types ahead of time
in unity, for the most part, you know the types ahead of time
UGUI / EventSystem's use of interfaces is pretty flawed
you look at the Unity API, only EventSystem does interfaces
there's IJob
is there an attribute to prevent auto API update?
which is really "a function signature"
there is but i don't remember what it is ๐ฆ
for example EventSystem makes you do something like "you must implement IBeginDragHandler in order to use IDragHandler"
UIElements, as far as i can tell, is just "the DOM"
which of course makes more sense
what should Unity have done instead? i suppose author a single UIBehaviour class (which exists by the way) with the one property public EventContext eventContext
eventContext.onPointerClicked += ...
eventContext.Cancel()
etc. etc.
EventContext.From(this).onPointerClicked += ...
no interfaces.
i can see how if you're a junior programmer and you like to plan out your thing using interfaces - i don't know why you wouldn't just make an empty class instead, but there is something in the education of this stuff that doesn't illuminate that strategy
i've seen it with my undergraduates
and it's fine. i tell them in their editor to just click "inline interface" and it's all better
I didn't read everything but are you saying we should never use interfaces in Unity ?
i think almost all of them can be eliminated, provided you aren't using closed source external libraries whose APIs require them
i am not opposed to "thinking by using interfaces"
which is why people actually use them
but you should try to remove them once you are "done thinking"
if that makes sense
you can also think using "a class"
you don't have to use an interface at all.
there's just something in the education that sticks to intefaces
if you can't possibly anticipate a type ahead of time
then you have to use an interface
that is what they are actually for
for making libraries that have to interact with stuff whose type you cannot possibly know ahead of time
for many APIs, generics obsoleted interfaces
If I have a player that can take damage and be attacked, I find convenient to create a IDamageable and a IAttackable interface, instead of deriveing from a DamageableAndAttackable base class
Though I agree as โYou donโt need more abstraction than you needโ
Interface is a protocol, you wonโt have same modularity and abstraction if you use class instead.
yes, but you only have 1 player
I think it's even better to just make Damageable a separate component and forget about the interface. Then communicate with other scripts via events or direct references.
pretty much everything in your game will be damageable and attackable.
or it won't
or, consider that such games, where you have these more complex rules, you have to do something that a junior developer is going to flop around and not do really well anyway
i don't think Jai has interfaces. if you really want to explore more about, what makes sense when programming games, i think jonathan blow has spent more time thinking about this than maybe anyone
Does anyone know if there's a first derivative of Mathf.PerlinNoise()?
what is your objective?
are you trying to ask for "a texture that shows the magnitude of the slope of the point at x,y of the perlin noise texture?"
I want to use the gradient of the perlin noise at a specific block like these:
it really depends how their perlin noise is implemented to get a perfect answer
take two adjacent samples and calculate the difference between them / the distance between them
that gives you the slope between the samples
Not a texture, I'm going to try adding a second layer of perlin noise on top which has a greater range based on the gradient
you can do this for both/all of the neighboring samples for a given sample and average them to get the slope "at" that sample point
well i might as well give you the "betetr" thing
what i wrote isn't really true
because you said derivative but you really mean something else
you're showing me a line, and Mathf.PerlinNoise is f(x,y)
Ah ye I've fixed the y value
which is more or less prateorblue's answer
I see, that makes sense
it really depends how right of an answer you need. it doesn't sound like you do
weren't you trying to make a cave path?
you're trying to find "turns" in your path?
i would do so iteratively
Yea I'll show you what I'm hoping for
in my experience it's easiest when you try to do this "only looking forward"
The darker line is perlin noise, the lighter line is a second layer of noise added where the range is greater for higher gradients:
Adds the back and forth aspect from my diagram yesterday^
so you can do
f(t) = g(t)
f(t) = g(t) + f(t-1)
f(t) = g(t) + f(t-1) + f(t-2) + ... + f(0)
you can either do something with the value you have immediately, only look at the previous value, or consider all previous values
hmm it looks like you're really asking how to layer noise
float NoiseWithFrequency(float x, float freq=1f) => Mathf.PerlinNoise(x * freq, 0f);
@ionic quartz does that make sense?
Would that be for the 2nd perlin noise?
hmm
i'm doing what you did
which is setting y to zero
do you see how "frequency" just means taking the argument to the noise function and multiplying it with frequency?
you might want to add an offset so that it doesn't look like the line squished
hmm
no
it would just be
2f.
That's just 1 layer of noise right?
do you see what's going on here?
I'm not sure I see what your seeing xd
Sin?
okay
would you say perlin noise looks periodic?
so if you want something periodic with a known derivative, that's one of your options
another derivative of cos(x) is cos(x+2pi)
(-1)^x is also periodic
and weirdly neglected
Why would I need something periodic?
here is some insight - https://farazzshaikh.medium.com/generating-noise-using-fourier-transforms-b6ccf64afb08
perlin noise is fast that's why people like it
well you don't
"rescaled and added onto itself"
that's what i was trying to illustrate for you
these are f(t) = g(t) methods, "no looking into the past" methods
maybe for cave it'll be easier for you to do, "i look into the past" methods
you can transform many look into the past methods into no looking into the past methods
don't think so, but I'm sure someone will have written an implementation in C# somewhere
^"biased random walk"
@ionic quartz to me this looks a lot like a cave
but here's the thing, we can hand you this stuff
or you have to like, slog through a lot of math and learn the names for these things
that's 90% of the problem
so if i had to make a cave, i would probably do "10,000 biased random walks across a grid. i keep all grid points that were visited N ~ 1,000 times or more, and all closed loops that were visited M ~ 100 times or more"
or maybe the amount of grid point i keep is based on some other factor
it's an art
I'm understanding bits of what you are saying now but not lots
yeah
i mean you'll google biased random walk
and it kind of look slike a cave
that's what matters ๐
i think there is stuff like "function zoo"
where you can just look at a graph of tons of stuff
and fish around for something that looks like what you want
Oh that's cool
i don't know what it'll be called though
Perhaps this? Except there arent lots of visuals, https://dlmf.nist.gov
maybe you should make one ๐
I love the motivation for more resources but I'm not sure I have the passion for something like that xd
Prehaps by the time my uni dissertation comes around I'll feel differently about functions lol
Hey, I ended up with everything working out really well but I have one more question about vert manipulation. Even after updating the bounds and reassigning the shared mesh, the scale of the mesh doesn't update. I tried using the bounds extents size but that was inaccurate. Is there a way to update the scale after manipulating the verts.
?
not 100% sure
I tied some subtle haptics to the dragging of the verts. Its trigged by changes to the scale of the mesh. I guess I could cycle through the verts being dragged and tie it to the position changes. But if someone has a shaky hand it would constantly call it
sorry just type thinking.
i think you're going to do great just keep cranking
this is part of the procgen journey
Hey guys, i have a problem with Bossfight, if someone can help us i would invite you in our discord server (we are 4 people) and can share the screen. would be nice ty ๐
Is there a good way to convert a http request for a .wav into an audio source?
Thank you ๐ I should have just googled it...
Is there any easy way to establish whether a collider is entirely inside of another collider? ie no intersection with the outer colliders perimeter? Or something I have to write myself?
Could just check for positional values when they collide and clamp a range for what you'd would consider full inside of it.
Interesting. It gets weird though with square colliders (box 2d) near the corners I think...