#archived-code-advanced
1 messages · Page 92 of 1
he went over the height texturing, but not biomes
I will try my best at something like that
I can make the textures change, I'm just now sure how to spawn certain Gameobjects in specific biomes with the texture system
I've not touched the biome stuff before, but I'd imagine you can pretty much use the texture for everything. If it defines the coordinates for heights and biomes, then you know the locations of these subsections and can just refer to it beyond generation of the terrain.
I'm writing a bit of a cockneyed validation report for a client. They have this database with a bunch of string keys for things like localization. I have some code that can check the value of a string (ie, attempt to identify if it's a "key" based string, and validate it against a list of keys), but I'm needing a way to iterate the project and scene hierarchies and find every string and its value across "all" the game objects and components.
Should I just use reflection and FieldInfo recursively, or is there a potentially better approach that isn't going to make running this report kill my machine?
An idea could be to look for string the moment they are drawn which will most likely be from a single component: TextMeshPro or Text.
These aren't for drawn/rendered fields, they're for database lookup fields..
hard to explain exactly but.. for example, maybe some prefab has a string value on it called "node type" and the value is "A_SomeAnimal" - that particular component would look up the animal with the key "A_SomeAnimal" and then pull out whatever it needs .. images.. integers, strings, etc
The same applies I guess, look when the call is being done and flag fraudulent call one by one.
The problem is the content team often typos these strings so they wanted some way to validate it
There's several hundred component types that have these string based keys in there
(it's awful)
And your objective is to find all of those keys ?
yeah. I have the keys data structure built, and I can cross reference data directly from the database pretty well.. but I basically just need a (huge) list of game objects and strings to poke a stick at
this is the current stab at it:
(not yet done)
You could try to directly read from the files, maybe that would be more efficient
hm.. that covers prefabs but.. they are also occasionally populating these strings by hacking together strings in the code
(so I couldn't catch any errors there)
Yeah, then I believe the best is to catch the string the moment it is used.
Don't know if I can find an example easily but .. it's in there.. stuff like
string filename = $"/Resources/Animals/{animal.Id}_{animal.MoodString}.png";
or localization strings.. keys look like this LOC_CONTENT_STRING_ENGLISH_ANIMAL_HAPPY_GREETING and they'll cobble that key together the same way: string localizationId = $"LOC_CONTENT_STRING_{currentLanguage}_{MoodString}_GREETING";
super hard to validate all that crap 😐
Personally, I would have refactor the codes such as that every string that is being used pass through a reduce set of endpoint. By example, all calls to Resources.Load would pass through a static function. Then from there I would collect the data.
But, yeah there is no magic solution
Either way, it is going to painful.
for sure, but I'm just a consultant here and the codebase is .. sorta what it is, several hundred services, several thousand lines of code, etc
I was thinking that I could make this enumerator to look at every active/live gameobject and component and string in the scene, and someone in QA could hit the button every so often to see if it sniffed any errors
but uhm.. I can't promise 100% "coverage" there and .. it's not really a very good solution.. I just couldn't really think of anything better
I see. I really believe you would be better off with what I suggest, but I understand why it is kinda hard to pull off.
Sorry to not be more useful.
all good, just lookin for ideas
It's even more complex because a lot of the data is in addressables so... it can't even really be validated until runtime
🤷
foreach gameobject, foreach string; foreach component, foreach string in that component.. god this is awful code. 😢
Just scan all yaml files and source files?
what yaml files..? the unity .meta files?
Wait this cant solve anything since you dont know is the field is really string key or other stuff, nvm
I already have that bit taken care of
I just want a bit ass list of string values to validate.. they (thankfully?) have a pretty rigid string structure for these keys
I create this dictionary by iterating their entire database and mapping keys to rows in the database.. then once I have a string value I just suss out what kind of key it is, and look it up in the right place. I can do this all already with static data that exists in the database, I just .. am trying to think of a way to get at the unity string fields for all of their various components
Unity uses yaml stores the screen tree and all serialised values
And you can use cpp for faster string processing
where are these files? and when are they created? at runtime?
I'm not gonna write something in cpp 😛
.unity ( the scene file actually) and i am not sure if .prefab is, you can open it in vscode in plain text to have a look first
prefab is also yaml
my recursive thingy seemed to work reasonably well.. code review me: https://hastebin.com/share/inicijaqez.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I'll look into the YAML thing but I'm not sure if it's the right approach for this problem
With YAML, you could make your code ignore the type of serialize object you are treating.
Instead of opening scene by example, you could use it directly
However, I believe it might be kinda hard as well to get correctly what you are looking for.
yeah I'm ... more interested in the runtime objects? I don't know about the yaml stuff but I can't imagine unity is writing out YAML files for instantiated objects at runtime
Those object come from something serialized, most of the time.
That why you need to scan the .prefab
Btw if you have external text source eg csv, verify them as well
Or consider simferoce idea, limit the place accessing the collections based on string key then throws if the key doesn’t exists and you can read the stack track, but this is passive measure
Is there anyone on here who is experienced with SQL databases that can take a look over my DB structure and give me feedback. It's pretty small. I can explain the structure easily and I have a diagram.
First database
sure, DM me
is there any kind of existing event I can subscribe to to be notified when a gameobject's transform has changed? I can't imagine checking hasChanged every frame on each of them would scale
at run time or in Editor?
at runtime
there's nothing build in but it's fairly trivial to make your own
I'm not sure how I can do that without having update running either on every gameobject that I need to check, or having a single update but looping over all of them every time
also doing it that way means if the transform changes over multiple frames it won't be consistent whether or not the callback will run every frame, since the update function modifying the transform can run before the check just as well as after
the simple option. write your own script which manipulates the transform using exposed properties. This could handle the calling of delegates. Then ensure all your other code works via this script
that won't catch updates caused by stock components like the physics ones, or ones from plugin where I can't modify the code to replace every transform access
true, for physics you will need a FixedUpdate
I just think this approach might be not the right from the getgo
not really sure but maybe you should run the code you're running on the change of the transform, on the object when it moves ?
and not observe the transform inside another script
Thats just what i immediatly thought of, might be wrong ?
Why do you need this callback?
it's a compute shader renderer that needs to know when a change to its "scene" has been made including a gameobject moving
I need to consistently be notified of all transform changes on the frame they happen, before rendering, and as explained there are things in unity that can update an actor's transform without you having any way to make it call custom functions instead
So you have some sort of persistent representation of the scene and you want to update it incrementally when changes happen in the scene?
yeah
the gameobjects have a component that hold signed distance field data, the compute shader receives all of them and renders them to a 3D volume, I'm trying to make it so it only re renders when there's been a change
So do you just need to know if there has been any change, in which case you re-render the whole scene SDF, or is it important you know which transform changed?
any change right now, but in the future depending on how I further optimize rendering I might need more specific updates
Well, one option is to use a IJobParallelForTransform. Since you have a component on each GameObject with the SDF data, it would be trivial to add their transforms to a TransformAccessArray in OnEnable and remove them in OnDisable.
One issue with that, though, is that there's no hasChanged flag exposed, so you would have to compare the transforms to their previous state, which you'll have to keep track of separately. Whether this scales better than checking hasChanged on the main thread, I'm not sure. IJobParallelForTransform is only able to split root game object hierarchies into separate worker threads. So if all your game objects are under the same root game object, only one thread will be used.
But since this job is also keeping track of previous matrices, you now have a free NativeArray with all the up-to-date matrices which can be passed to your compute shader.
If you do it in a single Update inside a manager it would scale very well
If that does not work for you you can use the job system and have two arrays of curent and prev pos and fill a third array with the change
is it good to use have the eventsystem inside an Dondestroy gameobject? and use always the same for every scene instead of use a different one for every scene?
that's exactly what I do, yes
There's no general answer. It depends on your overall project structure and how you like to manage things.
if there is no difference I would like to move it inside my global manager
https://github.com/jeffcampbellmakesgames/unity-jtween/blob/master/Unity/Assets/JCMG/JTween/Collections/FastList.cs. How is this implementation any faster than a regular List ? Am I missing something here ?
It has "fast" in the name, so it must be faster!
It's not, in fact it's rubbish
Im just curious why would the author make this. The rest of the code in the repo seems solid at least at a glance
Only thing I can see that might be faster is the fact that the internal array is public, so you can access the data more directly that way.
anyone familiar with .gf files?
it directly uses the backing array T[] buffer to store things, whereas List has to take couple additional steps for safety, and they reduced the bounds checks too
just from a quick look of it, not 100% sure
What extra steps does list take exactly ?
yes, in theory one update is faster than many but... When you have just one update you are going to have one big arsed complicated update and that will mean lots of unnecessary code being executed and a lot of page switching so, in real terms, it will probably even out
plus one big update will be a nightmare to debug and maintain, also worth taking into account
Well if you mean one single update for the entire game then yes I agree. When performance is needed I do one update per Mono type, akin to a system in ECS
I can testify that it is indeed more performant
wdym by 'Mono type'?
Well for example you have a Projectile: Mono and a Enemy:Mono , obviously you wont mix their updates
so one update per class?
Not always but yes
hey devs!! I have some queries regarding networking in unity... I have some knowledge of how things work in Unreal but dont have much idea about Unity and would love some help...
the SpawnBall() method is called when the Spawn Button is clicked in the UI... I want to know for instance I want to bind some events to the delegates inside the ball script from the controller class... after spawning the ball in the server, I dont have a valid reference to the ball... why is that and how can I solve it
I have this:
```
private BallScript ball;
public void SpawnBalls()
{
Debug.Log("Spawn Balls");
if(IsLocalPlayer && IsServer) BallSpawner();
else if(IsLocalPlayer && IsClient) ServerRPCSpawnBall();
}
private void BallSpawner()
{
// Only for 1 Ball
Vector3 spawnPoint = GetRandomPointInBox();
//BallScript ball = Instantiate(ballList.BallList[0], spawnPoint, Quaternion.identity);
ball = Instantiate(ballList.BallList[0], spawnPoint, Quaternion.identity);
OnSimulationParametersUpdate += ball.UpdateBallSimulationParameter;
OnBallMoveSignature += ball.UpdateBallLocation;
ball.GetComponent<NetworkObject>().Spawn();
}
[ServerRpc]
void ServerRPCSpawnBall()
{
Debug.Log("SpawnBallsServerRPC");
NetworkLog.LogInfoServer($"Server: {ball.gameObject.name}");
}
I am procedurally generating a simple 3d mesh using perlin noise. I am able to generate a mesh just fine, but I want the edges to all be at the y=0 level, as I want it to seamlessly connect to a flat floor I have next to this generated terrain. I'm able to do that by manually setting border vertice y coordinates to zero, but then obviously it looks very awkward as all of the hills made by the perlin noise that are near the edge are abruptly cut off. Does anyone have any idea on how to make the cutoff gradual or to reduce the amount of noise by the edges?
Multiply it with something that smoothly drops off to 0 near the edge.
I dont aee you calling the BallSpawner method on the server at all
since SIMD and stuff are relatively advance to use correctly, i notice that BURST does not implement NEON for arm platforms but does implement SIMD for x86 platforms
There does seem to be some ARM specific stuff supported https://docs.unity3d.com/Packages/com.unity.burst@1.8/manual/csharp-burst-intrinsics-processors.html
When i look in the package all arm neon methods are NotImplementedException
Might be WIP. #1062393052863414313 probably knows more.
Hmm ok
Because they're not implemented in C#, they get replaced with the actual instructions in Burst.
how ?
When the Burst compiler converts your code to assembly, it sees you are trying to call this method and knows to replace that with the instruction it represents.
hmm alright, how can i attach the burst compiler to the roslyn package so i can compile scripts with burst intrinsics at runtime
I've already told you before, the Burst compiler is not included in builds. Everything is precompiled when you make the build.
yes but the packages are exposed right ?
or is the burst compiler itself embedded in the unity editor itself and the packages simply interface with the unity editor internal burst compiler
Then you'd be doing something undocumented, unsupported and that I've never seen done before. No one here can help you with that
You cannot distribute the burst compiler
It ships under the Unity companion license, and the package distribution license
rip
Maybe I'm wrong in interpreting that licence though... I'm sure others have clarified it on the forums
But based on our previous conversations, it doesn't really make sense. You just want to add modding support and think that running Mono or Lua will be too slow, so you want to optimize it with Burst. But Burst has very strict requirements and not something you can use to optimize any script a user might make
LuaJIT can be very fast. Mono JIT can be very fast, the main bottleneck will be your interface to your game's code, which Burst can't help you with.
Burst really would not help that much with modding
burst would welp with optimizing specific perf critical sections like it does in unity itself
the same strict requirements would still apply
but would i think greatly improve the perf of largely integer/floating-point based functions such as audio processing and similar
But why would the mod code be doing audio processing
for audio based mods
such as an audio generator or effect
or a mod that expands the audio pipeline or something
or whatever else burst can help accelerate
in my case it would largely be UI and audio based plugins
maybe visualiser plugins too
But mainly these
Burst can help with such audio processing right ?
Right ?
Btw is burst just a IL transformation engine? Or is it actually part of the C# compiler unity uses
It's an IL transpiler
alright
IIRC it transforms IL to LLVM IR which is then compiled to assembly
Uhh, not sure on the internals but it's hard to invoke managed code from native by design
I'm trying (at editor time) to find the behaviour in scene that contain a property of specific type
MonoBehaviour[] behaviours = UnityEngine.Object.FindObjectsOfType<MonoBehaviour>();
foreach (MonoBehaviour behaviour in behaviours)
{
Debug.Log($"Found {behaviour.name} {behaviour.GetType()}", behaviour.gameObject);
PropertyInfo[] properties = behaviour.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in properties)
{
Debug.Log($"{propertyInfo.Name}", behaviour.gameObject);
if (propertyInfo.PropertyType == typeof(DictionaryOfLanguageAndString))
{
Debug.Log($"Found LocalizedString in {behaviour.name}", behaviour.gameObject);
}
}
dont know reflection, but i think it wont cast to the "childest" class for every monobehaviour it found
oh nvm, you have gettype
btw you can scroll up to have a look at previous conversation (we had discuss similar issue not about reflection but get "string key")
i think you need to use getfields and property
GetProperties() only returns public properties. You have to pass a BindingFlags to search for private properties.
Why not use an Interface?
because I need the class child of monobehaviour
I already have the classes in the scenes configured and used, i need to find where it is not fully configured
I would slap an interface on the classes in question and just use FindObjectsOfType<IMyInterface>()
mmm that would solve, but... I mean... i don't like to append an interface just for editor user experience, I'll use it as fallback in case of failure with bindingflags
It also has the benefit of guaranteeing the classes actually have the properties in question when they're expected to
Would the interface not be also generally usable in runtime code?
interfaces doesn't specify properties, only methods
they can specify properties
you can put cs int MyProp { get; set; } in an interface for example
yeah, sry, with property i was meaning fields
Then your code is totally wrong
behaviour.GetType().GetProperties();```
this gets properties not fields
oh
oh, it works on public fields!! thanks
i'm looking for both public and private (serializefield)
use the override that takes BindingFlags
foreach (FieldInfo fieldInfo in behaviour.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic))
e.g. BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic to get all instance fields (public or nonpublic)
mine doesn't find even public (that were found with 0 param method)
your filter works!
gj
yo, what does "object refference not set to an instance of an object" mean?
It means that something hasn't been set or doesn't exist. Post your code to #💻┃code-beginner
it means that object ferefence is not set to an instance of an object
i was playing but the fact that i got an actual response gives me hope
it means you have a reference variable that isn't pointing at any actual object, but you're trying to use it
Is it possible to access to the value after I found the FieldInfo of my type?
yes
yes!
MonoBehaviour[] behaviours = UnityEngine.Object.FindObjectsOfType<MonoBehaviour>();
foreach (MonoBehaviour behaviour in behaviours)
{
foreach (FieldInfo fieldInfo in behaviour.GetType()
.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
if (fieldInfo.FieldType == typeof(DictionaryOfLanguageAndString))
{
DictionaryOfLanguageAndString t = (DictionaryOfLanguageAndString)fieldInfo.GetValue(behaviour);
Thank you. As I thought. I want to cry. Had to confirm I wasn't going crazy.
If the Oculus asset is causing problems can I just delete the Oculus folder? I have no code in project that needs it. Or how does one go about fixing:
Assets\Oculus\Platform\Scripts\RosterOptions.cs(14,21): error CS0117: 'CAPI' does not contain a definition for 'ovr_RosterOptions_Create'
TIA
If you're not using Oculus I don't see why you would include it in the project
Hello! I want to make a game with PCG platforms. The 'routes' will be created out of chunks of platforms/blocks(4 types to be exact for now) and they all square. By chunks I mean there will be different widths and lengths to them and they will have a route(doesn't have to be straight for or fully filled with max width of blocks and length.
Anyways, does anyone have an Idea how and where can I find algorithms for these kind of PCG?
What's PCG? Partially Connected Graph?
Is there any reason standard graph algorithms won't work here? I.e. DFS/BFS, Djisktra's Algorithm, A*
Has anyone gotten jobs to properly call native plugin functions?
procedurally generated
Alright - I'd just use standard graph algorithms
I think I saw specific algorithms for PCG that work really good for them, thought someone might know and know where to point me for PCG platforms
I don't see how it matters if it's procedurally generated or not
It's a graph either way
Graph algorithms work really well for all graphs
Yeah, I understand you
I'm just not sure how those algos work(PCG)
Wave function collapse, Cellular Automata, and various form of Noise functions
Looks like your only option here is to actually learn that stuff yourself, procedural level generation stuff isn’t really difficult on the algorithm side, it’s mostly a design problem, that is, how you apply them.
If you don't know how it works, just learn it.
easier said than done brother 🙂
Well, you don't have much of a choice, do you? Either learn it or give up on whatever you have in mind.
I would love, but I have so little time, so I have to improvise 😦
Learning is always a better time investment than improvising and finding out you have to redo stuff because it doesn't work correctly. Did you ever hear the term "technical debt"?
How do I providing access to directories on IOS? I can only access persistent data and root
Pretty sure you just can't, iOS apps are sandboxed and don't get access to the full file system.
Is there a way to access a /var/mobile/Containers/Data/Application on the ipad itself then? (like for the users to share the screenshots, outside of the unity app)
What's the feature you trying to achieve?
Pretty much that my playtester can export the current .config file I save in persistent data and drop it via discord
I know they could download the container on xcode and stuff but not everyone has a macbook
Yes, apps only get accessed to a sandboxed file system, Unity's persistent data path is within the sandbox.
Are you trying to export some files?
If that's the case, I can recommend Unity Native File Picker.
Need some help with Jobs and Burst
Im getting this error
InvalidOperationException: The UNKNOWN_OBJECT_TYPE has been declared as [ReadOnly] in the job, but you are writing to it.
Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle.CheckWriteAndThrowNoEarlyOut (Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle handle) (at <5879d8d225474494bcffdfe64965038e>:0)
UnityEngine.Mesh+MeshData.SetIndexBufferParams (System.Int32 indexCount, UnityEngine.Rendering.IndexFormat format) (at <5879d8d225474494bcffdfe64965038e>:0)
sapra.ProceduralGeneration.MeshGeneration.DecimateJob.Execute () (at Assets/sapra.ProceduralGeneration/Runtime/_MeshGeneration/DecimatedMesh/DecimateJob.cs:20)
Unity.Jobs.IJobExtensions+JobStruct`1[T].Execute (T& data, System.IntPtr additionalPtr, System.IntPtr bufferRangePatchData, Unity.Jobs.LowLevel.Unsafe.JobRanges& ranges, System.Int32 jobIndex) (at <5879d8d225474494bcffdfe64965038e>:0)
You see that it appears when the actually burst is not enabled, this is a native problem
Looking at the code
namespace sapra.ProceduralGeneration.MeshGeneration
{
[BurstCompile]
internal struct DecimateJob : IJob {
public Mesh.MeshData meshData;
public NativeArray<Vertex> vertices;
public NativeArray<int3> triangles;
Bounds bounds;
public void Execute() {
/*---> line 20*/ meshData.SetIndexBufferParams(triangles.Length * 3, IndexFormat.UInt32);
....
}
But im not setting readonly anywhere, i dont understand wheres the problem
Not too familiar, but possibly because you have a readonly mesh data?
https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Mesh.MeshData.html
Use a MeshData struct to access, process and create Meshes in the C# Job System. There are two types of MeshData struct: read-only MeshData structs that allow read-only access to Mesh data from the C# Job System, and writeable MeshData structs that allow you to create Meshes from the C# Job System.
it's created with Mesh.AllocateWritableMeshData(count)
yes. thanks will try. Do all teammember need an dev account?
Dev account for?
You just need it to build your app
Having only one account and share it with all your devs so everyone can build on their own, having only one account and a build machine that uses it for building, or every dev having their own dev account, whatever works.
ah okay, thought the native exporter needs something special
don't crosspost. and maybe try providing some actual details in the channel you first asked in. #854851968446365696
again, read #854851968446365696
then take your question back to #archived-code-general
okay
How do I set ads not to be personalized in unity ads? Can it be for each user separately?
Is there any way to check if an oject is readonly or not in jobs/burst?
So I have some mesh data that becomes readonly, what could be the reason for that?
Is the mesh marked as read/write, if it's from an imported model?
Im allocating it with Mesh.AllocateWritableMeshData(count), and for some reason its giving me a readonly error even when its explicitly set with the WriteOnly attribute
Even without Jobs, it throws that error, but im not sure what Im doing to trigger it
If there was a way for me to check read access, I could pinpoint where it switches, but I cannot find a way to do that checlk
InvalidOperationException: The UNKNOWN_OBJECT_TYPE has been declared as [ReadOnly] in the job, but you are writing to it.
Disablign the safety checks everything works perfectly
for now I will just add this [BurstCompile(DisableSafetyChecks = true)]
but this is really weird
OMG, another C++ coder in the making
Show the code?
here
where do you define your meshData array?
on another script, before I call the jobs, with the AllocateWritableMeshData
Here's the full script of that
!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.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i dont know why it says java
but you are probably better with this one
I dont see how this
MeshGenerationData data = new MeshGenerationData(){
meshInstances = new GenerationInstance[count],
meshDataArray = Mesh.AllocateWritableMeshData(count)
};
is ever getting into this
public GenerationInstance DecimatedMesh(TexturePool pool, MeshSettings settings, out JobHandle handle)
It's not, the mesh data is stored separately, and then passed back in for DecimateJob
It's stored into the MeshGenerationData and not used until passe back to ProcessMesh
Where the Decimate Job is scheudled (and uses the mesh data) and gives the error
The problem is that, yoi see that switch? That where i decide the type of mesh to be generated
If all the meshes are of type Normal (using the StaticMesh) or all of type Decimated (using DecimateMesh) no problem, no error is thrown
However if i mix, some decimate, some static, that's where the problem happens
Away from the script shared, all of the methods and jobs and wathever is exactly the same, there's no difference between static and decimate, only here, in the process and in the switch
That's why i find it so weird, the decision to do x or Y is the same and only used on the script shared.
Anyone familiar with perlin noise terrain generation
just have a couple questions regarding how to set transition tiles.
if you ask your questions maybe somebody can answer them
I am working on terrain system with different biomes, each biome is defined by a black and white texture. How could I generate a 3d mesh that is the shape of the texture at runtime? https://imgur.com/a/gVVPEdS
What exactly does the texture define? Separation between biomes? Does the color correspond to one biome?
it is used in a shader to define the region
there is one per biome
that is the map with the biome maps
Okay, and how should it affect the mesh generation?
I assume we're talking about the terrain mesh..?
No, I want it as a mesh i can use as a volume for gameplay and visuals, I also plan to use it for biome specific object spawning definition
What do you mean by "I want it as a mesh"? How exactly do you want to transform it into a mesh?
Should it just be a plane mesh in the shape of the white color in the texture? Is that what you mean?
It should be the exact shape as the white area, it should then have height to it making what is essentially a 3d version of the biome map
Where does the height data come from then?
For generating the plane mesh, you should use a simple plane mesh generation algorithm, but sample the texture during generation and avoid generating vertices/triangles when the sampled pixel is not white.
if I use #ifdef unity_editor in a dll and use it in a Unity project, will it get turned off in a build?
No
a dll is a compiled code. All the defines are already evaluated at that point.
In such cases, should I be making a different dll for build and non build versions?
I'm making a logging library. AFAIK DLLs are the way to remove the debug.log from the callstack. I'm using #ifdefs to remove debug.logs in build. I can't remove it.
I guess I could move the ifdefs outside of the DLL. But that's kinda ugly.
Debug logs shouldn't really do anything in a production/shipping build iirc
There's no need to remove them manually
True. But for cleaner logs I modify the log messages a bit. Which means allocating new strings that would get created even if the log does nothing. I'd like to put them in an ifdef
Then you'd probably need 2 dlls
If I want logs in development build(#ifdef debug) but not in normal builds, I'd need two dlls and the one that should be picked depends on an #ifdef. Is it possible to do that?
nvm I found dll DefineConstraints
Look for texture -> mesh algorithms. One I can think of is 'marching squares', but there might be better options.
Or if you manage to generate a polygon from the edges, you can triangulate it with 'ear clipping' algorithm for example
Is there a code alternative to Unity Animation Events?
I have an animation where I have to do damage at a specific keyframe, I am using animation events to call a function and it works, but I hate that I can't follow the flow of execution in the scripts. It happened other times that my animator replaced the animation and I forgot to add the event again, debugging was painful
Not a direct alternative but StateMachineBehaviours let you add logic to your animation states
You can use the animation time instead and just check in code. Alternately something like animancer which let's your animations be code driven instead of the other way around
Hello, I have a simple SO that stores a list of transforms. All the objects who need to be added to the list, do so on Start functions, and are only removed in specific situations. Meaning if I start the game and stop it, they are never removed from the list on the SO! Is there a way to ensure this list is empty when the game starts?
`[CreateAssetMenu(fileName = "TransformList_", menuName = "SO/TransformList")]
public class TransformListScriptableObject : ScriptableObject
{
[SerializeField] private List<Transform> list = new List<Transform>();
public void AddTransform(Transform transformToAdd)
{
if (!list.Contains(transformToAdd))
{
list.Add(transformToAdd);
}
}
public void RemoveTransform(Transform transformToRemove)
{
list.Remove(transformToRemove);
}
public List<Transform> GetList()
{
return list;
}
}`
Just saying , scriptable objects are not editable runtime, any changes you make to them in the build will be reverted everytime you start the game
Not sure if I understand what you mean...
Before I press Play, the list is empty, when I press Play the transform I want is added, but when I press stop it remains on the list. I just wanted to make sure that when the game starts the list was always empty
Ok let me explain
Say you have list empty before doing anything, and when you play add objects via script, or do any changes to that scriptable object
While it may look like the changes were permanent, and you may look at scriptable object and still find it being changed after you exit the game, they are not
It's a bug in editor, to see what I mean leave the list empty, play the game, stop the game with it having changed via script
Restart the editor and you will see the list being empty
This is not an issue in the build tho, it will always be empty everytime you play the game in the build
Only permanent change you can do to a scriptable object is doing it manually in editor
TLDR editor is buggy, any change made during play mode doesn't persist actually
I'm still confused because if I press play, the Transform is added to the list, then I stop playing the Transform is still on the list, I delete it from the scene, the list now only has one element (none transform)
Changes on the editor are happening (though I might have to stop selecting the SO and reselect it for it to update properly)
My issue isn't on the editor, is the fact that the list remains with the transforms when the game's not running, which might mean when I press play those transforms might no longer be there (like in this case where I deleted one of them)
Do me a favor, close the editor, and re open the project. You will see list is empty again. It's a bug
I did it, the list remains the same as I left it (with a single none transform)
Huh weird, did you manually put a transform in there? Cuz I had this same exact issue but I later learned it's a bug.
Anyway this will not be an issue when you build the game
Just in case try clearing the list manually and repeat the experiment?
You could clear the list manually in Awake from some script. Or dont modify the SO asset, make an instance of it instead (Instantiate)
Clearing on Awake might the best solution, I'll try that!
This is how SOs are supposed to work and have always worked for me
Have your SOs reset between scenes?
It depends. For my use cases, I always added references in SO in OnEnable and removed them in OnDisable. This kept the SO clean.
But remember, when you change scene, if the SO are not referenced in the scene, they may be garbage collected
No, they haven't reset between scenes but they have reset between sessions
Just not in editor
Welcome to the most annoying thing about ScriptableObjects. They will not persist changes in a build, but they will in the editor.
Tried to explain that in best way I could 
Also even in editor they don't persist if you reopen the project
the work around is just create an instance if you're going to write to it
I have a question regarding the ECS/DOTS setup. Whenever I've seen examples of Baking it only is about 1 gameobject being turned into an entity and the components that come with it in one sample scene. But in a real world example, I can't seem to really find what the best practice is. Is the best practice to have multiple Sub Scenes in different parent scenes, one for each Gameobject you need to Bake, or is the idea that you have many sub scenes within the same parent scene?
It's not clear from the documentation I've looked through so far.
#1062393052863414313 is the best place to discuss this I think
Alright
Hi I have several questions related to the code for "Digital Services Act Notifications".
When I want to display a notification, I write: notifications.Message where notifications is List<Notification> notifications = null; notifications = await AuthenticationService.Instance.GetNotificationsAsync();?
And should I implement a system that calls: OnNotificationRead(Notification notification)?
And I receive this error: error CS0246: The type or namespace name 'Notification' could not be found (are you missing a using directive or an assembly reference?) la void OnNotificationRead(Notification notification)
Somebody?
hi im looking on how to code does anybody have good youtube tutorials i clud use
Does anyone know how could, instead of passing "i" to this function. Invert it so that I get the i that fullfils greater and smaller to be true?
private bool InsideChunk(int i, Vector3 original){
float correctMeshScale = Mathf.Pow(2, i-1)*GenericSettings.MeshScale;
float correctMeshScale2 = correctMeshScale*2;
Vector3 position = Vector3Int.RoundToInt(Player.position/correctMeshScale);
position *= correctMeshScale;
Vector3 position2 = Vector3Int.RoundToInt(Player.position/correctMeshScale2);
position2 *= correctMeshScale2;
bool greater = Mathf.Max(Mathf.Abs(original.x-position.x), Mathf.Abs(original.z-position.z)) > correctMeshScale;
bool smaller = Mathf.Max(Mathf.Abs(original.x-position2.x), Mathf.Abs(original.z-position2.z)) < correctMeshScale2;
return greater && smaller;
}
i dont know how to transform this method
I don't understand the meaning of the question you posted above.
Basically I have this method, that returns a bool with the input being an int i and a vector3 original. I want to create a new one where it returns the integer i, with an input of Vector3 original that fullfills greater && smaller to be true
Instead of phrasing it in terms of this existing function, maybe explain what you want the function to actually do
Let me try, but I think it's gonna be harder to understand than just simplifying this function
The meaning/purpose of this function is unclear
So it's unclear what it would mean to simplify it
Okay, i is the level of a quad tree lod system. Currently it have a for loop that I go through each level of the quad tree, pass it into this function and it tells me if the position is inside or not in that quad tree lod level.
I want to reverse it so that instead of going through each level, i can get directly, from a given position, the lod level
The Quad Tree is generated around the Player.position so i need to get the level of detail of that new position in relation to a quad tree system generated in relation of the player position
I can attach some images if it's not clear yet
i think i understand what you are trying to get
thinkg is there any way not to use loop
So while loop on I++ until (greater && smaller)
Because i would sometimes call this many times, so i prefer to mathematically get the right value instead of doing a for loop. Also I know for a fact that greater && smaller is only true once in the for loop
so run it in a for loop a few times and see if you can spot a relationship between originalPosition and the returned i
that function is the relationship
no it's not
yeah, it is
1d case: given meshscale S and the interval should looks like:
1S 2S 4S 8S 16S....
then after round and multiplication for p1 and p2 it can be mapped to 2^i * S (the i is what you want) and 2^(i+1) *S
that's what my original attempt was. but that's not true always for a quad tree that is already generated from another point
Here for example, if the player is in the middle, that relationship is true
However, if it's on a side, that is no longer true
Can you do a binary search instead of going through each level?
it should be possible get the level from a single distance and scale by
2 ^ i *scale <=distance and 2 ^ (i+1) *scale >= distance
Could you explain that?
but this is quad tree and everything is AABB thing gets complicated
the function i sent does that, kind of, generate the correct bounding box of each level containing the quad trees and then check if the point is inside or not. If it is bingo, if it's not check the next one
just a simple binary search. Instead of calling the function with i values in order like 1 2 3 4 5 6 7 8 9 10, you start in the middle of your remaining search area
It would require the function to return whether you're too big or too small
In computer science, binary search, also known as half-interval search, logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the middle element of the array. If they are not equal, the half in which the target cannot lie is eliminated...
ah, i guess that would reduce the amount of checks, but I wanted to completely remove it
but let's say you're searching for 7. Instead of having to search 1 2 3 4 5 6 7, youi would end up searching 5, 8, 7
much fewer checks
O(log(n)) instead of O(n)
quadtree is pre built and you dont know how the leaf AABB are placed?
I build the quad tree in a recursive manner. Check if inside, if it is subdivide, otherwise don't
but your quadtree is generated based on player position, if the player moves then rebuild?
I mean there may be an algebraic solution here but I'm too lazy to think about the math
if the player moves, check, if inside subdivide otherwise don't. If it wasn't subdivided before generate what you had to generate, otherwise just keep it as is. Since im going from top to bottom is fairly quick
it seems it is doing overlap circle and limits the depth of each recursive call (so different size of AABB can be append to the four child of each subtree) for each circle
btw reverse the function by ceil log(the max)/(log2 + log scale)?
or just storing all the points in quadtree and doing overlap circle query, for all points overlapped change their lod
I don't understand this sentence. (it's overlap square, but for visualization i made them look like circles)
and neither this one. how could I do an overlap circle query, or better, what would be the best way to store the points of the quad tree taking into account their size differences?
Does anyone know how to add the Unity.DemoTeam.DigitalHuman assembly definition?
How to add it to what?
I am trying to add it to a script so I can reference a script within the Demoteam.digitalHuman. Unfortunely I can't seem to add "Using Unity.DemoTeam.DigitalHuman" to my scripts.
Did you install or import the asset or whatever into your project?
I don't know much about those things but iirc they're standalone projects
I install the digitalhuman package from download a zip file and installing through the package manager.
It's just weird I can access the Unity.DemoTeam.Hair reference definition but not the Unity.DemoTeam.DigitalHuman.
I found a work around so no big deal.
is it safe to reinterpret a NativeArray<Vector2> as a NativeArray<float2>?
i have done this in unsafelist, btw try it and see
public Vector2 a=new Vector2(1,2);
public float2* b=(float2*)&a;
a->x=????
log a
Yes
yippee
Is it possible to prevent preloaders and code injectors such as unity doorstop and bepinex?
Prob not the right channel, but idk which is
Why would you want to do that ?
No
Okay
hi how are you, perhaps this video that explains the baking class can help you https://www.youtube.com/watch?v=nXcLOnRGG0w
Discover the brand new baking workflow of #Unity #dots and #ecs 1.0 released just a few days ago.
We will learn how to author our entities and how the waking workflow works. Why a baker is not the same thing as a baking system. And we will see how it differs from the conversion workflow used until ECS 0.51.
SOURCE CODE & FOLLOW ALONG CONTENT
-...
let me know if it helped
It didn't help can someone else please help me?
is there a good way to set the vertices in a polygon collider 2d from a nativeArray?
Since the API only accepts arrays and Lists, you'll need to work around it. It's possible to create a NativeArray from an existing managed array. This package handles that for you:
https://github.com/stella3d/SharedArray
Interesting! it seems though that it might be easier to just copy elements one by one. Actually, is it possible to blit an entire nativeArray back to managed memory?
I'm trying to calculate a collider polygon in a burst job and then use another (non-burst) job to actually update the collider
Sure, it's easier, but the point of this approach is to avoid the copy, which can be expensive. I assumed by "good" in this context, you meant more performant, since this data is coming from a job, probably for better performance.
fair enough
can you do the same thing with Lists? I'm actually writing to a nativeList
Not with this package. As far as I can tell, you can't create a NativeList from an existing pointer, like you can with NativeArray.
dang
I could just manage the current last element I guess
hmm but then I'd end up inserting a bunch of junk data
Are you writing to the list with ParallelWriter?
as far as I know, no
So the job type is not IJobParallelFor?
no
it's a sequential algorithm
by junk data I just meant leaving a bunch of unwritten data at the end of the array when writing to the collider
does Unity have an api similar to WeakReference? I've seen their objectpool api so hoping they've something similar for us to use for the weakref
Can't you just use WeakReference?
yeah, just asking if there's one that's native to the engine.
I've seen Unity using their own used for their internals but can't quite remember what it is
I don't see what the point would be when WeakReference is readily available. No need to reinvent it
Most of the internals of the engine are in C++
oh I meant a higher level api ones
Like UnityAction?
I don't think they're weakrefd? iirc their events are just binary serialized, for their persisten ones I think. Don't count me on this
Who's weakrefd?
oh was talking about pooling pattern which what the original post was about
Why would you want a weak reference in an object pool?
not being a dick here, but why not 😉
There's no equivalent to WeakReference for Unity native objects, because Unity native objects aren't garbage collected. They have to be explicitly destroyed. Their C# class representation can be garbage collected though, and you can use the regular WeakReference for those.
Hey 👋
this might be a strange ask but does anyone have any suggestions for resources or anything that utilises quake style air control as well as quake style movement direction calculation (wishdir, vel and accel) using rigid body movement instead of character controller
yeah it's not for UnityObjects, so I'm using WeakRefs for now
there's this https://www.youtube.com/watch?v=v3zT3Z5apaM
Explanation of how the player movement code in Quake gives rise to these three different player movement "bugs", with a quick look at TAS movement mechanics at the end.
Big thanks to the Quake Speedrunning Discord for helping me out with getting TASQuake running on my machine, and for clarifying terminology.
Here are the original C versions of...
but maybe that's what you've seen which is why you're using those very specific terms
ill watch the vid, i was going off the quake3 movement code
having a hard time understanding 😅
thank you
By converting the image you have in Height map and Splat map.
are Unity's mathf apis impl still using double-float conversion ? Or are they already migrated to System.MathF ones?
Still using System.Math.
https://github.com/Unity-Technologies/UnityCsReference/blob/2023.3/Runtime/Export/Math/Mathf.cs
confirmed
well, that sucks
Can anyone help me? I'm doing a project using Quest 2 in unity and I'm using hand tracker 2 in unity. I want to pick up an object and not let it pass other objects
ex: I took the book and didn't pass the book from the table and it collided with it but didn't pass
Does anyone know how to do it? to help me please?
Hello. I am trying to spawn GameObjects using an Editor script, in a prefab. However, it always results in the Scene Mismatch error as show in this shot. I noticed it's spawning the colliders in the Scene Heirarchy and not in the Prefab context Heirarchy. How can I get around this?
I think the other thing would be just to set the new object's parent as some object in the prefab asset
Thanks, worked perfectly!
In the official Unity Documentation they mention a "Physics Shape" component to use with ECS in place of the standard shape colliders.
However I cannot find this Physics Shape component anywhere, even after getting the physics package.
What am I missing?
They mention Physics Shape twice here
https://docs.unity3d.com/Packages/com.unity.physics@1.0/manual/concepts-simulation-set-up.html
Probably get faster help in the DOTS channels. They were moved to be downloadable from the Package Manager as Samples, as they are focusing on the baking from the original physics components.
Does anyone know what may be causing the build of my game to take so long to load when opened (my best guess is some graphics/render pipeline asset options)?
I my game is made in 2023.2.5f1 LTS, and the project uses HDRP
Define long
Graphics is rarely the cause. Unless you're baking something on start.
It's usually loading assets and other stuff from the disk.
I'm trying to think of a good system for this, but afraid I may be overthinking the issue.
I am working on a mechanic where the closer a given point A is to a path, the higher an arbitrary value is. The path is made up of defined points and lines are drawn between. The closest point will, in most cases, exist somewhere on this line between the defined points.
Currently the solution I have in my head is to find the closest defined point ( B) on the path to point A, compare the angle between point A and the points on either side of the defined point and choose the one closet to A (C), find the right angle intersection of point A through line B->C, use the distance of point A to this intersection point in order to find the weighted value.
This calculation will run on every frame while the user is choosing where to put point A and will stop running once the user places the point.
I'm worried this is an overengineered approach and will be slow and causes lag spikes but i'm not aware of a better solution
Another option that might be faster but less accurate would be to pre-calculate the line segments of the path and project X amount of rays from point A and theres an interseciton between point A and the polyline record it and choose the shortest distance. Not sure if it would be faster but it could be
So given a point and a set of lines,, find the closest line and distance between that point to it?
The simplest solution in my opinion is:
(Vector3? closestPoint, var distance) result = (null, float.MaxValue);
foreach(line in lines)
{
Vector3 pointOnLine = projectOnLine(point, line);
float distance = distance(point - pointOnLine);
if(result.distance > distance)
{
result = (pointOnLine, distance);
}
}
If performance is not what you want, you can:
- Reduce the amount of line by reducing the precision
- Use AABB to do a first pass to remove most line
- Use Burst
- Use parallelism (It is a Embarrassingly parallel problem - https://en.wikipedia.org/wiki/Embarrassingly_parallel)
- Reduce the amount of execution (Do you really need to run the code every frame given that most human have a reflex rate of 250ms)
- Use GPU parallelism (I really do not believe that you will need to get there)
- Use caching (If the line does not move, you might be able to know approximately what the distance should be given the movement of a point)
There is so many way to optimize the problem, I believe the first step is to actually make the code and profile.
Man, I sure do love it when Unity pushes regressions in functionality and when I try to implement workarounds, I'm greeted to this.
Code
Debug.Log($"{candidate.corners[^1]}, {hit.position} : {candidate.corners[^1] == hit.position}");
Output
(1.95, 0.08, -2.06), (1.95, 0.08, -2.06) : False
And people complain about JS not making sense.
That's just floating point imprecision
Looks like - ah, too slow. The values SHOWN are rounded, but the full float is different
Also that 😛
If you print out the individual floats itll show the full value
Yeah, I'm guessing as much. Someone should tell that to the Unity engineers working on the NavMesh rework since it's basically impossible for the current system to ever return a non-partial path. Instead I have to create my own approximation workaround -_-
Or call ToString("F7") (not sure if it works on vectors but works on floats at least)
That's a massive jump from the tostring implementation of a vector, to something about a navmesh.
Basically the hit.position variable is the result of a NavMesh.SamplePosition call on the NavMesh that the Agent which is generating the corners array is present.
IE Despite both sources of data coming from the same NavMesh, to the same point, there fails to be a complete path generated due to presumebly some floating point imprecision likely on the Y axis
It's a regression I identified this morning when I noticed some code that's been untouched for nearly half a year suddenly not working
So now rather than relying on NavMeshPath to tell me whether a path has been found, I have to create my own validator for when it returns a partial path, to tell me whether or not a path to a corner within 3 point accuracy has been located.
I want to make an interface for a bunch of monobehaviours, and a scriptable object that can get me the proper type of gameobject (that implements the interface), but I can't seem to make it work since interfaces can't derive from MonoBehaviour and I can't instantiate things that aren't MBs. Thoughts on how to make this work?
"Prop" in this example isn't property, but a prop in a cutscene (just to hopefully clear up confusion)
public interface IProp
{
public void Initialize(PropType propType, CrewType crewType, PoseType poseType, bool isLocked);
}
public class NormalProp : MonoBehaviour, IProp { ... }
public class CrewProp : MonoBehaviour, IProp { ... }
public class PropDatabase : ScriptableObject
{
// bunch of IProps:
[SerializeField] private IProp WallScreen1;
... etc x100 ...
public IProp GetProp(CrewType crewType, PropType propType) => (crewType, propType) switch
{
(_, PropType.WallScreen1) => WallScreen1,
// .. etc ...
}
}
// Now I want to create these in a scene at runtime:
foreach (ItemDefinition itemDefinition in _episodeDefinition.Items)
{
IProp newPropPrefab = PropDatabase.GetProp(itemDefinition.CrewType, itemDefinition.PropType);
IProp newProp = Instantiate(newPropPrefab, PropContent.transform); // can't instantiate an IProp
}
Could I just cast newPropPrefab as a GO? It always will be one..
It's probably a monobehaviour not and a GO
oh, uh, can I not cast a MonoBehaviour to a GameObject..? I sorta thought they were the same thing
ok, that works.. then.. to get the IProp interface... what.. cast it back to IProp? since IProp isn't a component itself
GetComponent<IProp> works I think
money, thanks
If you add a gameObject getter property in the interface, you don't even need to implement it in the mono inheriting from the interface!
oh, that's interesting too
Does it? Isn't the one in MB a field? and thus a Property still need to be implemented?
that is cooooooooooooool
public extern GameObject gameObject { [FreeFunction("GetGameObject", HasExplicitThis = true), MethodImpl(MethodImplOptions.InternalCall)] get; }
Ah nice
vanilla getter, no errors on the implemented class
so I could just access the gameobject without all the casting gymnasics.. thanks, neat tip
OK, followup (and maybe I'm violating early-optimization), but is there a way to get back to the interface after I've instantiated it without GetComponent? I try to not use it because of the cost, maybe that's not a big deal, but I imagine I'm going to be instantiating about... 400? of these items for some users
GameObject newPropPrefab = PropDatabase.GetProp(itemDefinition.CrewType, itemDefinition.PropType).gameObject;
GameObject newProp = Instantiate(newPropPrefab, PropContent.transform);
IProp iProp = newProp.GetComponent<IProp>();
just wondering if you could elaborate, what is that purpose of that vanilla getter? after implementing the interface to MonoBehaviour, you can already use the gameObject
Instantiate() is always going to return a parent gameobject, I imagine, so I imagine I just have to
I don't know what you mean? The interface doesn't derive from MB
ow is it to avoid casting to MonoBehaviour?
yeah
didin't know that's possible
I already "know" it's a MB
that's nuts
yeah, it's kinda cool, TIL
It's actually doubly smart since it forces any IProp to be a MB .. not that this is a likely bug vector, but still, it's nice
hm..... wait....... I bet I could put an IProp property on the IProp itself???
this might be ugly:
you could
You can always cast from an interface to another type
So I had a similar problem recently
oh wait, no, i still would need to GetComponent on the GO to get the iprop
I decided to just expose the things I needed as properties on the interface
public interface IProp
{
public IProp iProp => this; // if I already "have" the IProp, this isn't useful
}
hm, I guess that works
no, i mean, it doesn't allow me to skip the GetComponent<IProp> since all I have at Instantiate time is a game object
oh, this is not what I thought it was. lemme look closer..
not sure if you can avoid it at all
it's fine, I'm happy with the current solution
oh, I was double-wrong. that's exactly what I did :p
I needed a Transform in my case
can you do
var ipropGO = Instantiate(newPropPrefab, PropContent.transform);
IProp iprop = ipropGO as IProp;
or that wont work?
only if the type of newProbPrefab implements IProp
iirc casting is better performance-wise than GetComponent<>
if newPropPrefab is a game object, then this doesn't make any sense
did some debugging lately and i had Miner : Unit, and I was instantiateing Unit and doing GetComponent<Miner>
and turned out doing (Miner) was better in that case
in that case you had a reference to a Miner after instantiating
but the compile-time type of the variable you put it into was Unit
so that's a valid downcast
No, that doesn't work, can't cast a GameObject to an IProp
right. you just probably wouldn't name the variable ipropGO in that case :p
that's what I tried here: #archived-code-advanced message
If all you have is the game object then pretty sure you're gonna have to get component
that;s kinda different what i suggested
but in any case, my existing solution is great and i love the little tip from @modest lintel
you can't do it in one line
The workaround would be not directly using game object from the start
the important thing to remember is that a GameObject is...just a game object
even two lines, same thing
it's not any of the types of components that happen to be attached to it
yeah
GameObject will never cast to any of your own interface types because it has nothing to do with them
yes sorry I assumed that newPropPrefab is not a GameObject
the GetComponent<IProp> is probably a pretty mild cost here
but a class that implements IProp
newPropPrefab has to be a gameobject (that's the requirement of Instantiate) and instantiate itself also returns a GO
that's wrong
I don't understand
Instantiate takes any type.
Instantiate will return the component if you give it a component
you don't need to pass GameObject to Instantiate
ohhhhhhh?
My object pooling system uses components only. Much easier because I wanted to avoid get component
So I could create an empty GO, instantiate the component to keep the reference, and add it to the new GO?
that's an idea
no you dont instante "components"
there is absolutely no need to create an empty GO
if you instantiate a component object, Unity instantiates the entire game object
it then hands you a reference to the new component on the new instance
it will instantiate the entire prefab
[SerializeField] Bullet bulletPrefab;
...
Bullet shot = Instantiate(bulletPrefab);
How do I create a component? I just new() one up..?
with odin inspector, you can even do
(I've literally never done it)
[SerializeField] IProp prop;
IProp iprop = Instantiate(prop);
and yes you can drag&drop IProp to the inspector
but you dont need to do that
with OdinInspector, maybe
yes, as i said with OdinInspector only
it sounds like you've gotten game objects and components mixed up here
i find it very usefull
No I mean - I don't often compose my gameobjects in code - I tend to make prefabs with the components I need on them, and instantiate that entire prefab
That's what we're talking about.
Right so... I've got this SO "library" of IProps - how do I instantiate a naked GO and staple a new IProp to it?
[SerializeField] Bullet bulletPrefab;
...
Bullet shot = Instantiate(bulletPrefab);
it's the same as
[SerializeField] GameObject bulletPrefab;
...
GameObject shotGO = Instantiate(bulletPrefab);
Bullet shot = shotGO.GetComponent<Bullet>();
OK but for my use case, IProp isn't a component itself.. so I can't instantiate it.. the derived classes are components.. How do I get to the derived class from the IProp? like, what am I missing here 🙂
a reference
No, but I suppose I could?
You're thinking like:
public interface IProp {}
public class PropBase : MonoBehaviour, IProp {}
public class SomeProp : PropBase {}
and make the scriptable object instead return PropBase items instead of an IProp
then you can do
BaseProp baseProp = Instantiate(propPrefab);
IProp iprop = baseProp as IProp;
yeah, and then get all the benefits of the interface while having access to the unity side of things 🤔
well actually in that case you might even want abstract class
Maybe making an abstract class would be nicer here.
instead of a interface
Damn im slow
yeah.. i mean, it could be a tangible class and I could just put the "NormalProp" behaviour in here and make special props just override what they need to, but I get ya
what was originally written is completely fine until it is not 100 years later
I'd almost rather do it that way so I don't have this weird dangly bit - empty base class -
and override the logic in all the prop classes
your base class could also have logic
that will be common for all the other props
just override the methods in other prop-classes
yeah, Show(), Hide(), Unlock() are all going to be pretty much the exact same in all the classes, makes sense to put that in the base class instead of copying and pasting for all of the derived classes
yup
with interface you'd have to copy it
the same thing to all props
and with abstract/virtual approach you have more control
especially because usually the only difference in the actual classes is going to be different particle effects, but the prefab itself is simple - there's just "LockedProp" and "UnlockedProp" gameobjects that are turned on/off
and cleaner code
i kinda recently stopped using interfaces
due to abstract classes with virtual methods
they are doing the same thing for me as interface would
but with some more control and cleaner code/architecture for my use cases
this project uses both quite a lot and it works well for me.. i use interfaces to implement/describe behaviors and derived classes for instances of the types of behavior.. it was a bit of a mess at first but is now pretty clean and the logic "just works" most of the time
tile game, tiles are maybe IDestroyable or IDestroyer or IMergeable, but there's a number of different types of tiles that all might implement various interfaces or not
then the game logic doesn't need to check for .. you know, is it A or B or C or D, it just says "if it's IDestroyer destroyerTile and destroyerTile.DoesDestroy(targetTile) then destroy it"
i haven't really needed to go deep on the polymorphism thing until this project
do something once: do it
do something twice: copy and paste
do something 3 times: bitch and moan, but copy and paste
do something 10 times: polymorphism
maybe I should start doing it the right way at 3 times though 😛
what happens when you have to do something once...ten times...
then you write a code generator and ascend to another plane
I'm usually not a fan of interfaces here, because in most cases you'll end up only writing one class which actually implements the logic. Unless you are truly destroying things in unique ways that are completely unrelated to each other
could also achieve all that with virtual methods
and inheritance
we are 😛
Like, there's some tile types that (when destroyed) destroy everything around them; others that can only be destroyed for certain other tiles, etc
still can be done with virtual methods
OnPropDestroy()
and override each special behaviour
in the prop special class
and can still call it from the base class
just to be clear, props are for something else (cutscenes with props that you unlock from stars earned in the main game), these are "tiles" which interact in all kinds of goofy ways
prop.OnPropDestroy()
many of the interfaces have methods which make no sense for the base class, though.. like, the base class doesn't implement IDestroyable so DoesDestroy(targetTile) doesn't mean anything.. I could have it just always return false but that'd create a bigger and bigger burden to keep updating the parent class when adding a new interface
the base class only does stuff that's common to all tiles - like have an id, and a location, and ToString
like these snippets:
I don't need to do things (for say, the destroyer) that enumerate a whole bunch of different kinds of tiles that are destroyers; nor do I need to put an abstract method (DoesDestroyTile) in the base class that needs to be boilerplate implemented for every type of tile in the game.. if that makes sense
Here's a good example - there's a "snail" tile that is .. kind of inert.. just plods around the board doing nothing.. the entire class is:
pretty much nothing in it aside from movespeed = 1 and some tostring stuff
placementPosition = hit.point;
float distance = float.MaxValue;
for (int i = 0; i < points.Count - 1; i++) {
float A = Vector3.Angle(points[i] - placementPosition, points[i] - points[i + 1]);
float B = Vector3.Angle(points[i + 1] - points[i], points[i + 1] - placementPosition);
float sideA = Vector3.Distance(points[i], placementPosition);
float sideB = Vector3.Distance(points[i], points[i + 1]);
double area = .5f * sideB * sideA * Math.Sin(A * Mathf.PI/180);
double height = 2 * (area / Vector3.Distance(points[i], points[i + 1]));
if (A <= 90 && B <= 90) {
if (height < distance) {
distance = (float)height;
}
}
}
This is what i came up with. Guess we'll see how it goes
That seem so much complicated from what I initially understood from your problem. Why you cannot do a simple projection on line ?
(Vector3? closestPoint, var distance) result = (null, float.MaxValue);
foreach(line in lines)
{
Vector3 pointOnLine = projectOnLine(point, line);
float distance = distance(point - pointOnLine);
if(result.distance > distance)
{
result = (pointOnLine, distance);
}
}
This code doesn't work
projectOnLine is not a built in funciton, and youre declaring distance as a var which you can not do in that context. You're also attempting to use ditsance before its decalred
This is pseudo code, I was expecting you to know how to do a projection on a line...
Read how to do a projection on a line, this is going to simplify your code by at least 90%.
Without talking about performance
its a bit more complicated than just projecting a point onto a line. The solution i was looking for was finding a point on the line that creates a right angle to a given point. To project the point onto the line you will arleady need to know where that point on the line is
False ?
Go ahead, tell me how
Dot product of (A,B) with (B,C)
B + (a,b) normalized * result the previous operation
I mean, B is suppose to be A Actually, I wrote it with B
but whatever, you understand the principle
Taking a look
What do you mean by 'with'?
Dot product is between two vector. so
Dot(A-B, C-B), B being the point that is shared.
However, you should really study the matter if you havent seen it yet. It is one of the few mathematical things you absolutely need to know as a game developer.
Dot and Cross product.
Basis change is also an other really import notion.
Thanks for the direction
float projectionLength = Vector3.Dot(pointA - pointB, pointA - pointC)/Vector3.Magnitude(pointA - pointB);
float cMagnitude = Vector3.Magnitude(pointA - pointC);
float height = (float)Math.Sqrt((cMagnitude * cMagnitude ) - (projectionLength*projectionLength));
This is what i came up with
If it works, it works. It is still strange, but might just be different from what I am usually working with.
I need the length of the projection which is why the funky code is there
This is one of the reasons why properties are so nice, when you want to refactor in/out of an interface it just works. People should really do less public field abuse and use properties more instead.
is there any more efficient way to manage dialogue than this? i downloaded unity today and dont know much about what tools are available to me (this is also my first time using C#)
here is the full source:
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Why not use a proper system like YarnSpinner or Ink?
i wanted to do it myself
And please don't ask questions in #archived-code-advanced when it's your first time writing C#, this should be in #💻┃code-beginner
It also looks like your !ide is not configured
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Try #archived-code-general then if that concerns you, definitely not here
Use TextAsset and json parser
Hi! I'm wondering if someone can help me solve an issue. I've written a fairly advanced scriptable render pipeline, and one of the features for it involves interacting with renderers and their materials to set properties eg: lighting
so my issue is, are there any secret methods for getting a list of all active renderers in unity? I've sadly ran into a bit of a wall with things like FindObjectsByType<> where they don't return objects in prefabs you're editing, for example, as well as just being generally a bit weird and slow to have to run a search every frame.
I wonder if anyones investigated doing something like modifying the renderer baseclass via reflection to add a tag to it, to make them easily queryable? Or if there isnt some other arcane way to get this info
Ive looked at those, but those culling results do not return all the active renderers (That would be lovely if they did)
it seems the list of stuff to draw is never exposed to SRP space, which is a pity
you can use filters and layers do to manual culling there, but the list of objects you need to perform operations on isnt exposed
leaving me with my initial problem 🙂
Are you sure you need the actual renderers for what you're trying to acheive? I'm fairly new to the srp so I can't help much, but why do you need access to the renderers themselves?
mostly for the list of materials currently active in the scene, and their bounds
specifically we have our own lighting system (lights and shadows) hand crafted for mobile perf, so we can't use any of the default stuff
Does unity allow custom shader tag ids? That might be useful
the horrible way is we add matching components or tags manually to everything with a renderer on it, but thats really just pushing the problem around
it does! we use our own shader pass names extensively
but I dont think you can query against it, just choose to render it in a render pass
Sorry I'm not really sure of any solutions :/
thankyou anyway 🙂
can I hide some record properties from being accessible in the with expression??? I have a base record with Children getter, and when I do derived with {} the Children is detecetd as a valid property for initialization inside the with, and I don't want that.
You can create your own render class if needed.
can I somehow use that to get a list of all the baseclasses of it?
I mean, you can use register your Renderer whenever they are enabled. It is pretty much the less costly method to find all type of a component
yeah, makes sense. I was really hoping I could just leave the SRP I wrote as completely isolated without you having to mess with your scene like that though
If you are writing a SRP, you might look into how HDRP and URP does the renderer collection.
At some place, they need to render thoses renderer don't they ?
you'd think that right >_<
but no the way the SRPs are written is that you tell a camera to collect what it can see
but you can never get that list back
cullingResults
its just a handle to some internal lists
What you do if you handle the culling yourself ?
eeehh you can't really
Like what the SRP is supposed to enable you to do
they actually dont enable that 😄
on the step right after culling, you produce a render command which you can set some filtering on
I don't know anything about SRP but this seems to indicate you can get the culling results back? https://docs.unity3d.com/Packages/com.unity.render-pipelines.core@6.9/manual/Culling-in-SRP.html
This is because you are relaying on ScriptableRenderContext.DrawRenderers. You do not need to use this function to draw everything.
Also, have you consider function such as: ScriptableRenderContext.QueryRendererListStatus
I do not know a lot about SRP, but it seem like there is a lot of different way to handle the drawing and you are currently using one that is the most restrictive.
How can we use GetComponent and AddCOmponent on threads? I need to do heavy work on like 100k+ objects for initialization purposes after they're instantiated and I'm wondering the best way to thread this work away so it doesn't block the app for minutes.
no way
probably switch to ecs
GetComponent can be replaced/cached with a Dictionary.
AddComponent is a no-go
Is there a way with the Jobs system? This work is too huge to do on the main thread.
Use ECS instead of GameObjects/Components
While that would be cool, it's not feasible to migrate to ECS for prod yet. There's gotta be a way to get the calls to work on threads, even if it's "unsafe" we can guarantee it would be safe.
You don't, you add it to a queue to initialize (aka add/getcomponent) on the main thread and then you can defer back to your thread
The engine will actively kill your thread if you try to access that API from anywhere other than the main thread.
Navi's suggestion is the only way really
Anyone know the mechanics of [FormerlySerializedAs]? Like, could I slap this on a field, rename it, save, recompile, then remove the field and not lose the seralized references in the editor?
(I kinda don't wanna have a whole bunch of these attributes dangling in the codebase, but I also have a couple components that I need to rename fields on that I don't want to break a whole bunch of linkages in the project)
Yes
I don't think so - once you remove the attribute the name of the field in the yaml will change and you will lose all serialized data, no? 🤔
i looked at the best-guess decompiled code and it seems? like it's setting the "name" from the old name, so it appears like it should be safe
I just don't want to try it since rolling back this change would be.. non-trivial
right but once you remove the attribute that goes away
This editor tool is made to more easily force reserialization for exactly this case:
https://github.com/rhys-vdw/dirty-boy
and there will be no connection between the old and new name
wrong one
i swear with the amount of rhys' code in my codebases I'm gonna have to pay him or something 🙂
Or I guess maybe it reads from the old name and writes to the new name?
wait no, that's the wrong one
Yeah, I think that's the key - I'm dumb though, this is easy to test on a new component, I don't have to just dive in and try it on my component that's used in 800 billion places
The attribute just makes it so that when deserializing, it can use either the real name or the old name. Serializing will always use the real name.
yeah doa small scale test
looks like it works fine / as expected
- create component
- link to serialized field named "oldFieldName"
- put formerly on it, rename it "newFieldName"
- tab back to unity, recompile/reserialize
- go to code, remove formerly
- tab to unity, recompile/reserialize - linkage still works ✅
@kindred tusk <-- 3rd try
he might even be awake now.. NZ? AU? 🙃
I guess the key is you need to make sure it happens to every serialized copy of this component
Hey, I'm doing a 3D golf game, and I'm trying to recreate the curved ball effect when hit by the club. I pretty much have everything set up, I hit the ball, the ball flies, spins, and curves based on the spin strength.. What I am missing is how to detect if the ball was hit inside-out or outside-in, so I know if it should spin clockwise or counter-clockwise.
I need to check the angle between what, direction of the club movement, and...? The ball is stationary and I can stand anywhere around the ball
How does club motion work? What's the user experience there?
its a VR game, you can swing like in real life
I guess you'd more or less look at the motion of the club around the time it hits the ball and see if it's going left or right with regards to the direction the ball is hit in.
so you stand near the ball, take the club in your hands, and you hook or slice the ball like here https://www.youtube.com/watch?v=VFPC9vW9qT4
Fade vs. draw, what is the best golf shot shape on this hole?
wouldn't that be the same thing? the ball will be hit in the direction of club movement and will result in angle 0? or 180?
[FormerlySerializedAs("")] will allow you to retain a variable's data through a recompile when the variable has been renamed. Best practice add the attribute, recompile, rename the variable, recompile, remove attribute, recompile. Renaming a variable is just creating a new variable as far as serialization is concerned, so the attribute basically takes the value from the old name and applies it to the new variable it's on.
Does it reserialize the value? Doesn't it store it as the old name and thus you can't remove the attribute?
I think the implication is it will deserialize from both the new and the old name, and it will serialize to the new name
So theoretically after one cycle of deserialize/serialize, it should be migrated
Hello!
It will read the old and the new name. You can remove the attribute as soon as you are confident that every asset is updated.
But they won't be updated until they're reserialized.
You would keep the attribute indefinitely if you were providing the code in a library or similar
(or in a big company where you can't be sure that other people were making assets in a different branch)
If you have lots of assets to update, there's an editor method to force reserialization of an asset.
I used this to update a big pile of scriptable object assets
You can also just...reserialize every asset! This reduces the amount of random changes you get in version control
where Unity decides to update an asset you happened to interact with in the editor
Tried adding the NavMeshComponents to my project from git hub, failed miserably, tried to load up my backup save. and this is the only error I get. I suspect this is refrencing a prefab that I've deleted, but the system won't let me git rid of that prefab to fix the problem. What should I do to get my project back?
Update: I figured this out myself and everything is back to normal.
that is a missing script/class nothing to do with prefabs
Guys you know in games like getting over it, where you can use the arms to crawl around, and they move accordingly to how you drag your mouse around, like retracting and stuff
How could I replicate that in 2d?
Just so I can drag the player character around with the arm
like crawling
ok this is just procedural animation
I can add !DEVELOPMENT_BUILD but not DEVELOPMENT_BUILD in define constraints for a dll. has anyone dealt with this?
What does the error say?
I'd guess that DEVELOPMENT_BUILD is not a current define
Would additive scenes be a good option for chunk based floating origin?
like you slice up the map in 5km x 5km sections, each being it's own additive scene
Does anyone know a workable hack to control UI image sorting inside a single canvas in a situation where I cannot use more than one canvas and cannot use transform hierarchy for sorting?
Best practice is obviously to use multiple canvases and adjust their sorting order relative to each other, but for reasons I cannot do that in this instance
Basically is there a way I can hack myself to functionallity close to that of normal worldspace 2D-sprite sorting?
why not
Within a single canvas it's based on hierarchy sorting, and the only way around that I can think of is to use a custom shader that doesn't follow the rules
Pretty much every single project in Unity uses "other DI", because Unity's inspector assignment system is a form of DI.
I don't know if anyone is tracking statistics about it
Of all the Unity games that have been released? Probably less than 1%. But I don't have anything to back that up.
Some use it mostly as an alternative for Singletons, to make it easier to access global instances. Others use it to make it easier to isolate elements to test them in unit tests.
You can see how Niantic Labs used Zenject in Pokémon GO here:
https://www.youtube.com/watch?v=8hru629dkRY
Chris Mortonson (Niantic Labs) discusses the challenges faced when building the hit AR game Pokémon GO. He shares Niantic Labs' approach to scaling Unity from prototype to large, maintainable codebase.
Is it a mobile game with 3D elements in it? Most likely, it's made with Unity.
How can I do procedural 2d animation :\
From what I've seen, I don't really think you'll come to this conclusion. The only reasons I've seen people use it were what MentallyStable listed above, and these are really more "Enterprise" reasons if that makes sense. Really it comes down to publishing a game that people will play, that is all.
I dont think you even save time, infact you may end up writing more code
OK, thought problem for the big brains.
I'm consulting on a project that has a system that can take string content to issue commands to the game engine. The designers write up these scripts and stuff and the engine parses and does stuff with it, at run time. One of those commands is to pan and zoom the camera on a specific game object (by name). It's.. an interesting design, and this question isn't geared for criticism of that (because y'all know I have a lot of that, but .. you know, legacy).
The issue is that the product is worked on by a team of 20+ people dabbling in unity, some engineers, some artists, etc; and occasionally a game object or prefab has some interestingly named game objects that people decide to rename. Sometimes they need to move objects around in the hierarchy because of new functionality or whatever, and that's fine and expected.
The problem is that the system that's depending on zooming the camera to a specifically name game object now breaks.
Anyone have any ideas how to minimize or mitigate this process?
- The camera system can't really be validated because those game objects don't exist in the database in any format.
- Reworking the entire camera system to add a "target tag" might not really be a cost-effective option.
- I can obviously check at run-time if a game object no longer exists that the camera system is trying to find, but these are hard to check comprehensively because there are thousands (literally) of these commands.
Example of the "string" content command. This command is called TappedHighlight and forces the camera to zoom on the parameter of the command, which looks like this:
{HighlightId:"Node_Parent/NodeContainer/NodeNew(Clone)/UIOverlayOffset/HighlightAnchor",MapHighlightButton:"Node_Parent/NodeContainer/NodeNew(Clone)/UIOverlayOffset/YieldableBubble"}
(yes, including the "(Clone)" part)
if someone changes "HighlightAnchor" to some other name that makes more sense for whatever they're working on, this particular parameter for TappedHighlight fails (at runtime) because the engine can't find that game object anymore
So this is an on-going legacy project with a lot of parts already relying on this structure, so refactoring is costly? So the ideal solution would be some kind of workflow improvement, such as automatic validation to notify those that are renaming objects?
Yeah, I mean, the "workflow improvement" is the current process, but it's literally a slack message to at-everyone from an angry designer "please don't rename game objects or at least tell me if you do so" but.. I'm not sure if that's tenable, both in terms of the ask for everyone working with game objects, but also from the content designer's perspective - they're gonna get notified for a lot of useless/irrelevant GOs
The prefabs themselves might not even be the problem - in the example above NodeNew(Clone) is one specific node, but others might have different names that the designers want to make these camera zooms.. like Node_Parent/NodeContainer/MentallyStableEnemy(Clone)/UIOverlayOffset/HighlightAnchor .. and the problem is both with the prefab (like HighlightAnchor) and the name/type of the prefab (MentallyStableEnemy)
I just.. can't really think of a solution here.. I mean, frankly, I can just throw my hands up and say "you reap what you sow, because this is a terrible design" but.. I'd like to at least try to make something helpful
it's super painful for them, and a big source of runtime bugs that slip through QA
One option I can think of is an editor tool that detects hierarchy and name changes in the scene and adds a component to those changed objects with the old name, to act like [FormerlySerializedAs("old name")]. Then, the code responsible for finding objects by name can fallback on these components if it doesn't find what it's looking for.
Hmm, that's an idea.. Maybe I coudl also create a sort of... do-nothing component that .. maybe could be smart about creating a list of strings, starting with the name of the game object itself? But then exposing something like a list of "previously known as" names
And then just updating the "tapped highlight" command to do double-duty - look for this new component first and if it doesn't find it, then fall back to gameobject name hunting
pseudocode:
public class TappedHighlightTarget : MonoBehaviour
{
public List<string> TargetNames = new();
private void Awake() => if (!TargetNames.Contains(gameObject.name)) TargetNames.Add(gameObject.name);
}
maybe even it could be really? smart and do some editor magic if anyone changes the gameobject name it would add the previous name to the list.. maybe that's not a great idea though, i'd have to figure out how to resolve conflicts
Isn't that a pretty big change to the workflow, though? Now it's not enough to just put the name of the object in the command, you also have to add this component to it first? Or would this component be added automatically somehow?
yeah.. it's not great
They do a lot of fancy composition of game objects with custom components so that the designers (who are unity+ but not programmers themselves) can just add whatever components they want to game objects
Not saying that's a "pro" in favor of this approach but rather the opposite - there's already a zillion custom components that the designers have to remember to add to new prefabs
and also if someone removed the component the history would be lost.. or copied and pasted the component to a new object, it'd carry the wrong history, etc.. nevermind, bad solution
These scripts are known at design time right? Maybe you can parse the scripts and check if the referenced game objects exist or not.
The "content" isn't connected to the game, it's in a database and downloaded by the game at runtime.. it's just in a flat database-ish thing
so there's no opportunity to validate the content the designers are typing in - they're literally using google sheets with a custom extension to parse and put the data into a cloud based database / CDN
in fact, some of the content writers aren't even unity-capable so .. there's some friction there too.. like:
- content-writer: "hey I'd like to have this cutscene zoom in on X, what is the name?"
- unity-designer: "it's
Nodes/SomeNode/HighlightAnchor" - content-writer: "cool, thanks" types that into the database
- engineer: "why is this named
HighlightAnchor, it should beAnchorHighlight", renames it - everyone: 😡
Sounds like the Unity side is the source of truth then? The names are basically your public API surface, maybe make a way to export them, and use whatever suitable to ensure they are not breaking.
Even simple diffing can show you what got deleted/added/renamed, and the export also works as documentation for the writers rather than having to ask back and forth.
A lot of big games have a 'content' server which is the big kid version of that. It would need to be the actual source of truth but that's often handy anyway.
You're just missing the piece where there's tooling around the 'backend' so that designers are editing in a clean interface. You absolutely can do validation, you just have to build it into an editor interface (which sheets is not) and manage that on its own. Which is a lot of work and probably not worth it for most cases, but if that's what you need then solve the problem you have.
That is just a bad practice that should be avoided. I would hesitate to say go the API route of keeping specific scripts for each type of functionality. Sounds generally like someone tried to design a framework without knowing how good frameworks work. That and not keeping a single responsibility. Which I have a lot of components but because they are simple and designed to hook into each other they stay clean and someone doesn’t have to remember every component just how the component hierarchy works.
Likewise how y’all link scenes by strings sounds pretty horrible. No custome component selection menu?
nowadays, do we still need to copy the source to our asset just to use Il2CppSetOptions attribute?
Hi, does anyone know how to debug native crashes and burst crashes on Linux?
Almost nothing can be found for this on forums
Docs for 2023.3 at least don't suggest otherwise. https://docs.unity3d.com/2023.3/Documentation/Manual/IL2CPP.html
I see, thanks 👍
Attach the debugger and reproduce the crash.
It’s for a native crash in a player build - symbol files aren’t produced for burst, so we can’t debug the dump file
Can you not reproduce the crash in a controlled environment?
its an MMORPG game server - its difficult to reproduce the bug in a controlled setting. I would expect to have symbol files (including symbol files for bursted code) for a linux build so i can debug actual crashes in the wild
unless it only happens when burst compiled, how about turning off burst compilation for a build so you can debug the c# as normal?
does unity has anything similar to json.RawMessage in go.
so i can send json object inside another json object?
That might help in specific situations, but it’s impractical since the native version is what will be shipped
And we haven’t been able to replicate it locally
Then I believe your only course of action is to add logs before and after. Ideally, logs your assumption as well that are needed in the function.
ah i see... well, i don't know your situation but maybe running the slower version in production for a while is worth finding the bug 😛 if all else fails, you can get the burst inspector in editor to show you the assembly with line info for any supported arch, so maybe at the very least you can use that as a debug aid looking at a crash dump?
Hi all, has anyone had issues with reloading the current scene a player is in?
I have a scene that instantiates a lot of procedurally generated content and deletes some other content. When I use SceneManager.LoadSceneAsync I'm expecting the scene to revert to it's original state, but the content I generated or deleted previously does not reset.
Reload is reload, if it held over content generated from a previous incarnation that would be weird
also not a coding question
Anyone uses the KCC (kinematic character controller) I wish I've seen it sooner, but now I'm kinda deep into a project I think I should focus on content as oppossed to another rewrite of everything, but in the interest of research: I understand KCC runs it's own physics simulations, and allows putting a script on geometry that moves that allows it to interact with the rest of KCC systems. Is it possible to also put this on a rigidbody that's simulated by unity's physics already?
For the new Logging package. Is there a way to attach a gameObject to the message like in the Debug.log so when you click on the message it selects the object in scene?
no
the KCC physics engine revolves around doing the simulation for EVERYTHING so it can orchestrate the timing for everything
if you have a combo of RBs handled by KCC and unity physics, then the KCC RBs will not properly account for the movement of the unity RBs
I have the following code that works great for a single buffer of MeshProperties, but I need to make it handle mutliple buffers to skirt the CompuuteBuffer size limit in another part of my code. While this code renders some of the total meshes, it doesn't render all of them, only one (of 8). How can I make this code handle 8 buffers?
Shader "Custom/InstancedIndirectColor" {
SubShader {
Tags { "RenderType" = "Opaque" }
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata_t {
float4 vertex : POSITION;
float4 color : COLOR;
};
struct v2f {
float4 vertex : SV_POSITION;
fixed4 color : COLOR;
};
struct MeshProperties {
float4x4 mat;
float4 color;
};
StructuredBuffer<MeshProperties> _Properties;
v2f vert(appdata_t i, uint instanceID: SV_InstanceID) {
v2f o;
float4 pos = mul(_Properties[instanceID].mat, i.vertex);
o.vertex = UnityObjectToClipPos(pos);
o.color = _Properties[instanceID].color;
return o;
}
fixed4 frag(v2f i) : SV_Target {
return i.color;
}
ENDCG
}
}
}
Even my basic attempts to render one of the 8 assigned buffers fail:
Shader "Custom/InstancedIndirectColor" {
SubShader {
Tags { "RenderType" = "Opaque" }
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata_t {
float4 vertex : POSITION;
float4 color : COLOR;
};
struct v2f {
float4 vertex : SV_POSITION;
fixed4 color : COLOR;
};
struct MeshProperties {
float4x4 mat;
float4 color;
};
int _NumBuffers;
StructuredBuffer<MeshProperties> _Properties[8];
v2f vert(appdata_t i, uint instanceID: SV_InstanceID) {
v2f o;
float4 pos = mul(_Properties[0][instanceID].mat, i.vertex);
o.vertex = UnityObjectToClipPos(pos);
o.color = _Properties[0][instanceID].color;
return o;
}
fixed4 frag(v2f i) : SV_Target {
return i.color;
}
ENDCG
}
}
}
Implementing looping before getting this working makes no difference 😦
What mesh are you rendering with this shader?
I don't see how passing more structured buffers is gonna make it render more objects. I feel like you're misunderstanding something about how shaders work..? Or not giving us all the details.
Has anyone tried generating pdf in unity using a button? Pls, help on how I can start, I'm using pdf sharp but don't really know how can I integrate that? I'm thinking using it's dll?
Simple quad. Passing in the buffers is the only way to avoid the compute buffer size limit in my case.
Passing in more buffers will render more objects because I am spreading the load across all 8 buffers.
I just need to know the means to actually use all of the buffers.
A normal shader would render according to the vertex buffer that is passed to it. This is controlled by the engine and is usually taken from the rendered mesh. That's why it doesn't matter what other data you pass into the shader. It would only render the mesh data that is passed into it by unity.
"passing in more buffers", assuming you're talking about your structured buffers, wouldn't affect how many objects are rendered.
I am using indirect instanced rendering so I'm going to go out on a limb as say that a default vertex buffer is out of the question. Backed up by the fact that it's not working currently for rendering more than 1/8th at a time.
It's absolutely possible I'm missing something here, but as it stands passing my buffer that contains the matrix like "material.SetBuffer("_Properties", meshPropertiesBuffer);" does not work because I have 8 buffers of MeshProperties
Ideally instead I would like to use "material.SetBuffer($"_Properties[{bufferIndex}]", meshPropertiesBuffer);" which is how I am able to manipulate everything on the compute shader side.
#pragma kernel CSMain
int _NumBuffers;
struct MeshProperties {
float4x4 mat;
float4 color;
};
RWStructuredBuffer<MeshProperties> _Properties[8];
[numthreads(64,1,1)]
void CSMain (uint3 id : SV_DispatchThreadID) {
for (int i = 0; i < _NumBuffers; i++) {
MeshProperties props = _Properties[i][id.x];
// Set the matrix to identity, implying no transformation.
props.mat = (float4x4)0;
props.mat[0][0] = 1.0;
props.mat[1][1] = 1.0;
props.mat[2][2] = 1.0;
props.mat[3][3] = 1.0;
// Set the color to green.
props.color = float4(0,1,0,1);
// Write the modified properties back to the buffer.
_Properties[i][id.x] = props;
}
}
Valid and working.
I'm trying to make a Skew component, which I got working for images by implementing IMeshModifier, but now I'm trying to do the same thing for a TMPro.TMP_Text and I'm running into some troubles
I got it working to manipulate the mesh of each letter so I could skew them individually, but I keep running into issues with that approach
like if it goes onto the next line, it gets much more complex
or if the character spacing is weird
is there any way to just manipulate the entire mesh at once? Is there some way to access a mesh with 1 quad that I could manipulate instead of doing each letter individually?
like how with Images, it's just a single, easy to manipulate quad
or is there a way I can just manipulate the transform matrix?
i’m pretty sure you can manipulate the transform matrix
wait is this on recttransform?
I’m pretty sure that recttransform only exposes transform matrices as readonly properties
reflection isn’t the issue here
the issue is that the transform matrix is a readonly property, meaning it gets generated from other fields, which are likely mutable and exposed
i’m not sure is you’d have everything exposed to be able to apply a skew through the rect transform, which is mostly used for positioning. But I think you want to apply a separate (linear?) transformation to the mesh vertices
not sure if I can help you there. What I would try to do is define the matrix for the linear transformation, which will depend on the center point of where you want to skew, and apply it. You should be able to express (as a function) the new vertex position for any old vertex position, without seeing all the other vertices.
Alternatively, you could try to make your own shader. Not sure how hard it would be to make it works though
I could make it a shader, but it wouldn't work well if something needs a material
Does anyone have experience using MediaPipe trying to make a motion detection system but can't seem to get it to work
I'm trying to make a component that I can just put on any Graphic that makes it shearable
shaders hate if statements. If you want to split it for multiple lines, that will require branched code, and the GPU will not take kindly to that
that too
doesn't stop me making if statements for my terrain generation
as long as the branching code isn’t done by the GPU, it is fine
I've not encountered a problem doing so, but perhaps I'm not doing it enough to really see the implications of it. Shadergraph also provides you the utility of logical blocks to use in your shaders.
Okay, well that's a detail you should have mentioned at the very start. Share the C# side code.
Also, you say that an attempt to render one of the buffers fails(the second code snippet, but how exactly does it fail? Is there an error? Is the the retrieved data just uninitialized or initialized with zeros?
ok so I fixed my thing
one more question though
the skew basically works now, there's still a few bugs but this is one of the last ones
it seems that Unity regenerates Text stuff whenever anything in the canvas changes, which makes sense
Graphics have a IMeshModifier interface that I implemented which is made for this exact thing
but it seems that TMPro.Text, depsite being a child of Graphic, doesn't use this interface and I can't find out how to do a similar thing
as you can see, it immediately resets after any Canvas changes
TMP has samples that modify text geometry, so that might be a good place to look
Can anyone help me figure out how to convert a VRChat world that I made in Unity with Creator Companion into a standalone VR or 3D game that can run outside of VRchat?
turns out it was because I was calling a function that would activate OnPreRenderText so it was an infinite loop
now it's not rendering at all
I'm not sure if I need that bottom line or not and I think it might be what's messing it up but I'm not sure what to replace it with since the example I'm looking at has nothing at all, but when I have nothing at all, it doesn't work
Maybe this is a weird question but I created an Interface called IAction and I wanted to serielize it in a Scriptable Object, however it seems that I can't just drag and drop a script into the SO editor window, it needs to be a script attached as a component to an object in the scene, any workaround for this? I want my SOs to hold references to different scripts that inherit from IAction
You can't serialize interfaces by default
There are packages to do this, or odin serializer
I see, but I've tried with a normal mono behavior class and it doesn't work either
You mean the TYPE if the variable was MonoBehaviour?
I meant a class that inherits from MonoBehaviour
was that the issue?
No, the only thing that matters is the variable type
Ok, and Class_test is just a MonoBehaviour?
well you wont be able to plug in an instance, because assets cannot reference scene objects
what do you mean?
this SO is an asset, it cannot reference an instance of your mono because that would exist in a scene. the SO is not associated with the scene
yes you can? at least in run time, no?
either way I'm trying to have it store a reference to a class that's in the files, not one that is a component in the scene, if that makes sense
so I can have another script access the SO and instantiate that class
So you mean a prefab file?
Yes at runtime, but no otherwise
No I mean like, the SO "knows" a class which has methods, and one or many of my scripts maybe access the SO and execute said methods, while others might change the class the SO "knows"
Sounds like a bad idea, and im really not sure why you cannot just use prefabs for this. If you're going to assign a Type to the SO, why not just new up a GameObject directly with the Type as a parameter
Yeah but by having access to the SO, the scripts could instantiate the class they need
those prefabs would just be empty objects with scripts as their only components?
🤷♂️ or also what i said about just passing in the Type https://docs.unity3d.com/ScriptReference/GameObject-ctor.html
this definitely is not #archived-code-advanced though. you should really describe what you're trying to do because storing a Type in an SO that classes can modify then use to spawn an object sounds very backwards. Also dont even know what you're trying to accomplish
Yeah, this is definitely an XY problem
My idea was to make a State Machine with States that are customizable on the editor without being attached to an object in the scene, I wanted to be able to choose both Actions and Conditions (classes) simply by dragging which script I wanted into the State (SO) I created
you'd probably need some way of serializing Type then so you can allow yourself to pick these classes. i dont think you can drag just a Mono into a scriptable object like this at all
well yeah that's exactly the issue I had and why I came here :')
a simple way could just be mapping some enum to the actual type. i think there are implementations for a serializable Type online too
yeah, simplest is
- Use an enum in the editor. That way you can rename/move your action/condition classes around without breaking all your stuff
- At runtime, instantiate the action or condition class based on the enum which you selected at editor time
- Probably write a custom editor so that you can include parameters for the proper action as well.
(odin makes #3 really easy)
serializing types directly seems nice until you realize that someday people might have savegames which now all need to be migrated because you wanted to rename a class
Sure that's a solution, but I would probably have to make a switch case for all the actions/conditions (or something similar), which doesn't seem like a good approach
you can do it really neatly with pattern matching
that's the best solution i found if you want those things to be actually serializable (you might not need that for your game)
🤷♂️ you're gonna have to do something that has a drawback like what Prakkus said about serializable types
i actually think the SO way can work if you want to do things that way but it gets a little unweildy and has some limitations depending on how arbitrarily you want to be able to save/load your game state
To be honest, I remeber trying to do this before with reflection, and it just... sucked. Enums worked a bit better. Then I just... scrapped the whole idea and my life got better
//Toy is the alias of the sprite renderer sprite
public void SwapTexture(byte[] texture)
{
toy = Sprite.Create(new Texture2D(64, 64), new Rect(0, 0, 64, 64), Vector2.zero);
toy.texture.LoadImage(texture);
toy.texture.Apply();
}```
Am i loading in this texture wrong because the texture isnt showing whenever i put it into play mode
If you have each 'action' class extend SO, you can treat a reference to that action as the action itself, create the instance with CreateAssetMenu, and then pass any dependencies it requires into an Execute() method
it just...ends up being nice to be able to create actual instances of your actions and pass them around instead of having them always be a static method call, and you could solve that with closures but at that point just make your actions plain old instantiatable classes
if it helps im loading the data from another Texture2D
try creating the sprite not over top of the existing texture reference
then assign that to the renderer
yeah thats an interesting idea despite that, I'll definitely give it a try anyway
thank you!
basically this, iirc https://youtu.be/2AS88GJmxbs?list=PLuldlT8dkudpCEkYQJb_H26BcbE7ozisX&t=325
In this Unity tutorial we will look at how you can improve your workflow in Unity, avoid spaghetti code and tight coupling by using ScriptableObjects.
I've created a Scriptable Cookbook playlist that I will add all the videos I mentioned above to, along with any new videos I create in this series.
Here are the links to the resources mention...
but this way is better 😉
that works ty, but now its only displaying 1 pixel
holy fuck Unity 2017 is so much faster than the new stuff
it's like instant compile and domain reload
removing the visual scripting package should make the new stuff a lot faster
as well as using assembly definitions
these tricks nudges the needle away from "madeninigly slow" to "somewhat bearable" but don't even come close
even disabling unity modules
i'm loving it
only thing that scratch the surface of how fast the old Unity used to be is adding the hot-reload asset, even that is so buggy that you never know what you get
this hasn't made a huge difference but occasionally things do compile slightly faster
Funny enough, I had the opposite experience. That being said, it was a port of a completed project (made with 2017) to console (which require LTS - Used 2022).
Compilation in newer versions is practically instant compared to before, but all the c# packages being reloaded in newer versions far outweigh any actual compilation time in tiny projects, which means that for the average Unity project, it's just been getting slower
Hello, so I have a hierarchy of 'generators', and each generator generates a set of points of meshes.
The points are 'on' the meshes created by a generator's parent generator (sort of like a fractal I guess)
I have AnimationCurves that are used to change how a mesh generates depending on the parent. Like changing the width based on the vertical position within the bounds of the parent mesh.
The issue comes when I want to be able to for example, set the width to be a percent value of the parent's width.
Lets say that the parent generator has a width of 10 meters. But the Width AnimationCurve makes it go from 1 to 10 depending on bounds position or something.
This means that if I have a child generator that has the Width set to 50%, I need to get the width of the specific parent mesh instance. I can't just get the 10 meters from the Width of the property.
So what I am trying to figure out is how (if at all) I could pass the properties down.
- I could add them to each generated point/mesh. But then that would be a lot of extra data if I did it for every property, most of which would not be used.
- As soon as a mesh instance is created, I could then go create all of the children that go on that instance, that way I could just pass the properties without having to store the values in memory. But this makes multithreading harder and less efficent.
(plus I want to move a lot of this generation to compute shaders)
I feel like there is some sort of smart way to do this possibly that I am just not thinking of. But maybe not?
Not sure if I explained this well, let me know if I need to try to clarify it, or if anyone has any ideas. Thanks
Can you not scale after generating all the meshes ?
I could potentially do it as a post process effect for that one. But I have a number of different properties I want to do it for that would change how they generate.
Hey i'm having trouble with rotations using angularvelocity to align an object rotation with a grabber's rotation. The issues are:
When approaching the negative Z direction in world space, rotation becomes extremely jittery, and even skips completely over the negative Z direction. This issue persists with both setting the angular velocity, and simply using Transform.LookAt() to store a value, then set the rotation of the object to that value with a change in the Z rotation.
As well as, when using Transform.LookAt(), the closer the object gets to the negative Z direction, the more misaligned it becomes with rotation of the Grabber. Will send a short video as well as a code snippet from all rotational changes.
TWO HANDED GRAB
public virtual void LookAtSecondary()
{
//Rigidbody rb = GetComponent<Rigidbody>();
//Adjust Angular Velocity to rotate to hand
//rb.maxAngularVelocity = 20;
Vector3 eulerRot = secondaryGrabbable.transform.position;
//eulerRot *= 0.95f;
//eulerRot *= Mathf.Deg2Rad;
//rb.angularVelocity = eulerRot / Time.fixedDeltaTime;
transform.LookAt(eulerRot);
Quaternion r = transform.rotation;
r.z = mainGrabber.transform.rotation.z;
transform.rotation = r;
}
ONE HANDED GRAB
public virtual void GrabbedRotation(Transform rot)
{
if (GetComponent<Rigidbody>())
{
Rigidbody rb = GetComponent<Rigidbody>();
//Adjust Angular Velocity to rotate to hand
rb.maxAngularVelocity = 20;
Quaternion deltaRot = rot.rotation * Quaternion.Inverse(rb.transform.rotation);
Vector3 eulerRot = new Vector3(Mathf.DeltaAngle(0, deltaRot.eulerAngles.x), Mathf.DeltaAngle(0, deltaRot.eulerAngles.y),
Mathf.DeltaAngle(0, deltaRot.eulerAngles.z));
eulerRot *= 0.95f;
eulerRot *= Mathf.Deg2Rad;
rb.angularVelocity = eulerRot / Time.fixedDeltaTime;
}
}
Just worked out that the skipping has nothing to do with with the grabbed rotations
which makes even less sense
is there a way to apply custom shader graphs to text with TMP?
really! faster compile and domain reload in 2022?! maybe it depends on kLOC, this one only has 5kLOC
exactly that, compile is super fast since they threaded everything. when you look at editor profiler domain reload is insanely costly.
did you try disabling engine modules?
man, i'm getting near zero crash in 4.27 so I wonder what's causing those crashes in your project.
Unity 2018,2017 editor feel so much snappier too... sigh
I've never used anything before 2019
I'm currently on 2023 and it's got a lot of bugs sadly
although it feels a little less sluggish to me compared to 2022
2023 is not a lts version yet would not recomend it as a stable version to use