#archived-code-advanced

1 messages Β· Page 96 of 1

toxic marsh
novel plinth
#

I mean you can just do var versionNumba = Application.version; ?
Application.version is basically the readonly version of PlayerSettings.bundled

ivory salmon
#

Does anyone have a reliable way of checking that Instantiate is being called on a GameObject? When an object is cloned (or created from a prefab) I need to react by fixing-up some references that Unity can't understand.

austere jewel
#

Call a method on that object

ivory salmon
#

I could hook the serialization, but that happens at various times in editor, and when the game starts - so it would corrupt my scene if I always tried to do the postprocessing in it

#

Call what method?

austere jewel
#

One that you have defined

ivory salmon
#

To be clear: I need to know when instantiate is being called.

#

I am not calling instantiate

austere jewel
#

What do you mean? What's calling Instantiate then?

ivory salmon
#

Any game code could call it at any time - out of my control

#

(Ctrl-D in editor as well - althogh Ctrl-D is already broken in all versions of Unity since 2021, so I'm OK with just declaring that "if you do it, that's your own fault, you can deal with the problems")

austere jewel
#

I am not sure what is broken about duplicating objects

ivory salmon
#

That's a different topic, but the bug has already been logged with Unity. Ctrl-D was changed in 2022.xomething and stopped working correctly

#

My best other guess right now is to try detecting that OnEnable is being called ... and somehow guessing that its due to an instantiate rather than general eanble/disable

austere jewel
#

There is no way to detect when Instantiate is run, you have the same lifetime callbacks as anything else. Awake, Start, OnEnable. If you want to handle editor-runtime confusion then check Application.IsPlaying. If you want to check whether an object is new, then add a boolean of your own

ivory salmon
#

Ah well. This is going to be tough. Thanks anyway.

ivory salmon
#

The invocation order of callbacks got changed. So e.g. OnTransformParentChanged etc callbacks now get called at the wrong time (they get called before the object has initiatialzed, where they used to get called after), and Unity wipes any changes in the scene data you made to the new object if you change them in the callback.

#

This corrupts a lot of stuff that (correctly) relied on the callbacks to maintain state.

#

(it wipes the data, I assume, because: it now does the deserialize AFTER issuing the callbacks, which is obviously wrong, but menas the deserialize overwrites whatever data is now in place)

ivory salmon
# austere jewel There is no way to detect when Instantiate is run, you have the same lifetime ca...

FYI: In the end ... my path of least pain was to refactor all the fix-up code so that everything everywhere uses MonoBehaviours (this means lots of fake MBs). SerializeReference still not implemented for refs that are shared between MBs, so that wasn't useable. SOs don't work because Instantiate( ... ) on something with SO's - even Scene-SOs - only shallow copies (because Unity's implementation of Instantiate apparently is hardcoded to assume all SOs are asset SOs, and as far as I can see there's still no API param to tell it 'no, this is a scene object - clone it like you clone an MB).

Works fine, just ... was a lot of code to change, and sadly now every project has to have a lot of extra spammy MBs that don't serve any purpose (other than workaround Instantiate's lack of callbacks)

novel plinth
#

I mean, how you instantiated them? they won't just appear out of nowhere πŸ˜…

ivory salmon
#

As above ... I don't instantiate anything

#

Other people's code does

novel plinth
#

I don't get it honestly πŸ˜… .. it's a template that someone made or you're working in a team or ?

ivory salmon
#
  1. If you're writing code for large projects, you need to do RAII - you can't just guess, or hope, that your references will be 'sort of OK' - everything has to be correct, and manage it's correctness internally - e.g. if you silently add a component, you must also write code to silently remove that component (like: if you do stuff in OnEnable, you need to undo it in OnDisable)
  2. Most of the projects I work on are hundreds of thousands of lines of code, with lots of packages (otherwise its impossible to work on - too many conflicts between different people). If someone else is writing 'correct' Unity code, your code has to handle that - the distance between where they write their code, and where you implement your code, can be considerable (different classes in different packages on different repositories owned by different teams being edited by different people)
  3. A lot of the code I write is used in assetstore assets sooner or later. That makes all the above true x10 -- if you ship something as an asset and it's e.g. leaking resources or e.g. failing to keep references correct or e.g. corrupting some of the scene ... you are going to make life hell for the end users πŸ™‚
#

Also ... I still have some live Unity code that was originally written all the way back in 2013 ... there are times I find code that is just really bad πŸ˜„ and there are much better approaches/APIs in Unity for doing stuff today, but either "12 years ago I didn't know what I was doing and did this badly" or "12 years ago the modern APIs didnt work, or didnt exist, so we had to do it complex/dangerous/hacky ways"

ivory salmon
#

e.g. here only the meshes + the level geometry are part of the game project - everything else is from packages (the UI is my own CSS3/Flexbox asset, the car-building/editing is a separate package, the physics integration is an add-on package that detects the building/editing one and adapts it to work correctly with Unity physics, the level management / restarting is another package ... etc).

long ivy
#

I'm morbidly curious what the issue you're trying to solve is. References already work correctly with Instantiate, so if adding your code requires all this workaround, it's a strong indication that something is wrong with your design. Can't you fix the references themselves? What about them prevents you from fixing whatever the real issue is?

ivory salmon
#

In the video above, behind the scenes ... there's a lot of objects created and destroyed to maintain the connections between all the parts of the vehicle. And to enable it to be re-built (procedurally, automatically) when it explodes/crashes etc. There's a lot of callbacks needed to maintain Unity Physics (especially: Joints, because they're implemetned badly by Unity as a component-attached-to-one-of-the-RBs, instead of as a standalone MB/GO - so you have to carefully track which half of the RB pair the joint is from. And note: Unity's joint callbacks API is still AWOL so you have to also add and destroy extra components to manage the Joint itself).

And for the overall transform hierarchy (if no physics) or 'the random set of GOs in scene' (if using physics) to be editable by the player, when we don't know what they'll add, where they'll add it, whether they'll use physics or not ... requires a lot of adaptive adding/removing/reconfiguring of the various objects everywhere.

The first version of this stuff was fairly simple; the current version now has a huge amount of dynamic stuff going on.

#

If it was just one game, a lot of shortcuts could be taken. But most of the code is reusable in packages, and used it completely different projects (e.g. FPS with player-designed guns, e.g. architecture/buildings editor, e.g. visual scripting system in-game). So there's a lot of "this could be used in different ways, it has to work correctly in all of them", and can't taken any/many shortcuts

#

The main thing I had to change today was that the bidirectional links between sub-parts of the assembled car were originally MB <-> MB connections, but to support some edge cases they needed to be MB <-> objectA <-> objectB <-> ObjectA <-> MB ... and I think there may be an edge case in physics I haven't fixed yet where it'll have to be MB -> A -> B -> C -> A/B -> A/B -> MB, because of limitations in Unity's Joints).

... where A/B/C were just plain C# objects, and mostly easy to manage, but some cases were going wrong, so in the end I refactored all the related code so that A/B/C are now MBs. I have to now also manage them in the transform hierarchy which is a pain :(.

#

I agree there may be simpler ways of doing it πŸ™‚ but this was built from 'the simplest possible and no simpler', and then gradually extended over time. Everything in it has only been added because a game / app needed it and there was no other way we could find to make it work.

#

(although I'm always looking for bits that seem over complex and trying to refactor/simplify them if possible. Especially if it's code I originally wrote myself ;))

tired fog
#

Does anyone see anything that I can do?

novel plinth
tired fog
#

Im not sure either. But there's this Naughty Attributes attribute that makes all my variables look nice, regardless of type, in a node view. And looking at the code it looks like it doesn't do much.

novel plinth
#

well then how one supposes to help you if you're not sure πŸ˜…

tired fog
#

By nice i don't mean only the example sent. For example my other attributes work only if that NaughtyAttributes is added

tired fog
#

I does this.

#

And I checked, and the PropertDrawerBase doesn't do anything else. So basically, those three lines make it so all attributes work as expected. What I want to do is, when Im creating those properties by code, have a way to also add those three lines so that they are taken into account by default

#

And this is where I create the properties for the editor

#

If it was normal editor code it would be trivial, but im not sure how to translate it with UI Toolkit

novel plinth
#

I'm not sure i'f propertydrawer can be contained with IMGuiCOntainer or not in uitk, either way you should ask in #↕️┃editor-extensions it's more appropriate there i think

tired fog
#

Oh I didn't see that channel, not sure how xd. Thanks going there

manic pasture
#

Hello, I'm encountering some challenges with using "Asset bundles" to dynamically load game scenes. If anyone has insight on bundling them with scripts, I'd appreciate your assistance. Thank you for your help.

stuck plinth
manic pasture
#

I've been attempting to dynamically load my game scene by bundling it, but I'm encountering issues with bundling the script.

#

I am attempting to build an APK that can later incorporate games dynamically through a server.

stuck plinth
#

what does "issues" mean?

#

have you tried solving it?

manic pasture
#

I tried making it prefab but it didnt worked

#

I couldn't able to find any other solution for it.

stuck plinth
#

what does "didn't work" mean?

manic pasture
#

If I bundle the scene along with game-related scripts attached to it, the game object will reference those scripts and function properly when loaded dynamically. However, if I delete those scripts, I'll need to load them dynamically instead.

#

I attempted the prefab method, but the script wasn't loaded with it, resulting in missing reference errors. I'm seeking alternative methods to achieve this functionality.

stuck plinth
#

by delete the scripts do you mean removing components from the object or deleting the actual script files?

manic pasture
#

Deleting the actual script files

#

I'm aiming to make the process dynamic so that I can add other games to it easily through the server-side without needing to rebuild the APK.

#

I've utilized asset bundles to achieve this goal, but I'm currently unsure of how to load scripts. Are there any alternative methods I could explore?

stuck plinth
#

game code can't be modified by loading asset bundles, only assets and data

#

i've never tried it myself but if you're not using IL2CPP you might be able to build an assembly into your bundle as a binary asset and load it at runtime, otherwise i'd probably suggesting looking into embedding a scripting language or something

#

but it's not really possible to load classes that unity will recognize as scripts or serializable objects at runtime

manic pasture
#

Im using IL2CPP

manic pasture
pastel finch
#

Is it possible to do a medium large physics calculation as quick as possible, then just animate the results?

sly grove
#

Generally the idea is:

  • Make a second physics scene
  • copy all the objects you want into it
  • call PhysicsScene.Simulate a bunch of times, recording the positions of the objects at desired times
#

Then take the results back to your main scene and animate them

pastel finch
#

Interesting.

#

I'm working on a golf sim, so its pretty much only the ball that can be affected by physics.

coral citrus
#

heya, is anyone aware of a method I could use to pick out vertexes along an edge? f.ex, the red highlighted triangles are the ones I'd want to pick out. I'm using marching cubes to generate the geometry

atm, I've been thinking to check if a given vertex's y position is beneath the other vertices, but that'll also include all other vertical walls' vertices and obviously doesn't help the topmost flat vertices along that edge

#

my plan is just to bake this information into the texture uvs on mesh gen

#

my guess (though it seems inefficient) is just to loop through all the triangles and check if each triangle is higher or lower than triangles that share vertices with it

gray creek
#

I'm creating a toolbar overlay. I'd like to add some additional items to its context menu below the Panel, Horizontal, and Vertical items. How do I do this? I haven't found anything in the documentation.

gray creek
slate isle
#

Can someone help me privately? Because something is not working for me

flint sage
#

Better to just ask here

terse inlet
coral citrus
#

it worked out great

#

slow for sure at large poly counts but considering I'm working with 32x32 textures, it doesn't need to be very fast

river echo
#

is there a possible way to import reference dlls in unity?

lost stag
#

