#archived-code-advanced
1 messages · Page 58 of 1
can someone help me understand this piece of script?
https://github.com/KurbanismailovZaur/Pools/blob/master/Scripts/IPool.cs
why are there 2 version of this IPool interface?
interface IPool {}
and
interface IPool<out T> : IPool where T : Component {}
why does it need to inherit from a base only to renew each variables from the base with different datatype
that allows you to do List<IPool>
ahh, I see
so now you can add your pools to the list
Are there any negative performance impact if I set the bounds of a mesh to be extremely large to ensure it never gets culled?
Using URP, the mesh is procedurally generated and drawn with Graphics.DrawMesh.
can you add it to a layer that is never culled?
i don't know if you want to mess with the bounds unless it's legit
there are a bajillion ways to exclude specific things from the different kinds of culling
when i last did this i made a local copy of the hdrp package and manually included the object i wanted every time
Oh I'll give that a shot.
I have my custom shader so the bounds aren't even calculated atm, it's just all zeros.
there are lots of kinds of culling i'm not sure what the meaning of all of them are
the performance impacting things are like on directional shadows
if you don't cull a huge object your directional shadow light will have to include it in its map
The game doesn't use lights or shadows so that's not a factor.
Pretty sure it's frustum culling.
I can't seem to find a way to turn off frustum culling for a specific layer, or at all.
People seem to just get around this issue by changing the camera culling matrix in a way that will include literally everything, or change the mesh bounds to so large that it's always included (which is what I'm doing)
Surely there's a better way than that right?
i would think so
is it possible to include files in Application.persistentDataPath by default? so on a new build?
idk if this is fine, but you could do a workaround by just instantiating the file when the game opens and the files arent there
cause idk if you can add a file to the computer outside of the lets say game folder without having the application opened
maybe in some installer
?
not sure i dont know much about this
You can always make an install script for your game and have that bundle/copy whatever you like to any place you like
That’s Not a unity feature though
you mean after the unity build? inside the xcode files?
some specific folder there?
Installers are separate programs
typically you’d have the app crest anything it needs in the persistent data folder
It’s not supposed to contain parts of the applications static data
yeah, thought so... thanks anyway its not that important
ill include it in the resources , its just for doing some tests
@compact ingot ++
thanks @compact ingot
https://www.youtube.com/watch?v=oO3VdX-nQrQ
In this tutorial, he taught ApplyImpulse and got ref of physicsvelocity and physicsmass from Entities.ForEach. But this ApplyImpulse will be applied to all entities with described components.
The problem is I want to apply impulse on entities near my cursor. So obviously I cant use EntitiesForeach. I have reference for the DistanceHit entities. How do I do this?
Or is there anyway I can get the entities PhysicsVeclovity and PhysicsMass?
❗❗ Caution: This video was made with an older version of ECS. See pinned comment for further Details ❗❗
📌 Download the project files from this video: https://tmg.dev/ECSPhysicsVelocity 📌
💬 Join the conversation with other ECS developers at https://tmg.dev/discord 💬
👇 See below for time stamps 👇
🎮 Let me know what other topics you want to lea...
Hi guys, i wonder if it's ok having coroutine in scriptable object.
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Kahur.Scene
{
public class Scene : ScriptableObject, SceneInterface
{
[SerializeField]
private int id;
[SerializeField]
private string name;
[SerializeField]
private bool isActive;
[SerializeField]
private SceneStateInterface state;
private bool loadingInProgres = false;
private float loadingProgress = 0f;
public Scene(int id, string name, bool isActive, SceneStateInterface state)
{
this.id = id;
this.name = name;
this.isActive = isActive;
this.state = state;
}
public void LoadScene()
{
// do loading of scene
StartCoroutine(LoadAsync());
}
public int GetLoadingStatus()
{
return Mathf.RoundToInt(this.loadingProgress);
}
public bool IsLoading()
{
return this.loadingInProgres;
}
public SceneStateInterface GetSceneState()
{
return this.state;
}
private IEnumerator LoadAsync()
{
AsyncOperation operation = SceneManager.LoadSceneAsync(this.id);
this.loadingInProgres = true;
while (!operation.isDone)
{
this.loadingProgress = Mathf.Clamp01(operation.progress / 0.9f);
yield return null;
}
this.loadingProgress = 0f;
this.loadingInProgres = false;
}
}
}
The goal is to make object able to manage state & loading the scene by itself.
So there will be list of objects holding information on that particular scene and it's current state.
So to also shift the responsibility of loading and preparing the scene to this object and creating only public functions for for example SceneManager to be able determine status of loading of current scene and if to display loading UI and how to fill the progress bar depending on the status
But loading itsef and settings state of the scene I want to shift that responsibility to the scene object itself
That's already working or nah?
personally I'd do it like this
public abstract class MyClass: ScriptableObject
{
public abstract IEnumerator Foo();
}
public class OtherClass: MyClass
{
public override IEnumerator Foo(){}
}
The problem part is coroutine as it's not mono
So thinking of the best solution how to have responsibility of handling loading laying in the scene object ( not need to be scriptable one )
Simly put Scene class scope responsibility:
- Load scene
- Provide status of loading ( 0 - 100% loaded )
- Provide interface to update state / get current state ( data in scene, status, etc so simply to store information about dialogs, objects collected etc etc ), so state handling
So overally more higher level of manipulation with the scene.
So when the game I can access data of the scene object from other scene and update the state of the other scene accordingly, same applies for cut scenes.
and also it will help with management of scenes / loading / switching more independently of each other.
Want you want is a singleton that uses a ScriptableObject to load the scene. In my opinion, Scriptable Object should be immutable. This is due in part with the particular LifeCycle of a ScriptableObject. (There is multiple people that disagree)
Here something that hacked together rapidly.
public class UnityService : MonoBehaviour, IService
{
public void Init() { ... Instantiate ... }
}
public class SceneLoader : UnityService
{
public enum Status { ... }
public Status CurrentStatus { get; private set;}
public void LoadScene(SceneDefinition sceneDefinition);
}
public class SceneDefinition : ScriptableObject {
public int GetSceneIndex();
}
public class ServiceLocator {
private List<IService> services = new List<IService>();
private ServiceLocator ();
public static ServiceLocator Instance { get{...} }
public T GetService<T>() where T : IService;
}
I briefly tried using SOs in non-readonly ways
it's a gigantic footgun; the behavior is completely different in-editor versus in-build
There is a whole GDC conference with Unity member explaining how to use them. Even in one of their Devlog they use it.
https://www.youtube.com/watch?v=WLDgtRNK2VE
https://www.youtube.com/watch?v=6vmRwLYWNRo
I had tried using them in the way described here https://unity.com/how-to/architect-game-code-scriptable-objects
so you make an asset holding a FloatVariable SO, and then hand a reference to it to everyone that cares about the player's health
it winds up being...very funky
Get the assets here: https://github.com/richard-fine/scriptable-object-demo
This session goes over ScriptableObject class in detail, compares it to the MonoBehaviour class and works through many examples of how it might be applied in a project.
Richard Fine - Unity Technologies
00:00 Intro
1:34 The MonoBehaviour Tyranny
5:58 Uninstantiated pr...
I went through this video, quite interesting point
i am very suspicious of anything that mutates a scriptable object asset
That's why you make instances of then you can rip that one apart as much as you like
yeah
that's what I need to look into further
I'll have to give it a second chance :p
Well i love the idea of delegate pattern
It's helping structure the game
and make more self responsible parts
and reusable
so basically, the mono's can contain only logic affecting physics and collisions but the implementation what happens will rely on the scriptable object.
what is perfect when it comes to structure and keeping things clean and tidy
I see this as perfect, solution for ineractible objects, where you don't need to create "fake" objects making things "interactible or changing mouse cursor" but instead having set data for the game object with option interactive and the scriptable object will take care of drawing icon / text or whatever you require to when you get close / or point mouse to it
i have started using [SerializeReference] more
it's also very handy
I was previously creating a ScriptableObject class for each kind of effect (e.g. restore health), and then creating an asset for each instance of the effect (e.g. heal 100)
but I realized that this wasn't a great idea -- I don't want to share the effect instances between different things
now I use plain old classes and [SerializeReference]
i would show an example, but I'm in the middle of a...particularly violent redesign :>
my health potion is just a missing script error right now
[sonic lost rings noise]
I was originally just instantaiting SOs for my damage over time/status effects, but played around with SerializeReferences since it lessens the amount of assets you really need to make, but then I ran into problems where I did want to know types for when I was applying status effect info with my other abilities
stacking burn effects, ect
probably ways around it, but I do share a lot of the SO assets with my other abilities too
it shouldn't really be any different whether or not you use SOs
i was talking about this with someone on here actually
it does devolve into arg is SomeType tho
which usually indicates that you're not doing polymorphism right
e.g.
public override bool CanStack(Effect other) {
if (other is BurnEffect)
return true;
// ...
}
I'm thinking of implementing status effects in my soulslike game...exactly like in dark souls

