https://github.com/hecomi/uDesktopDuplication
Ive just stumbled across this so and it appears to be similar so π«°
#archived-code-advanced
1 messages Β· Page 96 of 1
I mean you can just do var versionNumba = Application.version; ?
Application.version is basically the readonly version of PlayerSettings.bundled
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.
Call a method on that object
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?
One that you have defined
To be clear: I need to know when instantiate is being called.
I am not calling instantiate
What do you mean? What's calling Instantiate then?
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")
I am not sure what is broken about duplicating objects
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
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
Ah well. This is going to be tough. Thanks anyway.
what is this bug?
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)
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)
I mean, how you instantiated them? they won't just appear out of nowhere π
I don't get it honestly π .. it's a template that someone made or you're working in a team or ?
- 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)
- 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)
- 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"
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).
Testing features for NinjaBuilder (physics integration +dynamic in-scene serialization) by dropping them into a driving sim game.
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?
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 ;))
Does anyone see anything that I can do?
I'm not sure what you mean by nesting, you mean stacking the element vertically?
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.
well then how one supposes to help you if you're not sure π
By nice i don't mean only the example sent. For example my other attributes work only if that NaughtyAttributes is added
I mean I know what the attribute does
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
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
Oh I didn't see that channel, not sure how xd. Thanks going there
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.
you'll get more of a response if you say what the problem is π
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.
I tried making it prefab but it didnt worked
I couldn't able to find any other solution for it.
what does "didn't work" mean?
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.
by delete the scripts do you mean removing components from the object or deleting the actual script files?
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?
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
Im using IL2CPP
Thank you @stuck plinth for helping me out.
Is it possible to do a medium large physics calculation as quick as possible, then just animate the results?
yes
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
Interesting.
I'm working on a golf sim, so its pretty much only the ball that can be affected by physics.
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
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.
IHasCustomMenu apparently does not work for ToolbarOverlay.
Can someone help me privately? Because something is not working for me
Better to just ask here
if your going to bake it, you can solve it with a slow approach:
I would code the simplest form of the detection like you mentioned above, and start adding rules to it. Refactor when you need to, and when stuck, sit down and think. You can also access normal data
#archived-shaders message
I actually just went down this route exactly haha
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
is there a possible way to import reference dlls in unity?
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)
Probably not a lot of overhead, but I'd still use plain classes where possible.
If you need specific numbers, you'll need to test and profile.
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.
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.
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
can you guys send me a video about making AI in video games? its really hard to make accurate AI
there isn't really a catch all "how to make AI" tutorial, since it heavily depends on the game you're making
for example a 3d stealth shooter
i mean i can check ranges, alert mode etc. but it feels so fake
There are many ways to implement ai in a shooter. I suggest to research some similar games and how they implemented their ai. There are several videos and articles on GOAP in F.E.A.R
Just add the dll to the project
Can I implement unity messages on an abstract base class that inherits from monobehaviour? (ie, Awake())
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
Yes, just make sure any child class calls the base method if they override it
(if they don't hide/overrride Awake e.t.c, unity will try to find the event methods in a base class)
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
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();
}
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
yes, I have tested it and it works
commonTokenStream.Fill();
var tokens= commonTokenStream.GetTokens();
I have found a better approach. It does not need to listen
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?
you mean it won't always be called export master?
what will it be called?
In theory yes
I'm not certain yet, it's a project in progress including things like the json files :/
it's really hard to give a good answer without a solid spec of what the format of the data will be
Ok no worries. That actually helps a lot since I can pass that info back haha π
You can use the JObject api if you need:
https://www.newtonsoft.com/json/help/html/ParsingLINQtoJSON.htm
but really you should just coordinate with whoever is setting the data up
and agree on a format
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
make a Plugins folder. Copy the dll into it
Check if the JObject is a JArray
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\
Quick note... anytime you use += it is good practice to pair it with a -=. Easy to get into some nasty situations otherwise
Why Fixed update?
I would change the implimentation... Track the starting angles of the gun/ look -> When shooting dont have it auto correct -> When shooting stops, snap it back to starting values over a very short period of time
@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 -=?
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);```
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
oh my bad i didnt notice that i just hit the copy url button and pasted it
@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.
Can you post the code for the reset, and for the time being, donβt have it lerp or anything, have it snap to the reset position instantly.
@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
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Set the initial rotation as well
https://hastebin.com/share/ayozupuqef lmao thought i did that too
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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
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
Where are you putting the generated code? Could it be an assembly issue?
Namespaces are unlikely to be relevant.
I'm not putting it anywhere, it shows up under source generators under Assembly-CSharp Dependencies in Rider
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?)
The fact that it is under the dependencies probably means that it's in a different assembly..?
Where is the file physically in your project?
C:\Users\inno\AppData\Local\Temp\SourceGeneratedDocuments\F4B23C4B9A85E26AA75D6C3B\TransportsSrcGen\TransportsSrcGen.NotwerkCommandGen @untold moth
Uhh... I think for unity to compile it correctly, the file needs to be somewhere in the project.
I would have thought so too, it seems to be putting everything in Temp while it builds tho
The source generator?
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.
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.
I think you're right, hadn't occured to me
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.
its compiling it into assembly-csharp
In the screenshot here, it does seem to be in the project. I'd check the path from root to the file for any asmdef files.
Are these errors thrown on build?
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
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.
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
Aight. That's a bit beyond me. Especially without access to the project.
thanks for your help π at least im not gonna be looking at IDE generated files thinking they are unity generated ones π
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
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.
interesting.
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 π
generate candidate points based on picked circle radius in traditional poisson disc sampling + next collider radius doesnt work?
How do I call the GeneratePoints in another script whenever an item is spawned?
considering GeneratePoints is a static list
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
can I access it dynamically? for each spawned object. So the GeneratePoints considers a different collider as per given item
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
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
I would try to random pick a different items, and a random items previous generated, and generate points based on their radius
radius of collider?
Yes
I will try
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();
}
What's the error you got with NativeList? It should be not much different from how you are passing in the enemy positions, you pass in a list just like that, and the job itself adds the detected enemies to the list.
i have to rebuild it but it was something that the list must be readonly (what is smth i can not use then)
i tried a NativeList<int> to return the indices of the enemies that should be pushed
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.
i will rebuild it later and will post it here
i think i have to use a NativeQueue<int> then?
oh thanks will have a look into that
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
yeah i will implement spatial partioning
but i want to get the basics running to have "something" to work with π
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.
you are correct .. will change that π
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)
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
Tiled materials seem to be the best way.
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
Assuming the room center is its Pivot, aren't you just looking for spawn.transform.localPosition?
(also assuming everything is scaled 1,1,1)
Everything is not scaled 1,1,1 sadly
You can fix the hierarchy so it is
Move your renderers to scaled sibling objects
how do I do that?
Dragging and dropping in the hierarchy?
Creating empty objects?
Make sure anything that has a child object isn't scaled
This is probably the right solution, though now I'll need to refactor a lot of code to function based on that
Doing a bit of testing this is close but not quite, as the values need to be relative to the spawns z axis
For example here, the x axis of this spawnpoint is aligned with the parents z axis, yielding the wrong value
i don't quite understand what you want here but if you want the center of the room in the local space of a spawn, you can probably do spawn.transform.InverseTransformPoint(spawn.transform.parent.position)?
This is a 2d simplification of the problem, the blue vectors represent the forward vector of the spawnpoints, and the orange vectors represent what Iβm trying to find.
Notice how the orange vectors are basically equivalent relative to the spawnpoints. Theyβd both be (0.5, 1.5)
Basically if you rotated this 180Β° it would look the same because they have the same relative position to the center
right, that looks like you want the center in each spawn points local space?
InverseTransformPoint the parent's world space position to get that in the local space of the child
This was almost exactly what I needed tyvm π just had to slightly tweak it to get the target values
{
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
this can be simplified a bit :
Vector3 FindShiftVector(Transform spawn)
{
Vector3 shiftVector = -spawn.InverseTransformPoint(spawn.parent.position);
shiftVector.z = -shiftVector.z - 7;
return shiftVector;
}
Wonβt this result in the y value being inverted though
Though I did remove the unnecessary transforms after realizing they werenβt needed
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
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
I use this, it works pretty well for me https://github.com/yasirkula/UnityAssetUsageDetector
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)
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?
It's unfortunately not quite as simple as that. You'll have to then reference other assemblies the code uses, like TMP
you need to put your test assembly in a separate folder so the assembly definition doesn't affect all your other scripts
I did add a reference to an assembly called Unity.TextMeshPro but that didn't fix it somehow
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
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
do you perhaps know of a resource where I could find out more about this because at this point I watched 5 tutorials on the topic but all of them simply brushed it off as "just create an assembly definition for your scripts", which works fine in their empty projects but not for me
Maybe look up resources that are specifically about making assemblies
the official docs have very clear pages about assembly definitions, assembly references, code splitting and setting up unity testing,
How did that problem happen anyway? Can you provide more details cause youre doing something wrong. Referencing Unity.TextMeshPro will enable all of the scripts in that folder and below to use TextMeshPro namespace
Okay so I just opened it up again to check and you are right. I guess adding the reference, saving, and trying to compile is not enough to refresh it?
It should be, I would guess you missed a step but it COULD be Unity bug.
Created new Assembly definition just to test it out if it works. It works but corrupted my library folder π€¦
π 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
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
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)
you can add context menu
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?
yes
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)
here's how it works currently - i have to manually set left/right/top/bot to 0 after the operation
Oh, wait, I got it working - sizedelta is relative to the anchors.. so just setting it to Vector2.zero fixed it right now
some error handling and it's done
you create an image in a weird way .. why wouldn't you just do: right mouse -> ui -> image?
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?
So you want to make a game engine within a game engine? That seems a rather strange goal to have
I am doing it in Godot
Great, I still dont understand why you would want to use a game engine to implement a game engine
Do you mean an actual game, or like allowing the user to make their own levels?
Oh, It's for a client he don't know coding but want to do some 2d rts
a game engine in a game engine to make games in that game engine engine seems like a pretty cool project
Ah, so you want to make a game framework
Yeah it has a map editor
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
sounds crazy but it's what the client want
Yea thousands of individual guys running around might not work with game objects. What you're describing so far all seems possible, you just need to be the one to code every possible feature, if they want to create the units themselves without code.
They just can change the graphics and the levels
And some properties like health etc
How i make to pack a scene and run in separate process in unity?
I guess the scene has to be compiled...
Oh as a separate program I am not sure how that would work sorry. I was under the assumption you wanted to do something like create the scene at runtime then populate it. https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.CreateScene.html
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.
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
A better question for #1062393052863414313 likely, you'll probably find some benchmarks on google as well
don't worry the 'tool' is just for personal use
Depends on how it is done, but between hundreds and millions
Thousands is very attainable. Millions takes a lot of consideration
and if I do multiplayer ECS how many?
Same difference
Multiplayer limits can be a lot different but that's stuff like bandwidth
Or just a user limit of their internet
what you recommend for multiplayer with ECS? Photon or netcode or other?
if you are seriously talking about supporting multiple thousands of units then no off the shelf solution will do it for you, you will need to build your own
Well, that thousands are for play against AI, I am flexible in total number of Units in multiplayer can be 2K with ECS?
my experience is that about 1,700 is the max for decent performance depending on the target platform
Thanks I'll take it into account
Netcode for entities obviously. Any other solution you would have to adapt to ECS manually afaik.
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
WHY DOES ANY UNITY METHODS like awake, update MAY STOP WORKING ON ALL UNITY EDITOR VERSIONS?
ahem
They don't!
also giving no details of what you changed and what you tried does not help
They had their logs hidden
They crossposted to all coding channels
Has anyone tested how far you can get from the origin before things really start breaking?
What I've always heard is 100k is pushing it (edit: typo at first)
Haven't tested it myself
100k sounds way too massive
Yeah. Exactly
Editor will give you a warning at that point iirc
I think I worded it poorly. 100k will break it I mean
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
Like static batching? That would either not move them or cause unity to regenerate the static batch.
Also, beware of using a single transform to shift everything because you will reduce your performance due to how unity is able to dispatch work on transform at the root of the scene.
If Static Batching does not work, you can batch them manually with https://docs.unity3d.com/ScriptReference/Mesh.CombineMeshes.html
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
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
did you profile which part is actually taking the longest? reading such a large json wont be quick, so maybe you can optimize what information you store.
I doubt you also have all 20000 objects being used at the same time. you could likely reuse some of them, through pooling.
you don't even need to destroy those gos, instead put them back to the pool and reuse them later as needed
20000 is insanely a lot for 2d game just saying
I can't seem to get anything useful from the profiler. "Sample Code" is where the JSON loop starts. Uses 0.8%. Most comes from the player loop, this spikes when the scene is loaded, I dont get anything from the profiler while it loads
yeah i understand. This is the object limit. If you have played geometry dash, levels have upwards of 200000 objects, so there must be a way to not use everything
only problem is loading the level. Once the level is loaded the frames go back to normal
π€·ββοΈ there isnt much to say about this, this is just because of the massive amount of objects. you most definitely dont need 20k all being spawned at once
that is a lot of GC but its not the main problem
i agree
Geometry dash uses 4000 objects iirc
and they all instanced
meaning it can be just 1 - 2 drawcalls
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
thousands of objects at once need special treatment if you don't want your game run like turtle
where did async come into this? just use object pooling and release objects as they are far away. Get objects as they are nearby
okay, i will try. thanks for the help
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
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
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
it's inside void Update()
what are these 500 child objects?
Why do they all need to be children of this thing?
bolts for engine and all parts
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
I know its the issue
im trying to find any way to fix it without removing those children
merge all the meshes into one object
Why can't you merge them?
those gameobjects moving + rotating at the same time ?
thouse are individual bolts
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
those bolts moving and rotating at the same time?
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
hmm Ill take a look into that
it's not for the faint of heart π΅βπ«
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
just make sure you profile first! It could very well be the performance issue is caused by something a little simpler to fix
what do you mean profile?
I know when I deleted these children it doesnt lag anymore so thats probably the reason
I mean use the profiler https://docs.unity3d.com/Manual/Profiler.html
no I dont
i was looking for some function to change position without updating physics but didnt find anything
What if you did:
Physics.simulationMode = SimulationMode.Script;```
then moved it
then reset simulation mode
hmm wait Ill give it a try
still the same
Ill do some optimizations and later let you know how it went
nah this ins't gonna do anything
is this an instant movement
or like
a movement over time?
I was saying do the whole movement then turn physics sim back on
its in render
I dont really understand
this simulationmode thing won't do anything unless it stays on Script through the FixedUpdate cycle
Let's say you're dragging the car over the course of several frames
(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
heres code for box collision optimization
if anyone needs
example use:
on start it will automatically make them components instead of children
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.
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?
you could just refuse to use the door at all when doing pathfinding
what algorithm are you using?
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.
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
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.
Yes, and the idea is that an entity on Team A won't treat a door as being a high-cost link to another grid cell -- they simply won't see a link in the first place
Ok so that requires a graph for each faction, yeah?
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.
Yeah, I think in this case I want the node searching to operate on a different calculation/mechanic depending on a starting parameter.
Do you have to tell the algorithm about every grid cell and every connection between them all at once?
I am not familiar with the asset.
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.
Yes, that alone will make it very likely they'll go another way.
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?
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
: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.
I wind up needing to check stuff from the scene whilst doing this, so I decided against trying to Burst it
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
A* implementation mostly just Manhattan distance π
reason it's so fast, simply bcos it's so simple... similar case like why linear interpolation is fastest among anything else π
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.
Not followed the whole discussion, but A* can be used for a variety of problem. You simply need to define, a state, an heuristic (which has a specific sets of propriety) and a notion of distance between state.
Action Planning could use A*.
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.
Not sure what you find hard in filtering node ? You simply need to define what you want when you add neighbor ?
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.
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...
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
What do you mean upgrade a graph
How do you "update a graph". A* does not have the concept of updating a graph..
Let's continue this in DMs so I can go into more detail and share images if need by.
No, DMs. If you want you can make a thread
Because, I'm not befriending people
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.
Is it tilebase ?
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?
Is people walking directly on tile or not ?
It is a real time strategy game so they can walk anywhere within a tile.
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.
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.
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...
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);```
The result I want is much closer to this
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
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
Not sure how angleaxis applies here. That just rotates around 1 axis
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
Well, refer to the post as it sounds similar to your problem
I already had a feeling that it had something to do with the up parameter of lookrotation
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)
AngleAxis you'd define different up axis depending on your rotation, so usually I'd do it for all axis
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
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
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.
@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
Aye nicee
you may want to use transform.SetPositionAndRotation if you're changing position & rotation at the same time
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
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
Anyone know how to reference the UnityEngine.UIElementsModule.amsdef?
This isn't a thing any more. UIElements is built-in, there is no asmdef
Is there any other way then that you know to hack into/get access to internal classes inside UIElements?
Reflection as always
Find another assembly that has access to it
hacing some certified private/internal moments rn 
ai, tried finding one, even tried the new App UI one, but to no avail. welp
The source (pinned to #βοΈβeditor-extensions ) has AssemblyInfo files at the root of assemblies that mention the other ones that have access
ill take a look thanks!
ugh
yeah don't do reflection in unity ever esp on runtime
why not? Even Unity uses it internally
reflection is fine in editor just sucks
dotPeek
on runtime reflections aren't GCd
so what, I would expect a certain level of competence if you are even considering using it
apparently they are changing to CoreCLR soon
by soon you mean 3 more years? π
lol
Don't cross-post
awesome thanks a lot
maybe Unity 7000 which is in 4976 years by my calculation
huh? I just didn't get help there, what should I do? wait for forever if this chat is active and the other one not
Yes. You wait. It's scarcely been 10 minutes
@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 :/
Yeah, it sucks at times. But at least the asmref hack avoids reflection for many things
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
what does this error mean?
you have a null reference
and, btw, this is #π»βcode-beginner not #archived-code-advanced
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)
it was actually a unity bug, but ty anyway
The concept still applies, it just might not have been your code this time. NullReferenceException is a very generic error so showing the rest of the stack trace is imperative to get a full picture of what's wrong m
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)
};
Is deep profiling on?
yes
can anyone DM me the rundown of procedural animation? i know its something todo with raycasting
procedural animation doesn't necessarily have to do with raycasting. It just means "animating something with code" rather than using prebaked animations. Oftentimes it's used for interesting walking animations and oftentimes uses raycasts to find IK targets though.
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
You either need to:
- Make individual references to each one (that you can use to compare later)
- Use a code generator (this is how the Input System does things)
- Use strings
- Use something like an Enum or something you set on the SO and use in code as a lookup key.
Yes, so both the string and Enums approaches I have looked at, howeve both approaches have issues.
Strings = Possible Typos
Enums requrie me to KNOW the EventReferences I want beforehand. WHen more apprear I would need to edit them
yes
Code generation is really the only way you're going to get true compile time safety here.
Hmmm, any leads I can follow for this ?
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.
Ya looking at this makes me thinkg it's just easier to have a mono class..
Yup!
would be amazing if I could serialize non mono classes though
problem would also be solved
you can serialize non monobehaviours
I tried but I don't see the class fields popping up in the inspector
[Serializable]
public class MySerializableObject {
[SerializeField] int mySerializedField;
}
ohhh I don't have the field part
My guess is no π₯Ή
ah
isn't static!
indeed
If you want to serialize a non-public field, you need SerializeField
Please refer back to the rules linked above
Got ya, These are just audio references to none will be private .
Thanks for your help
no sacrificing a goat today!
how do i make a physics based grab system ps im asking for a reason
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?
thank you @half swan , found it.
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.
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
May I DM you?
of course - i have initiated that DM
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
Man how did i not find this, i scoured google and the unity forum for hours yesterday
thanks
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!
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
Persistent across sessions: json, across scene loads: ScriptableObject or DDOL script, everything else: variables.
So, I should to use variables to save panel data states if I change information in the scene itself, right?
Not sure what you mean. But, whatever you do, variables are involved anyway
ok ty
When creating a desktop game is the final binary produced native or .NET?
depends on whether you are using mono or il2cpp as the scripting backend. il2cpp will convert the IL to c++ and builds a native binary. mono compiles to IL and will jit compile
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?
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?
#π₯½βvirtual-reality <- dedicated
handles work very differently from gizmos, when piling them up, use Matrhx4x4.TRS to set their position, and zero out pos, rot within each method
(wtf)
Mmm does this really belong there though?
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 >:(
lots of noobs, that's true, but also very seasoned vr app makers
I just thought I would get better answers from a more C# focused channel. I'll move there. Thanks.
maybe you'll be lucky here but there is far higher response Hz over there
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
Depends on what's easy or difficult for you. That sounds like a typical backend thing, where you'd want a database, whether relational or NoSQL to store the json files and their relation to the users, and then provide a rest api for Unity to make simple HTTP requests. But like you said there's a bunch of stuff to it, especially if you want things to be secure, use auth stuff, and so on
Authentication would be the most annoying part, the others are pretty trivial stuffs.
For me it would be the deployment stuff I think
Does anyone use Themida on their game?
i would like to basically outsource authentication to a steam/psn/etc account
but iβve never made anything like this, so i have no idea wtf iβm getting myself into
The drm?
No I think that's WinLicense? Not sure, but it's another one of their product. (https://www.oreans.com/index.php)
I'm talking about the code obfuscator
Ah, ok. Haven't used that.
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
I was looking on what people use, perhaps Themida, VMProtect, etc... but everyone seems to be using assets on the store (nothing wrong with that, just curious)
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
I imagine the easiest way is to simply make them transparent, but that only works for a monochrome background
the planes are besids each other and it should be something similar to this picture, this is what i want to achieve
You can accomplish this in a shader, or you can do it in code when your generating. But shader is probably your go to
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
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.
@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
Sure
Yeah, I read about async shader compilation. But when any change is done on a prefab in the prefab stage, it seems to be triggering a shader recompile for some reason
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?
Does it change some settings that could be relevant to the shader? Like enabling/disabling shader keywords or modifying shader constants?
Unless your class is not referenced anywhere in the build, it shouldn't be excluded.
It's happening even when there are no shaders and no scripts at all. For example create a new shader, add a cube primitive and move it. If you have auto-save ON, then each move (which ends with save of prefab) of the primitive cube recompiles the shader Wait, that's something else
This doesnβt happen. What is your problem?
How do you know that?
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
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
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
I knew something like that has to exist, THANKS GOOD SIR!
I wonder if that is a good indicator. Besides, it could be something related to batching. Unity would indeed do recompilation from time to time if there is no compiled shader variant available for the given situation.
That or there's an issue with your shader cache.
It also looks like you're dealing with some custom shaders..?
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
yes, I generate the shaders, but the the asset updates are not regenerated at that point
hmmm I think I may have an idea
Are you sure you don't actually modify the shader at this points? Can you add breakpoint or logs to see if any of it runs?
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
Yeah, that's possible. Maybe you can hook to the asset importer/processor pipeline to see if that's happening.
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
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?
is this just a sprite that follows the mouse?
Or is it also a curosr you want to control from e.g. gamepads
If it's the latter the best way would be through https://docs.unity3d.com/Packages/com.unity.inputsystem@1.8/api/UnityEngine.InputSystem.UI.VirtualMouseInput.html?q=cursor
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?
Not sure what you mean by "risk," that word means probabilistic events that you have no control of.
When the docs talk about third party libraries and them needing to be very thoroughly tested and maybe having bad performance here: https://docs.unity3d.com/Manual/overview-of-dot-net-in-unity.html
They are only talking about the IL2CPP backend right? Since for Mono, everything should just work if I use a .net library?
you'll have to do your own performance and functionality testing to ensure your particular use case/ access pattern works and is acceptably performant.
Well I have never done it, and I am trying to get help from more experienced people on the decision if I should include a third party library or not haha
Which isn't much different from what you'd do with your own code tbh
but am I right that this is only applicable to the il2cpp backend? For mono, everything is all right or not?
Yeah I mean that this is not something that's up to chance whether it works or not, you can test it yourself.
across all platforms?
no you'd have to do this no matter what
there's nothing that is going to guarantee performance/functionality for your particular use case / access pattern other than testing it
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.
Lots of C# Libraries generate lots of garbage because they aren't designed with interactive media in mind like Unity.
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)
ok, maybe to make my question simpler. Are these two statements correct:
- 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!)
- 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
what do you mean by garbage? like literally allocating memory? or just to much stuff?
Like how C# manages deallocating memory. Any object that you lose refernece to becomes "garbage"
Optimized Unity code typically prefers to avoid generating garbage when it can be avoided
e.g. by reusing objects whenever possible
Libraries don't target Mono, they target .NET Framework, .NET Standard, .NET Core.
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)
I'm not really sure if I follow here. Core/Framework are implementations, while Standard is an API Profile
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)
https://www.mono-project.com just for some education
did I make a mistake in my assessment, or am I missing something from that page?
Mono is just an open source project for linking C++ (the backend) to C# (the frontend)
That's my point, if a library targets NS 2.0, it doesn't mean it will have the same performance characteristics in all NS 2.0 compatible runtimes. So if a library targets NS 2.0 and is well tested in Core to have a 20% better performance than Y library, that doesn't necessarily mean it will hold true in any other NS 2.0 compatible runtime.
Ok, thank you, understood
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?
Well, unity should be switching to CoreCLR, but idk when that will be
Talking about this: https://github.com/SciSharp/NumSharp to be precise
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
but il2cpp will have to stay, for platforms without jit or not?
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.
They are working on that from GDC talks I watched, but I cant remember any exact date, at least its within Unity 6 scope
but when you say I should test. Do you mean just importing it on my pc, building for il2cpp and seeing if it works well on some simple examples?
Because as an indie hobbyist I just don't have time to prototype the full functionality with multiple libraries, and then test the performance across devices
they for sure do SIMD though in that library
its basically linear algebra, so very fast matrix multiplication and factorization etc
Well you said performance isn't a problem.
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
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.
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
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.
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
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.
There was like the number one google result pointing to a git thread, where some people seem to have problems because of adding manually some dlls that are needed and therefore causing errors on different platforms. But the threads posts are like 5 years old, not sure bout that
it wasn't number one for me, I searched unity numsharp a few times and found other issues only. Didn't search for il2cpp specifically though, since this is also something I only really understood thanks to this discussion
but just searching github issues actually showed me quite a few more issues
and also it didn't seem too actively developed anymore
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/
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
perhaps you'd be interested in the vector graphics package
note that it's still in preview
i found it a bit fiddly
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.
Unity
Symptoms:
I cannot modify built-in Unity packages.
Whenever I try to edit a built-in package, the package is automatically rolled back.
Cause:
Β
Being unable to modify a built-in package occurs b...
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.
I don't understand the difficulty
I was looking under the TextMeshPro folder since I was trying to edit TMP_Dropdown.
Thanks. I'll see if that fixes my issue.
Extention are better y
You can make Extentions
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.
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)
You can play both in different animator layers with an avatar mask.
Why would you need to do it via code?
And how much "via code" is it? Do you have custom shaders or animation system?
cuz i hate unity mecanim
Okay, so you have a custom animation system?
also i want "portable" game code. so in case i needed to switch from unity
wym?
Well, how are you planning to play these animations in the first place?
Without blending
idk thats why im asking
Ok, so the actual question is "how do I implement a custom animation system"..?
ah without blending i use the legacy way
Legacy animation component?
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.
i guess so but then i have to parse the fbx i guess
since unity doesnt provide anim curves or sth
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
or just directly export from blender ysing a script
but thats painful and straightup parsing fbx using assimp is easier no?
Maybe. Up to you. That's probably the minor of your problems if you implement your own system.
why? is it that hard?
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.
not gonna make mecanim. its garbage minus the ui, integration, interop etc...
Well, even just to make a "garbage" like that is a lot of effort.
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
Maybe you could use the lower level Playables API. I heard it provides more freedom.
It's what Mecanim builds upon afaik.
is makin anim sys hard? its just setting transforms and interpolating a bit no? am i missing sth?
Well, unless you know how to change mecanim animation at runtime, yes, mecanim is not really flexible
ive seen it and its still restricted and a headache to work with, impl a system is prob easier in the long run and more portablr
i never did this so i want ask if theres more to it
You can simply make your own "system" by using states and manually call play or crossfade
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.
The want to blend between many clips at the same time from what I understand. You can't really do it like that.
but i maybe oversimplifing it
Well, give it a try then. Though, I wouldn't call it "from scratch", as you're relying on the skinned mesh renderer(animator?)
not really im reading tranforms from fbx and changing them in the model
What "model"?
Playables by default is multithreaded π which is a huge W
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
why not build your own anim sys at that pt ?
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?
what do you mean edge cases ?
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
what does this mean ?
i'm not loading the fbx from mesh if you talking about that. just the animations (in a separate fbx)
you mean the shape keys?
NodeAnimationChannels mainly
mesh morphs will probably do it later. need to animate bones and transforms for now
Hey guys, I'm having some issues with calling js functions from Unity WebGL.
Been following this documentation: https://docs.unity3d.com/Manual/web-interacting-browser-js-to-unity.html
But I'm having build error Library\Bee\artifacts\WebGL\build\debug_WebGL_wasm\build.js: undefined symbol: HelloString (referenced by top-level compiled C/C++ code)
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]);
},
});
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
Not sure how much you want to change your existing code, but this would be trivial to solve with async/await.
await A();
await B();
await C();
_ = F();
await D();
await E();
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
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.
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.
Hm.. that's maybe the better idea than incorporating a new tech (either unitask or async/await which I don't use in my unity codebases). I could take a handful of sequences from the individual UI elements, chain them together in a new "async" sequence and set the on-complete of each to start the next and the on-complete of the entire thing to hit some callback ..
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
I'v used this for UI a few times. It works fine π
hm.. yep, I think this is the way.. dyakuyu
Yeah. Thats easy. You just get the percentage eg 0.8 and multiply that with the total duration of the sequence you want to branch off from.
Then you call TargetSequence.InsertCallback(0.8 * totalDuration, someCallback) or just Insert(0.8 * totalDuration, someTween/someSequence)
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
The master sequence onComplete does not work for you? Sorry I have not used tweens in a few years so maybe I am missing something.
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
I think it does. Test it out.
yeah, will do! again, thanks (can't believe this shit woke me in the middle of the night lol)
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?
Did you check, that it is not still out of memory and therefore backing up to CPU even with the next scene?
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
Can you show the script actually, otherwise its just guessing in the dark
`// 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();
!code
Posting code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
but what we added doesn't work
m_BakeBackend: 2
thats the setting that gets reverted to 1 for CPU
Pls reformat, its hard to read otherwise
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
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
does that work?
Better than this discord formatting π
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
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...
also...
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
would that work?
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?
isint coding all about testing and debugging?
Does native PInvoke overhead basically disappear when you build IL2CPP or how does that work?
there's a chance it can optimize the generated native code to reduce overhead related to PInvoke calls yeah.
Note this based on my own observation when doing native plugins, we have internal tools to check this, but it's NDAd unfort so cant speak much
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 π )
Short answer: no, but it's still faster.
Long answer: https://www.jacksondunstan.com/articles/5120
JacksonDunstan.com covers game programming
Where is this from? Are there code samples?
from .Net future development on the forum
I'm not sure why that would be a surprising result
it is satisfying, also knowing that the fact there are people in the industry getting paid just to porting burst to .net (outside of il2cpp π ) makes it even better π
ah, I could see how that would be reassuring
ah but it does work it turns out π
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.
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
Sounds like a #π»βcode-beginner problem. Post your code there and explain what's going wrong with it.
Istg it's not a beginner issue but ok
"my ground check isn't working" definitely a beginner issue
Looks very beginner to me
Something to keep in mind, a beginner won't be able to accurately assess what level of difficulty something is. If YOU are a beginner, everything should be posted in #π»βcode-beginner
HELP ME MAKE A GAME
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
Don't spam on the server, please. Take a look and #πβcode-of-conduct and helpful resources pinned in relevant channels. Also Unity !Learn should get you started.
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
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
What exactly are you looking to do? Which edges should be sharp and which should be smooth? Also why a computer shader? Is this for terrain? Where does your heighmap come from?