how much runtime ram/storage/usage/etc overhead does a scriptable object have versus just embedding the same data in a System.Serializable class in a couple of places(the class is pretty small, only a couple of fields)? I have some relatively small inner classes I'm thinking of converting to scriptable objects so I can share them across several copies of a component (its in different prefabs so I can't just do that)

untold moth
#

You can share plain class instances by refactoring your code architecture. You can also use SerializeReference to have access to the serialized plain class without each MonoBehaviour having its own copy.

exotic furnace
#

Does anyone have extensive UGS experience?

I want to know if there is a system in the UGS that would allow me to hold Community Event data. For example, a shared 'Mission' where players do X, and it is added to the global pot of the mission. Once the pot hits a value, we'll reward all those that took part.

soft marlin
#

I haven't used UGS at all, but given the description of the Cloud Code feature, all you would really need that isn't part of UGS is just a database. then a simple web api (or whatever the could code equivalent is) should be all you need

fervent mesa
#

can you guys send me a video about making AI in video games? its really hard to make accurate AI

soft marlin
#

there isn't really a catch all "how to make AI" tutorial, since it heavily depends on the game you're making

fervent mesa
#

for example a 3d stealth shooter

#

i mean i can check ranges, alert mode etc. but it feels so fake

untold moth
ashen shard
misty glade
#

Can I implement unity messages on an abstract base class that inherits from monobehaviour? (ie, Awake())

sand vale
#

Hey y'all, I was working around with Unity ML agents, and now I was thinking to write my own models in python in lieu of the pre given ones with unity ml agents. How could I set up the communication with Unity?

From what I've read it is recommended to use gRPC? not sure how to set it up though

#

alternatively, what would be the best thing to do to accomplish my goal

ashen shard
#