where each effect is basically just another stat meter, like health or stamina, except it goes UP when you get hit with it
and an effect occurs when the meter is full
that simplifies it enormously
At the moment I do have like abilities that have their own innate damage over time effect too, so there's some more checking of that too beyond the shared status inflicitons (so SerializeReferences would be better here in that case)
But Another reason I do prefer the SO instantiation idea is it does allow you to just create a handful of buffs/effects which can be shared about with other abilities
which is just more of a game design decision
ex. keeping buffs at specific amounts
Oh, and I did run into some issues of wanting to cache some of the formulated data before constructing, which I do read from the SO beforehand
anyone here familar with saveing data using Json.net or Jsonuntility? i seen where the Jsonuntitlty fuction was limited what it can save
If you don't mind the turtle-ness and bunch of unnecessary allocation you can use the Newtonsoft one packaged by Unity
OR a much better option
since 2022 and above Unity supports System.Text.Json, you can download the nugget package and add it to your project set your linker so it won't get trimmed when compiling (if you're using il2cpp, mono should work as is)
I feel the issue you were having is that you did not correctly divide the concept of the abilities with its actual behavior. I could be wrong, but here an analogy that can help you understand the concept.
Whenever you go to the market, you go with idea of buying something (Let's a fish); This is the immutable part.
Whenever you arrive at the market you buy the fish; This is the mutable part.
In the immutable part, you do not know what are the specific attribute of the fish. You only know what every fish share between them. (Name, Description, Visual, Price, etc.)
In the mutable part, you know the specific attribute of the fish. (Weight, Smell, Freshness, etc.)
In Unity, the Immutable part is most of the time represented by Enum, SO, Prefab, Const, String.
The mutable can be represented by MonoBehaviour, GameObject, POCO, [SerializeReference], etc.
@bleak citrus hello there, just want to thank you for what you posted yesterday about flattening the array, your answer didn't essentially fix my issue but it gave me a better understanding about how flattening works. My code works fine now and best part it now runs on a parallel Job! Went from waiting 10s each time for generating data to only 0.4s!
nice!
In the end the flattening was as simple as this
...
why didn't I think of that one
lol
Oh right, because I was writing an accessor, not flattening a whole array
i wouldn't want to count up all the way from zero
This hurt
Do you really need to copy all element ?
No worries, that is just some "psudocode" in the end I did not needed this function at all
I made a 1D array from scratch so its way faster
no conversion involved
are you suggesting an alternative where you just adapt the 3D array to be indexed by a single index?
so that you don't copy the entire thing into a 1D array
Use a 1D array from the start.
my game has black bars how to remove?
Yeah, I can think of ways I could go about mapping my data instead of relying on the SO type. Perhaps when I expand out my assets a bit more I'll go back to it, but I do enjoy having a collection of SO assets like 'Minor Intellect' and 'Major Intellect' type buffs which can be easily swapped around in the editor to make my potions and abilities to define a set range that's available in the game.
my game has black bars how to remove?
Hello good people of the unity discord, I come to you all in a time of great need. I have been attempting to debug an error for the past 4 days straight with little success. Here is a video that shows the intended functionality, a unit controller that moves groups of units around nicely with some help from A* pathfinding, and if you skip to the 35 second mark it should show you the bug. For some reason, one of the units gets set to the same position as the first unit, which is definetly not what you want to happen in the middle of gameplay. Help would be, a literal godsend because as you can see in the bottom of the screen its 12am for me and i am losing many braincells. The two scripts are also attached. The first script is the general tank controller, and the second script manages selection.
Group of Game Objects error
Just need a keyword to look up and I can research it on my own: I'm creating mesh and animation assets through scripts in the editor and I'm wondering if there's any way to group them together like fbx files are, how it has the little rollout arrow that shows you all the parts inside it.
You can export a gameobject hierarchy as fbx https://docs.unity3d.com/Packages/com.unity.formats.fbx@2.0/manual/exporting.html
Yeah, that was one of the options but I'm hoping I can skip the middleman, so to speak. Should I just use a folder instead?
(Appreciate the response, by the way 😊 )
I think this may be what I'm looking for. Scatterbrain moment, I appreciate it 💜
For a SO .asset in project, when does it get instantiated? docs say "at game start" but thats clearly not true, i have a fresh SO with an Awake message that logs and its clearly not logging. the SO has to be referenced by something in a scene maybe?
Whenever something that references it is loaded
Generally I'd say Awake in SOs is probably not what you want
because in the editor they're often loaded way before playmode
yeah am i trying for the wrong thing
ahhh
im trying to lean into using SO's as services rather than singleton "manager" monobehaviors on gameobjects
but in order to get a 'game start' event on a SO, should i just be having a simple monobehavior that links to the SO and kicks it off?
I would probably do that, or attempt to register some appropriate callbacks using one of the many static attributes Unity has
yeahhh isnt there an attribute or something that calls a method on gamestart
darnit what are those called
hm, SO's OnEnable seems to be called every time I enter playmode?
OnEnable is generally what I use in editor code that uses SO's, so if it's firing consistently it may work for you
huh i dont really want it firing constantly when im in editor
and now im even questioning whether i want it every time i enter play mode
after reminding myself that "test scenes are scenes" 🙂
i have PTSD from my last unity adventure a couple years ago... a decent sized project that ended up in unmaintainable hell. everything was a "manager" that had a hard reference to every other "manager" and had to all be on this big massive singleton object that you had to have in any scene for anything to work
i recently saw a few of the famous "SO's for everything" videos and while im not a total fanatic, there were a ton of great tools for the toolbox and im trying them out in my latest unity adventure
currently playing with netcode + facepunch and seeing what networking is like. one of the tute videos i watched is using a singleton mono to persist lobby info across multiple scenes. so i said "ah hah that should be a SO"
now that i typed that all out im even questioning that conclusion, i mean why not just make it a plain ol C# singleton
ok i need to think about this more lol
I'm trying to find how to convert NavMeshData generated by the new NavMeshSurface component to a mesh asset.
why?
Hello there, what is an alternative to IEnumerators / Coroutines? I am currently using jobs and burst system with an IEnumerator which basically displays me terrain chunks once the job has completed (Im doing a voxel game).
I have seen this IEnumerator produces some garbage collection which results in stuttering in a frame, this is pretty noticeable; I have managed to work around this by enabling the incremental package CG on the player settings but sttutering still happens once in a while.
UniTask is what I personally use and would recommend.
Coroutines are like caveman level of primitive async programming.
Is it compatible with job system?
It feels like that lmfao
Not sure, but you can wrap anything into a task with like 3 lines of code, just like regular C# async/await.
Very interesting, I will take a look into that, thanks!
I think newer versions of Unity also have their own new async stuffs, haven't looked into it.
No idea there, I am fairly new into async stuff / heavy optimizations
I have tried to use job.schedule in c# async function together with await task.delay , works
Oh, good to hear that, Uni task is the way to go then!
Did you see improvements compared to IEnumerators?
C# tasks still allocate, UniTask practically has zero allocation.
On i am using task not unitask
Ohhh okay, I miss understood, I though C# task and Uni task were the same thing
Ahh alright, makes sense now
Im gonna give a change to Uni task
My game already runs very smoothly, but I still want to prevent unwanted sttutering due to GC
Familiarize yourself with regular C# async/await if you haven't yet, UniTask reimplements basically the exact same equivalent API but in allocation free manner (you can find a table in their readme to know which UniTask API to use instead of C#'s)
Even if performance isn't a top priority, I'd still switch just so I don't have to touch coroutines, with any remotely complex async logic coroutine quickly breaks down into a ball of spaghetti.
Alright, I will take your advice, thanks you so much!
Oh noe, the big scary GC causes stuttering again.😱
In case someone runs into the same issue, the solution of setting a huge bound works, but it does seem to have negative performance impact even if you don't use lighting/shadows somehow.
Instead a solution that works for me is that, find a point that's within the view, invert the transformation matrix and multiply the point, and set that as the center of the bounds of the mesh you want to prevent being frustum culled (while leaving extents at 0)
I have no idea why we have practically no control over frustum culling and have to resort to these workarounds, but oh well.
is it possible to make an external CS file have the intellisense stuff from my unity project?
for purposes of modding
im pretty sure, correct me if i'm wrong, that the csproj file handles this stuff? but when i try to add my test mod.cs file to the Assembly-CSharp.csproj, it says the project has already been added
using visual studio
Anyone willing to hop on the call, to help me figure out the Unity C# issue maybe point me to the right direction what i might be doing wrong.
It's set of classes communicating with each other, but somewhere down there it's behaving quite weird. I'm trying to delegate responsibility, to the lower class ( no mono ) but when it calls the Manager ( mono ) it seems like even the object is in game and in ready state, the class at the moment of clicking does not have the data there ready
Maybe I'm doing something wrong implementation wise, so that's why it would be good if someone can hop on and tell me what i might be doing wrong in Unity
did anyone have written c(++) style macro in his code and using preprocessor (maybe gnu) to replace the macro?
if it works, i can inline some function.....
If you want to inline a function use the [MethodImpl(MethodImplOptions.AggressiveInlining)] attribute
macro actually guarantee it must be inline and you dont have to pass arguments (just code the same name) and you can write something like this without function pointer:
the only problem is no one can understand at first what you are trying to do
But why
There is no reason for this, if the compiler can inline it it will
Macros are oldschool and not useful in C#
i think macro is so convenient......
i find the second example wrong, it should be i=100;i>=0
if you're looking for IDE convenience, you could investigate customising code snippets instead
Thanks
Both for and forr should be default in any IDE though
how would u make miiverse style social media in unity 2018
How is this ever convenient
That macro is unreadable because nobody will understand what half of it means despite is being a simple loop
You have achieved very complex code by trying to make not complex code even less complex
it certainly doesn't do anything w.r.t. making sure something is "inline" if it's used to create a for loop :p
I am making a city builder game and for the roads I have methods that can return me the points of the road spline.
For in case of intersection I have designed a custom data structure to store the data of each point.
For example a rough idea of what my points of road spline would contain.
bool isConnectedToPower;
bool isConnectedToWater;
.
.
.
bool isConnectedToSewage;
Other data that a point can include are in the picture.
Do you all have any better idea on how to solve this problem?
I would decouple the power, water, and sewage networks
manage them all independently
and each of them is a standard graph structure
I am using the roads to deliver the services
and buildings connected to road that is turn connected to the service building will get the services
But how can this me made to work? Please explain
I am not using grid based world
You don't need a grid based world to use a graph
A typical graph representation is an adjacency list
Can you show me some pneumonic code?
no
If you're not familiar with graph data structures and algorithms and you're trying to make a city builder you might be a little in over your head
the internet is full of graph examples, tutorials, etc
This is what I had designed for a grid based system.
I'm having difficulty programmatically setting the LimbSolver2D effector without relying on the editor. I'm attempting to automate our character setup and wondering if there's a solution that i am not seeing in the code.
https://gist.github.com/kristiandelay/c1f17a39c5db7689b8291942b4ff1afa
have you looked at the source for the package?
is this helpful? https://github.com/needle-mirror/com.unity.2d.animation/blob/d481026c675b372e74f08f5f0afc270f67ca9af0/IK/Editor/Inspectors/Solver2DEditor.cs#L133
[Mirrored from UPM, not affiliated with Unity Technologies.] 📦 2D Animation provides all the necessary tooling and runtime components for skeletal animation using Sprites. - com.unity.2d.animation/...
yea from what i could tell there was no method or built in way to set the effector for a LimbSolver2d and let it build the chain like the editor does. i just wanted to double check before i write code to do it.
i was hoping there was some method that takes in the effector target and builds the chain somewhere but i didnt see it
everything the editor does is in the package i linked you
so whatever it is you want to do, it's there
for sure i figured that was the casse ill just write the code
seems silly its not built in method
I need some help in Barrcuda,
I am trying to use this model (specifically this one, and I can not use another one)
https://github.com/WongKinYiu/yolov7
I exported the pytorch model, using the python code in the repo above to onnx model.
When I imported it give warnings about end2end not supported (which I then removed from the exporting flag) and it give a warning about resize not supported, which according to
https://github.com/Unity-Technologies/barracuda-release/issues/271
can be fixed by setting the version to 9 (which I did by setting this line
https://github.com/WongKinYiu/yolov7/blob/main/export.py#L159
to version 9)
and the warning disappeared, however the output shape, was weird,
it was
n = 1, h = 1, w = 85, c = 25200
any ideas how to interpret this?
seeing the original python code
https://github.com/WongKinYiu/yolov7/blob/main/detect.py#L100
this is where it reads the predictions,
and this is where it get the box boundaries,
https://github.com/WongKinYiu/yolov7/blob/main/detect.py#L122
however, I am not sure what the code is exactly doing, nor how should i do a similar thing in C#
i suggest ticketing the repo with a colab notebook that exports the file with a unity project
to reproduce it
are you asking how to interpret the output shape?
If I don't care about analytics from IAP, but still use the Unity game services IAP libraries, do I need to enable the service, or will it work without the UnityGS linkage?
it's telling ytou here:
output_names = ['num_dets', 'det_boxes', 'det_scores', 'det_classes']
those correspond to the end2end model
not sure what you mean?
hmm... well i'm not sure what you are asking for
it sounds like you want little rectangles
with class labels
I know about notebook that have a python environment but what do you mean by a unity project?
exactly
why?
so, I can highlight the objects being detected within the scene
my current task at work,
integrate this model, in unity.
hmm
okay well you didn't do
When I imported it give warnings about end2end not supported (which I then removed from the exporting flag)
correctly i believe
do you know why you are trying to detect objects in the scene?
are you sure that's what you are trying to do?
what is your actual goal?
oh wait a minute
i remember you now lol
i mean based on the shape you exported the end2end model
so i don't know what you managed to do
or how you're messing with that repo
few months, ago It I run it with python
and it was very messy communicating between python and unity and never really worked well, so we hope this time we just use barrcuda (which I believe was your suggestion)
you probably still have about 6 months left
i think you should try to get everything to work with a known working image detector
and then try to get yolov7 specifically to export
because you're getting tripped up in what all of this stuff means
you're imagining it's a reusable software library
and it's not
it's just someone's research project
what do you mean, I don't understand what exactly, end2end is to be honest, I assumed it is some feature like doing float32 or float16, since I saw It was not supported, I just didn't pass
end2end on the command line when exporting.
less than a month.
have you gotten any object detection working?
I mean, I don't understand what you mean by object detection working? you mean with unity?
I had a play at this
https://www.youtube.com/watch?v=LhzKfx2kuDs&ab_channel=ThirdAurora
okay well you start with you have to use yolov7
but there are other object detection tools
that i think you found, that work in unity without you needing to export
do you have that working?
no, because I am not sure what other object detection tools have different?
it will consist of onnx model that you have to use, the way the model is built determine the output shape. I was expecting, the output shape to have count, and then an array of boxes and a label. but clearly I am missing something.
i think this might help
will have a look thanks.
But from your comment, you are saying that the shape I am seeing is normal?
25200, represent what exactly?
don't know
probably the class and array of boxes
you mean, the label of classes? 25200, that is a lot of labels
i'm saying it's a classification, a probability, followed by 4 corners or similar
well, it probably recognizes a lot of things
https://docs.unity3d.com/ScriptReference/SystemInfo-deviceUniqueIdentifier.html
WHY WHY WHY WHY WHY 😠
I've had to re-sign my application and now all my android users have different device Ids
Anyone have any bright ideas how I can .. resolve this?
When a user logs in, I'll see their device id (I'm keying a user file to that) - but I don't have another great data point that I can find their old user file from. IP address, device OS maybe..
You don't really, you have to map them somehow based on the data you have
sigh, that is a super frustrating gotcha
I'm going to have to have them log in, tweet/email support, manually figure out their new device id based on those other datapoints which I maybe have, and update the data in the database manually.. ARGH
i am sorry
As it turns out my solution from a few days ago did not fully work
I am trying to do a twitch-plays game using unity, (having mario party be the game chat plays)
Using SendKeys.Send works for most applications, but not in games emulated by dolphin emulator.
anyone know a good way to either get around this somehow or send inputs to other applications?
AHK sends real inputs i believe, that arent distinguishable from keyboard/mouse
What is AHK an acronym for/where can i find documentation on it?
it is its own scripting language, not something in unity
https://www.autohotkey.com/
It's easy to use, just make sure u always code an exit key incase something goes wrong :p
Free keyboard macro program. Supports hotkeys for keyboard, mouse, and joystick. Can expand abbreviations as you type them (AutoText).
is there a way to integrate unity code into autohotkey code?
From just skimming the github repo, you can either find a way to run these pre-defined scripts using whatever C# has to offer or you can copy from the source code itself
Also AHK is only for Windows
Idk if that would be an issue for you
my main computer is windows, however a device I intend to use this script on is a mac, as its a computer i dont use I could leave a twitch-plays stream up on it
Then AHK won't work for you
Unless you want to take the source code and make it cross platform
Also if you're using SendKeys.Send, that also only works on Windows
since it exists under System.Windows.Forms
which would explain why it doesn't work on dolphin
or mac, for that matter
Why would you build this in Unity, rather than just a regular C# application though?
i mean why would you ask it there shortly?
AHK is known for cheating anyway
If you want to automate operating some software you don't own and have no choice but to go down the simulating input route, AHK is still the most reliable solution
Lots of ways to simulate input with Win32 API, but each of them tend to work for only some software but not all, so you end up dealing with a ton of edge cases.
im very confused, I cant figure out on how to make "procedurally animated guns" because I cant find ANY tutorials on it?
When you mean for guns what is your goal with the guns animations?
ive seen lots of videos saying "my guns are all procedually animated" and it looks better than normal animations so i went to figure out what it meant and there was nothing.
Put your gun in an empty parent and animate the gun's local position and local rotation in code, maybe in LateUpdate or Update
You can use Mathf.Sin etc, and/or AnimationCurves
thats what i have been doing, but i dont think thats procedual (emphasis on the "think")
Mixing "traditional" and procedural animation is fine
You can have the walking animation from animation curves
ive been using the "DoTween" package to animate them but i dont know if its procedual or not, so i was just checking
But the turning sway can be procedural, for example
That could count as procedural animation, yes. I wouldn't get too hung up on the terms though.
If you have specific stuff in mind, ask away
Procedural is kind of a loose word here
ok thanks
you can get raw inputs in Unity via unmanaged api
but why? 😄
Original question wasn't mine.
var customOldUIClone = Object.Instantiate(customOldWorldInfoPanel.instance);
var gameObjectCopy = Object.Instantiate(customOldUIClone.gameObject);
var old_component = gameObjectCopy.GetComponent<UniqueFactoryWorldInfoPanel>();
Object.DestroyImmediate(old_component);
gameObjectCopy.AddComponent<NewUniqueFactoryWorldInfoPanel>();
What is wrong here?
is this supposed to be a puzzle?
I am trying to duplicate a panel
the panel is a UI that has a control class
and why do you think it is wrong?
i am trying to copy the UI remove the old control class and add the new class instead
it is a mod for a game
when you click on a building in the game it has an info panel opened
but when i click the building i get an error instead
NullReferenceException: Object reference not set to an instance of an object
have you attempted to debug this at all?
null reference exceptions are very common (and very straightforward to diagnose)
something is null.
the real issue is that although i copied the UI successfully when the ui do appear buttons dont work like close and when i debug it "this" is null
it is game specific so it is hard to explain
show your code with the debug statements added.
oh, you literally debugged it, gotcha :p
show the full stack trace of the error
the game has worldinfopanels which are sons of this class
yes, give us a stack trace
that means that you tried to call a fucntion on a null reference
if you're getting the error at this point - the code is being called on a destroyed script
actually, that might be more correct: would it even make it into the member function if the reference was null?
this is likely to happen if you:
- subscribed to an event and never unsubscribed when destroying the object
- kept a reference around to the script and never discarded it when destroying the object
True null no.
Fake Unity Null yes
ah, yes, that would make more sense.
Fake Unity null is what you get when you Destroy something
wait will show stuck trace.. although i don't think it will help
It usually helps quite a lot
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
stack trace, please
a powerful website for storing and sharing text and code snippets. completely free and open source.
wait a sec
Is it just me or are you calling PrefabUtil.TryCopyAttributes<BuildingWorldInfoPanel>(old_component, new_component, false);
right after you
Object.DestroyImmediate(old_component);
really not sure if PrefabUtil will like that
right so it's happening during OnClick handling for a button
which means you aren't unsubscribing/removing the listener when this object is destroyed
but i don't want the object to be detroyed
i am just replacing the control class
i want the UI to still work
Hmm, dnspy is generally used as a decompilation tool.. 
The code looks generated.
Then... don't do this I guess?
var old_component = gameObject.GetComponent<UniqueFactoryWorldInfoPanel>();
Object.DestroyImmediate(old_component);```
this is "UniqueFactoryWorldInfoPanel" the control class
anyway - we've helped enough considering
Directly discuss modding or decompiling.
Is in #📖┃code-of-conduct
ok moving to modding
is modding not allowed?
the game developers allow modding
This server doesn't support discussions about modding or decompilation - ill intended or not.
I see, is there a place i can get help?
Probably - unfortunately not in this discord.
#531949462411804679 if you want to discuss the rules with the moderation team
ok
There are likely other unofficial unity servers that can fill the gap.
ok
I am making a dash ability of player. I want the dash is able to dash through enemies. So, I disable the collision of player and enemies when dash start and enable it again when dash stop. It works but sometimes if player is still "inside" a enemy body, they will then push each other away like bouncing off. Is there any solution?
Consider what you're wanting to happen first.
check the endpoint u are gonna dash to and dont dash if collision
I dont want this. I want player to dash whenever they want.
many solutions:
- Don't allow dash if it will end inside an enemy
- Continue dashing further if there's an enemy where you end up (what happens if there's a lot of enemies in a row??)
- Disable collision temporarily with any enemy that you're inside when you end dashing
but what happens if your dash ends in an enemy?
you can also check positions around a collision point if you collide with an enemy scan for an open area to dash towards
I have tried to move the character away by its radius after dashing if they are inside the enemy body. But sometimes if there are many enemies in a area, the pushing still happen
theres simply gonna be cases where u have to disable dash if u disable collider
wall checks all kinds of reason
Generally in a 2d platformer, you'd prohibit the player from dashing through thick walls or enemies (horizontally large objects).
this is the important question that they aren't answering #archived-code-advanced message
What do they want to happen
i am in 3d and I have different layer for walls and enemies so no problem with the wall problem
What should happen if they cannot dash completely through?
wait till enemy is standing next to objects and walls
I want the player to move to the nearest transform with no enemies
"move to the nearest transform" is a weird way of saying that. the player should move to the closest empty space, it sounds like
are u using a nav mesh?
yes move to the closest empty space
sample position
You should consider dashing to the farthest "free" position from the start of the dash to the end of the dash.
I am not using nav mesh
But there is some time between dash start and dash end (0.3s). if the monster move, there will be chance to dash inside its body
Vector3 searchCenter = dashEndpoint.position; int attempts = 0; while (attempts < maxAttempts) { Vector3 randomOffset = Random.insideUnitSphere * searchRadius; Vector3 searchPoint = searchCenter + randomOffset; if (!Physics.CheckSphere(searchPoint, 0.5f, obstacleLayer)) { transform.position = searchPoint; break; } attempts++; }
check around the endpint
That is going to be costy.
for sure im just trying to give them an idea
dont copy paste it and say thats end of all be all
doing a few queries at the end of a dash wouldn't be the end of the world
It really depends on your targeted hardware and the amount of attemps.
lol for sure
sure, everything depends :p
in the current context (a function that runs at the end of the dash), it doesn't ring any alarm bells
just get it functioning first, dont get caught up in optimization of something that doesnt work is what i was taught lol
but I suppose the search is happened when the dash stop, thats mean the dash is already happened.
u can also cast a ray and dash so u end up in front of the object
or behind what ever choice u like to make. theres many ways todo it experiment and find the fun
ok this strikes on me. I would work in this direction
Thank you so much
Hey guys, is there any way to send the Debug.* function's output to files in unity ? Even for builds that we create?
It already outputs to the player log file in dev builds.
you can use the -logFile cli, use the default log file, or add a log handler
hey guys, quick question, anyone know if there's a simple way to pass an objects current velocity to a custom shader attached to a trail on that object?
dont even need to tell me how, just interested to know if it can be done trivially
you can bind values use a property binder in vfx graph
will look into it, thank you doctor ❤️
will I be able to access it as a vector in my HLSL code?
Hello, i am having the hardest time finding a good full-body FPS controller tutorial or anything online detailing best practices to make one, most of what i find are just people selling their asset packs for one but i really want to avoid just taking someone else's i would prefer to create my own as to fully understand it and have maximum customizability , ive tried creating it myself to no success. Im having trouble finding a method to rotate the upper torso spine. I can get them to rotate but i run into the problem of their local rotations obviously not being aligned so when rotating up they rotate the torso diagonal and stuff. Im unsure of the correct method to handle torso rotation. Any ideas or good tutorials someone could point me to?
what is your goal
Sounds like you want to rotate in world space rather than local
i want a full body fps controller often seen in milsim games like tarkov or squad something like that
right but if i rotate in world space then the up and down axis for the torso would change if he were to look left or right idk how to explain
as long as it takes i suppose
is this going to be a multiplayer game?
ideally yes
you should probably start with the online fps sample from the DOTS character controllers https://github.com/Unity-Technologies/CharacterControllerSamples/tree/master/OnlineFPS/Assets
ECS is the only way to make a robust networked FPS in unity
@crystal oar is that helpful?
sort of a waste of time to do an FPS from scratch in the gameobjects workflow
Here two tutorials that could help. One is on the whole controller while the other is on the animation. Knows that both are not necessary what is used for more realistic games. (Inverse Kinematic and Root Motion)
https://www.youtube.com/watch?v=FbM4CkqtOuA
https://www.youtube.com/watch?v=W0eRZGS6dhQ
More advance stuff:
https://www.youtube.com/watch?v=5DlTjasmTLk
https://www.youtube.com/watch?v=Xl_5roq4UlI
Hey guys, a small question: Where should we usually place files which we created for say communicating with an API, when we make the final build (Which folder does the api key file etc belong to in the final build)?
highly recommend not including any API keys in a client build
The secure approach is to have your own server which the client communicates with (with user authentication potentially), and your server communicates with the third party API.
If you include API keys in a client build, then anyone can take that API key and do anything they want.
If you are paying for API access for example they can now freely use that API on your dime.
Or spam the API and get your access shut down, etc.
I am trying to get this code to save the Time Since Last Breed time and recall it when the game is reopened, I need it to continue counting down while the app is closed but i cant even get it to recal the time when the app is reopened let alone keep counting. I have tried everything i can think of down to saving the timeSinceLastBreed value every single second to a playerpref. but when i close and re open the player in unity it reset the breeding time to the default, anyone proficient in C# who could spare just a moment to breeze over my one script n see if anything sticks out?
Start by using proper saving solution. https://blog.unity.com/games/persistent-data-how-to-save-your-game-states-and-settings
Ok I was under the impresssion playerprefs were ok to save things like that, that should be a better way, working on implementing that now.
What’s the advantage?
Is the DOTS networking system just more richly featured?
Or is there something about the ECS style that’s advantageous?
i have a moderate amount of experience working with ECS, but zero with multiplayer ECS
"The Netcode for Entities package provides a dedicated server model with client prediction"
ah, I think I'm answering my own question here
i know that Netcode of GameObjects has a nice list of ways to make multiplayer feel good, and then says "have fun implementing them"
i had a big conversation about this in the dots forum you should read - https://discord.com/channels/489222168727519232/1093995455475625994
the online fps sample has netcode
the essential thing to understand is this is the only way to engineer a multiplayer fps in unity
you can certainly also create a whole new engine and pretend to be using unity, and it can be not an ecs approach, but it will be worse
i'm going to be honest...I couldn't follow most of what you wrote. you talk about "physics" very frequently in contexts that are unrelated to physics
i did not come away from that with a strong belief that ECS is the only way to make a coherent multiplayer game in unity
people can try to remake Tarkov and Rust, the only two Unity multiplayer FPS experiences anyone plays
that's not a journey i want to take
you talk about "physics" very frequently in contexts that are unrelated to physics
the vast majority of unity developers making 3d or fps gameplay use raycasts, colliders and trigger callbacks, making them all users of physics
so in my experience, the context related to physics is most gameplay
are you talking about BSPs here?
i don't know what source 2 uses, but source 1 used havok for inertial physics. i think both use a file format called bsp that represents level geometry in a way that is efficient to do spatial queries in
i don't think it's a binary space partition
i know that's what BSP stands for
i know there's a colloquial name for that file format
i don't know what source 2 actually uses, but it's not a plain mesh like unity
it's hard to say! brushes are dead in source 2
so maybe it is Just Meshes and maybe i'm totally wrong!
they didn't know
that's why i didn't say what physics it uses
because i don't know
@bleak citrus it looks like facepunch is developing something called s&box that is roblox++ on top of source 2
that is maybe the official way third parties will build source 2 games. source 2 is ECS
so this seems pretty unequivocal for me in terms of how a modern FPS is made. everyone with experience shipping the biggest FPS experiences - valve, blizzard, facepunch - made an ECS engine
source 2 is ECS?
What's with you constantly telling people that it's impossible to write netcode in unity?
It's a complete lie
stop it
there's absolutely nothing stopping you from doing multiplayer networking in OOP unity. Rust, Tarkov and hundreds of others have been doing it for years.
i am certainly not convinced that there's some kind of fundamental difference that makes it impossible
It would certainly be much better to do it in ECS
But there's nothing stopping you doing it in regular unity
what's the key advantage?
so it's not that there's something about it that makes, say, server reconciliation easier
physx isn't designed to be rolled back. But you can still do it
and it works perfectly fine
so no, rollback isn't easier on ECS
rollback is a high level idea
ah right -- ECS physics is stateless. I imagine that makes it simpler to re-simulate?
no idea
you can get better deterministic results
since it's stateless
there's a lot behind the scenes that goes into writing netcode.
If you haven't started yet, I would probably go with ECS
oh yeah, I haven't got any plans at the moment
I experimented with Netcode for Game Objects, but I haven't tried Netcode for Entities yet
i'll probably give that a go (and then a second go) before trying any kind of major multiplayer project
my main experience with ECS is making a game that has ridiculous numbers of entities, rather than anything particularly productive
apparently yeah
Just curious, doctorpangloss
what do you think is stopping someone from writing proper multiplayer functionality in unity?
Or just keep ignoring me that's cool
nothing its just a large job
This is probably the third time I've opened advanced, seeing you tell someone that it's outright not viable
and hard to do right for a single person
not you passerby
which is why 3rd party libraries exist
him saying that ECS is the only proper way, is just false
until i try it myself it's really hard to say
yay ignored me again
I am unable to find anything to back this up.
When he's referring to ECS, he's probably referring to data oriented programming
which valve is likely using in source 2.
here's an example - https://wiki.facepunch.com/sbox/Entity_Components
Entities can have components, which are code classes that can be attached and detached from Entities via code during gameplay. Because Entity Components are open-ended, they can be used for almost anything from giving players power-ups, to handling ad..
s&box is the only third party source 2 game
i found it elsewhere written verbatim, but i think these snippets remove all doubt
This is all Facepunch's implementation afaik. They made a wrapper for C# for the source 2 engine, Valve is not using C#
even before unity had dots some people built ecs style systems into it
its just a pattern
Also this doesn't necessarily look like ECS, it looks like ECS in the same way that you can construe Unity's monobehaviours to be Entities and Components
is this even an entity-component-system setup
but yeah that looks more similar to how non dots unity works
those componets have logic in them
okay
where ECS components are pure data, and systems process that data
where are you getting this information from
i have a million pages open
i just read it
your patience is appreciated
it's a really esoteric thing to say verbatim
in a page
what
what that list link shows has way more in common with just a basic composition workflow like people normally use in unity then a "Entity Component System"
yes, it's very clearly an equivalent to game objects and components
sure it has replication and stuff in it out of the box
but that does not really differnet much from say UActors in unreal
it even has Pawns!
i think because it was originally prototyped on unreal 4
i am trying to get a verbatim answer
also goldSrc and Source alwyas called your base type a Entity
from people who have seen the source code
i understand these things... this engine is old, dating from 2015, it's going to have a lot of names for things
but like i said whats in that docs page is not following the ECS pattern at all, its just composition
that may or may not be different
Is this actually going to be relevant
no
Then we can probably put it to bed and go "who cares what source 2 does"
i think so.
There are plenty of FPS games in Unity, many of which have functioning non-ECS netcode. Whether or not it's going to be as robust as ECS, who knows? Afaik ECS will just help a TON with data compression and prioritisation
data compression isn't really the main idea of it
But #archived-networking is probably the better place to be asking about netcode, and #1062393052863414313 if you're using ECS
ECS is a pattern to solve certain problems like other patterns
that is all it is
you can still solve the problems with other approaches
It's a pattern for efficiently using cache locality
i have no strong feelings about this. the right "answer" is to not develop any more of these experiences
you. will. fail.
lmao what
i am trying to stay positive. there is a path to success for an indie developer here. that is why i am advocating for a technology purpose built to make networked fpses
you have not a damn clue what you're talking about
there's a specific sample written by 1 person that is highly representative of what you can achieve - the ecs character controllers OnlineFPS example. it looks good
you can certainly choose alternatives that are not meant for authoring FPSes. no one is stopping you
really if i was making a multiplayer fps with design similar to existing multiplayer fps's i would just not use unity
Animations hardly even exist yet in DOTS
"Yeah man you aren't gonna succeed unless you make your multiplayer game in ECS!"
What would you make it in?
If anyone wants to continue this convo, at this point please make a thread
depends on what i need design wise but unreal or some form of idtech
Unity is very good as a general use game engine, you can make pretty much anything and it will stay out of the way. but also because it stays out of the way and is less rigid in its usage is why having good netcode out of the box is much harder then something like unreal or idtech or source
yeah I don't think you're going to have a better time switching from unity at all.
on the flip side those engines have opinions on how a game should be made and fight you more when yours does not match that mold
The problems with using pre-existing networking models, is that if something doesn't work the way you want it, you're screwed
I'm sure you've played Garry's Mod multiplayer before, but source had an issue where they just didn't rollback physics objects in a multiplayer setting
and it pissed a lot of people off
Make a thread 🌈
👨🏿
Is there a way to make unity work with F# besides just compiling to a dll and importing it every time?
I'm thinking of something along the lines of hacking the asmdefs or the generated csproj files to allow F# sources next to C# sources in assemblies. Anyone ever done something like that?
I have not done it myself but I ran across a reddit thread with people who have, and apparently you can get it to work but F#'s functional code style doesn't work well with Unity's API design.
Yeah, but I still want to try F# for some things. Sadly all I can find on Reddit is people creating DLLs to include in unity. Which can be a pretty annoying workflow, especially since one needs to be really careful about referenced dependencies and versions in custom-built DLLs.
Yeah that sounds annoying to deal with.
Hello there, not sure if this should be posted here, but anyways... I have a burst compiled job that generates a procedural mesh, it adds its vertices and faces accordingly but when Its about the UV part, I need a way to somehow add the proper UV of a sprite (it is a procedural voxel, so It takes sprite UVs for setting up textures); since I can not pass classes inside a job, how would I pass an instance of a class inside my job?
the way I was texturing before using jobs system was actually calling a method from another class and do some calculations to set the UV coordinates and its sprite texture
Oh wait I think I can get it working
Just trying to check my work here...
Is this...
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "C:/$$$$/$$$$.exe",
Arguments = "-logFile C:/$$$$/log.txt"
}
};
The same as the following command...
C:\Users\$$$$>"C:/$$$$/$$$$.exe" -logFile "C:/$$$$/log.txt"
More or less. Note that Windows uses \ as a file path separator, not /. This may or may not matter.
You'll also need to enclose the path you pass as an argument in quotes, if it contains spaces. Otherwise it will be treated as multiple arguments
Added to the comment above, for System agnostic path seperators use this https://learn.microsoft.com/en-us/dotnet/api/system.io.path.pathseparator?view=net-8.0
Or better yet - build your paths with Path.Combine
Didnt know about that one, thanks
Hmmm. That line... "-logFile C:/$$$$/log.txt" doesn't seem to work. It doesn't generate the log file. ...and I doubt the / as opposed to \ has anything to do with it, because the .exe launches fine.
Worth a shot.
** I asked this in code-general but was pointed here. ** If I have a series of textures of concentric colors, and I want to procedurally create 3D-looking blob objects based on the colors. For instance, in this image, I'd want a blue blob in the center, a green blob around that, and an outer red blob based on the color shapes in the textures on the 3 planes. Then I could hide the outer blobs based on hit, revealing the inner blobs.
First, I thought if I could get the pixel data with world coordinates for each pixel and then spawn metaballs that are spread out on the mesh, that would work. So, maybe GetPixels would work but my final textures are on a wide cone, rather than a plane. I looked for ways to extract world coordinates from the location of a pixel in a texture, but could not find anything that was what I was looking for.
Then I thought raytracing might hold the answer, but that's very new to me and wondered if someone could point me in the right direction, if you think that may hold the answer.
isnt this something better done in a shader?
or are you planning on having collision for it
maybe if you draw a sketch of what you think you want the final thing to look like itd be a little easier to visualize
do you have any spaces in there?
since you're just passing one big string to Arguments, it's gonna need to split on something
Well it's just the two arguements. The logFile and the <log_file_path>. With a space in between.
The path does have spaces in both the Command Window and in the code. The code is encapsulated in quotes so it doesn't treat it as multiple arguements.
when you say "doesn't work"... what's actually happening?
The Command method launches fine and creates the file. The code method seems to get hung up on something (doesn't fully launch the .exe) and does not create the log file.
Also... why are you populating FileName inside the object initializer but the rest... later?
I think it's possible the Process constructor reads all the StartInfo data immediately and changing it later probably doesn't do anything
You sure?
if i am wrong MS's docs examples are wrong too
Maybe Process copies all the data from the ProcessStartInfo into internal storage in the constructor?
are there examples where it's done this way?
Ok fair enough
Have you tried checking what, if any errors it's outputting?
I'm not the original author, I'm modifying it. However, there are other arguements that were being passed this way (after the object initializer) and they were working just fine, so I don't think it cares either way.
Wait a moment.
Maybe @sly grove was right. I changed up the code a bit...
try
{
using (Process process = new Process())
{
process.StartInfo.FileName = "C:/$$$$/$$$$.exe";
process.StartInfo.Arguments = "-logFile \"C:/$$$$/Logs/log.txt\"";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardInput = true;
process.Start();
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
...and it generated the log file.
Definitely a head scratcher.
That's actually kind of the opposite of what I was suggesting - but maybe using a mix of populating before and after the Process object is created is the issue
A quick test might be:
var si = new ProcessStartInfo{|
FileName = "whatever";
}
var process = new Process{
StartInfo = si
};
if (si == process.StartInfo) {
Debug.Log($"The objects are the same");
}
else {
Debug.Log($"The objects are different");
}```
that could explain the issue - if the objects are different
... sort of, maybe?
Hmm. I'm going to keep that in mind. Especially since I have to put the other arguements back in.
Not exactly sure what you are trying to do. It seems to me that you are not using the correct tool for the given task. What is the true things you are trying to do ?
Why is it 3 planes but we are talking about "3D-looking blob objects" ?
What is a "metaballs" ?
Why you need to get a pixel ?
What do mean by "my texture is a wide cone" ?
Why you want world coordinate from a pixel in world ?
Why are they all renderer if only one is visible ?
If you could elaborate more on what is your issue, we could help you in a better way. It seem like a good challenge, but from I'm standing, I cannot help you because I do not truly know what you want.
Note: Raytracing definitely does not seem like the best way to achieve whatever you are trying to get done.
Maybe it's not the best way to do it? You basically want a blob surrounded by other blobs. Simplest way is to just make a mesh that looks like a blob and put it inside another mesh. Would this be okay? Otherwise you're going to get into the realm of either SDF's or 3D Textures
I want to take Radar slices from weather radars and convert them into 3D shapes based on the reflective color. However, I want to pull it in procedurally, and have it built on-the-fly as I pull in the radar maps. Here's the slices I have as an example. So I'd create a yellow 'blob' in the middle, a green blob on the outskirts, etc....
I was thinking if I could spawn metaballs based on pixel colors on the cone surfaces in the color of the pixel underneath them. Hence the raycasting to get the pixel location and color.
the three red planes in my first post above is my test bed to see if I can make this work. Then transfer it to the full project.
I was adapting the ideas from https://www.youtube.com/watch?v=ae6mW74FZSU but this video is based on pulling images from a flat plane, not the cones my radar profiles have.
A series covering level generation, editing, loading and saving using image files. This video, part 1, covers the basics for reading pixels from an image and working with the resulting array.
Skip ahead to 21:45 to adjust the images if you encounter any errors relating to read / write access to the files.
Big shout out and thanks to my Patreon...
I want to create something like this... http://grlevelx.com/gr2analyst_2/volume_renderer.htm but in real time and using VR.
I've figured out how to automate the radar data pull, now I'm working out how to turn it into 3D.
i am looking for someone who has a really solid foundation of Marching cubes for Astroid Generation in my project , one that would be willing to work with me to teach me more about it and how to use it
I have watched videoes but i find them to be lacking in explination in some major areas
while i understand the idea behind marchign cubes and how the faces are generated, i am having issues with understanding how to apply textures and at different depths specifically
Hello there, How do I pass a NativeList.ParallelWriter into a job? I am using NativeList<float3>.ParallelWriter verticesList = new NativeList<float3>.ParallelWriter(); but I get an error of not asigning or constructing vertices
@plucky sleetI don't know how radar weathercasts work, but if you want it to be 3 dimensional, each pixel color will need to represent a height
This is how terrain heightmaps work. Lots of games generate these procedurally.
So basically you'll end up having sort of an alpha value on the yellow/green range. Yellow could mean on the ground, and green could mean highest part of the atmosphere. Again, I have no clue how weathercasts work.
You may need to convert this to black and white.
I am trying to use memory mapping, but unity fails to open the mapped file
private string mappedFilePath = "C:\\Users\\karee\\ali\\py_test\\my_mmap";
private MemoryMappedFile mmf;
private MemoryMappedViewAccessor accessor;
void Start()
{
try
{
mmf = MemoryMappedFile.OpenExisting(mappedFilePath);
accessor = mmf.CreateViewAccessor();
Debug.Log("Successfully opened memory mapped file.");
}
catch (Exception ex)
{
Debug.LogError($"Error opening memory mapped file: {ex.Message}");
}
}
and I am sure the path is correct, because I tried catching FileNotFound and nothing was caught:
the error message i am getting is:
Could not open file
the errro happened because open existing is for named pipes
OpenExisting is for an already open MemoryMappedFile. You should be using CreateFromFile
can you please be more specific,
because this start to fail.
the memory mapped file Is already opened by another process, and the process is still running, is there a way that I specify, the sharing ability between two processes or does OpenExisting, is designed for that? (windows operating system)
Hey guys, is there a way to execute a particular script only from command line?
I am trying to integrate BuildCommand.cs into my application and I am getting the following error:
when you call CreateFromFile you must pass a mapName. You then use that mapName as the parameter to OpenExisting rather than the actual file name.
All of this is documented in the MS docs
but createfromfile itself is failing?
with an exception of:
"could not open file" and nothing more
I see no CreateFromFile in the code you posted
Sounds like you're not overriding the base class methods properly.
Is your ide configured?
my bad, when I said the issue was fixed, I actually did switch to CreateFromFile
currently the setup is:
process A in python opens the memory mapped file
and write something to it.
process B (unity) try to read the the mapped file.
python opens the file as a normal file with open and just do memory mapping on it
but if the python process is still running this fails (when I close it, it works)
I don't think so, how can we do that ?
These are really questions suitable for the #💻┃code-beginner channel though...
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
Do you mean to say I have to inherit the base class BuildCommand and override the functions for that?
Rename my custom BuildCommand class to something else and inherit the BuildCommand and override its functions?
Probably, I've never used build commands. But a more important issue is that you name your class the same way.
cant help you with that I dont do python
That's exactly what I'm trying to do. Give the textures height and make them 3D. I can create the heightmaps, but how do I extrude along the surface of the radar's cone shape based on color?
well, I would then ask.
what does the comment mean here?
https://github.com/dotnet/runtime/issues/16371#issuecomment-183581789
maybe, it is a more of dotnet question rather than unity at this point
but I tried opening the file from python, it works:
tried to open it from C++, it fails with SHARING_ACCESS_VIOLATION
That is absolutely correct.
Only one process (either python or C#) can create the MemoryMap from the physical file. All other processes Open the created MemoryMap using the mapName.
So does your python script allocate a mapName when you create the Map?
I see.
so, one creates, the rest opens it,
I don't do anything for the name I just open the file and I request to create a mapping for it.
(which I believe the same as the C version)
with open('shared_memory.bin', mode='r+b') as f:
# Memory-map the file
mm = mmap.mmap(f.fileno(), length=0, access=mmap.ACCESS_WRITE | mmap.ACCESS_READ)
mm.write(data)
basically, the file I am mapping is shared_memory.bin,
which was the same that I wanted to open in unity using CreateFromFile
yes, there you have no mapName. Check the python docs to see if you can add one
will look into it thanks
if you find you can add one, then on the C# side you will need to use OpenExisting and passing in that same name
sounds like you might need to tell python to close() and possibly unlink() from shared_memory.bin before Unity takes it.
unlink might remove the bin though
not with a MemoryMappedFile, that is exactly what they are for
It's just weird that with both reading at the same time it breaks.
I need it to be opened, I want python to continue writing and Unity continue reading, unless you are suggesting closing and opening it everytime
only one, , in this case python, is reading the physical file, C# is using the MemoryMap of the file.
This is just a problem of C# not knowing which memorymap to use because the python script does not give it an identifiable name
assuming the python code is doing things correctly
Are you trying to get the python app to send data to Unity continuously?
If that's what you want a file is not the right way to do it. Look into opening a TCP socket.
You need to use mesh generation. You set the vertex position base on the value on the image. Here a video that shows an example of what it could look like. The only difference is that you do not use random noise but texture coordinate.
https://www.youtube.com/watch?v=1qSjCu8av7Q&ab_channel=DanVioletSagmiller
that is way too slow.
It'll be faster than trying to coordinate exclusive access on a file
*Way faster
that is not the way memorymapped files work
I could not find anything relating to name the memory being mapped on python, but I made the C++ code works, by making the
CreateFile uses
FILE_SHARE_WRITE | FILE_SHARE_READ
There is difference between work and work rapidly.
Reading file is one of the slowest operation.
reading a file is a damn sight faster than network connections
Memory mapped file isn't disk IO at all
exactly
Yeah kinda right. But not if it is from itself to itself ?
once it is mapped it is not slow.
you still have all of the protocol overhead
Yeah, my bad. Stop bulling me. I just read people talking about sharing file.
The memory mapped file doesn't exist on disk, it simply maps to a section of the virtual memory (hence the name)
When a process reads from/writes to it, it's simply operating on the mapped RAM.
Okay, so are there other ways to open a memory mapped file? because I tried all the overloads with different access right combinations
your problem has nothing to do with access rights
😅 elaborate if you don't mind?
+
I assumed it has to do with that, because C++ was able to access it (maybe that is a different way of doing it, I don't know)
If you are talking about the named mapping, I really could not find a way for it
this is the way MemoryMapping works
Process1 Creates a Map from a file, it gives this map a name
Process2 Opens the created map using the name given to it
If python has no way of giving the map a name then no other process can open it so it's pointless
So in C# it is
Process1 : CreateFromFile(myFileName, "myMap");
Process2 : OpenExisting("myMap");
I'll look into it now. Thank you!
he's using something called mmap, I have no idea what that is other than a python extension
Unfortunately, that's still just morphing a plane (terrain). I need to extrude the texture into a 3D object, not adjust the height of a terrain plane.
Not sure I understand. Why is height map not enough ?
I'm essentially modelling clouds, not ground planes.
what is the difference? The concepts required are identical
well, I managed to make it work, but they kinda don't work as well (maybe this is totally wrong?)
But I create a file stream with fileshare.readwrite
and then create a mapping from that file stream (as suggested in the repo I linked)
This is so frustrating. This is my bad entirely and I'm sorry for it, apparently my communication skills are not what I thought they were. Calling them clouds is confusing the issue. I want to create fully 3 dimensional objects, from the textures, based on the colors of the texture pixels. Where there is a group of yellow pixels, I want to generate a yellow 3D object, where there is a group of green pixels, I want to generate a green object.
you horrify me. what was wrong with using this
where tagName is the mapName you needed?
I dont do python but I can google the docs and read them
Can someone explain and help me why my character is looking into the wrong direction than the way he walks?
public CharacterController controller;
public float speed = 6f;
public float roation = 0.1f;
float turnSmootheVelocity;
public void FixedUpdate() {
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal,0f,vertical).normalized;
if(direction.magnitude >= 0.1) {
float targetAngle = Mathf.Atan2(direction.x,direction.z) * Mathf.Rad2Deg;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y,targetAngle,ref turnSmootheVelocity,roation);
transform.rotation = Quaternion.Euler(0f,angle,0f);
controller.Move(direction * speed * Time.deltaTime);
}
}```
This is my movement script
Not deform a plane, create fully 3D objects.
let me try it, and nothing is wrong with it, I read it like 3 times, but could not somehow see the tagName
Just to be sure,
the OpenExisting, takes the tagName or map name and has nothing to do with the actual file name, is that correct?
because it returns FileNotFound
yeah, this is what I tried, created the tag name in python and passed it to OpenExisting
but it returns file not found
I will look into ways to inspect if I can see if it was actually opened or not (like view the mapped names on windows)
I suspect that python mmap does not implement the Win32 standard correctly so what you are trying to do may prove impossible
I do not understand what is the source of your data ? If it is a texture, how do you expect to make something else than an elevation ?
@dusty wigeon lol. That's exactly my question. Is there a way? I'm thinking if I raycast onto the surface of the texture, and where the ray hits, I get the location and pixel color, I can spawn an object at that location with that color. If it's a bunch of metaballs together, they can merge into one object.
The source of my data is the National weather service radar data. I can convert it into vector graphics or bitmaps.
Try flipping the z and x in your Atan2
Also, is it just me or are your character model's normals inverted?
I was thinking about it, but I guess using Left hand coordinate system switches them? (I am sure it should be z,x for Right hand coordinate system)
as this example shows:
https://docs.unity3d.com/ScriptReference/Mathf.Atan2.html
I would also not read from eulerAngles but have angle as a member variable instead
And feed it in and out of the SmoothDampcs angle = Mathf.SmoothDampAngle(angle, targetAngle, ref turnSmootheVelocity, roation);
- You should move a CC in Update, not FixedUpdate
Actually looks like you just need to subtract 90 from the angle
Currently working on tooling. is there a way to open an "isolated" scene instance similar to how opening a prefab in isolation does it? I don't really need anything in regards to saving a prefab, as it's pretty much just for configuring a serialized scriptable object
If you use a single texture, how do you expect to make a 3D shape other than by elevation ? And what is a metaballs ?
metaballs are a way to define a surface
you have a set of points that produce influence
any point in space where the influence is above a threshold is inside the metaball
so, the surface is the contour where the influence is at the threshold
here's an example in Blender, including one point that has negative influence
Ty, that was the problem, you the a G :D
👍put your CharacterController movement into Update though, it will be smoother
i will, ty 
@plucky sleet, if you truly want what @bleak citrus is explaining, you will need to look into that specifically. However, I still do not understand on how you will use a texture to create "metaballs". Also, I do not know what you are trying to do with that. How it is related to the original issue of having to show a weather map ?
Are you trying to make cloud ? Because if this is the case, I am sure there is multiple other approach you can use.
I'm trying to use the slices of weather data to create the 3d form of the storm's inner workings. The different colors represent differing reflectivities of the radar. I want to be able to model each reflectivity so that I can remove each to look 'inside' the storm. If it was a simple matter of modelling, that would be easy. Alas. I need to do it on-the-fly in real-time procedurally. Deforming a flat plane will not give me a true 3d model I can look at from ANY angle. I need an object with full 3d volume. You asked "how do you expect to make a 3D shape other than by elevation?" .. I do not know how. That's what I'm asking help in figuring out.
are you trying to do something like this?
I'm a part-time weather nerd so I might have some useful opinions here
ah yeah, there's what I was really looking for :p
this kind of thing
ok, so what's the shape of your data?
I'm extracting raw data from the NWS. I can make it an svg or a bitmap
i briefly looked into that when I had the great idea to make my own radar viewier
(i did not follow through)
so it sounds like you have 3D data, then
I have each slice of the radar eleveations
you have a sample in a 3D space, where the axes are angle, range, and elevation
so... yes,
and you want to, say, draw a solid shape that covers the region that's above a certain Z
I've modeled the radar profile for each degree of elevation from the radar but it's in the form of conic slices from the radar dome
we'll call it the radar point
I want to turn each reflective color and combine the slices into a 3D model of the cloud
give me a minute and I'll try to create a graphic to explain more
In cross section, each black line is the radar elevation data I can pull, it's in the form of a bitmap or vector-based svg. I want to create the yellow and green shapes in 3D
based on the radar 'slices' I can pull from the NWS
so yeah, you want to make a contour that outlines the regions that are above a certain reflectivity value
I'm not sure what kind of algorithm you'd use for that...
right. me either
I did it in 2D in an algorithms class a few years ago, lol
well, you didn't actually create contours there
you're just rendering the slices
a contour would be a single closed shape that covers an area
I'm trying to figure out how to convert the layers of radar into ... yes.. that
a simpler problem is creating a convex hull
a convex shape that wraps around all of the points
but that is insufficient for drawing these complex shapes
I only have a little experience with runtime mesh generation
I guess you could try to join several 2D shapes into a single mesh
you'd have to figure out what points connect to what other points in each layer, though
right..
maybe you could voxelize this: decide if each cube in a 3D grid is inside or outside the mesh
and then..I'm not sure what the next step is!
you could just draw all the cubes
that's a possibility
you'd get something like this
this is blender's remesh modifier in "blocks" mode, which isn't literally just voxelization
it's some kind of octree-based thing
That's why I thought maybe raycasting could help. If I could get the positional and color data of the hit and spawn objects at that location and color.
voxelizing might do something similar.
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
is anyone available to give me some assistance with Marching Cubes, thank you in advance
just ask your question
Is there a way to tell the Player instance what to omit from the player's log file? Whether through code or the command line... i.e. Tell it not to log warnings. Or tell it not to log Memory Statistics.
I essentially only want it to log Errors and Messages from Debug.Logs.
User custom Debug.Log wrapper.
That won't stop other things from being printed to the log file itself.
Yeah. I've thought about that. Figured I'd ask first, before writing up an entire solution, and there might be one already built in.
The one already built in you do not want it :P.
There are logging setting in the other category in the player settings
I took 2 memory snapshots and I want to know whats the difference, so why on the second the VirtualMachine has increased, what kind of objects should i look for difference then in the list?
like here , shall I focus specifically in some type?
or its all in global
That's just the Stack Trace settings. Not the logging as a whole.
how would i make it so the boss in my game turns to shoot at the player
you could google "unity rotate towards object" and find 30 results on the topic.
What's a good way to improve coding with good unity architecture? I felt a big improvement when I learned how to properly use singleton's, events but now I feel like a hit a roadblock again. I feel like the coding structure crumbles later than before but always at some point and becomes hard to handle
I know about SOLID and patterns but maybe I'm misusing them for unity. Or there is a better way to organize the architecture which I lack
@upbeat path
I solved the issue, and not really sure why, but anyway, following your advice, that python might have done something wrong, I switched the roles, and made python open an existing map with Unity creates it, seems to work so far
Better to give examples what you think you need to improve on since it is very dependent on what type of game you're designing.
Unity does recommend some ways to start and improve your systems, such as supplementing it with object pools and a game/scene manager, but beyond that there's not one best way.
I have a question regarding custom Player loop system. Lets say I make a custom system that runs before Update. How do I interface with it from a MonoBehaviour ? I suppose the custom system can have a list of delegates that get invoked but that seems slow, idk... if someone has used this api before I would like to talk to you 😄
A list sounds like the way to me. The player loop is just a fancy list of delegates itself.
Can you give an example of the kind of game your making when the coding structure crumbles? Otherwise something general I’d recommend is learning about C# extensions as something new to add to your toolbox if you’re not familiar with it already. Also generics.
One valuable thing is to look back at prior work you've done.
What were the pain points? What parts of your design wound up shooting you in the foot?
Where did you start having to violate the rules of your abstractions?
Interesting. Should not have been necessary but I'm glad you got it working
For the record, the file streaming from unity side also worked.
I just tested it to see if there is an issue with permissions? I guess there is in the end, but never the less.
That was solved.
Yes, I knew filestreaming would work but it would be soo much slower and error prone
I meant creating file stream, instead of opening it, then create a mapping for that file stream, not sure why it would be any slower?
because of the way filestreams work under the hood
I would expect the overhead to be just the opening, subsequent calls to the mapping should still be the same no?
no, mapping works differently on a filestream than it does directly on a physical file, there is additional overhead when using a filestream
that is definitely not expected
on a similar topic, (which is really csharp and not unity)
what is the equivalent for
CreateFileMapping in C++ for Csharp? this allows you to just use shared memory, and no files are required
you can use CreateNew to allocate a MemoryMap without having a physical backing file
Will look into it thanks!
you really should study
https://learn.microsoft.com/en-us/dotnet/standard/io/memory-mapped-files
Yes it is, you must remember a FileStream is held in Managed Memory which when using a direct file->memorymap is avoided
but anyway, this is getting very technical and is of probably no interest to anyone but us, so it may be better to start a thread if you need to continue the conversation
Thanks, It is very interesting for sure. I might as well start a thread if I need to discuss it more.
Thanks
I don’t know where to start making a mechanic where you can control/command 1-20 Soldiers (Roman Legionaries)
then start making a system where you can control one guy
you probably want to use a NavMeshAgent to do the movement
Hello guys,
I'm trying to schedule a compute shader for the async queue using Graphics.ExecuteCommandBufferAsync to do some work every frame while CPU is busy with physics. I need to fetch the results from the compute shader each frame, so an async readback is a must. I want to use CommandBuffer.RequestAsyncReadbackIntoNativeArray to initiate the device->host transfer when the computation is done (this I can do with fences easily). The issue is, I need to get the results back on the same frame, after the CPU is done with physics. With AsyncGPUReadbackRequest I could just do WaitForCompletion and force the CPU to stall until the data is available, but as per documentation, the callback for the readback request in the CommandBuffer method is only called after the request has been completed.
How would I go about this? The perfect solution would be to get an async request as soon as it's created, much like with GraphicsFence... Using AsyncGPUReadback.WaitAllRequests() works, but for obvious reasons I don't want to use it - while I can make sure that my payload is small and SHOULD be delivered in time and ready before anything stalls, I need to prepare for the case when the computation takes much more time than the cpu work. I cannot guarantee that for other async requests, hence the question.
Yeah
First, I want to make sure you're aware that async compute is only necessary if you want to run it in parallel with the graphics pipeline of the GPU. Compute will always run in parallel with the CPU. Not all platforms that support compute also support async compute.
As for AsyncGPUReadback, I'm pretty sure you're always going to have at least one frame of delay, because of how commands are dispatched to the GPU. As I understand it, in order for the CPU and GPU to work in parallel, the GPU will be working on the previous frame, while the CPU is getting the commands ready for the current frame.
Thanks for your answer! You said that there's always 1-frame delay - that's not what I experienced. If I schedule a compute shader followed by an async readback request (from a commandbuffer), then call WaitForAllRequests the CPU stalls and waits for the result. That's basically what I want to do, but for a single request, rather than many at the same time.
Also, some of my rendering is using this data (async compute seems reasonable here, I can always fallback for non supporting platforms), which creates a dependency. Again, a fence is used to ensure that the compute is completed before procerudal draw kicks in.
EDIT: I didn't want to convolute it more, but regarding your answer I think it could be relevant; I'm actually scheduling the compute to run between frames, simplest example being waiting for request at the beginning of FixedUpdate and scheduling new compute+fetch at the end of it.
Hey all, I have an interesting problem. I am using Voronoi noise to simulate generating city districts, since voronoi can generate blocky white-ish spaces with black-ish borders. The voronoi noise generator can create a Texture2D image just fine, as seen in "GenerateDistrctsMap" method. The issue comes during the FloodfillBlob method, which is suppose to floodfill each voronoi "blob" as a random color from red, green, and yellow to simulate zoning districts. For some reason, it causes the edges of the blob to generate in different colors resulting in a very rainbow/mosiac patttern. I think this is cause my code here checks for the targetColor (being a shade of white) when it should check for a range, but I'm not exactly sure how to properly do that. Here's my code: https://pastebin.com/CgkFk5i8 Below is a picture of the resulting voronoi noise
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
you can see the noise fragments around the blobs
Voronoi should give you cell index directly if I'm not mistaken. You can then color by that alone
Ohh. That'll be good for later generating the grid too
How would I check that? The voronoi implementation I have atm is from a public github repo
hold on
The secret lies in your "custom Voronoi class", just check what value it returns. If there are any comments it should be trivial to understand, if not then just find out what voronoi does so you can use it properly
hm I guess that would be here
//1. Determine which cube the evaluation point is in
int evalCubeX = (int)Mathf.Floor(x);
int evalCubeY = (int)Mathf.Floor(y);```
in Sample2D in the voronoi class
I would like to get back into ECS, what are your some go-to resources or can you recommend a place where I can learn the latest ECS? My main goal is to avoid getting outdated information.
Couldn't post this in dots-forum, getting an unknown error when I try...
I'm trying to decide if using mesh.SetIndices to set a Lines topology is a bad idea and if doing will let me do something like an old style glBegin(GL_LINES) with a mesh renderer. I'm currently doing some lines using Vectrosity, but its doing a ton of extra CPU work and making me do even more work to make it not freak out when points are behind the camera, but really all i need is a good way to efficently draw lines
This API is a core part of my work. I'm not sure what you're asking though
I've only ever used it in a static class, and I'm pretty sure that's the way it's intended to be used
You could always inherit from monobehavior and create your own "entity" type which has an available callback built into it. Your static class will be invoking the function on your entities.
The player loop system itself is a huge pain in the ass to get working. So let me know if you need assistance.
I can almost hear the UI/UX team shouting "Get your code off of my thread!"
I've deal with interops and interface with external library, which all rely on using static class and static method implementation. It's quite unusual to invoke arbitrary code before your main game update invokes.
Looking at the execution order - There's no Unity implementation to handle invoking method before Update() is called. https://docs.unity3d.com/Manual/ExecutionOrder.html
Can I ask what are you trying to achieve here? Could you consider invoking at the end of frame instead to invoke necessary api call for the next frame update?
Using update + custom execution order could help execute code before other code deterministically
I'm doing the following to have a callback before Physics in FixedUpdate and one right after, note that it's using my helper API:
private static void InternalStaticRegisterH2O()
{
H2O_PlayerLoopTools.IEdit e = PlayerLoop.GetCurrentPlayerLoop().Edit()
["FixedUpdate", p => p
.AddChildBefore(typeof(FixedUpdate.Physics2DFixedUpdate), new PlayerLoopSystem()
{
type = typeof(H2OPrePhysics),
updateDelegate = PrePhysics
})
.AddChildAfter(typeof(FixedUpdate.Physics2DFixedUpdate), new PlayerLoopSystem()
{
type = typeof(H2OPostPhysics),
updateDelegate = PostPhysics
})
];
PlayerLoop.SetPlayerLoop(e.Build());
Debug.Log("H2O subsystem registered");
}```
The idea is to use `PlayerLoop.GetCurrentPlayerLoop()` and `PlayerLoop.SetPlayerLoop(...)` to inject custom ticking. Then in each relevant `MonoBehaviour` I register it through a static manager during `Awake`. In the subsystem, `PrePhysics` and `PostPhysics` iterate over the registered objects. When an object is destroyed, it's removed the same way it was added during `OnDestroy()`:
```public static void RegisterSimulation(H2O_SimulationComponent sim) =>
_simulations.Add(sim);
public static void UnregisterSimulation(H2O_SimulationComponent sim) =>
_simulations.RemoveSwapBack(sim);```
I also do some checking for stale pointers just in case I missed something (assertions good), but that's about it, it's pretty straightforward
How do you handle the invoking?
Delegates? A list of components?
couple of a questions here:
first, I do have .netframework 4.8 installed but I don't see the option for it, is that normal? most of the online tutorials are saying
I should see 4.x and not just .netframework.
second, I am trying to use
Span<T>
It should be available inside Csharp 7.2 and .netframework 4.7.2 (which in Unity should be both higher, as the language version is 9 and framework installed is 4.8)
Yet I can not find it?
under system.span
(in fact System.Span does not exist)
Looking online suggests I should install System.Memory package, but When I looked at the
csproj, it is there in the references
<Reference Include="System.Memory">
<HintPath>C:\Program Files\Unity 2022.2.13f1\Editor\Data\UnityReferenceAssemblies\unity-4.8-api\Facades\System.Memory.dll</HintPath>
</Reference>
problem solved, I found it under System and System.Span
Right now I just loop through all of my mono-inherited entity references and invoke whatever functions need to be called.
Is there a better way? Probably.
Haven't put that much thought into this part of the program yet.
{
return;
}```
Assuming we're on the same page, this is all I'm doing. All network entities inherit it automatically so it's no issue.
Yeah. So is there a tangible perf increase to lets say doing it in a regular singleton mono
That is set up properly in the execution order
Just to clarify, you can have your custom loop sitting in the normal execution order
you can plug it into update, fixedupdate, etc
I know
that being said, there's probably little to no difference in performance on a mono singleton
I hate singletons and it required more setup for the end-user so I did player loops instead
Yeah my teat show no real perf diff as well. Then again I used delegates
My idea was that somehow I could improve cache locality but the more I think about it the more I see that I cant
yeah I was gonna mention that as well
I have no idea how delegates work internally in memory in C# so I can't comment on that really
Well the delegates are not the issue here
Even if we have a array of monos its still random aaccess
Theres no way the cache will be filled correctly
You can write bits and pieces of your program in data oriented
and probably still see a noticeable gain
I plan on doing that
Oh we already do
The best idea I currently have is as follows, systemA(can be custom player loop can be a singleton what ever) gets data from all registered monos and does a lets say parallel for job on data. If its a player loop we have a systemB that runs in lets say after late update it either completes the job or just checks if its done. It has the same list of monos, checks the data and for example if life <=0 calls destroy on the actual component
So in essence monos dont really know about their data, they supply it once to systemA(this is slow), but then if we stick it in a native array it has nice cache locallity( i think) , systemA mutates data and systemB( or in the case of a singleton mono its done in LateUpdate) checks same data( again I think nice cache locallity) and loops the list of components and calls methods(bad)
But there is no improving this
If we want to stay in MonoBehaviour land that is
Yeah for hybrid ECS, updating gameobject's transforms requires different steps but I'm not sure if there's a real performance gain when doing that
I've recently been thinking about this same stuff
There is a TransformAccess job that runs very very well
Updating transforms is trivial with it
How much gain did you see with your data oriented setup?
For most things at least a 2x gain. Burst compile the jobs and most of the time its a 8x gain or they simply blip off the profiler
Nice
For example my burst compiled frustum culling job takes at most 0.6ms on a thread
Have you written any manual SIMD stuff? For things more complicated?
Heck no
Thats what burst is for
People way way way smarter than me have worked on it
true
Hello everybody.
How do you track memory leaks on iOS builds?
I tried comparing 2 snapshots with the memory profiler but there is no visible difference in the tree view,
The memory leak seems to come from the Virtual Machine, and im not able to track the origin using the unity tools.
I'm currently trying the XCode tool Leaks but all i see is native code which doesnt help me too much.
Any help would be appreciated.
Thanks in advance
How do you know there's a leak?
I built a game file tester which loads one after another different gamefiles, after 30-40 games, game crashes, also i can see how the ram used increases eventually
Im using the Instruments Allocations tool, i think im on the right path
Symptoms
You need to profile the memory allocated on an iOS device.
Your app crashes after running out of memory.
You are getting memory warnings.
Resolution
You must attempt to identify any memo...
Im almost sure the reason are static references
main problem is i can't see the stacktrace, just native ios code, regarding the document by including the DYSM files in the build they should show but i can't see them
see the VirtualMachine allocation
after a few minutes
hey guys i'm trying to use firebase in unity and this is the code below:
public class FirebaseStart : MonoBehaviour
{
FirebaseFirestore db;
// Start is called before the first frame update
void Start()
{
Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
{
var dependencyStatus = task.Result;
if (dependencyStatus == Firebase.DependencyStatus.Available)
{
var app = Firebase.FirebaseApp.DefaultInstance;
}
});
db = FirebaseFirestore.DefaultInstance;
StartCoroutine(getData());
}
public async void newData()
{
if (db == null)
{
Debug.LogWarning("Firestore database is not initialized!");
return;
}
DocumentReference docRef = db.Collection("users").Document("testData");
Dictionary<string, object> user = new Dictionary<string, object>
{
{ "first", "Ada" },
{ "last", "Lovelace" },
{ "born", 1815 }
};
await docRef.SetAsync(user);
}
public IEnumerator getData()
{
DocumentReference docRef = db.Collection("users").Document("testData");
Task<DocumentSnapshot> task = docRef.GetSnapshotAsync();
yield return new WaitUntil(() => task.IsCompleted);
if (task.Exception != null)
{
Debug.LogWarning($"Failed to get document: {task.Exception}");
yield break;
}
DocumentSnapshot snapshot = task.Result;
if (snapshot.Exists)
{
Dictionary<string, object> data = snapshot.ToDictionary();
Debug.Log("data" + data);
// Use the data to update your UI or do something else.
}
}
}
So I know the newData function works but now that I added the getData() it always hangs on start. I'm probably writing something wrong, anyone can point out how to fix it?
What exactly are you loading in your app? Unity instances?
A game made by unity and built on iOS
not sure what you mean
uhm, i just saw the memory profiler for unity 2022 has more tools for i2lcpp builds
downloading
You said I built a game file tester which loads one after another different gamefiles.
What exactly do you mean by "loads different gamefiles"?
Meant savefiles sorry, user savefiles, are kept in a database, that database contains the 'savefile*' of the player , its a json.
So i took hundreds of savefiles, put them in my debug build and made a loader to load 1 after another
so the game runs
and loads the savefile of a player, after a few seconds, another savefile.....
What happens when it loads them? Does it load a different scene and stuff?
yep
the game is a city builder so it loads different cities
and helps me to find possible issues
It could be that you're loading resources/assets and not unloading them.🤔
But the profiler is weird indeed.
im doing a resources.unload all assets and im restarting the scene... and if that would be the case i would see it visually in the ram captures
its something that is not showing there
im downloading unity 2022.2
it says it has more tools for this
than 2021.3
(for i2lcpp builds)
Is that the dedicated memory profiler btw?
thats the unity memory* profiler yes
I mean, unity has a memory category included in the default profiler, and then it also has a "memory profiler" package.