#archived-code-advanced
1 messages Β· Page 184 of 1
Yeah, but why reply again when answers were already provided
I'm using png to made texture
chill, not all the answers need to be the same
Answers must be valid though
if the guy is using a material he only need to change the maintex not the entire material, he might actually want to just replace it witha user provided texture, we dont know what they want
That wasn't their question
I mean the initial issue is they didn't read the docs
^^
haha
but yeah, if he wants to change a material, then yeah he needs to use a valid resources path
Also where do these ugly casts come from, Brackeys again?
as XYZ will return null if conversion can't be made, it's very error prone
Hard cast will throw an exception, way better in most cases
The material is in the prefabs, it loads the database directory (but the material will always exist in the prefabs) and when clicking on a button it will inform the directory and set the texture in a GameObject
What I'm trying to do is load the material and set it on the GameObject, I'm tried this:
(WorldData.path = "Paints/Floor/Wood")
GameObject Model = GameObject.CreatePrimitive(PrimitiveType.Cube);
Material FloorPaint = Resources.Load("/Prefabs/GameData/" + WorldData.path + "/Texture.mat", typeof(Material)) as Material;
Model.name = "Floor";
Model.AddComponent<BoxCollider>();
Model.GetComponent<MeshRenderer>().material = FloorPaint;
But don't work:
Read this
This is advanced code, if you can't read the docs you should stick to beginner code next time
You've been sent there three times, take the advice
I thought beginner would be the difficulty level of a code, and it's not in documentation
...
Also please
Material mat = Resources.Load<Material>("path");
Use up to date, latest generic methods for this!
4th time
Don't lie to me
Also because I don't speak fluent English, I often use a translator, it's difficult for me, if you don't want to help, just don't help
You've been told what to do!
haha
Hello, We are trying to fill our variables with the response from the API of a website. Our back-end programmer with no Unity experience gave us a .dll file and instructed us to make a async task for the call to the api. It sometimes works and we get the response and sometimes the call just times out and fails.
Is using a .dll and using Tasks an acceptable way to make a call to an API? We have always used UnityWebRequests before.
"ApiLibrary" is the .dll that we are using. Our software is being used on the Meta Quest 2 (So its an android environment)
what do i need to do if i want to make an virtual "OS"
when i search the google i get prebuild real computers
Hello. Imagine There are 10 players. all of them must have the same boss. This boss will be randomly chosen from 5 bosses and be there for about 2 minutes, before next randomization. I want all players to have the same boss at the same time. I think time problem is solved using Greenwich's time (UTC) but generation gives me different bosses in different players. I tried to give the same seed every player (Depended on that Time) But it didnt work. can you help? Without using server to do that for me or with server. Thanks
Yeah, referencing external assemblies is pretty common, especially outside of Unity, a bit less common inside.
The dev did the API request inside the assembly so you don't have to use UWR, and in the event they change the API endpoint or code, you just have to re-import the DLL in your project and it works
As for why it sometimes times out, you'll have to debug that out
I see. Thank you. On the pc environment it works near perfectly but on the Quest 2, we have to keep restarting until it randomly works right now.
Also I think it's possible to simplify the code down to
Product product = await Task.Run(() =>
{
ApiProvider ap = ...;
return ap.GetProductDetail(ProductId).Product;
});
Other than that the async code looks good
What's pretty weird is that the API doesn't directly provide some async code
But you could try querying the API without async first, to eliminate the potential issue of "async not supported on this platform" like on WebGL
Thanks a bunch, I will look into these.
is this an openapi generated client?
it's hard to use plain c# async await in unity. use unitask
So I need to accurately (a few approximations are fine) calculate drag on a mesh. To do this, I need the cross section of the mesh. I saw a post on the internet that suggested
- Take pictures of the mesh from different angles
- Count the number of effected pixels
- Determine area using
coloredPixels / totalPixels * someSizeFactor
/**
* Drag is always opposite to motion. Since drag is dependent on the area
* exposed to the fluid (NOT VOLUME), we can do the "belly flop maneuver"
* (flip sideways to increase drag). TECHNICALLY the drag coefficient will
* also change based on direction, but let's not go overboard with the maths.
*
* Equation: F = 0.5 * fAv^2
* f = drag coefficient, 0.3 = car, 0.05 = plane foil, 1.0 = horizontal
*/
public Vector3 CalculateDrag() {
Vector3 force = new Vector3(velocity.x * velocity.x, velocity.y * velocity.y, velocity.z * velocity.z);
Vector3 n = force.normalized;
float area = crossSectionLookup[Mathf.RoundToInt(n.x), Mathf.RoundToInt(n.y), Mathf.RoundToInt(n.z)];
force *= 0.5f * dragCoefficient * area;
// Make sure the drag is opposite to motion
force.x *= velocity.x > 0 ? -1 : 1;
force.y *= velocity.y > 0 ? -1 : 1;
force.z *= velocity.z > 0 ? -1 : 1;
return force;
}```
I have this float[,,] crossSectionLookup that I want to fill in the Start method, but I am unsure on how to approach this. I would normally create a computeshader and simulate each ray, but I don't think ray-mesh intersection is possible on gpu.
crossSectionLookup = new float[3, 3, 3];
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
for (int z = -1; z <= 1; z++) {
Vector3 direction = new Vector3(x, y, z);
crossSectionLookup[x, y, z] = 0f;
}
}
}
A super rough "approximation" would be to precalculate the area from three directions (top/front/side) and assume the surface area from any direction is a linear blend of those three areas. Kind of like triplanar mapping.
That's a good idea, I'm currently trying to calculate each direction from a 3x3x3 cube, but Physics.RayCast is being mean to me
Currently it is causing a D3D11 device removed error
Hello π
Are there any best practices in regards of injecting values into [SerializeField] private fields of MonoBehaviours for the purpose of unit testing? As far as I can tell, there are 3 options:
- Option A: Create a new
Init()method just for the purpose of Unit testing (I dislike this) - Option B: Create a new scene with properly configured monoBehaviour (Also against this)
- Option C: Use reflection to get private fields and inject proper values inside (Kinda ok? It's somewhat volatile though)
Maybe:
D: create test prefabs with properly configured MB?
Hmmm yeah? That seems reasonable. It's a lightweight version of B I guess
Ah I still kinda prefer reflection here. B and D do have a flaw of not being able to test what happens if you fail to provide any of those parameters. How would you test that the method throws a certain kind of exception (or does whatever else) if no value was provided for one of those fields? Would you create another prefab?
@willow aspen couldn't you just use a bunch of raycasts along the direction of travel?
Which method exactly are you testing? A unity callback? Or something else?
You'd simply create a prefab for that test case though
E.g. one that's missing whatever required value
hmm
it sounds like your computer is having issues
does your object change shape?
No
is it concave?
Most are. Some arenβt.
okay
Hello, I'm trying to use ECS in the script but I get an error that Entities doesn't exist. I already installed ECS in the Package Manager, what else am I missing?
using Unity.Entities;
public class IntroSystem : SystemBase
{
protected override void OnCreate()
{
base.OnCreate();
}
}//*/
regenerate project files?
there are many ways to solve this problem
you can generate concave meshes from convex ones using something like vhacd
You mean restart my pc?
no i mean:
regenerate project files?
then, let's say that instead of drag, you're calculating the "aerodynamicness" (1 - drag) of the object
never heard of that word, that's that?
Edit -> Preferences -> External Tools -> Regenerate project files
which word specifically haven't you heard of?
ok
that worked thanks @sly grove
then the aerodynamicness of your object is
sum of
the direction of motion dot producted with a vertex
times the distance of that vertex to its neighbors
@willow aspen this isn't perfect but do you see the idea here
observe a sphere will have an aerodynamicness of zero from all directions, which makes sense
I am too tired to reason put vector math
Do you mean the normals of the vertices?
no
i mean literally from the center of mass of the object
treating them as directions
we're trying to approximate their contribution to the "mass" of the object in a certain direction
it works for a lot of shapes
like a pole (a long, narrow cylinder)
most of the "vertices" of the pole would be in the same direction of its motion
so it will appear highly aerodynamic, i.e., low drag
which makes sense
i think you would actually treat the origin not as the center of mass but as a point, "infinity" away from the direction of motion behind the object. that is the same as projecting the 3d mesh onto a 2d surface, i.e., a picture of the object from that view
which is the inspiration for a simple approach here
that's what an orthogonal camera image is
Youβve given me some stuff to think about, thanks
cool
you definitely do not want to raycast
or voxelize or stuf like that
it's obscuring that you already have data about the shape of the object and you need to interpret it correctly
https://en.wikipedia.org/wiki/Orthographic_projection you can 90% this using the matrix itself
Hello what does this class "CapsuleTag" belongs to? I don't know what library it came from. Is it using System.Collections;?
Make a local variable and hover it in your IDE. Should say where it came from
rightclick => search for refrences => it shows where it came from and where it will go
This came from a tutorial https://gist.github.com/JohnnyTurbo/95a7a761e4979e091f9700016f302e00 I actually found it hehe
Code used in System Lifecycle tutorial video on the Turbo Makes Games YouTube Channel - https://youtu.be/pViD_h8NXf0 - CapsuleTag.cs
So I'm new to async coding, using UniTask. I'm making a whirlwind ability. When the mouse is down, it spins. When the mouse is up, it should stop spinning. It has two modes, I'm currently testing the non-duration mode, so you can ignore that bit. It all seems to be working, except that my Cleanup method isn't being called. I was under the impression that I needed to cancel outside of the async method, listen for the cancellation in the task and make sure to dispose of it. The task appears to stop (I stop spinning) but I don't think WhirlwindCleanup is being called. Was my assumption about needing to listen wrong, and it just cancels the task?
Full code: https://www.toptal.com/developers/hastebin/ikipuvimer.csharp
Relevant bits:
private async UniTask WhirlwindSpin(CancellationToken token) {
float remainingDuration = whirlwindSO.Duration;
float timeSinceLastDamage = 0;
while (whirlwindSO.WhirlwindMode != Whirlwind.WhirlwindModes.Duration || remainingDuration > 0) {
Debug.LogFormat("Spinning");
if (token.IsCancellationRequested) {
Debug.LogFormat("Cancellation requested!");
WhirlwindCleanup();
}
remainingDuration -= Time.deltaTime;
timeSinceLastDamage += Time.deltaTime;
if (timeSinceLastDamage >= whirlwindSO.DamageInterval) {
DealDamage();
timeSinceLastDamage = 0;
}
// Spin the character. Temporary, just for testing.
Quaternion newRotation = _character.transform.localRotation;
newRotation *= Quaternion.Euler(0, 0, Time.deltaTime * 500);
_character.transform.rotation = newRotation;
await Async.YieldWithToken(token);
}
WhirlwindCleanup();
}
private void WhirlwindCleanup() {
Debug.LogFormat("Ending whirlwind, cleaning up");
cancellationTokenSource.Dispose();
_character.transform.localRotation = startingRotation;
}
Logs:
I've fixed it by just calling WhirlWindcleanup after StopWhirlwind, but I'm confused and would like some explanation. Are UniTasks different from Tasks in this regard? I was following a guide on regular Tasks with listening for the cancellation
Side question, why use async for this instead of coroutines?
Just trying to learn UniTask
Also I'm thinking we'll need it later when things get more advanced
Senior dev already suggested I switch over, seemed like a good opportunity
What i personally found is that there still are cases for coroutines. This is my general rule of thumb:
- If i want to wait for a result that will come later, use async
- If i want to do something over multiple frames, use coroutines
Makes sense
But eh i dont see an issue i think. I'd even say WhirlwindCleanup is called twice
I dont think you need to call canceltoken.dispose. I think i would personally add the iscancelrequested in your while-condition itself.
I wanted to pop it out so I could have it call cleanup
Dont you want to stop your loop/routine if the cancelation is requested?
Yeah, that's what I'm doing
e.g. if cancel is requested, you still go on. You dont break.
I should break though, forgot that
Where? You call cleanup, but thats it? You then still go on with the loop, no return no break nothing
Yeah, forgot the return/break. Shouldn't be relevant here though, confused about why the method isn't being called
Or maybe it is
I would just while(!token.IsCancellationRequested && whirlwindstuff){} WhirlwindCleanup();
Fair enough. Still wondering about my question though
Also not sure if I even need to make sure I'm disposing of it like this
I dont think so
Anyone know of any good tutorials or resources for learning UniTask in general? Been coming up dry. Docs are good, but a bit too terse. Not good for best practices, use cases, etc
Unless there are more docs than just the github page
I'm testing a method that Initializes the game scene (spawns stuff, sets values, whatever else is needed).
I've also asked this on the forum https://forum.unity.com/threads/constructor-alternative.1272353/#post-8075603 and someone suggested Zenject. I've been meaning to get into it for a while and will be proceeding with that then
Create an "Init" method for injecting whatever is an inspector reference just for the purpose of testing.
"Yuck." can lead to places, especially with using massive frameworks and heavy reflections just to avoid simple approach
anyone got any ideas for networking a floating origin via fishnet? my goal is a scene where each player can fly infinitely in any direction. i wasn't surprised when my singleplayer floating origin solution didnt fully work. one client sees the world update correctly and the other sees that player looping infinitely in the same space.
secondary "real" coordinate system
on doubles
any transforms in scene are local representations of real coordinates
So I've got this switch statement, and want to try the new C# 8.0 syntax to make it less ugly. I'm fading an object out. Trying to determine what happens when it's done fading, for context
switch (FadeOutMode) {
case FadeOutModes.Destroy:
Destroy(gameObject);
break;
case FadeOutModes.Pool: throw new NotImplementedException();
case FadeOutModes.Disable:
gameObject.SetActive(false);
break;
default: throw new ArgumentOutOfRangeException();
}
I'm trying to do something like this:
void _ = FadeOutMode switch {
FadeOutModes.Destroy => Destroy(gameObject),
FadeOutModes.Pool => throw new NotImplementedException(),
FadeOutModes.Disable => gameObject.SetActive(false),
_ => throw new ArgumentOutOfRangeException()
};
But I can't use a local variable of type void. I don't want a return value, I just want to do these things. Not finding any examples of how to use it this way, is it possible?
It's not possible
you can just return a delegate
var something = new Action(()=>
{
Destroy(gameObject);
);
(FadeOutMode switch
{
FadeOutModes.Destroy => (Action)something,
_ => throw new ArgumentOutOfRangeException()
})();
thanks @plucky laurel ill give that a go
To start off, inline switch statements are made to provide a result of the same type. This would not be good practice here as you are not getting a result.
That said, you could try this:
var @action = FadeOutMode switch {
FadeOutModes.Destroy => () => Destroy(gameObject),
FadeOutModes.Pool => throw new NotImplementedException(),
FadeOutModes.Disable => () => gameObject.SetActive(false),
_ => throw new ArgumentOutOfRangeException()
};
@action();
Not tested btw
I changed your destroy and disable state into a delegate, since your version actually invokes the method, rather than specifying a way to invoke
After that, make sure to actually invoke it.
That's alot of different, excessive and unreadable code tbh, sorry
You miss half the states
bruh
Both versions just hack out the use of switch expressions
Sorry if it's intentional, but it's confusing
Well yeah, that's what I said
I suppose returning a delegate kind of omits the issue though
Yeah, a regular switch statement looks and feels better
Dunno, I suppose inline switch statements like this are fine
You return an action to invoke depending on the state, which is fine
Fine, but not pretty for completely different instructions in the lambdas
How is it different?
A destruction, an exception throw, and a disable
The delegates create garbage
And that too
x switch is for expressions that have results
If your expression has no result, you cannot use expression switch
And all of the suggested alternatives have negative performance drawbacks
Trust me, just use a normal switch
And hacking it to forcefully make it return a value in some cases it shouldn't, is just bad practice
There is a proposal to support it as a statement: https://github.com/dotnet/csharplang/issues/2632
Sweet, thanks. Was able to shorten it to just
Action action = FadeOutMode switch {
FadeOutModes.Destroy => () => Destroy(gameObject),
FadeOutModes.Pool => throw new NotImplementedException(),
FadeOutModes.Disable => () => gameObject.SetActive(false),
_ => throw new ArgumentOutOfRangeException()
};
action();
``` and it seems to be working fine π
why you want to do this, I've no clue π
Fused's method didn't compile, wasn't able to find correct type for action iirc
I just want it to look nicer, tbh lol
It's interesting
this is not nicer compared to the regular switch statement
delgates allocate, you know
Yeah, fair. I was thinking I was just making a small syntax error originally
aight, goodluck π
I have no idea if it compiles, but apparently it's a bad way to program so I kind of gave up on improving it π©
Honestly just do whatever you want. You learn from it and nobody is going to notice the nanosecond it takes longer to process it
It's this exactly what I suggested, though?
Yeah, just didn't understand what the literal was for I guess
I suppose the apostrophe does not work as action is not an actual keyword even though I thought it was. Was that the error?
In my opinion a switch statement is bloated and having it compact like this looks much better
This is what I was thinking, the new syntax is nice. I would like to use it. Seems strange to me that this needs a workaround
And if you remove the apostrophe?
change @action to something else without the @
Changing it to action works, without the @
I see, then it's indeed fine to just use action
It's fine. you put an apostrophe before your variable if it's a reserved keyword, like event.
so you would do @event
Ah, you keep calling it an apostrophe too
Oh, it's not an apostrophe
But yeah, I see why you were using it now. Just thought action was reserved
The error isn't related to the @ though
Yeah
Let me check
Needs to know what to return from the switch, and the types are ambiguous so var bails out
That's my understanding of it
Yeah, the compiler doesn't treat Action as anything special, so it doesn't assume you want to use it here.
Any void delegate with no parameters would be valid here.
() => doesn't create an Action, it creates a delegate instance that can be assigned to any delegate type that matches the signature.
Makes sense
Yup, seems like it
thus, you need to cast it as shown in my example
When does the delegate allocation occur? If I were to make action here a class variable, would I just get the one allocation? Or is there one each time it's assigned
I'm assuming when it's assigned, and the allocation comes from a boxing operation of some kind?
Maybe not even boxing, if they're just the same type. Not sure how that works
when you do this Action act = foo.Something; it will compiled into Action act = new Action(foo.Something); which where the allocation occur
There can also be an additional allocation for display classes. That's when you have lambdas that need to capture an outside variable.
Is it the new keyword triggering it though? In this use case, if I were to use the local variable, I'm not using it (a new keyword)
Yeah, that part makes sense
Not sure what you mean about "display" classes though. Just classes using the delegate, that might capture variables?
This is what I mean by display class
https://sharplab.io/#v2:D4AQTAjAsAULIGYAE4kGFYG9ZNy5IEYSAsgKYAuAFgPYAmAFAJYB2FSNArhQM5N1kAagEMATk2EAjADZkAlDjzYYeVSgDsSBnKQBeAHwoIATgZde/IWIkz5AbkW4AvrCdA==
C#/VB/F# compiler playground.
Oh, I see. That just sorta happens to also use a delegate though
Since it's returning one and creating one in the process
You have to remember that it has to convert your lambdas into an Action. You're not just assigning a lambda to an Action variable. The lambdas are converted into new Action instances and because delegates are objects, that creates garbage.
Oh right, I didn't think about that
Action action = SomeMethod is the same as Action action = new Action(SomeMethod)
It's implicit
That makes sense. Thanks. So this would create several allocations
Just for the switch case it enters. And there's no outside variables captured, so no display class allocation.
Ah, was thinking that. I see 2 alloctions here then, maybe more with the throw
Hi ! Would you recommend JSON to keep informations such as :
- user's name
- path to a picture
those kind of simple informations
id say just use player pref system
if the data doesn't need to be secured, then id use them
I'd want it to be modifiable by the user when they start the app
yeah you can modify them in script
You can put whatever you want in JSON really. I'd prefer JSON serialization before PlayerPrefs any day
PlayerPrefs.GetString and PlayerPrefs.SetString
I see I see
yeah but player name and file path are both strings so I wouldn't say a Json file is needed
I think I'll need to keep track of some boleans and stuff in the future too
so ill try with JSON
but if it's too complicated i'll use payerpref
oki
I think player prefs can store float int and string (ofc you could use 0 and 1 for boolean easily if you want to)
how can i make a computer "OS" in unity
something similar to PC Building simulator lets say
hey guys, what's the best approach for checking if a method was called in the main Unity's thread ?
need to implement the same kind of check like the UnityEngine.Random has (it throws an exception if you access it from outside the main)
So far I only found something about using Unity's lifecycle callbacks to capture the main thread and use that reference to check against Thread.CurrentThread
but it kinda looks hacky, so thought maybe there's a better way
You can copy this class: https://github.com/NewBloodInteractive/com.newblood.core/blob/master/Runtime/MainThread.cs
And then use if (Environment.CurrentManagedThreadId == MainThread.ManagedThreadId)
There are internal methods on UnityEngine.Object that allow you to check for the main thread, but I prefer not to rely on reflection if I can help it
perfect, ty π
seems like they are not exposed in the API though
I'm not going to rely on this in the builds, need it for development, so that every time a task tries to use an instance it's not supposed to it would crash
Yeah, they're private methods unfortunately
I made a proposal thread to expose them (and a few other APIs) but so far it doesn't seem to have caught on
it does look useful for development for sure
The MainThread class does the job for now though, it's about as close as you can get currently without reflection
yeah, ty π
use unirx if you want to avoid touiching the main thread inside a task
it has a helper, and it also has await UniTask.SwitchToMainThread()
lots of approaches. for gameplay purposes, it's super low ROI.
if your goal is the ceremony of doing such a thing, try embedding BOCHs into unity and render the framebuffer to a texture
yeah, I want to review that library at some point, my current todo list is gigantic so need something simple and quick for now
good to know tho, ty π
not even entirely sure about the tasks yet
they did make the game 100% responsive during world generation, but I'm still debating if this is the way to go
unirx is very easy to use. trust me, just use it
you can't use plain tasks very easily in unity
you'll want all the helpers unirx brings
especially for dealing with editor mode
return on investment
I'll give it a go for the current branch then π
was doubting because native tasks have good support like breakpoints and being the native language concepts
I guess the library builds on top of that rather than trying to replace it
If you're specifically doing tasks I would personally prefer UniTask over UniRx (they're both by the same developer and can interoperate if needed). UniRx is heavily built with the Reactive Extensions paradigm in mind, which is by no means a bad thing but it builds a lot of extra concepts on top of tasks which you may or may not want.
I had no idea there was a difference between the two
goes to show you how tuned into React I am
I thought it was a single library too, granted I did basically zero research yet
I'm not sure of the exact history, but as I understand it UniTask specifically does just the aspects of UniRx that are "make Tasks work nicely and efficiently in Unity", without much or any of the React stuff. But it's not a subset or dependency of UniRx, it's its own independent library.
makes sense
I think UniTask may have been a later attempt by the developer to hive off just that part of the functionality from UniRx? But I'm not certain.
good to know, I'll need to review both then, not sure yet, but I might need reactive part too
UniRx and UniTask are a bit heavyweight if all you want is to access the main thread
They end up customizing the PlayerLoop to install a callback to do things on the main thread, which I'm not personally a fan of
(Unity already has a built-in SynchronizationContext implementation for this purpose)
the built in unity synchronization context is badly implemented
and has its own glitches
Such as?
if you rid your mind of " "heavyweight" versus "lightweight" " as an idea, you can ascend
The current UnitySynchronizationContext could be more efficient, but I wouldn't call it bad
the unitask one avoids a bunch of pitfalls
What pitfalls?
I'm genuinely curious
You said it has glitches but never mentioned what they actually are
I'm looking through its code now and I don't see any thread safety violations, so it can't be that
i don't remember the specific bugs i encountered
i vaguely remember it had to do with putting in a lot of in-flight tasks
i'm sorry... for some stuff it was so long ago
If it was a while ago it might have been fixed
UnitySynchronizationContext did used to have some issues
I think back in... Unity 2017? 2018? Or so there was a race condition that could result in one of your callbacks being called more than once
It was eventually fixed though
So I imagine that might be what you encountered
only the unitask one has been flawless
is it possible in StateMachineBehaviour class to get what part of the state has been completed?
i want to use it with lerp to move collider object
i would probably propagate the information when changing the animation state to a script on the animator object.
then you can read back the last state
Need a quick/clean way to get 3 random, distinct elements from a dictionary. Thoughts?
List<T> randomTs = dictOfTs.Values.ToList().OrderBy(x => Guid.NewGuid()).ToList().GetRange(0, 3);
Vomit or nifty? (assume dict always has 3+elements)
How do I get the InputAction control type class? So Axis would return a float, and so on?
Hi, Does anyone here know how to project a 2:1 texture to equirectangular cylindrical projection of the same aspect ratio and resolution? I've been trying several solutions over the last few days and have not had any luck, any help would be appreciated.
Does it matter if the 3 are consecutive
yeah, can't have consec
I'm picking a computer controlled lineup of 3 enemy characters from the pool of about 50, so if they were consec the player would always get the same players, or at least like 2 of them, if that's what you were thinking
{ 1, 2, 3, 4, 5, 6, 7 } might get 123, 234, 345 etc, which might feel stale
make a new List with all your enemies, when you select one you also remove him from said list
Feel like that might create a lot of garbage
shouldn't, it'd just be allocating the pointers, not the full objects
but i still also would have to randomise that list somehow, which is mostly the crux of what i'm asking π
quick/dirty/easy/mostly-random ways to randomize a list
Random.Range
(I'm actually ToList()-ing twice in my solution above, which .. maybe not great)
you don't need to randomize the list, just the index of the enemy you take
I'm getting 3 though, and I want no dupes, and don't want the same three adjacent items
Thatβs what Iβm thinking or just generate 3 random indexes and ensure theyβre unique
you mean never 3 adjacent or sometimes 3 adjacent if the rng god wills it?
if there's 50 elements, and I select a random, then get [i] and [i+1] and [i+2] that'll be stale pretty quick
3 adjacent is fine, but 3 adjacent every time isn't
Random.Range 3 times is what you want
then just randomize the index 3 times
i'm not sure i like doing the "get a random int and ensure it hasn't been picked already" because it'll end up sloppy
you could also make a List<int> of all the indexes and remove the onces you already picked but you might as well make a new List of enemies
int i0 = Random.Next(50);
int i1;
do
{
i1 = Random.Next(50);
} while (i1 != i0);
int i2;
do
{
i2 = Random.Next(50);
} while (i2 != i1 && i2 != i0);
I feel like that's ugly
yeah, this is maybe best
You could also only reset the List once there are only a certain number of enemies left, thus preventing getting the same enemy back to back
List<MyObject> allObjects = allObjectsDict.Values.ToList();
MyObject one = allObjects[Random.Next(allObjects.Count)];
allObjects.Remove(one);
MyObject two = allObjects[Random.Next(allObjects.Count)];
allObjects.Remove(two);
MyObject three = allObjects[Random.Next(allObjects.Count)];
allObjects.Remove(three);
it's not so much a number of enemies left, it's a "battle" mode thing, 3v3
Does appearance trump functionality?
At the end of the day itβs all syntax sugar
when there's a zillion different ways to do something i lean towards whatever is shortest and easiest to read and least likely to be buggy
nvm*
sort of why I'm liking this one the most so far, even though it's a long ass line.. it's still just one line
I lean towards least buggy
this is the concept
select 3 crew, go to battle, turn based blah blah blah
so as long as i have a quick/easy way to select 3 crew from a pool of dozens, that's good enough
probably harder fish to fry with the AI part of it
YourList.OrderBy(x => rnd.Next()).Take(3)
Yeah the first 3 of the randomized list
slightly different implementation, going from dict to 3 items - myDict.Values.ToList().OrderBy(x => rnd.Next()).Take(3) but still the same .. thanks
has anyone seen an example of RegisterThread in a native plugin?
i'm trying to profile a native thread
nevermind i figured it out
Hi, Does anyone here know how to project a 2:1 Simple Cylindrical texture to equirectangular cylindrical projection of the same aspect ratio and resolution? I've been trying several solutions over the last few days and have not had any luck, any help would be appreciated.
OK. Funtime.
I have an arbitrary sized grid (let's say 5x5). It has grid elements with an int contents = 1, 2, 3, 4... A "move" is moving any item on the grid to another unoccupied space on the grid.
When there's 3 or more items orthogonally connected, they merge into the next level. This is a good thing.
I need to write an algorithm to attempt to find a move (by the computer). Any ideas how to break this down?
I already have the logic to detect a completed "chain" (recursive "painting" of matching neighbor count) but am struggling to find a way to positively find a move when one exists.
"move" on a 4x4 grid shown here
I suppose I could iterate over every "drone" on the board and find every possible move and check for chains, but... that's going to be potentially really slow, I think
I suppose I could at least do that and prune search trees when obvious fail cases exist (like there are < 3 of one kind of item on the board)
there are lots of ways to prune a destination. but in principle, visiting every element of an NxN grid is not bad.
since there will never be a situation where there are three orthogonally connected pieces, you only need to mark when an item has a orthogonal same type neighbor.
var interestingMovesByType =
// for each pre-existing item
items.SelectMany(item =>
// examine its orthogonal spots
GetOrtho(item)
// are any the same type as me?
.Any(neighbor => !IsEmpty(neighbor) && neighbor.type == item.type) ?
// if so, return all the empty ortho spots as me as an interesting move
GetOrtho(item)
.Where(neighbor => IsEmpty(neighbor))
// store a tuple that stores the empty neighboring location and the type it was interesting for
.Select(neighbor => (loc: neighbor, type: item.type)) :
// otherwise, skip this (empty)
new [] {}
) // now we have the interesting moves. let's group them by type of tile
.GroupBy(interestingEmptyNeighbor => {
var (loc, type) = interestingEmptyNeighbor;
return type;
});
Yeah.. Did something along those lines. A couple of prunes, a little bit of testing, was no problem even under my fake load
yeah
I often overestimate the impact of something but.. it's hard to really load test this (since the computing is on the server of a multiplayer game)
but it was in the nanoseconds even for a 10x10 grid so.. no worries
i closed down the IDEs for now.. 12 hours is enough punishment for one day
you could achieve O(1/2 grid tile count) if you switch from visiting every existing item to every empty space when the board is about half full
but i wouldn't worry about it
i don't think you need to do any pruning
it won't beat what i wrote
i'd keep it simple
i actually am really low on the actual checks - i prune any checks against drones that can't possibly make a chain (ie, 2 or less of them on the battlefield).. so honestly average case performance for a 4x4 grid, even one that's reasonably full is like... 100 or 200 operations, it's.. nothing
i could prune big grids even further by keeping track of how many neighbors are in every square and then only checking ones that have 1+ to see if they'd get a chain, but.. yeah, i'm not going to work on it anymore .. it's fast enough π
fun little problem though, compared to doing UI work :p
is there a way to use clang for windows il2cpp builds?
and is there a way to make runtime initialize on load work for il2cpp?
It does..?
i set the Master compilation option
it's the only one i've tried, but it appears to have made my thing not work
does it matter if one of my native plugins were built with clang?
its worth a try if you build as Visual Studio Project. i dont know if that will work or not
is there anything arcane i have to do
it does. not for you?
the only thing i changed between these two builds was il2cpp + master versus mono
is it may be related to master?
im not sure how difficult it could be. but basically you can refer the source project files and get the important configs from there which you need to feed to clang
is there a way to set up a process that actively checks to see if there's an object of certain tag within a range of it?
surely theres a much more simpler way than I am trying (unsuccessfully) to do
maybe this is related?
[ 0s] Delete 71 artifact files that are no longer in use. (like Library\Bee\artifacts\mvdfrm\UnityEngine.RuntimeInitializeOnLoadManagerInitializerModule.dll_437B411B571BF089.mvfrm)
from the build log
not tags but you can efficiently do it with layers. using raycast sphere. with tag you need to raycast for all layers and filter all of them by your tag
try disabling stripping
so is layering essentially like filing? Like, "you, you, and you all go in here!"
it's already set to minimal
2021 can't fully idsable stripping
and engine stripping? not sure if that's gonna help with this
i see that runtime initialize on loads.json correctly references my method
Ok so for now I'll just focus on getting a smaller part working. I have the character able to automatically move to the enemy. The next step for what i have planned is to have something in play to see if the enemy is within a range of like, 1 for example. How should I go about starting that?
@tough tulip i give up... it's too late to diagnose this
Hi
I don't really understand Serialization, SerializeField in Unity
can someone please explain it to me ? I've read the documentation but i'm lost (I've had classes about object oriented development but that's hard)
(not entirely sure this is code-advanced)
What dont you understand?
(dunno, seems pretty advanced to me tho)
I don't understand in what context i'm supposed to use that
You dont have to use it.
But lets say you have a player, and that player can move. It would be nice if you can edit the movement speed without having to change the code
So you serialize a float speed, and change that.
Thats it
you can use serialzefields to show private variables in the inspector. but they will not be accessible by other scripts
ooooh
ok
because I saw it's necessary to use JSON
and I want to make a Player Class that has basic attributes (name..) that I can call in other scripts
like I have a script that'll modify an image based on a Player's attribute
No
You dont use JSON for this
This is all magic to you. You just make a [SerializeField] or public, and Unity sets a value for you
This is all you need. Then fill it iin in the unity inspector, and there's your value.
JSON is necessary for another part dw
it's pretty complex but I need to save a ton of data so I'll put that in a json file I think
but thanks ! Now I understand
Ok but thats something different then. I thought you were talking about editor serialization
yeah no sry i'm bad at explaining
Unity's JsonUtility uses the same attributes
yeah i'm using that but it's hard as hell since I don't know a thing about databases, json..
is there any insight into when d3d12 should be used over d3d11 / vice versa?
In my experience, only when necessary (consoles). Its usually slower than d3d11
okay, i just tried d3d12 in my situation and it made a bunch of problems go away
Do shaders care what line endings there are? I have some in LF, some in CRLF, and I was wondering if it's safe to convert them all to LF
Hello.
public List<OperationClaim> GetClaims(OrgAdminDto organizationAdminUser)
{
using (var context = new EfVrCloudContext())
{
var result = (from orgAdminUser in context.OrganizationAdminUsers
join baseUser in context.BaseUsers on orgAdminUser.AdminId equals baseUser.UserId
join userOperationClaims in context.UserOperationClaims on baseUser.UserId equals userOperationClaims
.UserId
join operationClaims in context.OperationClaims on userOperationClaims.OperationClaimId equals operationClaims.Id
where baseUser.UserId == organizationAdminUser.AdminId
select new OperationClaim
{
Id = operationClaims.Id,
Name = operationClaims.Name
});
return result.ToList();
}
}```
I got sick. Where am I missing do you think?
I want to get the user claims but returns null.
Could you please somebody take a look into this? Thank you in advance.
Well, like any projection you need to run a shader that converts pixel positions in the target projection to pixel positions in the source projection.
For cylindrical->equirect that's fairly simple: x coordinates are of course the same between both. For y coordinates, assuming -1 < y < 1, if you draw a diagram you should see that the conversion from the angles that are equirect y coordinates (ey) to the distances that are cylindrical y coordinates (cy) is just given by cy = h * tan(ey * halfpi), where h is a constant dependent on the height of the cylinder. You'll need to decide for yourself what to do at the cylinder caps where this gives out-of-range results (probably clamp, or return black).
What's the attribute that lets you ignore methods in log stacktraces?
I know there's StackTraceHidden in C# but I thought htere was also an equivalent for Unity
does unity seralization work like java serlaization
it creates a file with your Data
How does java serialization work?
What serialization are you talking about?
@shy violet
So you are asking if Unity makes a file with your binary data?
When?
I mean, yes, Unity makes a file with binary data.
Ok
you can try aggressive inlining. its not exactly what youre looking for, but it works
Definitely not what I'm looking for
i had a similar issue maybe last year with a custom logger. i ended up going with inline functions to prevent the internal assembly codes from being shown on stack trace.
idr if it worked in editor, but it does work in debug builds. the function name also is changed in release/master build (if the hiding method is the last method) although you dont get the full stack trace there obv
Does that attribute not work with Unity logger?
Not in the right version
Is it a recent addition?
Yes
there's something very different between how dx12 and dx11 interact with vfx graph and utility camera based effects like realtime reflection probes
Hello! How can I calculate velocity change while taking into the account other things that could change player's velocity? For example jumping forward?
This is my current movement code:
Vector3 _direction = input * walkSpeed;
Vector3 currentVelocity = rigidbody.velocity;
currentVelocity.y = 0f;
Vector3 acceleration = _direction - currentVelocity;
rigidbody.velocity += acceleration;
It works okay but there is one problem... If I would try and add force in the forward direction:
rigidbody.AddForce(this.transform.forward * jumpPower, ForceMode.Impulse);
The object would just stop because the velocity change in the script above isn't taking this force into the account... Any help?
why don't you just do the velocity change as a force too?
The entire point of forces is to effect a change in velocity
aka the exact same thing you're doing
rigidbody.AddForce(acceleration, ForceMode.VelocityChange); would be equivalent to your += line
Yup I'm aware of that I just didn't think about doing it for the forward jump too-
Thank you!
I'll give it a try
@sly grove hmm it did not help. I think the main problem is because the movement function is called in the fixedupdate function so it runs every phyics frame. It overrides any other velocity change im trying to do
that's why would I need to take jump force into the account in the line
Vector3 currentVelocity = rigidbody.velocity;
currentVelocity.y = 0f;
https://docs.unity3d.com/ScriptReference/Rigidbody-velocity.html
In most cases you should not modify the velocity directly, as this can result in unrealistic behaviour - use AddForce instead Do not set the velocity of an object every physics step, this will lead to unrealistic physics simulation.
You are aware of this?
Yup I am, but the problem is then if the player starts moving and the movement function is called again it will cancel out the forward jump force
even to I'm adding to the velocity not setting it directly
+=
Vector3 _direction = input * walkSpeed;
Vector3 currentVelocity = rigidbody.velocity;
currentVelocity.y = 0f;
Vector3 acceleration = _direction - currentVelocity;
rigidbody.velocity += acceleration;
But its telling you to do movement via addforce
you mean
rigidbody.AddForce(acceleration, ForceMode.VelocityChange);
```?
Yes, thats how Unity wants you to interact with rigibodies
yup but thats same thing as if I were to do
rigidbody.velocity += acceleration;
Not really no. Unity really wants you to do it this way
all of the velocity changes we're talking about are additive
none of them will override anything
you've got some other code probably that's overriding it
hmm but when I comment out this line
rigidbody.velocity += acceleration;
it works
i think the problem is because, if for example
oh it's because
look at your code
you're literally adding the exact amount of velocity you will need to exactly set your velocity to a certain amount
yup i know where's the problem I just dont know how to fix it
you're doing rb.velocity = _direction in a roundabout way
what are you actually trying to do with this code?
I'm just trying to move a character so it doesn't affect other forces
so the other forces aren't affected by it*
you just want this then:
Vector3 _direction = input * walkSpeed;
rigidbody.AddForce(_direction);```
and tweak the numbers to your liking
and potentially add a clamping to the velocity
or drag forces
hmm but what should I do then about the slow acceleration at the beginning of the movement?
Are you sure you want to use the physics engine for your movement?
Yes ._.
If you want faster acceleration, you add more force or reduce the object's mass
That's how physics works
there's also nothing stopping you from doing more complicated things. Think about real life. You can quite explosively start running from a standstill but once you're going fast your legs can't move much faster so you can't accelerate well when you're already moving. You can write code to simulate that kind of thing - vary the amount of force you can apply based on your current velocity and the direction you want to apply the force in etc...
getting "good" feeling movement is not going to be as simple as a few clean lines of code in FixedUpdate. It's a very complex subject
Yup I understand. And I'm not trying to do anything really complex right now it's a simple little stylized game but I was just stuck on this, I think I got it!
So thank you!
Does that even compile...
i didnt try yet LOL
Well you're in #archived-code-advanced
cause i didnt know if it was an advanced question or not
It really is not, that code can't even compile for many reasons
I think I figured it out π gimme 2 mins
that's silly code. You don't need to use GetComponent, you can just use .transform. And no point in the logic of this since instead of getting the transform you have to get this class, you are not really saving anything
Not to mention that you can't have a member with the same name as the class, and you're using a variable that doesn't exist
Ive just been trying to google but havent been able to find anything to help me get my code do what i want it to so i've been trying to stretch
Fixed the class issue, i'm new to coding so it was just something i wasnt aware of yet
Should probably stretch yourself over to #π»βcode-beginner
When i ask questions there, no one answers me. I figured it meant no one knew the answer
dunning kruger in full force
watch some beginner tutorials on gamedev in unity with c#....thats not good to say it nicely
Is there any way to define a constraint on an interface so that it can only be used with a class?
I'm trying to search through a generic list of an interface for elements of a specified type, typecast the element and return it. But it appears I can only do this for lists of elements with a class constraint.
Thank you for the reply, I have been trying to get what you said working. I have neglected to mention that I would prefer to do this directly through script rather then a shader, I can share what I have if you're still willing to help, I'll be happy to share any information needed to get my problem fixed π
Texture without the projection applied
texture with it applied
private Texture2D RegularToEquirectangular(Texture2D tex)
{
if (!_UseEquirectangularProjection)
return tex;
Texture2D output = new Texture2D(TexSize.x, TexSize.y);
InitializeTextureSettings(ref output);
float maxLon = TexSize.y / 2;
float minLon = -TexSize.y / 2;
float pi2 = Mathf.PI * 2;
float halfPi = Mathf.PI * 0.5f;
float height = TexSize.y;
for (int x = 0; x < TexSize.x; x++)
{
for (int y = 0; y < TexSize.y; y++)
{
float latitude = x;
float longitude = Mathf.Clamp(height * Mathf.Tan(y * halfPi), minLon, maxLon);
output.SetPixel(x, y, tex.GetPixel(Mathf.RoundToInt(latitude + _Offset.x), Mathf.RoundToInt(longitude + _Offset.y + maxLon)));
}
}
return output;
}
This is the script I'm currently using for this
?
what is your objective?
Something like this where the poles get more distorted to resemble that of longitude of a sphere
the radius of the cylinder would be textureWidth / (2 * Mathf.Pi), the height is textureHeight. This would work for any texture width. you can look at the UVs of the default cylinder, which already reserve a rectilinear space in the UV mapping for the curved part of a cylinder, or make your own
hmm
okay
are you asking how to convert between cartographic projections?
yes
did you try googling "cartographic projections library github"
the starting projection would be mappable to that of a cylinder
because that's the answer
I have
I've been doing that for 3 days lmao and came up short each time, most require me to use shaders and I'm not interested in using that for my project
public T GetState<T>() where T : IState
{
return states.Find(o => o is T) as T;
}
This doesn't work because IState doesn't have a class constraint and therefore can't be typecast as a generic class.
equirectangular cylindrical projection
i mean the process of turning one cartographic projection into another
oh, not quite?
based on what i'm seeing online, the term is "reprojection"
you can research the implementation here maybe
Thank you, I'll have a look and let you know what I find
okay
maybe this one will be best
okay but this also doesn't do anything
that's probably why it doesn't work
what are you trying to do?
Trying to find a state of a given type and return it, typecasted to that type.
okay, then just use OfType
there aren't sealed interfaces in csharp
that's the feature you'd need to implement what you want
however, if you use an abstract base class instead, and mark the subclasses as sealed, it will work
@fathom locust how about this?
this correctly errors for me
then you can FirstOrDefault
I just thought of an alternative. Instead of relying on interfaces in the first place, I can get around the typing discrepancy by using a wrapper class for everything else I need.
is it posable to build a custom editor that when typing in a string field it will try to auto complete from a list of words you have ?
want to enter item name and have it try and predict what im typing so i dont have to enter so many items manually or well less manually
Sure
I've seen assets do it. Know of a free one that does it if you wanna see how they do it
It uses a custom editor window though, but I imagine the process is similar
This bit here:
ty
Also a cool tool. np
with uielements you can do this pretty easily, you can register a callback on KeyPress events and check if the TextField is on focus
I don't recall there's any public function similar to onValueChanged for uielements textfield, but yeah, registering a callback is the way to go
cache those keypresses (while the textfield is on focus), then you can do it with delegate Func<string, string[]> or just a plain funcion that returns array of string of suggestions
You proly don't need to make registercallback on your own, there is this event you can subscribe to
hi i need some help with a rotation problem, (quite new to unity) Please dm me if you have any idea!!! ill show you the script
@tight cypress Don't cross-post
is GetComponentsInChildren order guaranteed? it is mentioned in docs that it internally uses recursion+dfs to search, but I'm really not sure if the order should be consistent
you can just sort it
oh wait, I thought you mean the plural version
yeah, use the plural version then sort it
yes sorry. i mean the plural only
I wanna say the docs mention order can't be guaranteed, but might be thinking something else
I'd be safe and say it can't be, because the hierarchy can easily change
sort on basis of what?
based on what you want? how am i supposed to know XD
no the hierarchy is not changing here. the hierarchy is fixed. I want to sync the hierarchy with server for the first player.
in my case, sometimes the order is not same, and is causing issues because player1 and player2 dont have same order
if you're only looking for specific component, lets say just one, then just filter it
i want to sort them based on the order in hierarchy
there you go, then yeah, thats very possible
Can use transform.getchild() to get their position in hierarchy, but you kinda lost me on why
comp1
comp1-1
comp1-2
comp2
comp2-1
comp2-2
i want them in order like comp1, comp1-1, comp1-2, comp2, comp2-1, comp2-2 and so on
Sounds like you're trying to basically use the hierachy as a list for multiplayer. Sounds like a bad time
yes. why is it a bad time?
Because it can change and it wasn't designed to hold data like this
huh?
So order can be wonky maybe, etc
no the hierarchy isnt changing at all
its fixed in the prefab
not changing ever. order is same throughout the lifecycle of the scene and also the application
It sounds like he's trying to use the hierarchy as a form of data storage, by pulling values from the hierarchy instead of some data class
Just sounds like a bad time, as I've noticed how vastly hierarchies differ in multiplayer
not really. i place the components in the scene. i need them to be in scene because they store positional data
as in the position of the components transform
Yep. You're using the stored hierarchy position. That's using it to store data.
Or maybe I'm just confused. I'm bowing out
let me explain fully what i'm doing in here. i have multiple objects in scene, whose main work is to denote their world position and rotation in the scene.
i send the number of objects to the server for initializing. basically the server just stores the total number of the component instances.
then to spawn some objects at the said points, the server will send a random index ranging from [0, componentInstances.Length-1]. basically just a number to client instead of vector3 positions and quaternion rotations (to save bandwidth)
then when the client receives the index, it will lookup for the index, and then get a world position and world rotation and spawn the object there.
the problem here is that, the index lookup is not same for all clients. because i'm doing GetComponentsInChildren whose order is not same across all clients.
array[10] for client1 and array[10] for client 2 are not the same when the list is initialized with GetComponentsInChildren<T>(true)
the fix im looking for:
- sort the collection based on something, preferrably by hierarchy order, or anything. but i just want to guarantee the order across all clients with that sort.
what i'm not sure of here is:
- if GetComponentsInChildren is supposed to return in order or not. If it should return in order, i dont know what then. But if it doesn;t return in order (which my case clearly shows) I will obviously go with sorting
the problem here is that, the index lookup is not same for all clients. because i'm doing GetComponentsInChildren whose order is not same across all clients.
array[10] for client1 and array[10] for client 2 are not the same when the list is initialized with GetComponentsInChildren<T>(true)
This is what I mean by using the scene to store data. I'm not sure why the order is different. Maybe GetComponents order can't be relied on. Maybe one of them was moved or reparented or simply disabled. I know inactive objects will not be searched, and some netcode will disable objects until their client is connected, or under other circumstances. This is why I say using it to store data is bad.
With that said, as an alternative, I could suggest storing these "position" game objects in a list instead. Put this list on whatever object needs these positions, probably the spawner. This way, this order is found at EDIT time instead of runtime and you should be all good
List<GameObject> positions
Then use positions instead of where you're using the results of the GetComponents call
idk why but this gives me wrong count or something else is happening so any idea how to fix this or what is wrong ?
i have multiple append buffers in compute shader
VerticesBuffer = new ComputeBuffer((Voxels.Count / 4)*8, ComputeHelper.GetStride<Vector3>(), ComputeBufferType.Append);
...
VerticesBuffer.SetCounterValue(0);
VoxelMeshGen.SetBuffer(kernel, "vertices", VerticesBuffer);
...
VoxelMeshGen.Dispatch(kernel, Size.x/4, Size.y / 4, Size.z / 4);
VerticesCountBuffer = new ComputeBuffer(1, sizeof(int), ComputeBufferType.IndirectArguments);
// Copy the count.
ComputeBuffer.CopyCount(VerticesBuffer, VerticesCountBuffer, 0);
// Retrieve it into array.
int[] counter = new int[1] { 0 };
VerticesCountBuffer.GetData(counter);
// Actual count in append buffer.
int count = counter[0];
Debug.Log(count);
// Get the append buffer data.
verts = new Vector3[count];
VerticesBuffer.GetData(verts);
VerticesCountBuffer.Release();
...
GetComponentsInChildren should return array ordered by hierarchy at the time the function is called.. its never wrong in order. unity fixed it long ago during HLAPI era.
What's the relationship between UniRx and UniTask?
I wouldn't trust the hierarchy order, just like how I don't trust GetChild(0) to refer to the same thing. In this example, ask yourself, do I really want the first child, or am I looking for something in particular, and I'm just assuming it's the first element? Maybe in the future I rearrange it, which would break the code. Coding it in a certain way resists constantly breaking due to things like that. In your example, you don't want the hierarchy order, you want to get a position/rotation using the index given by the server to grab on gameobject from an ordered set. The gameobjects can be put in a proper, synchronized order by giving them each a network ID of sorts. Basing in on anything else gives a possibility for desynchronization.
Is there any way to see source of Render Objects feature from SRP?
Hello there. I find myself working with Unity 2020.3.30f1 building for WebGL. I have created a file named JSBridge.jslib, which content is as follows:
mergeInto(LibraryManager.library, {
FireJSEvent: function (jsonstring) {
const obj = JSON.parse(jsonstring);
window.dispatchEvent(obj.eventKey, { detail: obj });
}
});```
I have placed this file onto the Assets/Plugins folder. Then, I have created a MonoBehaviour script named JSBridge.cs, which has the following lines within it:
```cs
//...
[DllImport("__Internal")]
private static extern void FireJSEvent(string jsonstring);
private void Start()
{
#if UNITY_WEBGL
FireJSEvent("{eventKey:start}");
#endif
}
//...
And the following error pops out on console:
EntryPointNotFoundException: FireJSEvent
JSBridge.Start () (at Assets/JSBridge.cs:32)
Any ideas on how I can remove the error? Will the code work if I compile it to a WebGL build?
When you add an anonymous method as an event callback, when is it removed? I'm having a hard time finding any concrete info on how this works behind the scenes
myClass.someEvent += () => print("some event");
I'm especially curious about adding an anonymous method to an event within the scope of an async task so the task can know when the event was invoked
var complete = false;
myClass.someEvent += () => complete = true;
await Task.When(() => complete);
// some event has now been invoked
// will the anonymous callback ever get cleaned up?
Is that okay π
Or do I need to manually remove the listener like so
var complete = false;
var completeAction = delegate() { complete = true; };
myClass.someEvent += completeAction;
await Task.When(() => complete);
myClass.someEvent -= completeAction;
// some event has now been invoked
I know it probably doesn't matter but it would bother me if these anonymous callbacks pile up over the app's lifetime
It does not get removed automatically. It will however be released with the owner of the event.
Gotcha, so it will get garbage collected along with the owner. If you were to add an anonymous listener to a static event would that mean the owner never gets garbage collected? π€
Yes, and it will hold onto everything contained in that event for the lifetime of the program
Roger that π
And to be clear, is the "owner" the class which holds the event, or the class which holds the callback?
If everything stops referencing the instance that has the event then it will be freed
I see. Then it seems like as annoying as it is, you really should manually unsubscribe your callbacks right? Is that how you handle event listeners?
Generally yes, unless you're in total control of your references you should find a way to unsubscribe
It will however be released with the owner of the event.
Practically false, your object will not be unloaded if there is an event subscription. You can use the memory profiler to figure this out.
You have to unsubscribe everything you do.
Well RIP anonymous methods then π
thanks for the clarification @austere jewel @tribal pivot @sage radish
Just wanted to make sure I wasn't off-base before mentioning this to coworkers π
You could set it to null entirely
Yea I guess sometimes. But the nature of events makes me think I *shouldnt make assumptions about other listeners not being important in most scenarios
The garbage collector doesn't arbitrarily hold onto things with events. If the instance containing the event is going to be collected because it is no longer referenced, then it will be freed.
I have 100% seen objects not being garbage collected because there was an event subscription on it.
Which object are you referring to? The subscriber or event owner? The event owner and the event delegate itself can definitely be garbage collected even if it has listeners in it still. As long as nothing is referencing the owner or the event.
But you're right that the listener can't be garbage collected if it's being referenced by an event.
You can even invoke the event, and the now null subscriber will get called, eventhough half of it is garbage collected. this will be null
Now you're confusing garbage collection with Unity object lifetime
We weren't necessarily talking about Unity objects
this can't be null. this == null can return true if this is a destroyed Unity Object.
You're right, garbage collected is the wrong term. Still, ive had event callbacks where this is null
Yes it can
You can't destroy objects in C#. That would be unsafe. Unity fakes it by overriding the == null check to return true if the underlying native object has been destroyed.
Unity objects also override ToString to return "null" if the underlying native object is destroyed.
It's a Unity Object. It's evaluating to null
You can confirm this by logging Object.ReferenceEquals(this, null)
Eh ok. Ok you guys are right.
Whats the difference though, practically speaking?
You should unsubscribe your events.
The question wasn't whether you should unsubscribe or not. The question was this:
When you add an anonymous method as an event callback, when is it removed?
Alright, you're right
Pretty cool series on GC btw: https://devblogs.microsoft.com/oldnewthing/20100810-00/?p=13193
Simple profiled example that self-references in an event and is released
use unirx if you want a more idiomatic way to manage event subscriptions. otherwise, what do you think is really passed to the right hand side of var completeAction = ?
it's not javascript, they're not anonymous callback function objects... it's something else that's going on
@subtle river memory/the code looks something like
some function D that is the delegate's source code, which takes an argument "address of a boolean variable" (i.e., the specification of its closure)
completeAction "1" is an instance of a "complete action binding class"
a pointer to the function D
a pointer to the address of a boolean variable
completeAction "2" is an instance of a "complete action binding class"
a pointer to the same function D
a pointer to a different address of a boolean variable
it's not like you create a big object that is a function
that stuff doesn't matter
the thing that matters is "pointer to the address of a boolean variable"
i.e., things in the closure
it becomes way more clear why the event references don't matter once you refine what the real question is - what are the lifetime of objects referenced in a closure? the simple answer is it is the min ( lifetime of declaring scope, lifetime of the function referencing it )
pretty simple.
the function with the closure (i.e., your delegate) has a lifetime too - it will die at the end of its declaring scope if it's not referenced anywhere else, for example in an event, which is just a fancy array
memory. everyones favorite bug :')
Hello guys!
i wanted to know whats the best way to draw the LineRenderer through code. since if the weapon is so close to the wall it wont be straight from the weapon barrel.
Anyone knows how to use read swift functions in objC? I created a unity project (2019.4.23) but i need native swift code to run in a custom UnityAppController
out of scope for this chat. there's documentation online about this
Thanks
#archived-code-general you can set the points making up the line renderer via code
get components in children returns in the order in which those objects were initialized i think*
i don't think the hierarchy order will be the same
sort on the names of the objects
Ok tysm
Beans5715 memorythe code looks something
what is the best way to establish communication between 2 unrelated objects in a scene? Drag&drop attaching references suck, .Find() is better but falls apart whenever you try to rename or change hierarchy, Find() with tags is kinda manageable, but there should be some message or event system that is easy to use, right?
asked in #archived-code-general and someone mentioned a static dictionary that would hold references to every object, and it seems like an interesting idea, but don't tags kinda accomplish the same thing? I've read up on Unity Atoms but it seems needlessly complicated for something so basic. I guess I'm asking about experiences, what worked for you guys in the past and if there are some must-have assets i'm overlooking
You can use the void Reset() Unity method. It's called when you add the script to a scene or click the reset button on it. If the scripts you want to find are unique you can use FindObjectOfType<ScriptName>()
what is the objective
like give an example
Drag&drop attaching references suck
how do you figure? like how could it get any simpler than this
somewhere, somehow, you have to declare the names / identities of the things that should communicate with each other
you can either have two fields, which seems the absolute bone dry simplest to me
or you can build a big cathedral that... still, eventually, has to declare the names or identities of things that should communicate with each other
there IS a message system that is easy to use, BroadcastMessage
an example would be a combat event log, where a message is logged on every attack any unit makes
this stuff exists in unity
but a message bus... like you have to register on the message bus, which is "declare the name or identity of things that should communicate with each other"
except instead of just declaring fields, now you also declared a message bus
do you see what i mean?
declaring the name or identity of things that should communicate iwht each other is unavoidable
my main issue here is having to rebuild half a scene (or more) whenever I want to test an object or a script, a middle-man object/script would work nicely here
That is doable yes, you can have a class that declares an event you can subscribe to, and invoke
Hey there, I'm using a Bluetooth library for my win64 exclusive Unity project and I'm running into an issue regarding the System.Runtime version of the project:
Assets\Scripts\Managers\BluetoothManager.cs(122,9): error CS1705: Assembly 'InTheHand.Net.Bluetooth' with identity 'InTheHand.Net.Bluetooth, Version=4.0.0.0, Culture=neutral, PublicKeyToken=ea38caa273134499' uses 'System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' which has a higher version than referenced assembly 'System.Runtime' with identity 'System.Runtime, Version=4.1.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
I've attempted to upgrade this package in visual studio using NuGet and adding the new version to the Asset folder, but it does not seem to solve the problem. Am I missing something?
it is certainly doable, but is it a good practice? I haven't seen a standardized way of doing this, or even a recommended approach
well i think i get into winding conversations like this all the time, where people are seeking to write a lot of ceremony
the net amount of code they write, in a big-O sense, doesn't change
and i'm trying to give you the insight as to why that's the case
Our game is entirely based on event subscription, works great
its a PITA to debug tho due to the way you subscribe
but if correctly documented, it's a good approach
for testing purposes, find all objects of type is your event bus
just gotta support it with a well thought architecture
i wouldn't overthink it
personally i would declare fields lol
because they are a superior way to declare a relationship between two components in Unity
and if you want to discover objects to add to your fields, use find all objects of type
and when you need to cross the bridge to make that exact method call fast, which is a short bridge but very far on your journey
imo if you have 2 unrelated objects that need to communicate
then you can deal with that
they arent unrelated anymore
i think people get stuck in a lot of brain farts like this
the opportunity here is to deconstruct what you are asking for
You can use tags and find objects but the sane approach would be to make them depend on a manager that sets up the relationship
"how do i write names for things?"
but that means code refactoring >_>
fields. fields are a simple way to write names for things
yep
sometimes you gotta refactor
because sure you are working on alpha and build an entire system that depends on that relationship and down the road you find up its messing stuff up, now you gotta refactor an inmense amount of work
well, with fields
it's like, okay... it's either null, or it's the wrong type, or it's the wrong name, or it's pointing at the wrong thing
4 possible bugs
extremely finite
and soon you have 100 extremely fixed and defined things
for normal people they should avoid ceremony
"message buses" have way more things that can go wrong, for little value
... thats good?
because you still wind up having to declare the identity of something somewhere!
it's unavoidable
eventually, you have to have
Message busses are also a valid approach, there is a reason why there are so many design patterns
just gotta use whatever works best for your wanted solution
field = some object // could be in the inspector
or
event bus . register (some object)
the big O of the amount of stuff you've written is the same
No, tracking 100 cities is a bad thing, when you can get into a train and only go to the relevant stations
well, the latter part is a design pattern
maybe for that specific case use it sucks
sometimes you want generic behavior sometimes MUST define extremely specific and defined behaviors, it depends
you cant just say "fields suck" or "message busses suck"
it depends
I wish programming was that easy
blanket statements like that mean nothing
Who said that
the expanding brain meme version of this is
1. I will use BroadcastMessage or FindAllObjectsOfType...
2. Those are slow, let's directly reference these things
3. I will use an event bus, dependency injection, and other discovery mechanisms instead
4. I wound up recreating something Unity ships with that was simpler / I recreated C# methods and variables, so I'll go back to using that but with caching
5. These things should not have been decoupled in the first place
i think a ton of people get stuck at 3
so they never get the wisdom at 5
this specific example... i mean of course your combat event log should just be a singleton / static instance, and anything that needs to log to it should just log to it
it shouldn't be decoupled
it's unavoidable
the big O of the code is the same in ALL SCENARIOS
let's say the event log "discovers" what can write to it
now you have IHasEventLogEvents on all of your monobehaviours
O(number of identities)
let's say each thing just writes to the event log instead
O(number of identities)
let's say you have an event bus. every way you cut the event bus
you will have to add O(number of identities) code to do this!
no matter what your pattern is
static events are super easy
I personally reserve singletons for managers that will survive the entire game loop but its a valid approach, yeah
either there are O(number of identities) registrations or there are O(number of identities) type checks of an event type
and then your event type has IHasEventLogTrait or whatever
do you see what i mean?
O(number of identities). O(number of identities). O(number of identities).
it's unavoidable
you will not be able to get better than O(number of identities)
don't try!
this is how i see it, I have a combat log that i'd like to test and work with, and I would like to do that without having to rebuild everything else in a scene. So my options here are
- rebuild a full scene with units/grid/abilities/etc and do hard references between objects
- have combat log listen for events of type A, where other objects can broadcast/dispatch events of type A, and ideally where I can just artificially send an event of type A with a single click
hey ive been trying to get a working mesh terrain system however I got weird behavior with the new mesh API where the first 4 triangles are always missing in my meshes
I would like to do that without having to rebuild everything
the best you can do is O(number of identities) = O(number of things that have to write to the event log)
i mean, how could it be any other way
CombatLog.instance.LogEvent()
the universe would be topsy turvy if you could do that with no work
"i would like code that writes itself"
tough cookie!
have combat log listen for events of type A, where other objects can broadcast/dispatch events of type A, and ideally where I can just artificially send an event of type A with a single click
this is still O(number of identities).
anyway @half path take some time to digest what i've been saying here and then it should help you make the choice that's right for you
i know, it's just an example, there are better ones, this is just what i'm working on currently
if you are interpreting "things" as "number of game objects" you ar emisundertanding me
i'm trying to get you to ascend here but maybe it's too early
ascension is only possible after 2pm
lol
"but what if i had a base class" well extending a base class is O(number of identities)
honestly i think this is a waste of time optimization. your game might have 50-100 identities, which as long as it's like 1-2 lines each will take you 3 minutes to do
also a common pitfall
Dont optimize until you need it
number of identities is irrelevant here, do you not agree that it is better to assign all those identities in a singular place than having a web of interconnected stuff that is hell to setup and debug
expanding brain meme:
1. Ugh, how do I automate this task! I guess I won't do it. Too many clicks.
2. I have written a cathedral (event busses, base classes, editor script) to automate this task.
3. Clicking on 100 objects takes like 3 minutes to do.
of course have common sense and dont raycast 200 times in an update loop but you get what I mean
they have the exact same possible (but finite) number of mistakes
you could forget to assign one of those identities in a single place
just like you could forget to touch something somewhere in some class
etc. etc.
and I immediately know where to look, instead of searching the entire hierarchy of references
it's up to you, i have shared the most wisdom i have
on this matter
the number of identities you're interacting with is the most essential part of this problem, because it will give you insight that the simpler way to enumerate these identities the better
you can build a cathedral to specify those identities (e.g., event bus, dependency injection) but it will burden you unnecessarily
my personal suggestion is CombatLog.instance.WriteToLog(...) in all the scripts that should write to it
that's O(number of scripts that interact with the combat log) ~ O(number of identities)
you could "forget" to "write to the log" when you define a new script, but you could also forget to register it on the event bus, add the interface, etc.
the big O of the number of mistakes you could make is the same
there will be like 10 attacks in your game so it will NEVER matter
and maybe you have an attack base class that you inherit from (still O(identities) but less janky for sure) that calls CombatLog.instance.WriteToLog(...)
an event bus just does not help here
I see what you're saying and it makes sense, but you're looking at this from a purely programming perspective... what if I, for example have a designer who doesn't do code or doesn't know enough game logic to interconnect stuff by themselves? Isn't it easier to tell someone to "drag here and connect to these 2 things" than teaching them how to setup an entire scene from scratch?
it depends how valuable my insight here is
if you value it, i'll tell you that having a designer do this stuff is a waste of time
How would I do CircleCast but in 3d? And with 3d colliders?
..spherecast?
The shere cast would also pickup on everything above and under, I basically want an flat box cast were the distance is checked so it's round π
I'd say a bigger waste of time is having to teach everyone everything. But it shouldn't matter if your project is small tho
sorry if I pinged you, it was accidental
Dont think that exists.
But you could do what you describe, boxcast and then discard anything with a distance > your-radius?
uh?
wdym by above and under
Yes, I'll be doing that for now. I was just wondering if there was a better way to go about it
a 3d circle cast would be the equivalent of projecting a cilinder
A overlapsphere is not flat
a sphere cast is a capsule
a bat is a chicken of the cave
which for 99.9% of purposes would be identical
I'm just looking for a flat overlapsphere
doesnt exist, should use the suggestion above
really confused about the use case for that haha
easiest way to do that i can think of is use a cylinder, squish it, then use a cylinder collider on it and trigger the OnStay or OnTriggerEnter
I would love to know what you did for your game with event subscription, if you're willing to share some general tips
we used actions
O ye, I might be able to do a overlap check on a custom shape
We just have managers that declare an Action, then components that needed to be invoked on said actions would subscribe to it
for example, the input system just calls a single function call for when an input was detected, and every component that would need to receive those inputs would subscribe to it
and if it needed to stop receiving them, it would unsubscribe, p useful
Hi, anyone knows how I can custom sort an array of objects based on a Color property?
with Linq you can sort by anything
I see, thanks!
No idea what Linq is
Is there another way of custom sorting?
Because Color has no CompareTo and I can't just implement one because I got no access to that class
This lets you add new methods to a class that is already defined
Thanks
you know how when you export webgl's and if you dont do build and run it doesnt work because build makes it so its just local
Is there a way to reverse engineer a local webgl one because i lost everything on it but i have the one thats just build on google drive
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.sort?view=net-6.0
Look you can pass in your own compare
Extension methods are not useful for you here
Its not like if you make a compareto it will be used.
Use the sort method with a custom comparer
Alright I'll check it out, thanks
I've got another question, regarding inheritance.
I have a gameObject that is a Player Board, and has a script of Player.
Now I have a class Computer that is derived from Player and I wish to use it as an AI.
However, it seems I am unable to have polymorphism in that way where:
Player p = new Computer()
Why not?
?
I basically have a game object that is linked to the Player class.
I intend to have a Player variable that can either be a human player or a computer player.
If he were a human player, I'd just get the script component from the object without a problem.
If he were a computer player, I'd assign him a new instance of a Computer class, as that class has extended functions specific to the AI.
But still have them use the object from the game, just like the player.
in unity you are supposed to define what a gameobject is by adding components. A human player gets a HumanPlayer component, Ai gets AiPlayer, both derived from Player, which in turn is derived from MonoBehaviour.
I dont get it, youre confusing object and component.
Or just skip inheritance
Player = GetComponent<Computer>()
you donβt new components, you add/remove or enable/disable them
The pattern is called composition
#π»βcode-beginner you should probably start with a unity tutorial
?
are you saying you lost your project?
Anyone knows why I have this exception?
Here's the code:
public void FirstAlignment()
{
List<Tile> tiles = new List<Tile>(hand);
tiles.Sort((Tile t1, Tile t2) = t1.GetValue().CompareTo(t2.GetValue())); line 25
for (int i = 0; i < tiles.Count; i++)
Debug.Log(tiles[i].GetValue());
}
your list has one or more null entries in it
which means hand has one or more null entries in it
Oh I see
that means that null gets passed into your comparison function, causing that error
I am aware there are null values in the hand at first, which is why I wanted to pass only the non-null elements to the list
I assume there's no short way of doing it?
why would you assume that
Because I'm pretty sure I can't do it in one line
although - why do you have null in hand in the first place?
ist that intended?
It can definitely be done on one line, not that that is the best way to do things always π
Yes. The hand has 22 tiles but starts with 14 only
π¬
And what would that way be?
List<Tile> tiles = hand.Where(t => t != null).ToList();
with using System.Linq; at the top
Ahh Linq
I think I'll pass with Linq tbh, I just don't want any random errors that I can't understand to pop up
you could also just let your comparison function handle null entries, if you want tiles to contain the nulls too
not sure what you mean by this, but just use a for loop then and filter the nulls out if you're averse to Linq
Yeah might go with it thanks
(and I meant that I didn't learn about Linq so yeah)
var tiles = hand.SortBy(t => t?.GetValue() /* ?? a default value */).ToList()
no idea what GetValue() returns
but you can deal with nulls just fine
It's basically just the numerical value of a TextMesh that's all
Alright. Thanks
Today I installed new version of unity(2021.3.1f1) after upgrading my project I'm getting this error
Assets\Backend\Scripts\JsonUtilities.cs(34,39): error CS0433: The type 'JsonValue' exists in both 'System.Json.Microsoft, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' and 'System.Json, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
How can I solve it
hey
can i get some help
iam programming a RTS game and trying to set a Local Avoidnace while using the Nev mesh.
does anyone have a soultion for that?
bec my Units stack on eachother tho
hello, i don't really know a whole lot about straight c#, but does anyone have any idea how I could get Apache kafka working with unity? I've found this library (https://www.nuget.org/packages/Confluent.Kafka/) and these examples (https://github.com/confluentinc/confluent-kafka-dotnet/blob/master/examples/Producer/Program.cs#L45) and in stack overflow I found some people saying that I only need to install the package and then copy some .dlls into the unity project, but I have 0 clue on how to do that. stack overflow for reference (https://stackoverflow.com/questions/54898608/unity-confluents-apache-kafka-net-client)
void Update()
{
if (hasHit)
{
if (!firstHit)
{
colliders = Physics.OverlapSphere(landingSpot, 4f, monsterLayer);
Debug.Log("gonna hit for init damage");
foreach (Collider col in colliders)
{
//Debug.Log(col);
if (col.gameObject.transform.CompareTag(enemyTag))
{
col.GetComponent<MonsterHealth>().TakeDamage(initialDamage);
nextShot += hitsPerSecond;
firstHit = true;
}
}
}
if (Time.time >= nextShot && hitsLeft > 0)
{
Collider[] activeColliders = Physics.OverlapSphere(landingSpot, 4f, monsterLayer);
Debug.Log("gonna hit for normal damage");
foreach (Collider col in activeColliders)
{
if (col.gameObject.transform.CompareTag(enemyTag))
{
col.GetComponent<MonsterHealth>().TakeDamage(damage);
}
}
Debug.Log("just hit for cling damage");
foreach (Collider col in colliders)
{
//Debug.Log(col);
if (col.gameObject.transform.CompareTag(enemyTag))
{
col.GetComponent<MonsterHealth>().TakeDamage(clingDamage);
}
}
nextShot += 1/hitsPerSecond;
hitsLeft -= 1;
Debug.Log("I have " + hitsLeft + " hits left");
}
if (hitsLeft <= 0)
{
hasHit = false;
firstHit = false;
Destroy(gameObject);
}
}
}
This code is supposed to hit once, then wait, and do that 10 times, however, it hits all 9 times in basically a second.
The same " nextShot = 1/hitsPerSecond" and "if time.time > nextShot" works just fine on another script which is why im surprised why it doesnt work
ignore the 1 error and warnings, the error is to do with the spectator which is completely unrelated and has been like that before the error appeared, the warnings are debug.logwarning
Hey hey people, I've in a little pinch understanding the whole ECS gig.
Googling yields either too abstract or too hardcore stuff.
I'm no coder, I'm a generalist so I may misuse terms to a varied degree of misuse.
Say in our game, we have a horse which the player could mount.
In poor oop that'd be, in pseudo,
some stats
mount():
...
dismount():
...```
So, whatever stuff you can do w/it is written under their single class.
In more functional, "better OOP" as I tend to think it, that'd be
```class horse
...
mount(target):
...
dismount():
...```
Here, a horse is a stat bunch w/maybe some behaviour & mount/dismount functions outside their class.
How would this same functionality look in ECS?
Basically, all I saw out there so far were examples of doing the *same* thing to every X component there is, such as moving every movement component in a certain direction. What if we wanted every actor on a scene to move where their AI system tells them to?
Any input highly appreciated, a book even or whatnot.
Perhaps the example listed poorly illustrates that little bit of puzzle I'm struggling with, if it does I'll try conjure up another one.
Cheers π»
in any ECS system you separate data and functionality. You don't get to have mount method in horse. Separate it into two different things: HorseComponent and HorseMountSystem. Assign horse component to an entity, then run a system that handles your mounting logic. The horse component would probably contain bool isMounted which would allow you to handle mount-specific logic. It's tough to picture your example in ECS terms because it depends on the mount functionality. If it's about setting something on PlayerComponent, then your system should gather information from InputComponent (on the player entity as well) and change state of PlayerComponent and MountComponent.
"Basically, all I saw out there so far were examples of doing the same thing to every X component there is" - this is what ECS is about. You need to stop thinking in terms of OOP, it takes a while to get used to it.
"What if we wanted every actor on a scene to move where their AI system tells them to?" - their AI system would set the necessary values in each component, then a separate system should handle their movement, according to different state of the components involved. It all depends on the exact functionality that you want to implement.
Also sorry for not being able to provide code examples, I never used ECS in Unity but in my day job I'm developing and maintaining similar system to this under UE4
Neither I am using ECS in unity, nor plan to. Just a learn-how.
So, if I'm following you, for
every actor on a scene to move where their AI system tells them to
We'd have actor entity with MoveComponent, MoveSystem and AiSystem.
MoveComponent would (roughly) have stored pos and targetpos.
AiSystem would iterate over all entities that have MoveComp. and set it's targetpos to a certain value.
MoveSystem would then iterate over all entities with MoveComp and actually change their pos?
Yes, although in certain situations you might want it the other way around; the MoveComponent would query a different component to take different action - in this example it doesn't make much sense, but in some scenarios that could improve cache coherency. For this situation (although still broad), I'd do just what you described
Yeah seems so.
Still, while it does make sense for tons of stuff happening, can't figure out how this blends into the horse example.
You need to stop thinking in terms of OOP
If I didn't, I wouldn't ask. : )
If we throw in a system for this and a system for that, iterating over our couple dozen components all around the game, I imagine an update cycle looking sth like:
sys2.update
movesys.update
aisys.update
...```
wouldn't that cause weird racing?
What exactly do you want the horse to do though? We use "tags" to easily filter the components during iteration - if I wanted to change movement behaviour of a player, say, entering a vehicle, I'd set a tag on the player that prevents movement system from iterating over that entity and let the HorseMovementProcessor take over. The mounting/dismounting would be handled by a separate system - getting nearby mounts and filtering for players with a certain input state. Then change the state of the components to represent mounted state
That is correct. I'm not sure how Unity handles it. We use read/write locks for component pools. Then the scheduler picks the best available job and splits it into chunks for the worker threads to process. I'd guess unity uses something alike
Yeah, they had JobSystem along with the ECS package. A while back that is, frankly I've little idea on the state of unity ECS/DOTS at this moment.
I can recommend these talks to wrap your head around it. Helped me a lot
https://www.youtube.com/watch?v=zrIY0eIyqmI
https://www.youtube.com/watch?v=JxI3Eu5DPwE
I actually came here after these two. : )
This one is kinda helpful though. Thanx
It's more of a conceptual mental block that I can't seem to break out of rather than understanding the principle itself... Case closed for now
π»
I guess it would become more clear if you try implementing something with it. Practice ftw : ) Good luck!
I can definitely relate to that, for a period of time I was focusing on the deep technical stuff in our system without a proper understanding, actually doing something with it really made a difference. Cheers
use coroutines
i think you need to explicitly import JsonValue
navmesh has primitive local avoidance built in. are you sure that's the issue you're seeing? aron granberg's a* has RVO
is there a big difference between writing a normal if-statement with brackets and writing those one liner with the ? and : (Condition?True:False)
I mean does it save performance or anything or is it just for look and different workflows?
Just for looks. Using the ternary operator is a shorthand for doing if else statements
well the ternary operator can evaluate to something
i don't think you can do x = if(statement);
string x;
if(statement) x = "True";
else x = "False";
ternary would generate the same equivalent IL code as above
Ternaries can cause the compiler to be capable of doing more optimisation (removing a local variable sometimes) under specific circumstances, but this is generally true
you shouldn't care about performance in here. its a very very beginner thought for many programmers. even if there was a difference it would be very very negligible.
you should focus more on bigger things.
one FindObjectOfType will have much much more search time that more than thousands of such negligible optimizations.
unless the profiler complains about it, or unless unity doc mentions performance costs, youre good
thanks guys
Yes iam sure
Hi! I'm trying to run automated tests using parameters that are defined in my scene.
In my case, I'm trying to have a few test cases to test if different types of enemies are successfully navigating certain obstacles.
I managed to do it as a single test, which loads my scene, finds the script with test definitions and execute all combinations. This works ok, but the test stops once an assertion fails, and which one of the cases failed is not very visible after the testing is ended. It would be a lot better if I could have each combination visible in the test runner (Like parametrized tests), but the test's data is defined in the test scene. Any good ways to deal with this?
2 million iq i forgot about those
Hello people, I would like to know which is the best way to manage source contorl with unity! I've always been using SourceTree + Git, but I wonder if it could be better to use perforce or plastic.
Which option could be better for a big project?
I heard some companies do
Git is good. Plastic is decent
You need to set up git properly for unity: https://thoughtbot.com/blog/how-to-git-with-unity
I would def use git 100% of the time
The only reason you might not use it is if your team is somehow incapable of learning git IMO
Because the others are apparently a lot easier to use
But if you're just starting out I'd recommend toughing it out
For now this is the only option I know and use! That post is insightful didn't know about a tool to help with dependency injection
Is there something abut DI in there??
yep π
I don't see it
they suggest to use this https://github.com/modesttree/Zenject that is about it
Oh don't do that
That library sucks
Maybe useful if you have a large team
4 people?
Nah, not worth it
IMO
Honestly I just hate that thing.
Also if you are to use it, make sure you use the fork
I am also looking to autogenerate UML, do you know any tool to do it?
The original creator had the IP stolen from him by an employer
No. UML is not very useful
UML is just out of date
I think
I have never heard of a programmer using it
I think ti's a 90s thing?
The trainer in unity certified professional program used it XD (2017)
lol weird
I mean I dunno, I learned it in uni
But like... does it even make sense for unity?
Inheritance relationships are not that interesting
I was wondering it. It may have sense at the beginning in order to plan the code well and fasten the development
What does this even mean? I have been building Standalone windows builds since forever. I am attempting to use this build settings thing so I can use subscenes, but it's already broken out of the box
Are you sure you have windows build platform installed on your editor?
Hi, was wondering if anybody could point me in the right direction for this problem: I'm trying to deform a 2d mesh(square, circle, etc) so that it fits and lays flat on a given section of irregularly shaped terrain.