(if they don't hide/overrride Awake e.t.c, unity will try to find the event methods in a base class)

misty glade
#

turns out I'm going to need to implement it on the children anyway since what I wanted to do was add a button in Awake() and then call a callback in onclicked - but the callback is set in an abstract method signature which the children need to implement anyway

#
    public abstract class PropBase : BetterMonoBehaviour, IProp
    {
        public abstract void Initialize(PropType propType, CrewType crewType, PoseType poseType, bool isLocked, Action callback);
        public abstract void Reveal();
    }

  public class CrewProp : PropBase
  {
      private Action _callback;
      private void Awake()
      {
          Button b = gameObject.AddComponent<Button>();
          b.targetGraphic = CrewImage;
          CrewImage.raycastTarget = true;
          b.onClick.AddListener(OnClicked);
      }

      public override void Initialize(... child specific shit ... , Action callback)
      {
          _callback = callback;
      }
#

basically since the children have their own clickable image.. the button needs to be added to the children, not the base

#

(i was hoping to be able to do that button init in the abstract PropBase)

#

but good to know that works.. i might still do something clever like try to find all the images (from the base) and attach the button to an onclick on that image, but that's gonna probably be a bug or confusing functionality later when i forget

timber flame
#

Have you worked with Antlr? I want to add syntax highlight to my language.

#

Is it the correct way to do it?

public override void ExitFile(DeadLangParser.FileContext context)
    {
        var currentIndex = 0;
        var builder = new StringBuilder();
        foreach (var colorTag in _tags)
        {
            builder.Append(_content[currentIndex..colorTag.StartIndex]);
            builder.Append($"<color={ToHex(colorTag.Color)}>");
            builder.Append(_content[colorTag.StartIndex..(colorTag.StopIndex + 1)]);
            builder.Append("</color>");
            currentIndex = colorTag.StopIndex + 1;
        }

        HighlightedContent = builder.ToString();
    }

tiny pewter
#

no, but have you tried it to see?
if the parser doesnt change your file context and the startIndex and stopIndex is indicating:

[<  tag start    >      )[Context)[<tag end>)
 start index     stopIndex
```ie the bound is [start index,stop index) and not point to the actual [Context), then you need to append substring from now\_tag.stopIndex to next\_tag.startIndex.
again i havent use the parser so i dont know what startIndex and stopIndex actually pointing to
timber flame
#
commonTokenStream.Fill();
var tokens= commonTokenStream.GetTokens();

I have found a better approach. It does not need to listen

hybrid belfry
#

Hi, I am looking into reading JSON. I'm using Newtonsoft Json package to do this. I'd looking for a way to effectively always find the Array of Objects without knowing the arrays name. In this example, the array name is "Export Master". Is there a way I can do this?

sly grove
#

what will it be called?

hybrid belfry
#

I'm not certain yet, it's a project in progress including things like the json files :/

sly grove
#

it's really hard to give a good answer without a solid spec of what the format of the data will be

hybrid belfry
sly grove
#

but really you should just coordinate with whoever is setting the data up

#

and agree on a format

strange bane
# river echo is there a possible way to import reference dlls in unity?

what you mean by reference dlls. you can import dlls into your project and call functions from that dll by using some specific C# api.

you can also add dlls into your .asmdef (will only work if the source code of that dll available in your project AFAIK)

https://stackoverflow.com/questions/5010957/call-function-from-dll

upbeat path
terse inlet
minor wraith
#

sorry for the vagueness hard to explain. i have a script that simulates a guns recoil (on the camera) basically lerps the current position to the target position then resets to where it started. the issue is if you move the mouse down to control the recoil, after you stop firing, even if you are not moving the mouse anymore, it will reset lower than were it started. i want it to be in the same spot you started, or just not have it reset at all but every time i try and implement either of those the screen jus go crazy start shaking after firing a few rounds. https://hastebin.com/share/vikujugara.csharp\

terse inlet
minor wraith
#

@terse inlet sorry big noob. used the fixed update for framerate independence ion know if it really matters for the situation. as for pairing += with a -= not sure what you mean by that, something along the lines of "Value += plusValue - minusValue"? or like how i have it set to increase the multiplier when firing with +=, i should decrease the multiplier after firing using -=?

terse inlet
# minor wraith <@395118955460689922> sorry big noob. used the fixed update for framerate indepe...

also note, https://hastebin.com/share/vikujugara is the link that actually works.

Gun.recoilInput += Fire;
pair your event subscriptions with a unsub. In the event that the Recoil script is destroyed, it will be kept alive in memory, since its still being referenced, and then when you click it will call the Fire code on the monobehaviour that you destroyed. Nasty stuff

Fixed Update is for updating when the physics systems run...

//here the Time.deltaTime is doing the frame independence 
currentRotation = Vector3.Lerp(currentRotation, Vector3.zero, returnSpeed * Time.deltaTime);

//here the Time.fixedDeltaTime is doing the frame independence 
        Rot = Vector3.Slerp(Rot, currentRotation, recoilSmoothing * Time.fixedDeltaTime);```
minor wraith
#

oh my bad i didnt notice that i just hit the copy url button and pasted it

minor wraith
#

@terse inlet so i put the subscriptions in an OnEnable, opposite in OnDisable. Combined the update and fixed update. stored the cameras initial position before firing, reset it after firing but it has exactly the same effect, shoot, camera rises, stop shooting, it will return exactly where it started, as long as you dont move the mouse down. it will reset to the position where you would be looking if you were not firing and just looked down if that makes sense. say im looking at the horizon and start shooting but pull down with the mouse to keep the camera pointed at the horizon, stop pulling down and stop shooting at the same time, it will reset below the horizon.

terse inlet
minor wraith
#

@terse inlet https://hastebin.com/share/ozejuyehiz line 64 i commented it out, it does not snap to the reset position, acts the same tried to get it to but idk

terse inlet
#

Set the initial rotation as well

minor wraith
minor wraith
#

ye i have no idea. not very experienced wit c# or coding in general. got the scipt minus the multiplier and some other logic from a youtube video a few weeks ago and just edited it for what i wanted. cant figure this one out tho

sick moat
#

Hey all, been fighting this for a solid 3 days now, decided it was time to ask if anyone has any insight
I've got a source generator that works great except for one particular file. No matter what I do, change the name of the file, the struct, the methods, comment them out etc, it will throw the error CS0234 for every type and namespace in the file. If I copy the contents of the generated file and paste them into an empty one in my project, the code works fine. Other generated code works fine. (The other generated code uses burst and Unity.Collections, and is in the same namespace. I've tried making the problem code a partial struct, and including an empty partial in my project. The worst thing is that the generated code was working fine until I changed the name of the struct. Then no amount of changing it back, reverting, etc is helping. I've deleted the Library folder, I've reimported all, rewritten the source generator from scratch, using a SyntaxReciever, without... the only thing I can think of is that I've been cursed. Anyone have any ideas?
(Image is a pic of some of the errors, there are plenty more)
Generated Source: https://hastebin.com/share/axebugamep.csharp
Generator : https://hastebin.com/share/cocofirula.java

sly grove
sick moat
#

this generated file has no errors whatsoever:

#

even if I comment out all the code from the problematic one, I still get
Error CS0234: The type or namespace name 'Entities' does not exist in the namespace 'Unity' (are you missing an assembly reference?)

untold moth
sick moat
#

C:\Users\inno\AppData\Local\Temp\SourceGeneratedDocuments\F4B23C4B9A85E26AA75D6C3B\TransportsSrcGen\TransportsSrcGen.NotwerkCommandGen @untold moth

untold moth
sick moat
#

I would have thought so too, it seems to be putting everything in Temp while it builds tho

untold moth
#

The source generator?

sick moat
#

the generated files

#

all the unity generated ones are in Temp also

untold moth
#

I don't know anything about source generation and your source generator in particular, but I'd assume that the final file is actually somewhere in the project.

#

This temp file could be just something for the intellisense.

sick moat
#

well that makes sense

#

because the intellisense is working perfect

untold moth
#

Unity files are often compiled into dlls or some other form, so it generates temp source code files for the ide. Not entirely sure how it works. Just something I've noticed.

sick moat
#

I think you're right, hadn't occured to me

untold moth
#

Once the file is in the project folder, unity would compile it as a part of one of the assemblies, and if the assembly has the correct references, there shouldn't be a problem.

sick moat
#

its compiling it into assembly-csharp

untold moth
sick moat
#

there arent any

#

looks like when I get this error

It doesn't compile the assembly

untold moth
#

Are these errors thrown on build?

sick moat
#

however if I comment out that part of the source generator so it just generates an empty file, it builds assembly-csharp

#

they are only thrown in unity

#

on recompile

#

I can compile manually fine

untold moth
#

When is the file generated?

#

I'd expect it to be generated somewhere before recompile starts and put in the project for unity to compile.

sick moat
#

unity does it behind the scenes

#

it runs the sourcegen as part of the build step as far as I can tell

#

if I prevent it from attempting to make that one file, it makes the rest:
the TestCommandsNetworkCommandSystem is source generated

#

its also burst compiled

untold moth
#

Aight. That's a bit beyond me. Especially without access to the project.

sick moat
#

thanks for your help πŸ™‚ at least im not gonna be looking at IDE generated files thinking they are unity generated ones πŸ™‚

sick moat
#
public void Execute(GeneratorExecutionContext context)
        {
            foreach (SyntaxTree? syntaxTree in context.Compilation.SyntaxTrees)
            {
                SemanticModel semanticModel = context.Compilation.GetSemanticModel(syntaxTree);
                IEnumerable<StructDeclarationSyntax> structDeclarations = syntaxTree.GetRoot().DescendantNodes()
                    .OfType<StructDeclarationSyntax>();

                foreach (StructDeclarationSyntax? structDeclaration in structDeclarations)
                {
                    if (semanticModel.GetDeclaredSymbol(structDeclaration) is not INamedTypeSymbol structSymbol || !structSymbol.Interfaces.Any(i => i.Name == "INotwerkSerializable")) continue;
                    string generatedCode = CreateINetworkCommand(structDeclaration, structSymbol.Name, context);
                    context.AddSource($"NetworkCommandDB.cs", SourceText.From(GenerateMapSource(), Encoding.UTF8));
                }
            }
// context.AddSource($"NetworkCommandDB.cs", SourceText.From(GenerateMapSource(), Encoding.UTF8));
        }```

Turns out when I have it inside the foreach it works, outside breaks
scenic forge
# untold moth I'd expect it to be generated somewhere before recompile starts and put in the p...

FYI source generator runs as part of the compiling step (and every key stroke in your IDE to provide instant intellisense), and the generated files do not get written to disk (unless instructed to do so), so comparing to generating via editor scripts, source generator has the major advantages that generated code are instantly available as you type and always in sync without you needing to tab back and forth between IDE and Unity editor, and generated files are completely in memory so they don't pollute version control. A big part of Unity ECS is built on top of source generator.

shadow rune
#

hey there, anyone having good hands with Poisson Disc Sampling in unity? I need help
I wanted to have a minimum amount of distance among spawned items including their coliders' size. So I tried poisson disc sampling from youtube, made a static class. But now I am confused how to use it in my project considering every object has different collider size.

#

or any other approach would be helpful πŸ™‚

tiny pewter
#

generate candidate points based on picked circle radius in traditional poisson disc sampling + next collider radius doesnt work?

shadow rune
#

How do I call the GeneratePoints in another script whenever an item is spawned?

#

considering GeneratePoints is a static list

tiny pewter
#

Whether it is a list or an array or any other collection is unimportant to the algorithm itself….

#

Just access the list and generate points based on it

shadow rune
#

can I access it dynamically? for each spawned object. So the GeneratePoints considers a different collider as per given item

tiny pewter
#

Oh mb, i see the problem why my way doesnt want since it is not poisson disc sampling, you are asking for packing circles in some area,
The only two ways i know are try and error or use physics system to push the circles

shadow rune
#

I will be more clear, I m making an endless runner. So I have coins, cars, and pickups, all have different types of colliders and sizes. So i was going through PDS and thought how would I apply it in my project

#

or any other method that can do that

tiny pewter
#

I would try to random pick a different items, and a random items previous generated, and generate points based on their radius

shadow rune
#

radius of collider?

tiny pewter
#

Yes

shadow rune
#

I will try

paper moth
#

so i tried prototyping the collision detection and ran into a problem. I can detect the nearby enemies. But how do i actually give this information back so i can do smth with it in a new job e.g. I tried using a NativeList but got errors with that. I red smth about a NativeQueue but not sure how to use it properly. Can s.o. give me a hint (and feel free to comment the code if it is e.g. not efficient or smth like that πŸ™‚ )

    private void DetectCollision()
    {
        enemyPositions = new NativeArray<float3>(transforms.length, Allocator.TempJob);

        for (int i = 0; i < enemyPositions.Length; i++)
        {
            enemyPositions[i] = transforms[i].position;
        }

        var colDetectionJob = new CollisionDetectionForEnemiesJob
        {
            _enemyPositions = enemyPositions,
            _maxDistanceToPush = maxDistanceToPush,
        };

        collisionJobHandle = colDetectionJob.Schedule(transforms);
    }

    //[BurstCompile]
    public struct CollisionDetectionForEnemiesJob : IJobParallelForTransform
    {
        [ReadOnly] public NativeArray<float3> _enemyPositions;
        public float _maxDistanceToPush;

        public void Execute(int index, TransformAccess transform)
        {
            float3 pos = transform.position;
            for (int i = 0; i < _enemyPositions.Length; i++)
            {
                if (i != index)
                {
                    float3 distance = _enemyPositions[i] - pos;
                    if ((math.lengthsq(distance) < _maxDistanceToPush))
                    {
                        Debug.Log("i detect the nearby enemies here");
                    }
                }
            }
        }
    }

    private void LateUpdate()
    {
        moveJobHandle.Complete();
        collisionJobHandle.Complete();
        enemyPositions.Dispose();
    }
scenic forge
paper moth
#

i tried a NativeList<int> to return the indices of the enemies that should be pushed

scenic forge
#

That sounds like it should work to me, though will have to see the code to know what's wrong.

#

Ah nevermind, didn't see that you are doing a parallel job, so probably multiple threads are trying to add to the same list.

paper moth
#

i will rebuild it later and will post it here

#

i think i have to use a NativeQueue<int> then?

paper moth
long ivy
#

you're going to run into performance problems with the naive way you're handling collisions though, your algorithm is n^2 so performance is going to be trashed

#

you probably want to do some sorting to avoid having to check every enemy against every other enemy

paper moth
#

but i want to get the basics running to have "something" to work with πŸ˜„

scenic forge
#

On a side note about performance, it seems like you are allocating and disposing a new array every frame, you can instead just allocate once and reuse it over and over.

paper moth
misty glade
#

I have level icons with connectors that are material based and unfold with a bit of shader trickery.

Any ideas on how to make these connectors with a dotted line? (see image)

Tiled material?

#

I kinda want to ... do the shader reveal alongside the dotted line disappearing - here's the current effect (one material & one shader) (it's kind of behind some other animations, sorry)

honest hull
#

With the raytracingaccelerationstructure addinstances(), is there a way to add instances in more than 1 submesh at a time? or does it really need to be seperate obejcts for each submesh

dusty wigeon
vocal ore
#

I need help calculating a vector in unity. Basically, I have spawnpoints off of a room prefab and I need to determine their relative offset to the center of the room. The vector should represent the shift from the backwards direction of the spawnpoint to the center of the room (which is the spawns parent). For example, if the vector found was (10, 5, 8), that would mean that the center of the room is 10 units right, 5 units up, and 8 units forward relative to the backwards direction of the spawn. The following is my very much not working method: ``` Vector3 FindShiftVector(Transform spawn)
{
// Get the position of the parent object in world space
Vector3 parentPosition = spawn.transform.parent.position;

    // Get the position of the spawn point in world space
    Vector3 spawnPosition = spawn.transform.position;

    // Calculate the vector from the spawn point to the parent object's center
    Vector3 offsetVector = parentPosition - spawnPosition;

    // Reverse the offset vector to simulate the backwards direction as forward
    Vector3 reversedOffset = -offsetVector;

    return reversedOffset;
}``` The attached image shows an example prefab, where the blue vector is the forward direction of a spawnpoint. All spawns are pointed outwards from the parent room.
#

Been trying to figure out a valid formula for this for a couple hours but I feel like I'm missing something essential to do this

sly grove
#

(also assuming everything is scaled 1,1,1)

vocal ore
sly grove
#

Move your renderers to scaled sibling objects

vocal ore
#

how do I do that?

sly grove
#

Dragging and dropping in the hierarchy?

#

Creating empty objects?

#

Make sure anything that has a child object isn't scaled

vocal ore
#

This is probably the right solution, though now I'll need to refactor a lot of code to function based on that

vocal ore
#

For example here, the x axis of this spawnpoint is aligned with the parents z axis, yielding the wrong value

stuck plinth
vocal ore
#

Basically if you rotated this 180Β° it would look the same because they have the same relative position to the center

stuck plinth
#

right, that looks like you want the center in each spawn points local space?

vocal ore
#

I guess yeah

#

Not currently at my pc so can’t test solutions yet

sly grove
vocal ore
#
    {
        Vector3 shiftVector = spawn.transform.InverseTransformPoint(spawn.transform.parent.position);
        shiftVector.x *= -1;
        shiftVector.z = -shiftVector.z - 7;
        return shiftVector;
    }```
#

Now I don't need to do a giant refactor to have all the room parent's be 1x1x1

novel plinth
vocal ore
#

Though I did remove the unnecessary transforms after realizing they weren’t needed

novel plinth
#

ah yes, you're right

#

missed the y axis yeah

vocal ore
#

This is now fully dynamic though. It is able to intepret the roomPrefab to figure out how to rotate and shift it so that it fits without overlap or awkward placement

#

Makes it way more future proof than my previous solution of manually assigning shift values to every spawnpoints

cinder dirge
#

hi guys

#

how to add a new entry into LocalizationTable using script ?

hardy jacinth
#

can I check (inside editor!) if there are more than one references to an asset from game object?

#

across multiple, possibly not loaded scenes etc

#

in the whole project

#

assuming I don't bother checking this at runtime anymore, only in editor

long ivy
gusty stirrup
#

Hey guys! Does anyone know how to prevent my parrelsynced unity project (clone) from connecting to oculus quest link, this overwrites the main connecting to the VR device one and bugs it out. I was looking into blocking a specific application instance from accessing the network but couldn't find anything (only .exe specific using the firewall)

hollow hull
#

Hello, could you guys perhaps help me with setting up unit testing?
All sources I find online are telling me that I need to create an assembly definition for my scripts and it should be as simple as creating a file in my Scripts folder.
However, when I do this, my project cannot build anymore as my scripts no longer have access to TextMeshPro or any package I have downloaded for that matter.
What would be the proper way to set things up?

devout hare
#

It's unfortunately not quite as simple as that. You'll have to then reference other assemblies the code uses, like TMP

stuck plinth
hollow hull
#

I'm still getting errors such as The type or namespace name 'TextMeshProUGUI' could not be found

#

not to mention the other packages, some of which don't event have assemblies I could reference

#

so I feel like there is something I'm missing here

devout hare
#

If you put the assembly definition to the root folder it's bound to create problems. Usually you'd divide the scripts into smaller groups with assemblies, which usually takes some time and care if you do it afterwards in an existing codebase

hollow hull
devout hare
#

Maybe look up resources that are specifically about making assemblies

hardy jacinth
flint wraith
hollow hull
flint wraith
#

Created new Assembly definition just to test it out if it works. It works but corrupted my library folder 🀦

hollow hull
#

πŸ˜† yeah I'm playing around with it a bit more and some times it does work, it seems to be pretty hit and miss tho

fiery vine
#

I'm loading in a TTF font and creating a TMP font asset out of it at runtime.
In screen space, it works fine, shows fine.
If I move that canvas to a World-Space canvas, it is invisible.

I imagine it might have something to do with it using the Mobile/Distance Field material, but I'm unsure of what I should be using instead.

This only happens with my runtime-generated fonts, not the prebuilt ones

Edit: It was a material issue. The default material Mobile/Distance Field didn't show, but Distance Field SSD did

misty glade
#

For UI objects that I want to scale proportionately to the parent but aren't anchored (stretched) to the exact dimensions, I find I'm needing to calculate the anchors manually, which is tedious. For example, if something is a square 150x150 somewhere in a 750x750 object, then I set the 150x150 to stretch, then divide all the left/right/top/bot pixels by 750x750 so that the item underneath keeps both the proportion and position to the parent.

I'd like to create an editor extension for this (even just as simple as a button in the RectTransform component that does the calculations) but .. don't know if it's possible to override/extend OnGui for unity components. Is it? How could I keep the existing functionality of the inspector component and add my own code to it (without needing to manually add a script component to any object I want to do this calculation for)?

#

Example: I have this thing called an EpisodeCoverImage - it appears in a few different sizes through the app, but the components within need to scale.. it looks like this (images) - note how the "Episode 2" text stays right in place, but also the background image is .. where you'd expect (it's not actually anchored to the top/left/right - there's a few pixels of buffer)

plucky laurel
#

you can add context menu

misty glade
#

This is what my RT looks like for that background image - left/top/right/bot are 0 but the anchors are (tediously, painstakingly) calculated by me

#

context menu to RT?

plucky laurel
#

three dots

#

UnityEngine.ContextMenu attr

misty glade
#

so it'd appear here?

#

i'll google that, thanks

plucky laurel
#

yes

misty glade
#

K, nearly working but I'm having trouble untangling which properties of RectTransform are calculated. When I see the anchorMin and anchorMax, it's changing the sizeDelta (which I want to keep constant). When I save and then set the sizeDelta after the calculation, it's making it .. larger. How can I set the anchor min/max (in script) without it changing the sizedelta? Code here: https://pastebin.com/9yFWJ9Z5 (yes, it's super verbose, just wanted to make sure I knew which data points are which as I go)

#

Oh, wait, I got it working - sizedelta is relative to the anchors.. so just setting it to Vector2.zero fixed it right now

craggy spear
#

you create an image in a weird way .. why wouldn't you just do: right mouse -> ui -> image?

woven meteor
#

Hello I want to make a game in Unity for creating other games. I know is possible in Godot because I am switching to Unity. Is possible to pack a scene and run in separate game as quickplay feature? If it's, how to do that?

upbeat path
upbeat path
#

Great, I still dont understand why you would want to use a game engine to implement a game engine

tall ferry
woven meteor
#

Oh, It's for a client he don't know coding but want to do some 2d rts

wicked verge
#

a game engine in a game engine to make games in that game engine engine seems like a pretty cool project

upbeat path
woven meteor
#

the problem is it will have thousands of Units and I am considering switching to Unity ECS , I have heard support them...

#

the project has two parts the 'Tool' and the 'Game', when you click QuickPLay it runs the Game

woven meteor
tall ferry
woven meteor
#

And some properties like health etc

woven meteor
#

I guess the scene has to be compiled...

tall ferry
woven meteor
#

He wants a standalone exe for the final user

#

...without the tool

tall ferry
#

That part is out of my expertise, maybe someone else knows how you could. My closest suggestion would be 2 programs, 1 for him as an editor to make levels (however you choose to save the level data). Then a 2nd for the final user, which they can download the created levels into.

woven meteor
#

Hmm, good idea, like a level editor...

#

BTW, how many units will support Unity ECS?

tall ferry
#

The only real issue would be how you could get users to even download levels. If this is something on steam, there is the steam workshop. Otherwise you'll need to host it somewhere

tall ferry
woven meteor
#

don't worry the 'tool' is just for personal use

half swan
woven meteor
#

and if I do multiplayer ECS how many?

half swan
tall ferry
#

Multiplayer limits can be a lot different but that's stuff like bandwidth

#

Or just a user limit of their internet

woven meteor
#

what you recommend for multiplayer with ECS? Photon or netcode or other?

upbeat path
woven meteor
upbeat path
woven meteor
untold moth
knotty obsidian
#

I did hit a rate limit, I was indeed deleting players one by one because I didn't find a batch endpoint. Apparently there is NO way to batch remove players

candid hare
#

WHY DOES ANY UNITY METHODS like awake, update MAY STOP WORKING ON ALL UNITY EDITOR VERSIONS?

#

ahem

brisk pasture
#

also giving no details of what you changed and what you tried does not help

half swan
#

They crossposted to all coding channels

plush hare
#

Has anyone tested how far you can get from the origin before things really start breaking?

half swan
#

Haven't tested it myself

plush hare
half swan
#

Editor will give you a warning at that point iirc

#

I think I worded it poorly. 100k will break it I mean

plush hare
#

You can't move static objects during runtime, but you can move their parents. Is there any penalty for doing this?

#

For doing something like an origin shift

untold moth
#

Like static batching? That would either not move them or cause unity to regenerate the static batch.

dusty wigeon
cursive perch
#

I have an optmization question if anyone has experience. If i have a 2d platformer level editor, and I would need to instantiate about 20000 prefabs, each with their own colliders/ spriterenders / saved info, what are some ways can I optimize the loading of the scene? Currently have a list of prefabs in the class, then instantiating them based off their information saved in a JSON. JSON is around 3.5MB

novel plinth
#

thats a heck lot for 2d game

#

pool them instead?

cursive perch
#

i will look into it, but I would still have to instantiate all the objects regardless no? i thought pooling was only useful if you were destroying objects

tall ferry
novel plinth
#

20000 is insanely a lot for 2d game just saying

cursive perch
cursive perch
#

only problem is loading the level. Once the level is loaded the frames go back to normal

tall ferry
#

that is a lot of GC but its not the main problem

cursive perch
#

i agree

novel plinth
#

Geometry dash uses 4000 objects iirc

#

and they all instanced

#

meaning it can be just 1 - 2 drawcalls

cursive perch
#

yeah

#

so maybe a script where it only loads the closest 4000 objects to player? then just have the rest loading async in the background

novel plinth
#

thousands of objects at once need special treatment if you don't want your game run like turtle

tall ferry
#

where did async come into this? just use object pooling and release objects as they are far away. Get objects as they are nearby

cursive perch
#

okay, i will try. thanks for the help

solid basin
#

sorry for the late reply! didn't see your message no ping πŸ˜”

#

It seems as though it uses some macros not defined just in SRP? Or where can I get them - e.g just trying to pull in Blit.hlsl in an empty test shader:

#

Error here:

#

Is this an unintended issue with Unity? Or does SRP have non-SRP dependencies?

#

It's actually the case with a bunch of these macros in here --- More than just the top-level includes seem to be required

bleak citrus
#

It looks like you're intended to define TEXTURE2D_X to expand to either TEXTURE2D_ARRAY (in XR contexts) or TEXTURE2D (for non-XR rendering). Both the URP and HDRP packages include code that's roughly

#
#if defined(USE_TEXTURE2D_X_AS_ARRAY)
  // define a bunch of A_X_B things as A_ARRAY_B
#else
  // define a bunch of A_X_B things as A_B
#

that's in ShaderLibrary/TextureXR.hlsl for the HDRP

spring tulip
#

Hey, I have a problem with performance, so I got a game object that has around 500 children (child inside child etc.) everything works fine, layers are set so those children dont have any collision with anything other, game is working good but problem occurs when Im moving this object, it causes massive lag, when I do it in update (every frame) it makes game unplayable, is there any other way to animate this object and those children without making that huge lag?

#

its important it doesnt lag on regular play, only when updating position every frame

sly grove
#

Why do they all need to be children of this thing?

spring tulip
sly grove
#

For performance concerns you should use the profiler to see the problem but it seems obvious that it's related to Unity having to update the positions/rotations/etc of the whole Transform Hierarchy tree here

spring tulip
#

im trying to find any way to fix it without removing those children

sly grove
#

merge all the meshes into one object

spring tulip
#

i cant

#

those are individual bolts

sly grove
#

Why can't you merge them?

novel plinth
#

those gameobjects moving + rotating at the same time ?

spring tulip
#

each with own script and own logic

#

Im not that stupid trust me if it would be possible I would write script to merge all meshes on game start

#

but it wont work in this case

novel plinth
#

those bolts moving and rotating at the same time?

spring tulip
#

no

#

but player can look at this bolt and unscrew it any time

sly grove
#

You might have do a complex optimization like merging all the meshes and then when the player interacts with a particular submesh, you instantiate a GameObject to represent that particular submesh or something along those lines.

#

First step of course would be profiling

spring tulip
#

is it possible to detect which submesh was collided?

#

i mean in ray

sly grove
#

yes

#

you can get the triangle index which then can be used to find the submesh

spring tulip
#

hmm Ill take a look into that

sly grove
#

it's not for the faint of heart πŸ˜΅β€πŸ’«

spring tulip
#

first im writing box collider optimizer, later today Ill take a look into that

#

I already have BoltManager which controls all bolts on spcific object so it will be easy to do I think

sly grove
spring tulip
#

I know when I deleted these children it doesnt lag anymore so thats probably the reason

sly grove
spring tulip
#

oh yeah I did use it

#

it shows PhysicsUpdate

#

as 90ms per frame

sly grove
#

ahhh i thought it might be this

#

do you need physics to update?

spring tulip
#

no I dont

#

i was looking for some function to change position without updating physics but didnt find anything

sly grove
#

What if you did:

Physics.simulationMode = SimulationMode.Script;```
#

then moved it

#

then reset simulation mode

spring tulip
#

hmm wait Ill give it a try

#

still the same

#

Ill do some optimizations and later let you know how it went

sly grove
#

is this an instant movement

#

or like

#

a movement over time?

#

I was saying do the whole movement then turn physics sim back on

spring tulip
#

its in render

spring tulip
sly grove
#

this simulationmode thing won't do anything unless it stays on Script through the FixedUpdate cycle

sly grove
#

(I don't know what you're actually doing)

#

you turn off physics sim when you start dragging.
Do all the dragging
Then turn it back on

#

so you skip all those frames of physics simulation

spring tulip
#

oh so I cant do it like this

#

I need physics to be there all the time

spring tulip
#

something is working

spring tulip
#

heres code for box collision optimization

#

if anyone needs

#

example use:

#

on start it will automatically make them components instead of children

flint mica
#

i've got a mobile game that runs in portrait mode and i've noticed that when the touch keyboard appears, it pushes the unity game canvas upwards. i'm using TMP_InputField for the text field and this happens on both ios and android. is there a way to keep the unity game canvas fixed in place when the keyboard appears?

in other words i want the phone's keyboard to just cover the bottom part of the game, instead of pushing the entire game canvas upwards to make room for it.

raven flicker
#

Alright so I have a 2D map with nodes and pathfinding all working off a single graph. The map can be modified at run time so modifications update the graph locally when this happens. The graph is used by 5 different factions. Recently I've added doors and the ability for each faction to lock them. With regards to enemy factions, they consider the door a higher path cost but still pathable, and their AI routine will check for doors and cause them to attack/destroy them if they are trying to path through one. But for same-faction doors I'd like the door spot to be unpathable entirely. It isn't clear what the best approach to resolve this might be. Give each faction its own pathfinding graph? Or am I missing something obvious?

bleak citrus
#

what algorithm are you using?

raven flicker
#

I'm using A* via the arongranberg.com asset. Its a grid graph with weighted values, and each AI actor generates a path and then updates it about every 250ms. Walking from node to node. I've expanded its path modifying function to remove redundant nodes and add some noise for more realistic walking paths. Its not too different from my own, prior implementation of A*, just much much more performant.

#

The thing is there might be a valid path adjacent to the door, and I'd be afraid they'd stop at the door and not use the available path as a result.

#

I'd rather the path fail entirely if the door is closed so they can take the happiness hit and complain about it, if that makes sense.

bleak citrus
#

A faction-aligned locked door should make the entity not even add the grid cell on the other side to the "unvisited" set

#

That will make the entity behave exactly as if there was no path at all there

raven flicker
#

I'm not sure I understand? The door might be used by the player to restrict movement within his own territory.

#

ie, you might wish to separate one group of NPCs on one side, and another on the other.

#

Luckily I can make doors occupy entire tiles so I don't need a casted graph or anything. I can still work just on the grids.

bleak citrus
raven flicker
#

Ok so that requires a graph for each faction, yeah?

bleak citrus
#

I guess this depends on how much control you get over the A* process

#

I use A* for goal-oriented action planning. It's basically pathfinding over world-states, where the edges are actions the entity can perform

#

This is an infinite search-space, so it would be a very bad idea to start with a list of every possible world-state

#

It starts with just the current state, and new states are added to the unvisited set as they're discovered

#

A* does not require you to know all of the nodes and edges from the start.

raven flicker
#

Yeah, I think in this case I want the node searching to operate on a different calculation/mechanic depending on a starting parameter.

bleak citrus
#

I am not familiar with the asset.

raven flicker
#

There is a graph object that populates based on a dataset you provide it. Each node in the graph can be weighted.

#

Its possible there is some additional flexibility but I'm still learnin the ins and outs.

#

Something you said did make me think a bit though.

#

If I gave the door a high weighting it would probably allow actors to find any obvious open pathing routes.

bleak citrus
#

Yes, that alone will make it very likely they'll go another way.

raven flicker
#

And I may be able to just interrupt their trying to go through a locked door and handle it. Which honestly may be better for feedback.

#

Having an NPC on one side of the city complaining about "NO PATH" isn't as helpful as a bunch of NPCs bunching up behind the locked door.

#

Did you write your own A* algroithm?

bleak citrus
#

Yeah, it's pretty simple at its core

#

although I'm currently not using a priority queue, which is sub-optimal lol

#

i should fix that

raven flicker
#

:nod:

#

This asset heavily leverages threading and burst so that's been a nice performance boost vs my own implementation.

#

I still use my old algorithm alongside it for simple things.

bleak citrus
raven flicker
#

From what I can tell when a path is kicked off, the threading allows it to occur over multiple frames. But if the graph is modified during that time, it will reset the operation.

#

And you can define custom rules for the graph generation.

#

In any case, if performance is adequate I'd never recommend a change :p

novel plinth
#

reason it's so fast, simply bcos it's so simple... similar case like why linear interpolation is fastest among anything else 😌

raven flicker
#

yeah, with Fen I was just curious what other features his action planning system might have needed.

#

I'm finding that pathfinding is a whole lot more complicated than just gimme point A to point B quickly, heh.

dusty wigeon
raven flicker
#

Sure, I totally understand that.

#

I was just curious if he repurposed an asset, or wrote his own and what additional features it may have required.

#

My need is Pathfinding based and so my questions were pertaining that that...

#

The math needed to support filtered node traversal are coming up too heavy, and I can't think of a way to simplify that in a meaningful manner. Who says math degrees aren't useful haha... and I am leaning towards giving each faction their own pathfinding graph also too heavy. Instead, I am considering having doors cut the graph for all factions. I'll keep a list of all the doors and when enemy factions wish to raid, they'll pathfind to the closest door instead of what it does at present, where they pathfinding directly to the capture point and attack any doors they find in their way.

dusty wigeon
raven flicker
#

I want each AI entity to have its own weighted node list in essence based on its type. But that results in very heavy calculations as with a dynamically changing map it must change for each actor on each update.

#

Its the typical problem of all the hard things on a limited performance device. So, trying to make concessions and simplify the original problem down.

dusty wigeon
#

Why ?

#

I mean, you simply need to weight your graph ?

#

Why is it heavy ?

raven flicker
#

Faction A might use one weighted graph and Faction B would use another. I'm trying to avoid maintaining multiple graphs.

#

Maybe I should start from the top...

dusty wigeon
#

Why would you avoid that ?

#

It is only memory

raven flicker
#

Updating 5 graphs of a 96x96 tilemap when updated in a real time game is too heavy for an older android device is why. At least with my capabilities as an engineer.

#

Give me a few years of improving my math skills and I'm sure I'd be up for it :p

dusty wigeon
#

What do you mean upgrade a graph

#

How do you "update a graph". A* does not have the concept of updating a graph..

raven flicker
#

Let's continue this in DMs so I can go into more detail and share images if need by.

dusty wigeon
#

No, DMs. If you want you can make a thread

raven flicker
#

Oh, huh ok. No DMs then.

#

Any particular reason why? Just curious.

dusty wigeon
#

Because, I'm not befriending people

raven flicker
#

Oh. I always forget Discord changed how that works a little while back.

#

I had thousands of player-friends with another game I developed for so just got de-sensitized to it.

#

Anyways, I have 2 pathfinding cores in my design. One is a routine written by myself that operates on a weighted grid of values representing the tile map. The other uses the A* Pathfinding Project asset with a grid graph it generates from the tilemap itself. It is exceptionally optimized, multi-threaded, Jobs system, etc. I want to focus on my game and not reinvent the wheel on pathfinding and it generally does what I need it to. But i've run into a hiccup trying to support doors. With 5 factions, each could potentially place a door that needs to block pathfinding just for their own faction. Enemy factions will find a path through the door, but engage when they get close so it doesn't matter that it doesn't technically block them.

#

My own routines have weighting. But I can only at present support one weight per tile. I'd need to expand that to at least 5 for the 5 factions. And its much slower for long runs on the tileset. The A*PP can support tags, but not performantly for unwalkable instances. They are intended for weighting traversal.

dusty wigeon
#

Is it tilebase ?

raven flicker
#

In discussing this though, I think I have come across a way to simplify the original problem so I don't need to modify anything.

#

I have a 96x96 list of tile objects representing the map, that gets turned into the Tilemap on the screen. If that answers your question?

dusty wigeon
#

Is people walking directly on tile or not ?

raven flicker
#

It is a real time strategy game so they can walk anywhere within a tile.

dusty wigeon
raven flicker
#

The paths are in that manner, yes.

#

Once I have a tile center-to-center path to the target, I filter the node list and apply a stochastic noise to make it look more realistic.

dusty wigeon
#

Then you can easily implement your own solution.

#

It really is easy to implement A* on such scenario.

#

Usually, what makes it hard is the generation of surfaces, but as I understand you do not need that.

#

So, if your asset requires you to build a Graph and the Graph is to slow, ditch the asset because you do not need to build a graph.

raven flicker
#

Hmm. Perhaps managing 5 graphs wouldn't be a bad approach.

#

I might have too quickly dismissed that.

#

Presumably the host is selecting the map here, and will load the scene which then allows others to join?

#

SceneManager.LoadScene(2); is generally the call to load a scene by index.

#

In my game I created a scroll collection to display all the levels contained in a directory.

#

To clarify, each level is its own unique scene and everything is contained within it?

#

I have to ask, because in my game I only have 1 game scene and when it loads it sets it up for the specific map.

#

You'll need to do some learning about the various UI controls and how to effectively use them, if you don't already. Here is what my main menu looks like with all the elements turned on -

#

So I have one set of buttons for what the player wants to do, and that opens secondary UIs

#

The save/load is separate from the level selection / editing.

#

I have a scroll list control that gets populated from what is read off the disk

#

In this case you don't need to go to the disk, because presumably all the scenes are in the project.

#

So I'd get familiar with a scroll control and how to add things to it if you aren't already. Or decide on what control type you want to list all the levels you could select. My targeted platform is mobile so its largely using big buttons. For a PC thing you could get away with something more minimalist.

#

You'll display everything that the player could load, and then in the button trigger it would call SceneManager.LoadScene(IndexNumber) where IndexNumber is the index of whatever level element in the control they had specified, for example.

#

Does that make sense? If you need help with how to create a .cs file with the button trigger, and adding it to the button, then its probably not the right place here in code-advanced.

#

Ok in that example I don't see where the user would specify the scene to open. I'm not familiar with the multiplayer asset you are using to know how it intends you to select a scene prior to someone joining the map.

#

Usually MP games have the host pick the level in the lobby, or prior to creating the lobby.

#

Do you have any game scenes actually created at the moment?

#

With maps, and enemies, and all that stuff.

#

Well, I'd add something unique to each so you'll actually know if/when they load successfully.

#

But you'll need to add a control to display the levels for selection.

#

As I described previously.

#

Edit the CreateRoom screen to have a place to select the scene you'll be loading for the level sort of thing.

#

I can't walk you through the entire process. There does seem to be good tutorials on using the UI and hooking all of that up properly. Then you'll just loop through the scenes in the SceneManager object to list them, have the player select them, load them, and proceed.

#

Hope it helps! Multiplayer is still a ways off for me to get into haha...

delicate mural
#

Quaternion wizards.... I summon you
This simple line of code is what I'm using for 2 handed grab in VR

#
                Vector3 handsDirection = hand2.position - hand1.position;
                transform.rotation = Quaternion.LookRotation(handsDirection);```
#

See how it only flips when the gun is facing directly towards you?

#

The flipping is based on one of the main (right) controller's rotation

#

I dunno how to do that

#

Please, this is day 4 i'm on this

regal lava
#

common problem in fps games and usually why they lock your x rotation to 89 degrees

#

it does look like gimbal though, and usually how I get around it is by using angle axis and being discreet on the ordering.

#

Not 100% sure how that all works with VR though

#

probably related

delicate mural
#

This issue isn't exclusive to VR realy, I just need to know how to rotate an object in a way that it faces a direction (the vector between the hands) and have the "flipping point" somewhere at the back where the gun is unlikely to face

regal lava
#

Well, refer to the post as it sounds similar to your problem

delicate mural
#

but I tried every combination and it either freaks out or doesn't do the right thing

#

(i.e. setting it to be the back vector of the hand does not work at all)

regal lava
#

AngleAxis you'd define different up axis depending on your rotation, so usually I'd do it for all axis

delicate mural
#

Okay, what would that up axis be though? It still has to be up if you want horizontal rotation, or right for vertical rotation

#

Could you help me with the code? Still not sure how using angleaxis solves the gimbal issue

regal lava
#
public static Quaternion AnglesToRotation(Vector3 angles)
{
    Quaternion rot = Quaternion.identity;

    rot *= Quaternion.AngleAxis(angles.z, Vector3.forward);
    rot *= Quaternion.AngleAxis(angles.y, Vector3.up);
    rot *= Quaternion.AngleAxis(angles.x, Vector3.right);

    return rot;
}

I use this for my particle controller, but beyond that I've not really tested it out on any other types of controllers

#

usually you would just do the y into x rotation for a fps I believe

#

but this solved a lot of issues I was having with other methods, primarily stuff like eulers

regal olive
# delicate mural ```cs Vector3 handsDirection = hand2.position - hand1.position; ...

Like I said before, there are infinitely many orientations that "look at something". The method is doing what it says it does, it's looking in the direction you want. That's not really enough information to define a specific orientation

Part of this is a design problem. I don't even know how I would go about it because there's behaviour that idek how I'd define. Like if you twist a controller one way, and twist the other controller the opposite way, which way does the gun rotate? The rigidity of a gun would prevent you from doing this in real life, but that constraint doesn't exist on VR controllers so idek philosophically what it should do.

delicate mural
#

@regal olive @regal lava This code worked wonderfully. I figured it out.

                Vector3 handsDirection = hand2.position - hand1.position;
                transform.rotation = Quaternion.LookRotation(handsDirection, Vector3.Cross(handsDirection, hand1.right));```
#

So long as you keep your wrist pointed in the right direction, it doesn't flip

regal lava
#

Aye nicee

novel plinth
rugged radish
#

I'm trying to come up with an algorithm to smooth transitions between voronoi diagram regions
and thought maybe there's a known algorithm that would help here ? because the idea I came up didn't work
my idea was to determine a surface point's (a) triangle (ABC) in the delaunoy triangulation, then use a curve function to evaluate the height at a' and same curve function to evaluate height at a
but it produced asymmetric results - surfaces of ABC, BCA and CAB diverge

spring tulip
#

hey im combining meshes but faces are missing - original mesh (screenshot 1) combined mesh (screenshot 2)

#

and no - faces are not flipped

#
private void UpdateBoltsMesh()
{
    GameObject boltPrefab = Resources.Load<GameObject>("Prefabs/bolt");
    Mesh boltMesh = boltPrefab.GetComponent<MeshFilter>().sharedMesh;

    CombineInstance[] combineInstances = new CombineInstance[bolts.Count];

    for (int i = 0; i < bolts.Count; i++)
    {
        combineInstances[i].mesh = boltMesh;
        combineInstances[i].transform = Matrix4x4.TRS(bolts[i].position, bolts[i].rotation, Vector3.one);
    }

    Mesh combinedMesh = new Mesh();
    combinedMesh.CombineMeshes(combineInstances);
    print(combinedMesh.vertexCount);

    if (boltsObject == null)
    {
        boltsObject = new GameObject("Bolts");
        boltsObject.transform.parent = parent.transform;
        boltsObject.transform.localPosition = Vector3.zero;
        boltsObject.transform.localRotation = Quaternion.identity;
        boltsObject.transform.localScale = Vector3.one;

        boltsObject.AddComponent<MeshFilter>();
        boltsObject.AddComponent<MeshRenderer>();
    }

    MeshFilter meshFilter = boltsObject.GetComponent<MeshFilter>();
    if (meshFilter == null) return;

    meshFilter.sharedMesh = combinedMesh;
}```
#

heres code, any idea?

#

I found those are 2 different materials, probably thats the problem

lofty solstice
#

Anyone know how to reference the UnityEngine.UIElementsModule.amsdef?

austere jewel
lofty solstice
#

Is there any other way then that you know to hack into/get access to internal classes inside UIElements?

austere jewel
#

Find another assembly that has access to it

lofty solstice
#

hacing some certified private/internal moments rn crycat

lofty solstice
austere jewel
lofty solstice
#

ill take a look thanks!

lofty solstice
novel plinth
#

yeah don't do reflection in unity ever esp on runtime

upbeat path
#

why not? Even Unity uses it internally

lofty solstice
#

reflection is fine in editor just sucks

novel plinth
upbeat path
#

so what, I would expect a certain level of competence if you are even considering using it

novel plinth
#

okay I'll change my statement then, "it's up to you" πŸ˜„

wicked verge
#

apparently they are changing to CoreCLR soon

novel plinth
#

by soon you mean 3 more years? πŸ˜„

lofty solstice
#

lol

austere jewel
#

Don't cross-post

upbeat path
#

maybe Unity 7000 which is in 4976 years by my calculation

rain sandal
austere jewel
lofty solstice
#

@austere jewel found a work around thanks to your pointer, thank you! It's still not great, but maybe workable... if only Unity had made some of their private fields protected :/

austere jewel
#

Yeah, it sucks at times. But at least the asmref hack avoids reflection for many things

lofty solstice
#

yes, which I am very thankful for not having to do πŸ™Œ better than nothing, just to hoping Unity starts to expose some of their cool internal stuff sometime

rain sandal
#

what does this error mean?

upbeat path
sly grove
# rain sandal what does this error mean?

You told the computer something like "damage the enemy" but without properly telling it which enemy to damage. Your reference to the enemy is null (just an example)

rain sandal
sly grove
tired fog
#

I just found this process sometimes taking an absurd amount of time 15ms, does anyone know what could be the reason?

#

This is the code that schedules the job

IGive<HeightData> warperX = WarpX as IGive<HeightData>;
HeightData xData = warperX.RequestData(globalArray, terrain, mesh, dependancy);

IGive<HeightData> warperY = WarpY as IGive<HeightData>;
HeightData yData = warperY.RequestData(globalArray, terrain, mesh, dependancy);

JobHandle onceFinished = JobHandle.CombineDependencies(xData.jobHandle, yData.jobHandle);

        NativeArray<Vertex4> vertices = mesh.meshPoints.Reinterpret<Vertex4>(Vertex.size);
int verticesLenght = vertices.Length;

NoiseSettings settings = getsettings();
        HeightData data = new HeightData{
            jobHandle = WarpedNoiseJob.ScheduleParallel(vertices, globalArray, settings, terrain.Position, 
        warperX.noiseID*verticesLenght, warperY.noiseID*verticesLenght, noiseID*verticesLenght, 
        mesh.settings.Seed+noiseID, mesh.settings.Resolution, onceFinished)
        };
tired fog
#

yes

slender ermine
#

can anyone DM me the rundown of procedural animation? i know its something todo with raycasting

sly grove
fallow dune
#

I think I am trying to do some voo doo magic here. I might need to go sacrifice a goat or something, however !!!! I am using Fmod Studio. Now I want to add my EventReferences to a scriptalbeObject. Easy right? But I want to add them in such a way that I can add more later and simply call them based on their name. I am trying to avoid strings because of Typs and I am instead trying to build something that will allow me to access them like a method.

FmodEventsScriptableObject.PlayFootstpesReference or FmodEventsScriptableObject.PlayOpenDoorCreek.

And still have all of this serializable.

#

Currently they are a mono class and is attached to a gameObject

sly grove
fallow dune
sly grove
#

yes

#

Code generation is really the only way you're going to get true compile time safety here.

fallow dune
#

Hmmm, any leads I can follow for this ?

sly grove
#

you'd basically scan the project for SOs of that type and generate identifiers that refer to them in the generated code.

#

This way you can type like BobEventReference for the SO named "Bob" by generating that name

#

and it will be compile time checked

#

Honestly I doubt it's worth the effort but it could be if you have a lot of these things.

fallow dune
#

Ya looking at this makes me thinkg it's just easier to have a mono class..

fallow dune
#

would be amazing if I could serialize non mono classes though

#

problem would also be solved

sly grove
#

you can serialize non monobehaviours

fallow dune
#

I tried but I don't see the class fields popping up in the inspector

sly grove
#
[Serializable]
public class MySerializableObject {
  [SerializeField] int mySerializedField;
}
fallow dune
#

ohhh I don't have the field part

sly grove
#

did you follow the rules of the serializer?

fallow dune
#

ah

#

isn't static!

sly grove
#

indeed

fallow dune
#

do I still need the [SerializeField] though?

#

if the entire class is serialized ?

sly grove
#

Please refer back to the rules linked above

fallow dune
#

Got ya, These are just audio references to none will be private .

#

Thanks for your help

#

no sacrificing a goat today!

regal olive
#

how do i make a physics based grab system ps im asking for a reason

half swan
#

Do you have the required using statement?

#

Also, this is not an advanced issue

#

I don't see how that answers my question. But alright.
Try UI.Navigation. perheps it is ambiguous.

"Not working" is simply too vague to really answer. Do you have errors? Is it just null? What?

jolly storm
teal radish
#

Hello guys! I have a question, is anyone familiar with ChatGPT API calls from unity, i want to make a text chat input system where i can ask questions and the AI responds in more realistic ways then predefined scriptable responses using information keys.

tiny pewter
#

Call api from unity are no special from calling from other C# app, defined the c# class and request the data and checking if the stream end

teal radish
olive cipher
#

Hey, asked this yesterday in code-general but nobody had an answer so I though of taking it here:

Hey, im using a roslyn code generator to generate this sample class right here:

using UnityEngine;

namespace EntityFramework {
    public class ComponentList {
        public static void Main() {
            Debug.Log("");
        }
    }
}```

Whenever i generate it though it gives me this: https://img.sidia.net/ZEyI5/DOyUwaCa97.png/raw (Show references: https://img.sidia.net/ZEyI5/nozaRopu17.png/raw)

There is only one file, if I modify it by hand it is the same regardless of what reference i follow

This is the code generator: https://gdl.space/tozaqozoke.cs
scenic forge
olive cipher
#

Man how did i not find this, i scoured google and the unity forum for hours yesterday

#

thanks

olive cipher
# scenic forge https://forum.unity.com/threads/source-generator-generates-code-multiple-times.1...

After I implemented this the ComponentList was not generated at all, so I investigated, my ISyntaxReceiver threw in error which was not shown anywhere (cause unity just swallows code generator errors), I now output errors with a context.ReportDiagnostic + try/catch and found out why i dont get a generation cycle for Assembly-CSharp, fixed the error and now everything works as expected!

So thanks for the thread, helped me find my error!

split bane
#

hi people, someone knows how to save temporal data for a quiz navigation with different kind of questions and options and back to previous answer in the same panel 2D, unity 3D 2022. I was looking for a JSON file, scriptable objects and just variables in my class

compact ingot
split bane
compact ingot
split bane
#

ok ty

craggy kettle
#

When creating a desktop game is the final binary produced native or .NET?

thin mesa
dapper cave
#

what's the behavior of Handles in a DrawGizmos? seems different than Gizmos.Draw* in that it only draws one instead of all 3 bones:

#

see how the Gizmos.DrawCube draws all of them but the Handles.DrawWire only draws the first one?

delicate mural
#

Hello friends

#

So I am making an interaction system for VR

#

And I can't quite figure out two hand grabs

#

I have the code for it, it's done, but structuring how everything works has been challenging.

#

The way it is right now is an object can have multiple GrabInteractable scripts on it, you can link one to another through another GrabInteractable field called main in the inspector. This will make it act as a "secondary" grab point

#

Now I already don't like how that works, but this results in chaotic two hand grab logic where the secondary interactable (the one with the main assigned) will have to do it FROM THE PERSPECTIVE of being the main interactable. Everything it references must be kind of inverted (I haven't even got it to work yet)

#

Now I really really don't like that

#

Additionally, even simple stuff like managing the rigidbody is really weird. Since the main interactable has no knowledge of its secondaries, therefore it can't know whether the object is still being grabbed by another hand upon release, making the rigidbody kinematic upon grabbing has to be done from the hands outside of the whole script. That totally breaks the encapsulation of this and is really finnickey

#

Can someone help me with this?

dapper cave
#

(wtf)

delicate mural
#

This isn't a VR exclusive issue, more about how you should structure an interaction system

#

Everyone there probably uses those interaction toolkits anyway and has never coded one themselves >:(

dapper cave
delicate mural
#

I just thought I would get better answers from a more C# focused channel. I'll move there. Thanks.

dapper cave
cerulean wasp
#

Let’s say I need to make a server for my game that just mostly saves a set of json files + metadata for each user account, and allows my game to query the files on the server.
Is this simple or very difficult?

#

imagine a game where you upload/download user-made content, and of course all the overhead that comes with it

steady stirrup
scenic forge
#

Authentication would be the most annoying part, the others are pretty trivial stuffs.

steady stirrup
#

For me it would be the deployment stuff I think

craggy kettle
#

Does anyone use Themida on their game?

cerulean wasp
#

but i’ve never made anything like this, so i have no idea wtf i’m getting myself into

native beacon
craggy kettle
native beacon
#

Ah, ok. Haven't used that.

limpid hull
#

Hi there I'm standing to get quite annoyed regarding some compatibility issues.

Using Unity 2021.3.35f1 in the net standard 2.1 compatibility mode (given the managed folder contains the type forwarding netstandard.dll 2.1.0.0 assembly)
Appears to be unable to properly use System.Collections.Immutable because the nuget package only has a version targeting net standard 2.0 available.
net standard expects nerver versions to be backwards compatible
but an assembly targeting this version expects to have a System.Memory.dll implementing System.Span however net standard 2.1 has System.Span build in as per the spec.

So with other words System.Collections.Immutable appears to be targeting the version of System.Memory spesfic to netstadard 2.0, but mono implements it's own version of System.Memory so the spescfic version targeting will fail.
Using the System.Memory from net standard 2.0 that System.Collections.Immutable expects will fail, because then System.Span and many other times are implemented twise (both in System.Memory and netstandard - besides that will likly fail at runtime anyway since I'm pretty sure the mono runtime expects it's own special implementation of System.Span)

#

Hmm odd, looks like I must have had some other random System.Memory installed, copying it from a different install appears to have fixed it, so I guess I have set up my dependencies correctly after all

craggy kettle
outer barn
#

I am creating a bunch of planes programatically simple planes , some are grey some are silver, I want them to blend colors where they collide with each other , how can this be achieved

vocal ore
#

I imagine the easiest way is to simply make them transparent, but that only works for a monochrome background

outer barn
#

the planes are besids each other and it should be something similar to this picture, this is what i want to achieve

terse inlet
#

You can accomplish this in a shader, or you can do it in code when your generating. But shader is probably your go to

hardy jacinth
#

Where do I hook into PrefabStage.prefabSaved in my script, that is used on a root game object of a prefab? I need to do some post-initialization when a prefab is saved.

#

no, scratch that, what I actually need is perform some initialization after the prefab is saved shaders are compiled for a prefab

#

no Idea how to to it

#

OnValidate seems to be running before shader compilation

untold moth
# hardy jacinth OnValidate seems to be running before shader compilation

On validate is not related to shaders in any way. Unity would reimport(and compile) the shaders at several occasions, for example when it's first imported in the project and during a build. I don't think it has to do anything with saving prefabs though, a prefab just references the shader asset. Thus "shaders are compiled for a prefab" sentence doesn't make sense.

outer barn
#

@terse inlet been trying since 2 days, nothing seems to work I can share my code snippets if you can point out or find something I might be missing

terse inlet
#

Sure

hardy jacinth
hazy bear
#

I need help as there is nothing in the web about that topic.
I know Unity makes some optimalizations when building the project, which in many cases includes flattening the hierarchy of the classes, which makes some of them literally dissapear. There is a lot in the web about how to EXCLUDE class from a build, but nothing about how to ENSURE that given class will exist in a build. Anyone knows something about that?

untold moth
untold moth
hardy jacinth
terse inlet
hazy bear
#

The point is that i have a debug tool that uses reflections and helps me to see all fields and properties in various static classes in my game, but one of these static classes seem to not exist in a build so I cant see the variables in it

#

in editor I can, in build it dissapears

hardy jacinth
#

with the primitive I thought I saw the cyan color when shaders recompiled, but now I see it's not, it's only the icon inside the assets directory flashing. But in case of my prefab the whole object flashes cyan for a split second, indicating shader recompilation

hazy bear
#

and yes, propably it isnt referenced, it just stores info about input stuff etc, at some point may be even deleted, but for now i need it for debugging reasons

hazy bear
untold moth
untold moth
hardy jacinth
#

I am regenerating the shader assets and sub-assets at various points though, but the edits that can be seen on the video don't change the shader nor material, they only trigger uniform updates

hardy jacinth
#

hmmm I think I may have an idea

untold moth
hardy jacinth
#

yeah, I am sure, I log on every shader regeneartion and it's not happening.. but...

#

I am attaching my generated shader+material as sub assets to the prefab

#

so I think whenever the prefab is saved, it is reimported along with any sub-assets

#

and THAT may cause the sub-asset shader to recompile

untold moth
#

Yeah, that's possible. Maybe you can hook to the asset importer/processor pipeline to see if that's happening.

hardy jacinth
#

yeah, I caould try, although I didn't mess with the asset importers before so I'm not yet sure how and where to hook into that

#

but, on the other hand, seems like I resolved one of the roots of the problem somehow, after I closed and reopened the prefab stage β€” namely I wanted the uniforms to reinitialize when the said shader is recompiled

glass hill
#

So, I have a custom in-game cursor which does not use the mouse (but is of course linked to the mouse position, in part). I want to allow this in-game cursor to trigger IPointer events. What's the best way to go about this?

#

Should I use a detection system on the Cursor script to detect when I collide with objects that have those Interfaces and just target the methods, or is there perhaps a better way to do it?

sly grove
#

Or is it also a curosr you want to control from e.g. gamepads

shut hedge
#

How risky is it to use third party libraries with unity? For example if I want to have numerical computations, I'd like to include numsharp. Is there a high risk of it not working in unity?

scenic forge
#

Not sure what you mean by "risk," that word means probabilistic events that you have no control of.

shut hedge
sly grove
shut hedge
sly grove
#

Which isn't much different from what you'd do with your own code tbh

shut hedge
scenic forge
#

Yeah I mean that this is not something that's up to chance whether it works or not, you can test it yourself.

sly grove
#

there's nothing that is going to guarantee performance/functionality for your particular use case / access pattern other than testing it

scenic forge
#

Lots of libraries don't write with Unity as a target in mind, they tend to target .NET framework/core, and there will be different performance characteristics between .NET framework, .NET core, Mono, and IL2Cpp.

sly grove
#

Lots of C# Libraries generate lots of garbage because they aren't designed with interactive media in mind like Unity.

scenic forge
#

Performance characteristics can even differ for different versions of the same backend.

#

(I do wish there's an easier way to benchmark specifically Unity though)

shut hedge
#

ok, maybe to make my question simpler. Are these two statements correct:

  1. If a library is well tested in Mono, then it will also have the same performance characteristics in unity with the mono backend as elsewhere (good hint also for telling me that they might target .net core!)
  2. For il2cpp, since this is basically only unity, I'd have to test it myself, since the chance that somebody has done it are relatively low if the library is nieche
shut hedge
sly grove
#

Optimized Unity code typically prefers to avoid generating garbage when it can be avoided

#

e.g. by reusing objects whenever possible

scenic forge
#

If a library targets .NET Standard for example, it doesn't say anything about its performance characteristics, because .NET Standard itself doesn't impose any performance characteristics (well besides the APIs that explicitly say so)

shut hedge
#

But what you are saying is that mono is niche enough that even if the library is used a lot in .net, it might not be well tested in mono?

#

(and for sure not in il2cpp)

shut hedge
wicked verge
#

Mono is just an open source project for linking C++ (the backend) to C# (the frontend)

scenic forge
shut hedge
#

and how small is mono in the C# world compared to .core? If I have a project with multiple thousands of github stars, I can probably have some trust that it will run fine in mono or not?
Maybe also to clarify: I am not talking about 5% perf increase here. I basically want to use a library which has some numerical algorithms instead of implementing all of it again myself
This is not in a very performance critical part of the game

#

I am more asking of what are the chances of something in the end then taking 30x longer or not working at all in mono, or il2cpp.
If my intuition is right, in mono I have a very good chance of everything working relatively well, while in il2cpp, even if it targets NS 2.0, it could be really bad or not work at all?

wicked verge
#

Well, unity should be switching to CoreCLR, but idk when that will be

shut hedge
#

but does not really matter too much, I also want to understand what I have to lookout for when choosing other libraries in case that one does not work

shut hedge
scenic forge
#

You can always try it and see πŸ˜‰
Normally I would say vast majority should work with no issue, but I'm not familiar with that library in particular and maybe it has some black magic with SIMD or something that breaks with IL2Cpp.

#

I have not personally run into issues with libraries not working with IL2Cpp, albeit I also don't use many of them. Libraries have "just worked" for me.

midnight violet
shut hedge
#

they for sure do SIMD though in that library

#

its basically linear algebra, so very fast matrix multiplication and factorization etc

scenic forge
#

Well you said performance isn't a problem.

shut hedge
#

its not a problem on the scale of 20% increase, maybe not even 100%

#

but it is a problem on the scale of my own quick matrix factorization implementation vs some BLAST implementation haha

scenic forge
#

For a popular library you can also just search "Unity" in their GitHub repo issues, that should give some good idea of its Unity support.

shut hedge
#

Ok, maybe one last question to summarize all of the before. Assuming I find a library, I find that some people have used it in unity (however you never know if they actually went into production, or ever built for il2cpp etc.).
How high is the chance of some parts of the library, which I'll use later and maybe not test directly, suddenly not working anymore at all, or taking magnitudes longer (x10, x100) when I switch to il2cpp?

#

But also thanks for everyone being so helpful

midnight violet
#

I dont think, anyone can answer that, tbh. If you get into fancy calculations with unique plugins/libraries, you HAVE TO test those to fit your individual case. And aside from calculations, you never know what libraries are based on and how they perform too, until you test it and read the code/docs.

shut hedge
#

well I have an overview of the kind of algorithms that are used, I don't think that'd be the problem

#

if there is any problem that'd be with the compilation and things that I actually do not understand myself

#

but actually I just found an issue due to @scenic forge tip and it seems there are problems with numsharp + il2cpp, so that library is out of the window I guess

scenic forge
#

IL2Cpp and Mono compatibilities aren't "whenever I add a library, roll a die and if it lands on 1 it doesn't work" kind of bad, if that's what you are worrying. Beyond that there's really no magic answer but you just have to test it out.

midnight violet
delicate mural
#

IL2CPP

#

Do you?

shut hedge
#

but just searching github issues actually showed me quite a few more issues

#

and also it didn't seem too actively developed anymore

tribal wyvern
#

Hi, I'm trying to use SVGImage Component provided by a Unity Staff from the forums. And I'm having Runtime NullRef errors whenever I try to GetComponent<SVGImage>().sprite = newSprite. It seems that the Script Component is missing something that I can't get the SVGImage Component itself to modify it.

Anyone here uses SVG Images for their UIs? How do you update/modify it during runtime without getting NullReffed? The built-in Image Component obviously does not have this problem.

The SVGImage Script Component is provided by the Unity Dev Staff here: https://forum.unity.com/threads/unity-ui-svg-support-script.551254/

frozen ravine
#

is there a way to sample a 3D animation on a GameObject?

#

I'm trying to make an editor that'll let me preview a 3D animation by scrubbing

#

I know how to sample a 2D animation, but not a 3D one

#

nvm it's the same way lol

bleak citrus
#

note that it's still in preview

#

i found it a bit fiddly

glass hill
#

Trying to edit some existing packages (some Unity UI elements and TextMeshPro) https://support.unity.com/hc/en-us/articles/9113460764052-How-can-I-modify-built-in-packages
having a bit of trouble. can't seem to find the assembly definitions so I can add my own assemblies as dependencies and import the code.

#

Anyone else made changes to unity provided packages before? I moved the two packages in question out of the Library folder and into the Packages folder as instructed.

austere jewel
glass hill
#

I was looking under the TextMeshPro folder since I was trying to edit TMP_Dropdown.

#

Thanks. I'll see if that fixes my issue.

strange iron
#

You can make Extentions

glass hill
#

I haven't really made extensions before. I mostly work on my own systems, so this is a relatively new foray for me.

#

I'll probably end up doing that.

wet sail
#

hello, anyone knows how to combine two animations using code?
animation 1 is attack (lower part aka legs dont move in the anim), second anim is walk (upper part doesnt move at all in T pose)

untold moth
#

Why would you need to do it via code?

#

And how much "via code" is it? Do you have custom shaders or animation system?

wet sail
#

cuz i hate unity mecanim

untold moth
#

Okay, so you have a custom animation system?

wet sail
#

also i want "portable" game code. so in case i needed to switch from unity

untold moth
# wet sail wym?

Well, how are you planning to play these animations in the first place?

#

Without blending

wet sail
#

idk thats why im asking

untold moth
#

Ok, so the actual question is "how do I implement a custom animation system"..?

wet sail
#

ah without blending i use the legacy way

untold moth
#

Legacy animation component?

wet sail
#

apparently i have to do so

#

i want avoid that

untold moth
#

Well, either that, mechanim or you implement your own system from scratch.

#

And I don't think it's possible to blend anims with the legacy component.

wet sail
#

i guess so but then i have to parse the fbx i guess

#

since unity doesnt provide anim curves or sth

untold moth
#

I think you can convert a unity animation clip to your own data. Would just need to implement a tool that does that.

#

I'd worry more about the animation system itself.

#

You'd need custom shaders and stuff

wet sail
#

or just directly export from blender ysing a script

#

but thats painful and straightup parsing fbx using assimp is easier no?

untold moth
#

Maybe. Up to you. That's probably the minor of your problems if you implement your own system.

wet sail
#

why? is it that hard?

untold moth
#

Sure. Unity had a team working on Mecanim for years. If you want something similar developed solo, it's either gonna take a long time or be a subpar implementation.

wet sail
#

not gonna make mecanim. its garbage minus the ui, integration, interop etc...

untold moth
#

Well, even just to make a "garbage" like that is a lot of effort.

wet sail
#

my game is social game and trying to achieve where a person can play about 20 anim at a time, blended and very reactive. i have already trained a model to predict clips to merge based off keywords, but i cant find a way to do play them using mecanim, and the unity api is too "restricted"

#

do you have a suggestion

#

or workaround

untold moth
#

Maybe you could use the lower level Playables API. I heard it provides more freedom.

#

It's what Mecanim builds upon afaik.

wet sail
#

is makin anim sys hard? its just setting transforms and interpolating a bit no? am i missing sth?

somber tendon
#

Well, unless you know how to change mecanim animation at runtime, yes, mecanim is not really flexible

wet sail
wet sail
somber tendon
#

You can simply make your own "system" by using states and manually call play or crossfade

untold moth
#

I don't even know how to approach developing an animation system. Would modifying the bone transforms with a skinned mesh renderer be enough?πŸ€”
It's one big system of the engine, so it's definitely not easy.

wet sail
#

i guess not necessarily bones? just tranforms?

#

and interpolating a bit?

untold moth
wet sail
#

but i maybe oversimplifing it

untold moth
wet sail
#

not really im reading tranforms from fbx and changing them in the model

untold moth
#

What "model"?

novel plinth
shut surge
#

You can jig your own blending system with the Playables API by using AnimationScriptPlayables, would suggest reading up on it in the docs @wet sail

#

Had to roll my own animation system for a similar reason and I’ve found that it gave me enough control to run complex blending algorithms + other stuff like IKs

wet sail
#

why not build your own anim sys at that pt ?

novel plinth
#

they're not easy to make, you're dealing with lots of edge cases when dealing with bones

#

why reinvent the wheel and not just use Unity's?

wet sail
#

what do you mean edge cases ?

novel plinth
#

well, for example, Unity's will do tessellation to the vertex mesh based on the geometry.

#

this if we're talking about bone system for rigging purposes

wet sail
#

what does this mean ?

#

i'm not loading the fbx from mesh if you talking about that. just the animations (in a separate fbx)

novel plinth
#

you mean the shape keys?

wet sail
#

NodeAnimationChannels mainly

#

mesh morphs will probably do it later. need to animate bones and transforms for now

red shell
#

My .jslib file looks like this:

mergeInto(LibraryManager.library, {

  Hello: function () {
    window.alert("Hello, world!");
  },

  HelloString: function (str) {
    window.alert(UTF8ToString(str));
  },

  PrintFloatArray: function (array, size) {
    for(var i = 0; i < size; i++)
        console.log(HEAPF32[(array >> 2) + i]);
  },

  AddNumbers: function (x, y) {
    return x + y;
  },

  StringReturnValueFunction: function () {
    var returnStr = "bla";
    var bufferSize = lengthBytesUTF8(returnStr) + 1;
    var buffer = _malloc(bufferSize);
    stringToUTF8(returnStr, buffer, bufferSize);
    return buffer;
  },

  BindWebGLTexture: function (texture) {
    GLctx.bindTexture(GLctx.TEXTURE_2D, GL.textures[texture]);
  },

});
misty glade
#

I have this feature that plays tweens sequentially and it works pretty well but I want the ability to play some tweens without waiting.. In other words, if my tweens were A-F, instead of some sequences being ABCDEF one at a time, I might want ABC and then DE and F to play at the same time (F starts immediately after C finishes). I need a callback when the whole thing is done, and a sequence doesn't know anything about the others.

Here's the code: ~~~https://pastebin.com/eHz90tPM~~~ https://pastebin.com/LHCfa9GR (edit, added syntax highlighting)

My current approach is using a class called NamedSequence that is pretty light (snippet 1).

And each UI element that can do an animation can return a NamedSequence of some sort (snippet 2), and the "parent" orchestrates them in a queue (snippet 3).

The problem is that each Sequence can only have one OnComplete callback (which I don't think has a getter - I'd have to check the DG docs). I can't seem to dream up how to structure this so that I could fire some animations without waiting. A queue of Queue<NamedSequence>s? That felt ugly.

TIA

scenic forge
misty glade
#

Hm. I know there's UniTask, but I haven't used it yet. I generally don't use async/await in unity but if that works with dotween that might work

scenic forge
#

I know UniTask has integration with a tweening library but I can't remember which one.

#

But even if it doesn't support DOTween, it's easy to wrap it:

var utcs = new UniTaskCompletionSource();
sequence.OnComplete(utcs.TrySetResult);
sequence.Play();
return utcs.Task;

And that's all the code it takes to turn something into a task, then you can just await it.

tender light
# misty glade I have this feature that plays tweens sequentially and it works pretty well but ...

Have you looked at the Insert method for Dotween sequence? It makes the tween/sequence start playing at the same time as the previous one.

So

Tween a, b, c, d, e, f, g = new();
Sequence sequenceABC = new().Append(a).Append(b).Append(c);
Sequence sequenceDE = new().Append(d).Append(e);
Sequence total = new().Append(sequenceABC).Append(SequenceDE).Join(f);```
Its kinda sorta pseudocode. Cant be bothered to boot up an IDE. You can probably figure it out.
misty glade
#

Ideally what I want to replicate is the end of level workflow in Royal Match - there's a bunch of staggered animations that don't finish completely before the next one starts.. but I do need to wait for the entire thing to finish before allowing the user to start the next level

tender light
misty glade
#

hm.. yep, I think this is the way.. dyakuyu

tender light
misty glade
#

Yeah, no problem there.. just trying to figure out an easy way to "await all" (without actually awaiting). Like.. let's say I'm doing the same animation sequence as Royal Match where there's say.. 5 modules, and each has a "gain currency" animation that's 1.0 sec long.. I ask each module to provide it's Sequence and then at the parent, create a "master" sequence with a short delay between each but .. the only thing that's occuring to me is having a callback from each sequence's oncomplete where I increment/decrement a "sequences playing" counter, which seems fragile

#

keep in mind I don't know how long each module's sequence is.. so figuring out when the "entire thing" is done would either be callbacks with a increment/decrement counter or some potentially fragile math to calculate the TOTAL sequence duration based on the length of each.. summed up.. along with the delay of each = fiddly and potentially bug prone

tender light
misty glade
#

oh, maybe I was misunderstanding.. lemme write some pseudocode (maybe it'll rubber duck this)

#
Sequence master = DOTween.Sequence(); // empty master sequence
Sequence a = SomeUI.GetSequence();
Sequence b = SomeUI.GetSomeOtherSequence();
master.Insert(0f, a);
master.Insert(0.5f, b);
master.OnComplete += ...; // Does this fire when a *and* b are done? or at 0.5f?
#

if that last line "just works" and fires when both A and B are done then... we're done and I'm good to go

#

demigiant docs don't make this clear.. also I'm not sure if this blurb means I can't do the above:

#

oh, wait, that's fine - i'm never reusing a single sequence, I'm creating each one from scratch when needed

tender light
misty glade
#

yeah, will do! again, thanks (can't believe this shit woke me in the middle of the night lol)

spiral grotto
#

I asked this in lighting, but this is also a good place I think because it's more of a code issue...

I have a script that bakes 1 map at a time, the problem is if it runs out of memory once it defaults to CPU mode, the problem is the next scene stays in CPU mode instead of going back to GPU mode.
is there a way to make it try GPU mode first, every single map?
second problem, though less important, if I bake in UI it skips baking if maps are baked, but if I bake via script it voids existing maps and rebakes, is there a way to prevent this so it only bakes unbaked maps?

midnight violet
spiral grotto
#

yes, there are only a small hand full of levels that run out of memory

#

I verified several that dont and set up a test case where it does
Known good
Known Bad
Known Good

and end up with
GPU
CPU
CPU

midnight violet
#

Can you show the script actually, otherwise its just guessing in the dark

spiral grotto
#

`// Place this file under Assets/Editor
using UnityEditor.SceneManagement;
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using System.Diagnostics;

public class CustomBaker
{
[MenuItem("Tools/Bake All Scenes")]
public static void BakeAllScenes()
{
// Fetch every enabled scene from the Build Settings
// These are the scenes that have been added through the Build... window
List<string> scenePaths = new List<string>();
foreach(var scene in EditorBuildSettings.scenes)
{
if(scene.enabled) // remove this if you want to bake disabled scenes
scenePaths.Add(scene.path);
}
UnityEngine.Debug.Log($"Ready to bake {scenePaths.Count} scenes.");

  // Open, Bake, Save.
  // This will run until all the scenes are baked. You won't be able to cancel.
  foreach(var scenePath in scenePaths)
  {
      UnityEngine.Debug.Log($"Baking scene at {scenePath}");
      EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single);
      Stopwatch sw = new();
      sw.Start();
      Lightmapping.Bake();
      sw.Stop();
      EditorSceneManager.SaveOpenSc5enes();
      UnityEngine.Debug.Log($"Done baking scene at {scenePath} | {sw.Elapsed}");
  }
}

}
`

#

but then we added....

#

sw.Start(); LightmappingSettings lightSettings = Lightmapping.lightingSettings; LightmappingSettings.lightMapper = LightmappingSettings.Lightmapper.ProgressiveGPU; Lightmapping.Bake(); sw.Stop();

thorn flintBOT
spiral grotto
#

but what we added doesn't work

#

m_BakeBackend: 2

#

thats the setting that gets reverted to 1 for CPU

midnight violet
#

Pls reformat, its hard to read otherwise

spiral grotto
#

so I need to find a way to make it try 2 first every time

#

I'm not acually a programmer >.> I just play one on tv... ill see what I can do

#

does that work?

midnight violet
#

Better than this discord formatting πŸ˜‰

spiral grotto
#

anyway i figured out when it fails it changes m_BakeBackend: 2 to m_BakeBackend: 1

#

but in memory, not in the file, it only changes the file when you close unity

#

so we need to set it back to 2 every time

#

but im not really a programmer, I'm an environmental artist/level designer, so I usually don't end up this deep in code

#

so i dont know how

spiral grotto
#

I just need it to read the settings from file every map

#

since it doesn't save it until you close the editor, that would do the trick >.>

#

in theory...

spiral grotto
#

also...

#

would that work?

long ivy
#

that is effectively the same as the code you've already added that doesn't work, so I'm going to guess no? My suggestion didn't work for you?

honest furnace
plush hare
#

Does native PInvoke overhead basically disappear when you build IL2CPP or how does that work?

novel plinth
#

Unity nerds at #allowunsafeblock can easily answer this tho πŸ˜‰

#

(i've sworn I've seen your name there, just incase it's the same person 😌 )

novel plinth
#

NAOT(optimized) almost toe to toe with BURST, that's just insane

sage radish
novel plinth
abstract basalt
#

I'm not sure why that would be a surprising result

novel plinth
abstract basalt
#

ah, I could see how that would be reassuring

spiral grotto
#

now I just need to get it to check if it HAS to bake each map first... right now it just bakes it no matter what.

regal olive
#

Hey yall

#

I'm working on a 2.5d platformer script

#

I'm adapting off of this other 2d script

#

Can someone help me in figuring out where i'm going wrong with migrating?

#

The ground checks aren't working

sly grove
regal olive
sly grove
#

"my ground check isn't working" definitely a beginner issue

regal olive
#

shhhh

#

that's not the issue turns out

#

doesn't look beginner to me

#

πŸ’€

sly grove
#

Looks very beginner to me

regal olive
#

🫑

half swan
haughty wolf
#

HELP ME MAKE A GAME

rugged radish
#

still trying to find a good and compute shader friendly solution to smooth out heightmap based on a voronoi diagram
tried to interpolate by using interpolated delaunoy triangles, but while inner areas look smooth, seams are a problem
another thing I tried is to sample with a constant step first and then interpolating the samples, but it expectedly has this "stairs" look

has anyone seen something that would help here ?

I also found papers that do solve this problem, but are pretty expensive computationally and also use data structures that aren't very suited for hlsl

frozen imp
thorn flintBOT
#

:teacher: Unity Learn β†—

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

spice ocean
#

why tf unity isn't calling frame update loops when starting the game as batchmode? in editor the entire game works fine asf, but in batchmode update loops isn't getting called, anyone may know why here????

#

i have like 6 hours seeing why and i still dont found the problem

#

when running in batchmode the first scene loaded is bootstrap that calls the .Host method that adds to the invoker class queue the server.tick metod that it supposed to be called every tickrate and the invoker check for that every lateupdate call but the lateupdate call isn't getting called and it should because the object exists also it's being marked as dont destroy on load so it supposed to never destroy when switching scenes but why tf is getting called I feel too suffocated because I can't find a way to fix it

plucky trellis