#archived-code-advanced
1 messages · Page 94 of 1
!code
and probably code beginner
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hi, I am struggling with this part of the development. I have a working Dictionary<String, int>(). Probably using it for players ranking system based on each players crossed checkpoint. Also able to sort out Dictionary using OrderByDescending. The last step getting index not working. Did lot of debugging and cross checked sorting works. Just cant get index of it to assign it to the rank parameter. ALso have created new array using ToArray() to detect proper rank but that also failed. BTW I have two types of player objects, 1 > AI, 2 > Player both has same name parameters and setting except controller / waypoints. The Dictionary inside GameManager. My code is here : ''' ``` //Here we update the Player score by it's name
gameManager.mydict[userName] = _crossedCheckpoints;
//Sorting
foreach (KeyValuePair<string, int> kvp in gameManager.mydict.OrderByDescending(_Player => _Player.Value))
{
gameManager.mydict[kvp.Key] = kvp.Value;
Debug.Log(kvp);
}
rank = gameManager.mydict.Values.ToList().IndexOf(_crossedCheckpoints); ``` ''' How do I get index based on key for rank ? Any ideas?
how many players do you expect to have in that dictionary?
currently its 14 npc 1 player
dictionaries aren't sorted... there's another class which I think does this (SortedDictionary? SortedList? Something like that)
this one if you debug it shows its getting sorted
what could be the issue?
the OrderByDescending enumerator is sorted, not the dictionary
I see, so can get that sorted data from enumerator?
if you need thing to keep sorted, use sorted dictionary (no idea why ms calls it dictionary not tree)
but than sorted dictionary will allow me to Descending?
Also do sorted dictionary gets auto updated or have to place in FixedUpdate?
any sorted data structure accept custom comparator
if you dont update it, then ofc it wont update
btw you want the sorted set supports get by rank (ie the index of key)?
Sorted List can do decending, SortedDictionary cannot
forget dictionary, and just use List
you can just use a list or dictionary and sort it when you need to 😛 (unless you need it way too often)
if yes then go and found if there is source code of indexable tree/ indexable skiplist source code you can copy and paste
yes based on Key I awnt to get rank not by value. but value also get sorted.
sorted set/dictionary doesnt support query by rank, so copy other one
If I use list than I can't use String with Int. Bcz I think I need string as key to compare ad get exact rank
I think I should give this a try
in case you cant find and copy the code from other, do you know how to write avl tree? (i dont know how to rb tree but the way to indexify it should be the same)
btw if the list is updated every update() then just sort it every update(), the time complexity are the same compared to update the whole sorted list unless number of query/insert/delete > number of updating whole data structure
binary search tree is slower than hash table. I don't see the appeal of sortedDict tbh.. I'd just go with List
hash table is not ordered....
will you please base your answers on the obvious lack of knowledge shown by the question instead of just showing of yours
thus, List as suggested
as you can tell, it's a language barrier issue, they got a point tho
Dictionary is kinda fine... you just need an IndexOf thing, which LINQ doesn't have? am I being sleepy or something?
he want query by rank on a sorted set so you cant use unordered set ie hash table
sort it every time seem unrealistic but you can still doing it as i said if you updating the everything in every update()
oh, i miss the point that he needs to query by the key in O(1).....
they don't need O(1) for anything would be my guess
~review the problem
obviously the rank of all players probably change in every update, then sort it every update
i probably just consider this:
List<string float pair>//player and its score, what ever
Dictionary<string,int> map;//player to the index in the list above
```~sort the list every update then repopulate the dictionary, sparse set with sort function
simple is the best.....~
update:
the key is based on some criteria of "checkpoint" then probably wont be updated so frequently
yes, on collision trigger for each player to any checkpoint, I am trying to update / modify values.
WIll try this one too
Hello guys, I'm going through every chat to get help because I can't get my proximity spawner to work, I tried everything and nothing works. NOw it just spawns enemies endleslly in a intervals of X seconds. Here is my code
not code advance
your yield return doesnt do anything
I know but I need help lmao
Already tried it with the canSpawn false and true
this belongs in #💻┃code-beginner
Hey guys, do someone know where I can edit the source code of the Cinemachine SetCartPosition() method from CinemachineDollyCart? Ive installed my project on a new laptop and now its accusing this method im overriding in another custom script doesnt exists anymore, ive been through this before and what i know is that ive to set virtual one class from cinemachine, but the one im accessing is locked, and I dont remember which one should i put virtual , any glue?
A package installed from a registry is immutable, which means you can’t edit it. If you want to edit a package, you can make it mutable
by copying it to your Projects folder. This package type is called an embedded package, and it overrides what’s in your package cache. Later, you can delete that embedded package’s folder from the Project folder, and the Package Manager will automatically change to the immutable, cached package.
Hey Simferoce thanks for the support! I remember I just put virtual in a class / method before so I could override it. I just dont remember which, and from what I remember it was untrackeable or ignored by the source control (Plastic), I dont believe ive made such a complex thing in the past, which I fear causing major errors on the project if I go for this path. QUestion is which class and how I did it, I honestly dont remember
Is CM 2.9.7
I don't know how you did it, I just know this is how it should be done.
You move the package, then you can simply add your virtual whereever you want.
Maybe I could delete the current package files and just copy and paste the package old files of the old project
Guess that should work too, what do you think?
I gave you the exact procedure. Follow it.
I tried this, and its worked. Super duper thanks to @upbeat path @tiny pewter @fallow echo @novel plinth
public void EquipArmor(int index)
{
if (!IsIndexValid(index)) return;
if (items[index].item is ArmorSO)
{
ArmorSO armor = items[index].item as ArmorSO;
equippedArmor = armor;
items.RemoveAt(index);
}
}```
I have two methods, EquipArmor and EquipWeapon, that pretty much do the exact thing but instead they are different types. I want to reduce the amount of code and use a generic method. How would I go about doing this?
public void Equip<T>(int index) where T : something that EquipArmor and EquipWeapon derive from
{
if (!IsIndexValid(index)) return;
T armor = items[index].item as T;
if (armor != null) {
equippedArmor = armor;
items.RemoveAt(index);
}
}
Perf, thanks!
Hi! I want to know what exceptions can appear when: var response = await CloudCodeService.Instance.CallEndpointAsync... Thank you!
The possible exceptions are listed in the docs: https://docs.unity3d.com/Packages/com.unity.services.cloudcode@2.4/api/Unity.Services.CloudCode.ICloudCodeService.html#Unity_Services_CloudCode_ICloudCodeService_CallEndpointAsync_System_String_System_Collections_Generic_Dictionary_System_String_System_Object__
if (item is WeaponSO)
{
this.item = item.Create(item as WeaponSO);
}
else if (item is ToolSO)
{
this.item = item.Create(item as ToolSO);
}
else if (item is ArmorSO)
{
this.item = item.Create(item as ArmorSO);
}
else if (item is MaterialSO)
{
this.item = item.Create(item as MaterialSO);
}```
there's gotta be a better way of doing this...
I have scriptable objects that all inherit from ItemSO, and i want to create instances of these scriptables without losing the data inside.
This is the current way I'm doing it, which works fine, but I want to get the exact type without using an ugly if statement like this
Watch this, It's applicable to what your doing:
https://youtu.be/_IqTeruf3-s?list=PLJWSdH2kAe_Ij7d7ZFR2NIW8QCJE74CyT
In this video we will be using scriptable objects to make an Inventory System for #unity3D
Source Code: https://github.com/sniffle6/Scriptable-Object-Inventory
If you like this channel, or just Unity in general, consider joining my Discord at: https://discord.gg/5yj4Ecp
● Su...
thats not really exactly what i'm getting at. I know how to make an inventory system, I want to know how to improve the code I made above with generics
i could roll with the code that works but I wanna know if there's a cleaner way of doing that exact thing which wouldn't require me to 1-1 map every single inheriting class
Yes... it says inventory system, But everything it teaches you will tell you how to avoid these if statements to do what you need to do
Oh lol I didn't see there were multiple videos in the playlist, my mistake
I'll take a look!
another option is to prevent the internals of the SOs from spilling out. The fact that a SO has to take itself casted as something else is a design smell. Why not have each SO implement a Clone() method, and then your Create just calls Clone and returns the result? Ex:
public abstract class ItemSO : ScriptableObject {
public abstract ItemSO Clone();
public ItemSO Create() => Clone();
}
public class ToolSO : ItemSO {
protected override ItemSO Clone() => Instantiate(this);
}
you can see from this that you don't really need Create after all
The issue has less to do with this piece of code in particular but more with item.Create(). Not sure why it needs an argument which you are just passing the item itself back in.
It's a symptom of a deeper problem in your item.Create() or even the whole code architecture.
If you have no way to change it, you can improve it a bit by using switch expression and pattern matching:
this.item = item switch
{
WeaponSO weapon => item.Create(weapon),
ToolSO tool => item.Create(tool),
// ...
};
But really, fixing the root of the problem is more important.
The cloning worked! It's a bit late so my code started to get very very messy... that's probably a good sign for me to go to bed. Yeah, the architecture for this inventory system as a whole is not the best, i tried to make one completely on my own to test myself without using many tutorials. I appreciate the help everyone ^^
Yeah, this is the more ideal solution such that you should know the type you're casting to even though the return itself would be that of ItemSO, though you could consider generics if you dislike the base return type, but that's more preference than actual knowing the type beforehand.
the problem with that in the above case is that the caller would need to know the return type to invoke the right generic, which is the exact problem to be solved. And if you already know the concrete type, you would just use Instantiate instead of Clone
Right, so I guess you're doing the comparison somewhere, before or after the creation, though I like to pass stuff around as the lesser derived type and just type check when I'm actually using the object.
it just becomes more of a problem when you're type checking against numerous types, but that can be solved with grouping identifiers. And, as mentioned above, you can just use limited type checking for behaviors when using the object.
Which can be further reduced with polymorphic method calls
How do I identify the main game thread via attached debugger?
Seems all these threads are sleeping.
I'm getting a full editor freeze so I thought maybe I could pause and see if I was in an infinite loop of my own creation.
It should say main thread afaik.
If it's not in the threads list, perhaps it already shut down?🤔
This doesn't look like a list of threads from VS though. Where is that screenshot from?
vscode
Okay, maybe something wrong with vscode then
Hello I'm currently making a game using Unity for a college project. I'm trying to implement a programming compiler in the game. I tried using WebView, but when I click the object again opens the UI that has the compiler, and it stops running. Any advice ?
Click what object and what is the "it" that stops running?
this is my problem.
when I click on the chest object that I assign on the webview asset. it works for the first time. but whenever I exit the web view and open the object again. it stops working. do you guys have any solution to this
You'll have to show the code
Seems like a mistake in disposing resources of something when it's closed
I have a job that takes a NativeArray<Foo>. I'd like to be able to pass in multiple chunks of Foo -- in this case, it'll be one big unchanging array, and then a smaller array whose contents are constantly changing.
NativeList<NativeArray<Foo>> is forbidden, so that's not an option.
Perhaps I can just pass a list of pointers?
Collections package has Unsafe* collections which can be put inside Native* ones.
Although, can the smaller array simply be a view? So you'd have one giant NativeArray<Foo>, the first N elements are the big unchanging array, the rest M elements are the smaller changing array and you pass that as a view to some other places that want to modify it.
That'd work here, but it'd get annoying if I wanted to include more arrays
Foo is a single "influence" that needs to be considered by an AI when deciding where to go
The problem I can immediately see is that I might wind up trying to modify these arrays while a job is trying to use the data in another thread..
So I guess I should just pass in a persistent array and a temporary array
I also might just skip using jobs entirely, since the work I'm doing is already very fast when Bursted
im working in a scriptable object right now in a EditorScript
does someone know how to trigger a event when this variable is changed?
i tried with a getset like you see but the get set cant work because i cant give it a body without serializing
this screenshot shows two completely unrelated variables
this is the correct way:
[SerializeField]
private string className;
public string ClassName {
get => className;
set {
className = value;
myEvent?.Invoke();
}
}```
Again you still have two completely unrelated variables
you should try to learn how properties work in C#
my example will work perfectly
nope
so i have a editor window right
Are you talking about triggering an event when the value is changed in the inspector??
Because that would be a totally different subject
making it here
then i want to show all the objects in my UI
like nodes
then i have a inspector like this
ok this is a totally different question
that probably belongs in #↕️┃editor-extensions
oww i thought this needs to be in coding
You have essentially two options
- implement the change detection in a custom inspector or property drawer
- detect the change in OnValidate
#↕️┃editor-extensions is for editor code
There's also plugins like https://dbrizov.github.io/na-docs/attributes/meta_attributes/on_value_changed.html
aa yeah sorry thank you very much
Hey, I'd like to optimize mesh initialization for my voxel chunks. Currently, I've got all the custom stuff I've wrote to an efficient state, but the Physics.BakeMesh function I'm using for my mesh collider is taking forever to crunch out. What I'm wondering is if there's any way I can plug my custom algorithm into the physics system where I can generate the baked collision data for the mesh myself. I'm using a voxel mesh so I believe there are a number of optimizations I can do to speed up mesh physics data baking time.
I'm not sure but I did see this snippet in the docs which might be a little helpful at least:
You can use BakeMesh with the C# job system.
Yeahh
That's what I'm currently doing, but when I generating a ton of chunks at once this bogs down the worker threads a lot
The code I've wrote takes a small fraction of the time the physics engines Bake function does, it's the bottleneck
And that's while running all baking in the background
Is there a way to add null fields on a serialized list of custom class objects from the editor
[System.Serializable]
class exampleObj { /*PublicMembers*/}
class ExampleComp : Monobehaviour
{
[Serializedfield] List<ExampleObj> ExampleListInInspector = new List<ExampleObj>();
}```
I.E. is there a way to use the editor '+' functionality without at the same time filling the new list slot with a exampleObj?
Perhaps with OnValidate if not the editor itself, or otherwise just do it in Start()
Only with the SerializeReference attribute, but that will introduce a lot more editor complexity
Maybe Im overthinking it. Making a grid system that is not mathematically coherent, so I need to specify the siblings for every hex on the grid before runtime, and my current Idea was to have every hex have a local class member for its position and then have every sibling carry a reference to that member
Really want to be able to read the references in the editor for debugging purposes, so a list of gameobjects doesnt really cut it
I guess I could have every hex have its own scriptable object and then have a list of those or something
what do you mean by "not mathematically coherent"?
There is no consistent formula to get from any set of coordinates to any bordering ser of coordinates
0,0 could border [9,5], [3,3] and 6 others, whereas some other node could border only 2 nodes
idk if im using the correct nomenclature tbh, maybe there is a math solution to this im not aware of
but I need to construct it as a 2d grid for other parts of the code that dont have to do with traversal
so, some hexes are connected to hexes that are not adjacent to them?
how large would the maps be? setting them values like that is gonna be tedious on larger maps... you may wanna do some editor thing that makes it easier
80ish nodes
okay, so not too many, I guess
they are visually adjecent, just not mathematically lol, therein lies the problem.
"read the references" you wanna read the coordinates or what?
Ideally I would be able to create N null fields for the siblings on every Gridhex script, and then drag and drop a reference to each individual siblings position member in the inspector
been playing around with serialized reference now but I cant get it to work right
I have no problem making an algorithm to do all the connecting at runtime, but I would like to be able to look at it and debugg in the inspector
kinda shaving a yak a bit here I suppose
if you can connect automatically - do that
aaand you can make a custom inspector that shows the data that you want from the references
(Sort of an editor question) I have a ConfigurableJoint on one of my gameobjects, and it's clearly affecting the gameObject, but it no longer shows as a component in the Inspector. I have no clue why I can't find it.
you can always type it in the search box and see where it went, I guess, no?
there's a search above the hierarchy, if you type the exact name of a component, it'll show you GOs that have it
In the hierarchy you can type "t:[componentName]"
apparently the t: isn't even needed these days
Oh, nice. Thanks
it highlights nothing when I type configurablejoint
and you're sure it exists?
The behavior is still applying to the object
its sliding back and forth like I created the configurablejoint to behave
are you certain you are not adding it at runtime
You can search DURING runtime. To verify
Yeah it doesn't appear in my search @ runtime and I remember making it in the editor
Just to be sure is there anyway to like search all my scripts at once?
your IDE should have a search feature
perhaps Ctrl+Shift+F and you type what you wanna search
yeah.. this might be a unity glitch idk. Might just delete and recreate the gameObject
Ah, interesting.
Okay, I was wrong.
It's not a Unity glitch, nor is anything missing
sry
and thanks for troubleshooting it helped me
a sketch of what you have in mind could help immensely
there is a great resource about hex grids: https://www.redblobgames.com/grids/hexagons/
still not sure what "mathematically incoherent" vision you have in mind
Using profile markers, how can I know the total execution time of all the hits of the same marker in a single frame?
Search by marker name and sum all the durations?
This is going to be a vague one. I'm pretty sure I read that, even if you really just want to store 3-vectors, it's smarter to use float4 everywhere when passing large native arrays to jobs.
I understand that SIMD instructions can be used to add four pairs of float4s simultaneously
But I'm trying to figure out if I should default to using float4 everywhere, or if this is just..well, a thing I think I read once (:
Hi, I would like to ask a question about advanced programming, but this is my first time on this Discord. Is this the right place ? Am I interrupting something if I ask my question now ? Thanks !
go ahead!
Cool, thanks !
So, I'm working on a turned-based game that plays on an isometric grid. Think Into the Breach to picture it !
I'm trying to structure the whole thing around a MVC framework, with commands.
What I have is basically two commands buffers : a combat buffer, that invokes commands for the model (eg. A deals damage to B), and a view buffer, that invokes the view commands.
When a combat command is invoked, the involved GameObjects will fire events that the view will listen in order to add the view commands to the buffer (*eg. MoveCommand(zombie, position) calls zombie.GridMover.MoveTo(position), that invokes OnMovedEvent?, and the view will update accordingly).
First question : is it a good decoupling strategy ?
My second question is about the view. Let's say I have a Damage command, that goes IDamager.DealDamage(IDamageable, 10). This goes to the combat buffer. When the command is invoked, an event will be fired and an animation will play. But I will need the IDamageable item to play its hit animation at the correct frame (i.e the impact). How should I do that ? I have a lot of different monsters, some deal poison, some deal burn damage, some deal damage to different positions at different stages of the animation. How should I keep all that info, while maintaining that decoupled model and view ?
Hope I'm clear ! I tried to summarize, but I can give much more info if needed ! Thanks a lot 🐸
it depends how much control you need, you could add the timing info to the commands somewhere, a bit like animation events where you add frame markers for different events? but you could also maybe just make your command invoke method async/return a coroutine so you can just let each command do what it likes over as many frames as needed and wait until it's done
Thanks for your answer !
The second option is what I was doing previously. Each command had a bool m_IsDone; and was updated until this bool was set to true. The thing is that this would kill the MVC framework, as the Model would be waiting for the View at some point.
I think this is the same problem with option 1 : the Model would be aware of the view, and dictating View logic, where it should not be worried about it.
what's the controller part of your framework? it seems like that would be a good place to handle time, checking if the animation part was done and telling the model to continue with the next step of the current command
Reading my message again, I think I should mention that my units views have an AnimationController, with a Queue<Action>. At the moment, I directly add the callbacks to that queue, in the order in which they happen in the animation. Then, I have an animation event that says m_Queue.Dequeue().Invoke();. This works, but again this is the type of framework that I want to get rid of because it mixes logic and view.
The controller is the unit's brain (a class that dictates the unit's strategy).
But I don't think the controller would be the issue here. The logic commands execute their logic and are discarded, and the view commands yield until their condition is met. For animations, they yield for the length of the animation clip for example.
I think my issue is really about how to handle the animation events : should the target be aware of the attacker, or the other way around ? for example, if multiple cells are attacked in a single animation, how should I make sure that the correct targets update their view at the correct frame, etc
I'm a fan of the action/viewer system outlined in the "Collectible Card Game" Tutorial on this page http://theliquidfire.com/projects/
Broadly, I'd say that having each unit manage itself is a mistake and you need something which can coordinate visuals between different units in an action-aware way. None of the units should be aware of each other or even what is happening. They just get told to do stuff by a Viewer which is the thing that's aware of whatever in the scene is needed to make that happen visually.
That is very interesting, thanks. I never thought of this that way.
Just to make sure : you mean each unit managing its view right, not its behaviour ?
I mean that a 'view' should be an abstraction on a higher level than a 'unit' and should be able to manage multiple units, coordinating them to accomplish whatever series of 'actions' (or commands, whatever) is being executed
Ah, ok !
I understand the principle, but I'm not sure about how this would look like in practice. Would it be like a manager class, that apply the translations to the views ? In the case of attacks, would it be a sort of middle man that serves as a channel between the unit and its target(s) ?
sounds about right
you can read the tutorial and everything is explained in detail
I'll dive into that, thanks !
i don't know that you'll want to do exactly what he did (i didn't) but there are solutions to these problems in there which you can run with
ok I need serious advice about a hacky idea. So we have a certain prefab that is referenced in a whole bunch of scene. I need to quickly replace that prefab with another prefab. Can I like manually swap their GUIDS and will that work ?
Yes
I tried replacing the guid in the scene file directly and this results in a missing obj
ah I need to replace the file id too
Hey guys i 'll try to explain briefly, i have a radial circle that gets fillAmount from 1 to 0, meaning your character/player attacks, but i want enemies to maybe Freeze / CC so it would make the the radial fill to stop at that specific moment, and with the Math.Lerp i shouldn't be doing that. Any idea for that?
sounds like not code advance, whatever fill you can stop the process manually, you dont need to increment the t and run one more timer, but i may misunderstand your problem
So I am setting terrainData.SetAlphamaps, but right now I am getting the float values from a compute shader in a array,
// in a CommandBuffer RequestAsyncReadback() callback.
NativeArray<float> data = request.GetData<float>();
int index = 0;
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
for (int d = 0; d < depth; d++)
{
splatMap[x, y, d] = data[index++];
}
}
}
terrainData.SetAlphamaps(0, 0, splatMap);
The issue is that this is really slow. Any ideas for making this faster? Do it in a compute shader as well somehow? In a job? Some sort of memory copying...?
Slow as in it takes a long time for the async request to have data ready, or do you mean a freeze on the main thread?
As in actually executing that code, not that readback time.
That is for the heightmap only (as far as I know), and is terrain > texture
Actual profiled result so you can see what I mean. It is just a lot of get_item() (understandably so)
This method is designed to work with both the alphamap and holes texture.
https://github.com/Unity-Technologies/UnityCsReference/blob/79868d37d65d6efb5196aaf002f97a6f87b22f97/Modules/Terrain/Public/TerrainData.GPUCopy.cs#L59
Hmm, interesting, thanks. Not quite sure how to transform the third dimension of the splatmap array to the render texture... 🤔
oh
I'm pretty sure the splatmaps on the GPU are just 4 channel textures where R = weight of first layer, G = weight of second layer, B = weight of third layer, A = weight of fourth layer.
And then you have additional splatmaps for more layers than 4.
Ahh the third dimension of the 3d array is the layer, and I just saw the Copy method takes a textureIndex which I assume is that
So would call this method once for each alphamap layer
Thanks, this looks like what I was wanting exactly! 😄
ymmv, but a lot of this overhead is likely to be just the bounds checks, i can't remember if you can turn those off in editor or only in burst-compiled code
Ahh, was wondering what it was.
on a previous project, i saw a huge speed up for an editor tool which needed to do something like this by getting the unsafe ptr to the native array's data and using that instead
Huh, interesting to note. I will keep that in the back of my mind for future projects. Thanks.
How do you make a game object go towards the position go to a raycast hit.point while also taking into consideration a walking animation
!cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
Thanks
Hi, I have a shader that changes the screen. I want to store those changes and apply them back to the main texture. I'm using a render texture and a temporary render texture to store the changes, then applying them back to that main texture.
public class ShaderTextureUpdater : MonoBehaviour
{
public Material material;
public RenderTexture mainRenderTexture;
public RenderTexture tempRenderTexture;
public string mainTextureProperty = "_MainTex";
void Start()
{
mainRenderTexture.filterMode = FilterMode.Bilinear;
mainRenderTexture.wrapMode = TextureWrapMode.Clamp;
tempRenderTexture.filterMode = FilterMode.Bilinear;
tempRenderTexture.wrapMode = TextureWrapMode.Clamp;
}
void Update()
{
Graphics.Blit(mainRenderTexture, tempRenderTexture, material);
Graphics.Blit(tempRenderTexture, mainRenderTexture);
material.SetTexture(mainTextureProperty, mainRenderTexture);
}
}
This doesn't work for some reason, anybody got any idea why this might be?
Why i did it for myself not for you lol 😂
Oh lol I thought you did it to help me with my problem and it will so thank anyways lmao
How could a link to the c# server possibly help you with your issue?
But also, that kinda belongs in #💻┃code-beginner or #archived-code-general
Plus explain a bit more about what you have now and why it isn't working
It's a coding issue
Ah thanks
Yes, we have code channels...
I'm new 😅
Howdy folks. I am trying to analyze my project with the Standalone Debugger and Memory Profiler. To obtain an accurate picture, I've built and am analyzing the development build of the project itself, not the Editor. However, even for a blank scene in a 3D project I find my GPU Usage is >25% on an RTX 4080. I'd like to minimize any impact that has, but those tools appear to need the Editor open to function. What tricks or techniques have folks used to get more accurate results here? Thanks!
GPU utilization as a standalone datapoint is pretty much an irrelevant statistic. Unless you are actively limiting your framerate somehow, your computer is going to churn out as many frames as it possibly can, up to the limits of your hardware
I'm not using it as a standalone datapoint.
You could have an empty scene with 3000FPS using 100% hardware
Well for one I am using Vsync to limit the impact there.
Ok that's an important datapoint. What's the framerate
60fps.
The overhead from the Editor just seems statistically significant and I'd like to discount it when comparing architectural approaches for underlying game mechanics.
You can use the frame debugger if you want to see how the scene rendering is being broken down: https://docs.unity3d.com/Manual/frame-debugger-window.html
Does that tool work standalone?
I've used it a bunch, just haven't tried outside the editor
:nod:
yeah I mean, you're basically always going to deal with heisenberg's uncertainty principle to some degree when doing profiling
in order to profile it, you will use resources for the profiler
I'm not sure there's a satisfying way around it
Understood. I intentionally exacerbate the system being profiled to amplify the impact of my changes. But was surprised when moving from 2D to 3D at the magnitude of the editor impact.
have you tried closing the scene and game view windows?
That sounds like a cue for me to make an asset, lol
I've loaded up just a blank scene. I don't see a way to close a scene entirely and operate without one? Am I missing a close button somewhere?
well I mean you can close the scene window and game window
I don't think you can not have a scene loaded
I'll see if that improves the results a bit. I also am forward thinking a bit to when I'm developing on the go with a laptop that may not have sufficient RAM to isolate the editor and standalone runtime for profiling.
can somone help me figure out these errors?? the pow and fmod errors specifically
... the "i" error is fixed
These are beginner compile errors.
#💻┃code-beginner - provide your code there NOT in screenshots and the full error messages
Also this doesn't even look like Unity code, it looks like C or C++.
Get the difference between the raycast and the gameobject as a Vector3, normalize this and this is basically the base offset the gameobject should move towards
After that move it however you want it
Also looks like my chat way scrolled way up so I just answered a question that is 17 hours old
Is there a way to turn an existing Prefab (that already is the parent to multiple Prefab Variants) into a variant of another Prefab? I just decided to make a more abstract prefab - but I find no way to make the existing root prefab a variant of that newly created Prefab
please post !code correctly
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
im in the wrong channel, deleted the message. going to code beginner lol
so the try again button calls RestartGame?
yup!
Put some debugs in there to verify this
when the tryAgainButton appears through the OpenEndScreen it works fine, when it opens through OpenWinScreen it just restarts the game sucessfully but time remains 0
because when you set timescale back to 1 your Update starts running again and so OpenWinScene is called again?
well the score though goes to 0 when the game restarts so i dont see why it would do that
but LoadScene takes time, it is not immediate
ill add a delay to test out
set scorevalue to 0 in RestartGame
Hey guys, I have a shader that has the results of the effect on a render texture. It changes a part of the screen while the player overlaps it. What I want it to keep those changes so that I can generate a sort of trail everywhere the player passes. Is there a way to do that? I'm thinking : store the changes in a temp render texture and write that back to the main texture that is being displayed.
I tried it and it's not working. Any other solutions you can think of?
you should be able to just use the texture once you write to it
or like do a copy if you're modifying it constantly
I tried doing that but it doesn't keep the changes
Is there something that I need to do in particular with the render textures besides setting the right dimensions and enabling random write?
I'm trying to reproduce this, essentially : https://www.youtube.com/watch?v=TdTMeNXCnTs @regal lava
A short video demonstrating an interesting persistence of vision (POV) effect where objects being animated on a random field of black and white pixels are only visible when they're moving.
The graphics were generated by a simple Win32/C++ app that you can find at https://github.com/ChrisBLong/POV
EDIT:
Some related stuff that has come up in th...
I'm thinking I have two options : writing directly into the texture via the shader (not sure if that's possible). Or do a main tex to temp, temp to main tex copy?
This may sound like a dumb question, but is there a way to load two instances of the same assembly/dll in Unity Editor (don't need in a build)? Curiousity purposes only currently.
Context : There's a assembly with some code in it in the UnityEditor project, and I'd like to create another instances of that assembly....to create a separate sandboxes if you will, with shared UnityEditor sandbox, if that makes sense. The goal is to just not share statics defined in this secondary sandboxe with the main "instance" created by the unity app domain.
I tried creating two separate app domains, and load dlls in them, but they seem to be the same one as statics were shared across them. Ig, I have a lot of questions about Unity<>AppDomains.
One option I can think of is to use Mono.Cecil (accessible as the Unity package: com.unity.nuget.mono-cecil) to create a duplicate of the assembly in memory with a different name, so the runtime thinks it's a totally different assembly which just happens to have all the same type definitions as the original.
I'm not sure what exactly needs to be changed for the runtime to recognize it as a different assembly. It might be a GUID, the name, version or some combination of all of them.
I haven't used Mono.Cecil to do this, but it should be fairly trivial. Just load the .dll with Mono.Cecil (this is basically just opening it so it can be inspected like Reflection and edited), modify the assembly name, then write it back out to a .dll file or just a byte array and load it into the runtime like normal.
I did try searching the route of cecil, but couldn't connect the dots. This seemed very relevant, <https://stackoverflow.com/questions/62203795/how-can-i-properly-rename-assemblies-after-theyre-been-compiled
Theoretically, I have couple of other questions with this still. I assume Unity Monobehaviours will not function in this approach? i.e. Start/Update. And, would, the Editor actually be able to consider the type from this new dll? Because AddComponent<T> would just provide info on type/assembly, and then that begs the question whether Unity would search this newly loaded one dll for the type 
I'll try this out, thanks!
I would think as long as you don't have any other assemblies that are referencing the sandboxed/duplicated assemblies, there shouldn't be any problems. Unity shouldn't treat the duplicated assembly any differently from a normal one.
If it normally works to load a .dll at runtime with Assembly.Load or AppDomain and use MonoBehaviours from it, it should work with an assembly edited with Mono.Cecil.
Okay, last question, this would be loaded into the current AppDoman right? i.e. using AppDomain.CurrentDomain.Load(). And the reason I asked the latter question, is because I would be importing it into Unity Play mode, and not as an asset itself
That stackoverflow answer is focusing on fixing assemblies that are referencing the assembly you just renamed. But it links to another question that deals with just renaming an assembly:
https://stackoverflow.com/questions/4683913/renaming-icsharpcode-sharpziplib-dll/21753873#21753873
But it uses ildasm.exe, which I don't think is guaranteed to be available on the user's machine.
I would just use Assembly.Load, but that probably does the same thing as AppDomain.CurrentDomain.Load
Read that one too 😄 , was just too lazy to bother trying it because I wanted C# itself
Got it, thanks!
Hey all... I'm having an issue where BuildNavMesh() is interrupting running coroutines. EX: as soon as the buildNavMesh() function is called, if an existing coroutine is running, it stops at the next yield, even if its just a WaitForEndOfFrame(). I've been doing several tests and have narrowed it down to that function. Has anyone encountered this type of issue?
I've also tried using the AsyncOperation UpdateNavMesh() with all relevant things manually constructed and I get the same result
that will happen if the GameObject running the coroutine is destroyed or deactivated
it is not
the object enabled/active state is never changed during runtime
in fact, the coroutine that is being interrupted is on the same object that is running the BuildNavMesh() function
https://codefile.io/f/vyYLg8ZcsH here is the relevant code. In the PlayTileReveal coroutine, if NavMeshBuild() is called at any poitn during execution, it never reaches the "print('tr5')" line
The only 'solution' i've found was changing the PlayTileReveal function to an async, but since my game changes timescale with playe rinput, thats a no go
Any exceptions being thrown
Where does this code run? What runs this coroutine?
Both of these functions are on my WorldController object, there's a MapController object that initiates the code with the following.
var tilesBeingRevealed = selectedTileUnlocks.ToList();
rs.uic.ToggleMapForTilePlacement();
foreach(var tilePos in tilesBeingRevealed){
// yield return new WaitUntil(() => !rs.wc.revealingTile);
// yield return new WaitUntil(() => !rs.wc.revealingTile);
// Debug.Log(tilesBeingRevealed.Count);
Debug.Log(tilePos);
var exisitingTile = rs.wc.activeTiles.Find(x => x != null && x.tilePos == tilePos);
Debug.Log("here");
if(!exisitingTile){
StartCoroutine(rs.wc.BuildMapTile(tilePos.x, tilePos.y));
Debug.Log("here1");
}
Debug.Log("here2");
exisitingTile = rs.wc.activeTiles.Find(x => x.tilePos == tilePos);
Debug.Log(exisitingTile);
while(exisitingTile == null){
Debug.Log("STUCK");
yield return new WaitForSeconds(0.1f);
}
yield return StartCoroutine(rs.wc.PlayTileReveal(tilePos));
// yield return new WaitForEndOfFrame();
// yield return new WaitUntil(() => !rs.wc.revealingTile);
// while(rs.wc.updatingNavMesh && rs.wc.revealingTile){
// // Debug.Log("--Waiting--");
// // Debug.Log(rs.wc.updatingNavMesh);
// // Debug.Log(rs.wc.revealingTile);
// yield return new WaitForSeconds(1f);
// }
Debug.Log("DONE");
var marker = PlaceMapMarker(unexploredImage, tilePos);
marker.transform.SetParent(unexploredTileHolder.transform);
marker.name = tilePos.ToString();
rs.gc.sleepSunderLevel += 1;
}
}```
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
use a paste site for large blocks like yours
Sure thing
i've updated the codefile https://codefile.io/f/vyYLg8ZcsH
Note that:
yield return StartCoroutine(rs.wc.PlayTileReveal(tilePos)); ```
It appears like you are calling StartCoroutine on potentially a different object than the one that owns the coroutine code. The monobehaviour/GO that StartCoroutine is called on is the one we care about. If THAT is being deactivated or destroyed, the coroutine will end
that also does not change
both the world controller and map controller never change states
that's what's so confusing. I've been googling and testing for... 13 hours now 😦
and I've done nuemrous tests and narrowed down specifically to the BuildNavMesh() function
i was going to try just to move that completely to a seperate thread, but BuildNavMesh is locked to the main thread 😦
Are you modifying time scale anywhere?
I am, but even if i dont modifiy timescale in the tests, it still fails
Also yes are you calling anything not on the main thread
async has nothing to do with multithreading
multithreading would be using System.Threading.Thread or Task.Run
Still no, sorry for misunderstanding
or potentially UniTask
why comment out updatingNavMesh = false; ?
I -did- create a sperate task for the PlayRevealTile function, which solved it, but again, the player can change timescale so that was a whole issue
@upbeat path It was a gate I was using to wait until it finished the coroutine to start the next update of the navmesh, but even when everything was gated where it wouldn't update until the PlayRevealTile finished, and it wouldn't PlayRevealTile until the navmesh was updated, it still failed
i've iterated over these three functions so many times my eyes are bleeding lol
I just wish I could see the BuildNavMesh function to get a better idea of what it's doing, but of course its dll'ed
maybe set up a quick fresh project with just these isolated pieces as a sanity check? if you have nothing but a nav mesh and some simple coroutine, is the issue still happening?
cause it's possible that under the hood the object is being swapped out or coroutines stopped but as you say, we can't really look at that, but you can try to isolate as many variables as possible
I can do that. My first assumption was there was some weird coroutine memory interference since the UpateTiles function was originally a coroutine with a whileloop, but even moving it to a base function that runs out of lateupdate gives the same result
I guess ill do that quick project and see
Quick tests seem to be fine... hmm
Yeah tests are fine. I guess there's just something more complex I"m not seeing 😦
results like that that always generate such mixed feelings: oh, my component works, that's great! Now I have no idea where to look for this bug next, that sucks.
@abstract folio exactly... like it works fine if the player doesn't move and cause the navmesh to update, but then disaster. sigh Oh well, back to banging my head against my desk for another 13 hours lol
you can always start adding 'real' pieces into that test project until it breaks but yeah, it sounds like there must be something outside of what you've been considering thus far that's interfering which is at least a place to start
Yeah... the other two pieces that I didn't add to the test are obstacles that carve the navmesh on tile instantiation, and the player moving between tiles. But the only thing the player does in relation to the tiles is report it's current position to the world controller. I'm sure i'll find it eventually...right?... RIGHT? slightly insane laughter
If anyone has a couple minutes and wouldn't mind getting eyes on it live I would be extremely grateful lol
Nevermind, I finally figured it out. Sometimes I do something so dumb haha...
Is it possible to extrude the NavMesh to make geometry? If not, it is possible to export the NavMesh as geo so I could extrude it in another program?
hmm, you could use https://docs.unity3d.com/ScriptReference/AI.NavMesh.CalculateTriangulation.html to build a mesh and work from there
so guys
im making a rhythm game
but im stuck on how to make a system where the notes go down and you can hit them
thats more of a #💻┃code-beginner question, or #archived-code-advanced at best
thats where we are
sry meant #archived-code-general hahahahah
but to answer question, register key press and if object, the note has Y value between lets say -12 and -13 it is correct otherwise player fails, simple implementation
true
but im also stuck on how to add something like an editor
something that'll cut down on the amount of hours needed to place every note
and that needs to work with the note system
so just
complicated
i guess what im asking is how to make an editor for my rhythm game
Why don't you get started and ask more precise questions as they come?
I have a prefab in my game that renders cutscenes from json based data.. I have another unity project that's the admin tool for editing cutscenes, which generates the json data. Obviously it would be great to have the admin tool be able to render the cutscenes in a manner identical to the client, but I haven't thought of a good way to be able to "share" a prefab and scripts between a project like this. Scripts are no problem, but prefabs and scriptable objects are making this a little hard.. and it gets worse if I want to make a change to any of that code, because now I have to do it in two projects.
Any ideas?
I mean, I suppose I could generate 100% of the prefab manually (through scripting) but that feels tedious? Like instantiate the game objects, size them all, add the components they need, cross reference the fields, etc..
Hi, I don't want you to see my character while others see it. I did it a bit by myself and a bit from a guide and I got an errors:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class gamemeneger : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (gracz == gracz.mojgracz)
{
gracz.gameObject.transform.Find("Man_Full").gameObject.SetActive(false);
}
else
{
gracz.gameObject.transform.Find("Man_Full").GetComponent<Renderer>();
}
if (gracz.team == Team.BLUE)
{
gracz.gameObject.transform.Find("Man_Full/Man_Half_Body_Mesh").GetComponent<MeshRenderer>().material.color = Color.blue;
}
else
{
gracz.gameObject.transform.Find("Man_Full/Man_Half_Body_Mesh").GetComponent<MeshRenderer>().material.color = Color.red;
}
}
public void SpawnGracza()
{
GameObject mojgracz = PhotonNetwork.Instantiate("Gracz", new Vector3(58.29f, 0f, -837.0149f), Quaternion.identity, 0);
mojgracz.GetComponent<FirstPersonMovement>().enabled = true;
mojgracz.GetComponent<Jump>().enabled = true;
mojgracz.GetComponent<Crouch>().enabled = true;
mojgracz.transform.Find("First Person Camera").gameObject.SetActive(true);
}
}```
secound script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class gracz : MonoBehaviour
{
public static gracz mojgracz;
public string nick = "";
public PhotonPlayer pp;
public Team team;
public static List<gracz> gracze = new List<gracz>();
public static void debugujliste()
{
string dbgS = "debugujliste" + gracze.Count;
int i = 0;
foreach (var gracz in gracze)
{
dbgS += "id:" + i+ "nick:" + gracz.nick + "team:" + gracz.team;
i++;
}
Debug.Log(dbgS);
}
private void Update()
{
if(Input.GetKeyDown(KeyCode.L))
{
debugujliste();
}
}
public static gracz ZnajdzGracza(PhotonPlayer pp)
{
for(int i =0; i < gracze.Count; i++)
{
if (gracze[i].pp == pp)
return gracze[i];
}
return null;
}
}
public enum Team { RED, BLUE}```
If someone helps me, I will love him
❤️
Maybe #archived-networking
my walk system is working wonky, instead of not moving forward when I collide with something like a tree if I just keep trying to walk it phases through
Is this an issue with code or colliders?
Could be both. Though, likely you're not moving the object in a physics compatible way.
Btw, this kind of questions are definitely not advanced and fit more in #💻┃code-beginner
I wasn't sure if it was advanced or not, thanks
When you really deal with advanced questions, you will know it. If not sure, start in code beginner and people will redirect you if it seems like the question is too advanced.
k, thx
This is an actual long shot, but when loading a scene, is it possible somehow to change the types referenced in the objects in the scene being loaded to another set of types?
This is still curiosity purposes, but, i have a duplicate dll loaded at runtime, via Assembly.Load, and the scripts sitting inside it, I would Unity to load those types rather the ones sitting in the editor scene originally. Any form of ugly code is acceptable 😄 This is supposed to be editor only and just a testing project for now.
So, I know, in prefabs/scenes, fileIDs and GUIDs for normal scripts, its the guid of the text asset of the script and fileID is constant 1150000. When scripts are used out of dlls, the GUID is the GUID of the dll and the fileID is computed using an algo.
But I don't have the GUID of the dll loaded in the runtime so I can't change the text file itself. I could import the dll in edit time, but its just not something I want to do, because then I'd have to keep a copy of all assets also inside the project.
All I want in essence, is to either
- Load assets from outside the Assets/Packages Folder in UnityEditor. [All assets].
OR - Be able to change scripts before Awake on scene loads and instantiations
https://docs.unity3d.com/ScriptReference/RuntimeInitializeLoadType.html
These look any helpful?
Yeah, it does, I can use BeforeSceneLoad and change references in that scene somehow too. But, I'm still unsure about prefabs or SOs
And this is still only for the first scene, not all of them
Ah, I'm not too sure inbetween scenes besides doing the logic in a manager before loading the next scene.
i need some help, i'm trying to make an hashing function for procedural seeded generation, but unfortunately has a lot of patterns. does anyone have good resources for removing patterns from hashing as much as possible?
Maybe, but probably not, you might be able to get the MonoScript instance of the duplicated class types and replace the reference in the m_Script serialized property of each MonoBehaviour component using SerializedProperty. But I don't know much about how MonoBehaviours from compiled dlls work differently from normal script assets. They might just not have any MonoScript asset tied to them.
still haven't been able to fix the patterns, but i found this hashing pattern that looks mesmerizing
it really does
Are there any things i should consider when starting a coroutine on a mono? Currently i have a FSM with each state being aware of the context which is a monobehaviour. I want to start an IENumerator, and do this using context.startcoroutine from the non monobehaviour class "DashState". This is not working properly and i get stuck in the dash state sometimes.
pretty vague description. You should be aware of how coroutines work and how their lifecycle is tied to GameObjects I guess. If you have a specific code problem you should share the code and explain how it's going wrong and what debugging steps you've already taken.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hey guys im making changes to a package script but idk if the editor or unity, keeps rolling ng back my changes to the original package script. ex. im editing a method on a package script, after I save the Unity backs the method to before my changes (original form the package) how do I disable or solve it?
you can't modify packages unless you turn them into local packages
Read the part about "Copying a Unity package from the cache"
Should I keep both packages on the cache and on the Packages? How does the project will know which one is correct, should I make it inherit specifically to the modified copped?
Bumping this. If anyone's familiar with render textures and all that, let me know 🙂 I already have the shaader that does the effect, but it only applies it over the area the player is. I can't manage to make it "stay" on the render texture.
If you havent found your solution yet, what hashing function are you using?
There are many examples online for proper cryptographic hashing functions, in which you should have a LARGE output space
Is there a way to use a toggle-able/boolean option in the Editor Toolbar section?
I'd like to add persistant options to those I already have (see image) such as "Always Reset Level" etc.,
I don't know if it's possible in this menu, but you could create and attach some toggleable buttons in the toolbar below. Also i don't have a tutorial at hand for this topic atm, but here's an implementation of a toggleable button for steam integration, which you could adapt pretty easily for sure. https://github.com/BoundfoxStudios/fairy-tale-defender/blob/dbc85ba87a2c1c867e0d8793261f3510c878533e/FairyTaleDefender/Assets/_Game/Scripts/Editor/Menus/SteamIntegrationButton.cs
assuming you want a toggle check next to an item in that menu, you can use Menu.SetChecked + an editor pref, ex:
https://hatebin.com/oqzcctyllj
using random stuff finally i have somewhat decent distribution, thanks for the article @cursive horizon
What’s your goal?
seeded deterministic parallelizable map generation
Any crypto hash should give you basically Gaussian noise
I mean what kind of noise function do you need?
now i'm using noise just for simple visual, i would need many different layered functions and post chunk generation processing
im interested in crypto hash tho. i'll try some
Is there some good way in Unity to perform data binding between regular C# objects and properties?
For example if I have a child game object with some state (changable in editor as well) and I want to react to these changes reactively in parent
I would like to have more declarative approach instead of "isChanged" checks etc
I'm sure there are some libraries out there
generally I would advise against it in a unity context because:
- unlike in an event-based app, unity is going to render new frames all the time anyway and most of that cost is not in updating the properties of the objects
- when performance does matter, it really matters, so it's nice to have explicit data flow so that it's simple to optimize the places you need to
and you want to be very careful with data flowing 'up', so when that needs to happen, it's good to make it explicit
You’d probably be interested in UniRx, System.Reactive or the lightweight version of that in UniTask. Declarative design generally has not produced useful results in gamedev outside tool development (because it is hard to optimize and often a memory hog) so most such projects have been abandoned.
I'm trying to do data down, events up approach, but damn, it is hard, especially for editor tools when I need to build intermediate state based on some game object tree hierarchy and all nested component properties
fortunately for me, the majority of the usecases for now would be in the editor code
I’d expect databinding to only offer a ROI in large enterprise’ish teams.
You can build a primitive reactivity system in less than 100 LoC and transform the way you write a lot of code, in most cases cleaner especially for managing a complex application state.
It's problematic to use in editor because reactivity systems all rely on setters being triggered when you change things so it can notify subscribers, and Unity serialization does not work on properties but only fields, so you need to do extra to fire them.
I’ve heard most people end up with code that nobody in the team understands anymore. YMMV
Partly, depends on how far your reactivity system goes.
takes some effort to train the average developer to think reactively
Rx in particular is very far into that end of the spectrum with a high learning curve.
personally my forays into it ended up quite convoluted
But a simple reactivity system's learning curve is relatively low. The primitive is really just a simplified box with a property setter which fires a NotifySubscribers() method.
for me it's conceptually cleaner, because you basically have a bunch of immutable data and the data flow is almost always "downstream"
it's far easier to reason in "if X is Y, then Z is W" than a seqence of interlocking steps from possibly multiple methods, paired with unity lifecycle events
idk, clean is a concept that does die rather quickly in most projects
and Rx is weird when just one guy does it
Yeah, but not all reactivity systems are like Rx, Rx even by reactivity system standards is very complicated.
imo Rx is too generic/powerful
I like a system that coaches the team into doing the right thing and encourages them to be creative in what they build and not in how they work around stuff that puts boundaries on what they should do.
Sure, Rx is way too high of a buy in cost if your team doesn't already know it. My point is that not all reactivity systems are like that, simple reactivity systems can be written in trivial lines of code and trained to use effectively in very small amount of time.
Whether that provides enough benefit, is a different question though. Some projects simply don't have complex states that demand such a solution, and writing good old procedural code is good enough.
Do you have an example for a complex state system where you really saw it pay off?
Well, a complex system is hard to explain in a few words, but I can give a simple example written in procedural code and highlight some of the problems, and then show the same code written with a really primitive reactivity system to show you how those problems get addressed.
I don’t mean to explain one, just name one
It applies to anything really, not just one particular type of system.
I really wanted to data-bind UI stuff... and the main reason why I haven't investigated it further is because the new UI system is just around the corner... and has been for the past 5 years or so
reactivity systems are just a very easy way to connect code while satisfying the open closed principle, imo
you can make better reactivity systems, but a mediocre reactivity system is still vastly superior to no reactivity system
(Got interrupted in the middle of writing it)
Let's take a very simple example: you need to write a multiplication calculator that when given lhs and rhs, multiplies them together and shows the equation on screen. The equation should update automatically whenever the equation changes.
You might have some code like this, first have some fields that store the values:
int _lhs;
int _rhs;
Have a method that will update the equation:
void UpdateEquation()
{
_equation.text = $"{lhs} * {rhs} = {lhs * rhs}";
}
Whenever anywhere that changes either lhs or rhs, remember to call UpdateEquation. For example in some event handler:
void OnUpdateLhs(int value)
{
_lhs = value;
UpdateEquation();
}
void OnResetCalculator()
{
_lhs = 0;
_rhs = 0;
UpdateEquation();
}
// etc
Notice some issues with this approach:
- You must be aware that
UpdateEquationimplicitly depends on_lhsand_rhs. There's no way for you to know that it does, unless you look into the implementation. - With that awareness, whenever you change
_lhsand_rhsyou must remember to callUpdateEquationmanually. If you forget, that's potentially a bug. - If you refactor and change
UpdateEquation's implementation so that its dependencies change, you need to now find reference of all usages ofUpdateEquationto remove it being called in places where old dependencies being changed should no longer trigger an update, and find all usages of new dependencies getting changed and insert calling it. If you forget, that's potentially a bug.
Even in such a trivial system, where there are only two states and they are both owned by the calculator itself, you can still see problems brewing. When you have a complicated application with lots of interconnected states owned by different parts of the app, it quickly gets out of hand.
You might say, well this is a simple problem to solve, just make lhs and rhs a property with setter triggering the update:
int _lhs;
int Lhs
{
get => _lhs;
set
{
_lhs = value;
UpdateEquation();
}
}
// same for rhs
And you would be right, that solves the issue nicely. If you want to expose it, you can simply make a void SubscribeToLhsChange(Action callback) method (and also one for rhs) for others to hook into.
A very primitive reactivity system is no different than this, it merely takes the exact same idea but goes half a step further: instead of having a Lhs property and an accompanying SubscribeToLhsChange method, it's a separate interface:
interface IDep
{
void Subscribe(Action callback);
}
interface IDep<T> : IDep
{
T Value { get; }
}
And an implementation of it could be called a Signal<T> with a public API surface of:
class Signal<T> : IDep<T>
{
public T Value { get; set; }
public void Subscribe(Action callback);
}
The implementation of Signal<T> is so simple to writethat it can be done in a few lines of code. Some reactivity systems call it "signals," some call it "observables," and lots of different other names, but fundamentally it's just a box holding a value and notifies subscribers when the value changes.
Now you might be thinking, what does this layer of abstraction do? It seems useless, I can just write the good old property + subscribe method than using this abstraction which seemingly only saves a few lines of code.
By having the signals in a box rather than a loosely connected property + method, it allows you to pass the boxes around and operate on them.
For example, a simple Computed method can be made:
IDep<T> Computed<T>(Func<T> getter, params Dep[] dependencies)
{
var computed = new Signal<T>(getter());
foreach (var dependency in dependencies)
{
dependency.Subscribe(() => computed.Value = getter());
}
return computed;
}
This simple method allows you to derive new signals out of existing signals:
var equation = Computed(() => $"{lhs} * {rhs} = {lhs * rhs}", lhs, rhs);
This means the signal providers no longer need to care about what signal consumers want, as consumers are free to combine and create their own signals out of the ones you've provided, with a concise and simple syntax.
Take a simple example: a player can have a list of buffs, each buff can have some effects. One effect might be making player invincible and undead until the buff wears off. How do you calculate the "is alive" state of the player?
Without a reactivity system, it's a tricky and error prone code to write, as when buff with the invincible effect expires you can't just simply set players to no longer be invincible, there might still be other buffs having the effect. When you clear a player's buffs, you also need to remember to check things (similar to the issues of the calculator example prior)
Using a reactivity system like that, it's trivial to express:
var invincibleExpireTime = Computed(
() => /* loop over the buffs and find the max expire time */,
player.Buffs
);
var isAlive = Computed(
() => player.Hp > 0 || invincibleExpireTime > Game.Time,
player.Hp,
invincibleExpireTime,
Game.Time
);
And that's it, the logic is crystal clear: player is alive if hp is > 0 or is currently invincible, and will also be correctly updated whenever those change without you having to worry about "aha, I need to recalculate when I clear the buffs" etc.
Obviously this is an extremely primitive reactivity system that is merely half a step of abstraction above the basic subscriber pattern, you can go way further than this. For example automatically tracking dependencies so you no longer need to write Computed(() => a + b, a, b) but simply Computed(() => a + b), and Rx takes the abstraction very very far and results in a beast of a way to express your logic.
But yeah, a reactivity system does not need to go so far into the abstraction like Rx to provide lots of utility, and it's extremely helpful when you deal with managing lots of interconnected states.
Hey dudes, I want to use raycast but in the projected camera. I want a method first to convert a cursor to world space point and second, a method to raycast
It sounds like you have exactly what you need to google there; you've identified the elements.
is there any way to make spline mesh work in runtime like I want road laying mechanic using splines.
Sure. You can work with splines at runtime and generate meshes from them.
I don't know how to do that and I am unable to find any tutorial for that
Well, since you're asking in this channel, you should be able to read and understand docs.
https://docs.unity3d.com/Packages/com.unity.splines@2.5/api/index.html
You probably want to convert the cursor position to a ray, not a world space point. Look up ScreenPointToRay
Bumping this in case anyone can help :
Hi guys, I'm trying to achieve this effect : https://www.youtube.com/watch?v=TdTMeNXCnTs
So far I have :
- A shader that XORs a render texture when the player overlaps on it
- I'm rendering the final result on that render texture and showing it to the player
However, right now it only shows the area the player is overlapping on as changed, when what I want is for every area the player visits to get xor'd.
Any ideas on how to achieve this?
A short video demonstrating an interesting persistence of vision (POV) effect where objects being animated on a random field of black and white pixels are only visible when they're moving.
The graphics were generated by a simple Win32/C++ app that you can find at https://github.com/ChrisBLong/POV
EDIT:
Some related stuff that has come up in th...
However, right now it only shows the area the player is overlapping on as changed, when what I want is for every area the player visits to get xor'd.
not really clear what you mean, but you'll want to reuse the output texture as input, it will naturally "save" its history
showing the code and/or a video of what is happening might help
I have a question, friends. What systems do you generally use for projects? For example, systems for saving, inventory, skills—what is globally or critically important for almost all projects and worth building a more quality template for?
Service Locator
I guess it depends on the games you're making. I'd say don't try to build extra smart systems, until you need extra smart systems for something. 🤷♂️ Over time you'll get some stable/reusable systems.
I've a bunch of templated management systems for stuff like object pooling, particle systems, locators for my singletons de-coupled objects that would otherwise be singletons
save system stuff included because that's usually reusable
public class ShaderTextureUpdater : MonoBehaviour
{
public Material material;
public RenderTexture mainRenderTexture;
public RenderTexture tempRenderTexture;
public string mainTextureProperty = "_MainTex";
void Start()
{
mainRenderTexture.filterMode = FilterMode.Bilinear;
mainRenderTexture.wrapMode = TextureWrapMode.Clamp;
tempRenderTexture.filterMode = FilterMode.Bilinear;
tempRenderTexture.wrapMode = TextureWrapMode.Clamp;
}
void Update()
{
Graphics.Blit(mainRenderTexture, tempRenderTexture, material);
Graphics.Blit(tempRenderTexture, mainRenderTexture);
material.SetTexture(mainTextureProperty, mainRenderTexture);
}
}```
And this is what I got
As you can see, part of the screen changes. But what I want it for every part of the screen the rectangle passes through, for it to remain changed
what happens if you change Application.targetFramerate?
Let me see
there's not a lot going on from the code you've shown, on face value it should work - I'm curious if the framerate is lining up perfectly to run an even number of times at each pixel so it reverts any change
Put it at 30 still the same
Yeah it's weird. Could it be a URP issue?
As you can see here, this is the Quad onto which I put the material that has the shader and the textures I'm using
if you look closely in your video there are some pixels that do flip, and stay flipped - I feel like it's more something to do with the movement and scale
what happens if you reduce the speed of the object, or change its size, etc
Ok let me check
I wonder if it's a compression issue on the video though
I think it<s on the video, just reduced the speed to 0.1 and nah
These are the render textures I'm using to do the swap. Looks like it should work, at least to me.
are you possibly referencing the asset material instead of the instanced material used on your target?
Maybe, let me check
I'm refering to the render quad, which contains the pixel changer material (with the shader that deos the effect), and the render texture is has is the one that is in the assets
Which is normal, right?
if the material in your ShaderTextureUpdate is referring to the asset, but you're updating the player mask property on the instance, then it wont be applying that in the blit
How it works is that the shaders compares the main texture and the playermask. If the pixels are white on the player mask, apply the shader on those pixels.
And that texture ends up being a render texture that renders to a quad
And that is what is shown to the player
I'm now wondering if I should just apply a normal unlit texture material on the rendering quad. And then when I blit apply the shader material
if you do that as-is you'll probably see what I mean - you're not actually applying your player mask in that blit
try setting your public Material material; in ShaderTextureUpdater.cs to the material your quad is actually using at runtime, i.e the instance
public GameObject materialContainer;
void Start()
{
material = materialContainer.GetComponent<Renderer>().material;
}```
This is what you mean, yeah?
that would work, yeah
Graphics.Blit(mainRenderTexture, tempRenderTexture, material);
Graphics.Blit(tempRenderTexture, mainRenderTexture);
material.SetTexture(mainTextureProperty, mainRenderTexture);```
This is what I'm thinking next. Applying the material directly in the blit. Does this make sense?
Do I have to refer to the render textures at runtime or can I assign them from the project? I thought I could assign them directly, when it comes to Rendertextures
I'm trying to wrap my head around what you said, not trying to be dense on purpose,l ol
you can, but you may be modifying the original assets if you don't clone them
Is anyone here experienced in firebase? I must have spent almost 100 hours on trying to get firebase to function properly with my game and whenever i fix one problem three more are created. I just wanna be done with this damn thing so i can back to actually developing the game!
We're getting somewhere babyyyy
this is a test done with cloning the render textures in the assets
Really not clear what you are actually achievement and what you want. Are you working in 2D or 3D ?
Here
Why cant you just write back in the texture then ?
I don’t know how, can that be done via the shader?
Yes and no ? You can modify the texture by shader.
You just need to save the results of the render
Here’s what i got now, I would like to write that change on the rejder texture
I saved it to a temporary render texture and then copy it back to the one on screen
But it’s not working. Doing that through Graphics.Blit. Using URP
Keep at it, you should be able to do it one way or an other.
I would expect that you render on render texture and the render texture is the "background".
Yeah it’s the screen
Or whatever is rendered to thr player. The effect in the end is sort of a screen scramble with the noise
Hello, I'm in the midst of making my game's authentication. I want for the client to attempt to authenticate itself without freezing the entire game.
private CancellationTokenSource _cancellationTokenSource { get; set; }
private Task<bool> _initializationTask { get; set; }
private void OnEnable()
{
_cancellationTokenSource = new();
_initializationTask = Task.Run(() => Initialize(0), _cancellationTokenSource.Token);
}
private void Update()
{
if (_initializationTask.IsCompleted)
{
if (_initializationTask.IsCompletedSuccessfully && _initializationTask.Result)
{
Debug.Log("Successfully initialized GameClient");
// TODO
}
else
{
Debug.Log("Failed to initialize GameClient, retrying in 5 seconds");
_initializationTask.Dispose();
_initializationTask = Task.Run(() => Initialize(5000), _cancellationTokenSource.Token);
}
}
}
private void OnDisable()
{
_cancellationTokenSource.Cancel();
_initializationTask.Dispose();
}
private async Task<bool> Initialize(int delay) {...}
Is this a correct approach to accomplish what I am trying to do?
Depends on what Initialize is actually doing.
Your retry logic can also be simplified if you do proper async/await.
private async Task<bool> Initialize(int delay)
{
await Task.Delay(delay);
Logger = new UnityLogger();
GameClient = new Client(GameConstants.ClientScheme, GameConstants.ClientHost, GameConstants.ClientPort, GameConstants.ClientServerKey, UnityWebRequestAdapter.Instance)
{
Timeout = GameConstants.ClientTimeout,
Logger = Logger,
};
GameSocket = GameClient.NewSocket(true);
string authToken = PlayerPrefs.GetString(GameConstants.PlayerPrefsAuthTokenKey, null);
string refreshToken = PlayerPrefs.GetString(GameConstants.PlayerPrefsRefreshTokenKey, null);
if (string.IsNullOrEmpty(authToken))
{
if (!await AutheticateWithDevice()) return false;
}
else
{
GameSession = Session.Restore(authToken, refreshToken);
if (GameSession.HasExpired(DateTime.UtcNow.AddDays(1)))
{
try
{
GameSession = await GameClient.SessionRefreshAsync(GameSession);
}
catch (Exception ex)
{
Debug.LogFormat("Error refreshing Session: {0}", ex.Message);
if (!await AutheticateWithDevice()) return false;
}
}
}
GameSocket.Closed += () => Connect();
Connect();
try
{
GameApiAccount = await GameClient.GetAccountAsync(GameSession);
}
catch (Exception ex)
{
Debug.LogFormat("Error getting API Account: {0}", ex.Message);
}
SaveKeys();
return true;
}
Doesn't async/await just treat the function as synchronous, so basically the game would freeze until the above function finishes it's course?
Which is what I am trying to avoid
No, that's not how async/await works.
Async/await merely gives you the ability to write your asynchronous code in a synchronous manner, it doesn't change the fact that the code is asynchronous.
yes but awaiting that very async function will suspend until that async function completes?
It will suspend execution of rest of the task, not the thread.
Which is exactly what you want.
ahhhhhhh, I apologize I'm new to Unity
I thought the thread was going to get suspended, I guess I can simplify my complicated code now lol
appreciate the help
Yeah your entire retry logic could just be rewritten into:
while (true)
{
if (await Initialize())
break;
// Retry delay
await Task.Delay(TimeSpan.FromSeconds(5));
}
And remove the delay from your Initialize.
and that would be inside the OnEnable I assume?
Yeah.
And your usage of cancellation token might not be exactly what you think it's doing, I'm not sure what you want to achieve with it, but there's a good chance that Task.Run(..., token) isn't really what you think it is.
All the examples I saw used it, however all of them had checks for it within the tasks, which isn't my case so I guess it renders completely useless in my code?
It depends on what you want to achieve with that token in the first place.
Well it was to prevent Task from running after OnDisable
Your currently code only cancels next retry attempt, it will not cancel the currently retry attempt that is awaiting the Task.Delay, it also will not cancel the inflight initialization.
So something like this could very much happen: OnEnabled is called and starts initialization; while awaiting AutheticateWithDevice(), OnDisable is called; afterwards AutheticateWithDevice() finally finishes and it proceeds with rest of the initialization. So after everything is done, you are in a state of initialized but the game object is already disabled.
Ahhhhhh, good point I didn't think of that case
Are AutheticateWithDevice and GameClient.GetAccountAsync your own code?
No that's Nakama
One more thing, I'm reading the ExecutionOrder doc page and something I'm not sure I understand is:
While inside the lifecycle loop, does the Thread wait for all OnEnable() functions to run before moving to the step, in this case Reset()?
Is that how to life cycle works?
Do those methods have overloads that accept a cancellation token?
AutheticateWithDevice is my function which in turn calls Nakama's AuthenticateDeviceAsync ***
But yes it appears to be the case
Okay, so they do support cooperative cancelling.
If an async method does not accept a cancellation token as argument, that means it does not support cooperative cancelling and once started it will run to completion (or throw)
For those kind of methods, if you want cooperative cancelling then you must check the cancellation state afterwards and perform cleanup manually then throw:
await SomeMethodThatDoesNotSupportCooperativeCancelling();
if (token.IsCancellationRequested)
{
// Cleanup and
token.ThrowIfCancellationRequested();
}
If your method supports cooperative cancelling, the convention is to have an argument for cancellation token (even though in your case your Initialize method can just access the class field _cancellationTokenSource directly, you should not do that and still make it an argument instead)
Then you simply pass around the token:
while (true)
{
if (await Initialize(token))
break;
await Task.Delay(TimeSpan.FromSeconds(5), token);
}
And inside your Initialization, you will pass down the token to all the await calls.
With that, you should have proper cancellation logic that won't get into race condition and invalid state like "initialize but game object is already disabled."
I still need to do this though right?
private void OnDisable()
{
_token.Cancel();
}
Correct.
alright damn, thank you so much for taking the time to help me
i dont know how to short summarize this, but does anyone know why when using the binarywriter while iterating through a collection like dictionary or list makes the order go completely out of whack. im using anonymous methods also i can use a for loop to write an array Vector3[] just fine, but as soon as i try to foreach through a collection to perform that on several randomly generated lists it throws an error that shows the order of binary is out
can you show code? generally it should have no problem with order, and not sure what you mean by order on dictionaries as they're kind of unordered
yep ill try provide a clearer problem
try to help you but i cant search write vector method in ms docu....
btw i think you want to pick the data like this?
ID length data ID length...
4bytes 4bytes length*4 bytes 4bytes 4bytes...
as pulni said hashtable is unordered so i have no clue what do you mean
i think i understand what you mean
assume you have a buffer
[data1,data2,data3....]
picked as this
[[data1.start,data1.end],[data2.start,data2.end],[data3.start,data3.end]...] (it is not an array of array, just showing the order of start and end in the buffer)
```after you write something new:
```cs
[data1,data2,data3....data_new]
```all the stuff is being shifted
```cs
[[data1.start+random offset,data1.end+random offset],[data2.start+random offset,data2.end+random offset]....]
```i doubt the buffer got realloced when you writing new data but binary writer is writing something into file so not realloc, also as long as you dont keep raw pointer it should be safe
https://referencesource.microsoft.com/#mscorlib/system/io/binarywriter.cs,cf806b417abe1a35
not realloc, also it uses the stream.write
Don't cross post asking for help
oh, sorry
DLL scripts don't have mono scripts tied to them as far as I could tell so, that's also out :(
Tried various approaches, but, in the end, as far as I can tell, there's no way for unity to load a type defined outside guids and file ids.
any idea how to tell where the third asset postprocessor is coming from?
so i made my own package and hosted it on a scoped registry using Verdaccio. It was importing to unity just fine and then i had to update some code so i pushed the package with new code to verdaccio.
Now when i import the package from within unity, it keeps downloading the package with the old code.
I've made sure there arent multiple versions of package on the server and neither is there a duplicate of the package on the server.
What's even more strange is when I download the package manually from the Registry (not through unity package manager), it downloads the correct code.
not sure i'm allowed to post links here but here's the hosted package.
http://3.95.15.12/-/web/detail/arcana-auth-sdk
i understand not wanting to go on a random link from a random person. but any help would be appreciated... dont know why unity keeps downloading old code...
when you install packages via the package manager Unity stores a local version in your global package cache, this will be what it is using thereafter. Afaik Unity does not auto update non Unity packages when newer versions become available you have to re-download them yourself
global package cache
this isnt the same as MyProject > Library > PackageCache
is it?
no it is not
https://docs.unity3d.com/Manual/upm-cache.html
ahh found it
tysm, ill try and see if deleting old package fixes it 😄
in future i should probably publish a new update with a different version number so its easier to update i guess 
If I set the rigidbody to Kinematic, everything works great. Initially it is set to false, and upon collision with a meteorite it is set to true, resulting in the destruction of the rocket. The problem now is that the limit no longer works because there is no rigid body that behaves as if it were dynamic. However, when I choose a dynamic rigid body, even if the gravity scale is adjusted, all the parts start to fall, or it happens that the parts do not move together. Here are all the scripts and a video.
https://gdl.space/utalucucuy.cs PlayerScript (Rocket)
https://gdl.space/xafuwozure.cs BoundaryScript
https://gdl.space/vojajuvoge.cs Rockpart (Wings,Body,Engine,Arrow have that script)
https://www.youtube.com/watch?v=jvGmYJef-Sw
I'm posting it here because either no one at code general knows about it or no one wants to help me. I hope someone would like to help me. I would be very grateful 🙂
Can't see the video, but it sounds like a question for #💻┃code-beginner
How did you fix it?
I removed the rigidbody from the children and only gave the empty object rocket the normal rigidbody and then made it via script when the player touches the boundary or just before it, add the rigidbody to the children, the kinematic and if he doesn't touch it, remove it again
now wait i say shit
ups wait
Wait, I removed the rigid body from the children and then added a rigid body to the parent and as soon as the player touches the meteor then the meteorites get the rigid body and then it flies out of the box, that's exactly how it was.-- sorry for the confusion, it was a lot of testing :()
So yeah that's a beginner level issue.
code advanced is where I look into to snatch some new features
Hi, I'm trying to get the wsa project settings value under Publishing Settings > Package Name
If I right click the var and get the property name, it gives me "metropackageName", which I can see in the ProjectSettings.asset file. When I try to run PlayerSettings.GetPropertyString("metroPackageName"), I get the error:
Unknown Property: 'metroPackageName::metroPackageName'.
I'm eventually trying to set these values, I'm just getting for debug purposes, I don't understand why this property doesn't seem to exist. Any ideas?
Vector3 dampingFactor2 = new Vector3(
Mathf.Max(0, 1 - Damping2 * Time.fixedDeltaTime),
Mathf.Max(0, 1 - Damping2 * Time.fixedDeltaTime),
Mathf.Max(0, 1 - Damping2 * Time.fixedDeltaTime)
);
Vector3 acceleration2 = (((referenceObject.transform.eulerAngles - gameObject.transform.eulerAngles) * Stiffness2) - Vector3.Scale(currentVelocity2, dampingFactor2)) * Time.fixedDeltaTime;
currentVelocity2 = Vector3.Scale(currentVelocity2, dampingFactor2) + acceleration2;
currentPos2 += currentVelocity2 * Time.fixedDeltaTime;
gameObject.transform.eulerAngles = currentPos2;
some help?, i cant get my gun to face camera direction
Hello, I was wondering if there is any difference doing this ```public class Sample : MonoBehaviour
{
//code
}
#if UNITY_EDITOR
[CustomEditor(typeof(Sample))]
public class SampleEditor : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
}
}
#endif```
and moving editor script into the editor folder. What is the better approach and why.?Thanks
no difference but it is much better practice to have 2 scripts
i have a sparse grid of tiles like this (...'s and arrows represent potentially more tiles). as can be seen, tiles 1-5 all have connectivity through tile 1 and possibly through other tiles not shown. i want to know if removing tile number 1 results in tiles 2-5 becoming disconnected from each other in some way, and if so, what is the resulting connectivity (in other words, what is the resulting set of strongly connected graphs - is it 2 and 3 plus whatever they're connected to as one sgg and 4 and 5 as another?). the most obvious way to do this is just to run a pathfinder algorithm from, say, tile 2 to tiles 3, 4, and 5, but in the worst case, this is way less performant than running a single pathfinder algorithm that determines that there is no path, since you would need to test 2 against 3, 4, and 5, then 3 against 4 and 5, and then 4 against 5, resulting in 6 "no path" pathfinders. what is a good way to do this?
I'd probably just do flood fill (BFS?) and see if it connects to all...
(and you can do this multiple times if you need to cover the whole graph and see what's connected to what...)
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
hmm ok thanks
Does anybody have any idea why this is happening, even on the new project?
A bug probably.🤷♂️
Try breaking with a debugger and seeing what the main thread is doing.
It is happening on every project I have, even on an empty one. Its not a single project problem. I reinstalled editor a couple of times
Every time I need to quit unity with taks manager
Never said it's a single project problem. Just that it's a bug.
That you can investigate.
https://www.geeksforgeeks.org/articulation-points-or-cut-vertices-in-a-graph/
DFS or BFS is the easiest, but you might be able to use something like Tarjan’s Algorithm. Not really something I would suggest though.
i've looked at tarjan's algorithm but couldn't figure out how to make it work for the situation where nodes are repeatedly added to or removed from the graph. or at least i couldn't figure out how to make it faster than just a breadth first search.
What is the size of your Graph ?
i'll probably just try the BFS, with the understanding that the most pathological case is not likely to be common
the situation is the graph is made up of specific tiles on a 2d tile map. so the size is as large as the entire map, however large i decide to make it, and as small as 1 or something
the current idea is to start with a row-by-row based algorithm to detect connected components and then update component ID based on a BFS on node removal
I would expect that if you want performance you would want to limit your graph size instead.
Anyway, a single search should do the case.
what do you mean by limit the graph size?
Divide the maps, in chunks
ok that makes sense...
at this point i'll try the BFS and if it's insufficiently performant, i'll try something more fancy
How many search you do ?
Because I believe that doing a search for each nodes that was previously connected would be the worst case scenario in your case.
yes that seems to be correct
In fact, a single search should even work
how would that be done?
Because, if you are not able to reach a nodes that was previously connected from any of the previously connected nodes that mean that they are not connected
Hence, the graph is no longer a single graph, but at least two distinjoint one.
right but in my case i'd need to assign an ID to each possible subgraph
not just detect lack of connectivity
so even if 2 and 3 aren't connected, i still need to know if 2 and 4 is connectd, etc...
so it feels like a search in the pathological case here requires 6 searches
2-3, 2-4, 2-5, 3-4, 3-5, 4-5
but in the vast majority of cases, those searches will be simple as their graphs will be small or the entire graph will be dense enough that BFS will detect connectivity quickly
I though the objective was to figureout if removing a node would result in a disconnected graph
the pathological case would be like a wheel with spokes
i have to know at any point what all of the sub-graphs will be
because the nodes can derive properties from any node it is connected to
Then you just need to do a search for 2,3,4,5.
Not 2-3, etc.
If you search for 2 and you do not find 3, then 2-3 is not connected.
If you find 3 and 4, then 3-4 is connected as well as 2-4 and 2-3
in the worst case though, you can determine that 2-3 is not connected, but not know if 2-4 or 2-5 is connected. you can also know that 2-3, 2-4, and 2-5 are not connected, but this doesn't tell you whether 3-4 is connected or 3-5 is connected
similarly, knowing that 3-4 and 3-5 are not connected, you don't know if 4-5 is connecteed
The worst case is a search for every previously connected nodes -1.
Not for every combination of nodes.
i'm not sure what you mean. i'm not trying to determine whether 1 is connected to those things. i'm trying to determine the new sub-graphs if 1 is removed.
If 2-3 and 2-4 is connected, does 3-4 is connected ?
yes
Then you simply needs to search for 2,3,4,5.
Worst case,
2 is not connected to 3,4,5
3 is not connected to 2 (Already Know),4,5
4 is not connected to 2 (Already Know),3 (Already Know), 5
5 is not connected to 2 (Already Know),3 (Already Know),4 (Already Know)
Hence, you only need to do a search for each previously connected nodes -1.
what do you mean by a search?
BFS or DFS
ok... so the BFS is a search of 2 for connectivity with 3,4, or 5
that's wht you mean right?
so the bfs is efficient in that situation because you are n ot revisiting nodes, you are checking for the targets (3, 4, or 5)
i think we might be saying the same thing though which is that the connectivity combinations you need to check for is 6 in the example above
the first check checks for 3 connecitivites with 1 search
You could see it like that
At the end, you only going to visit each nodes once at worst
right
ok that makes sense.
i think the other thing you were saying - chunking the graph - is a good idea but is probably a lot of work at this point if i don't need the performance
unless that's not true?
Usually, you get gain a considerable amount of performance by using group of nodes for Graph Algorithm instead of each individual nodes.
ok...
i'll have to look into that
i guess i can make like a... hierarchical space partition? and have a structure saying whether the larger squares are connected? and ignore that larger structure for the square in which the deletion occurs?
Usually, it is a conderable amount of works.
Exactly
ok that makes sense. i can try that
But yeah, only if you need more performance
Which would be suprising
Given the problem you have at hand at the moment
i think the way this works, in my situation, a BFS will give the correct result after a very short search through the nodes in the vast majority of cases...
the pathological case will be extremely rare based on player behavior
thanks for talking through this with me
one optimization in my case would be to sort the search starting with with the sub-graph with the smallest number of nodes. there will probabyl be a lot of 1-node subgraphs, meaning you can eliminate a lot of possibilities very quickly by starting with that node. contrasted with starting the search with the largest sub-graph, which would require traversing a very large number of nodes to get the same result.
on the other hand, how do you know which sub-graph is the smallest if you're trying to determine whether a node is part of its own subgraph...
so maybe that's not the right answer...
how to secure a string that noone can read it except you
who is "you"
the developer? The player? The person who owns the computer? Is this a multiplayer game or something?
write it on a piece of paper and put it in your desk drawer
If you ever have a piece of data that you don't want anyone else to see (for example API credentials) you cannot ever let it exist on hardware you don't own
Create a web service which your Unity game makes requests to. Your web service should be the one making requests to whatever AWS datastore you're using.
Unity should not directly write to anything
This way you can store your API credentials securely on your web service
Did you ever do this and what would be the steps to make something like this?
@stoic otter Probably easier for people to help you if you just say what you are exactly trying to do.
Answer to "how to secure a string" is indeed to not give the string to anyone, but odds are that isn't super helpful with whatever you are trying to accomplish.
Well I have a aws server.
I want to send analytics like heatmap data to the server.
But the aws server needs a key to send data to it. That key we want to save in the project but we don't want people to read it. Because than they can just upload to our server
That does not sound like an AWS server, do you mean a S3 bucket?
Networking isn't my main subject however, why would you not then use an intermediary or obfuscate the key?
I'm assuming that's what you want with this
So if you're not going to use advanced networking techniques why not obfuscate the key?
You should already be obfuscating software you push if you're making it for commerical purposes, except in certain cases
Although I suggest using what Unity already provides when it comes to Web Services
obfuscation is essentially no security at all
someone motivated will find it, and they will use it.
Assuming your game is popular enough for people to care.
especially if you're setting a network request straight to AWS, it would be trivial to sniff it out with a network proxy
if its for a single string, coding defensively and obfuscating it should be sufficent enough given this isn't a larger title
Again if anyone cares enough to try, it will be easy to extract
am never concerned with obfuscation, like if someone steals yours stuff and some how makes it to market before you and does better marketing for it. the problem was not them getting the logic
a relatively simple question about jobs ... I have a job which reads a NativeArray<float3>, but I set this array from outside of a job first, basically:
for (int i = 0; i < _vertices.Length; i++) {
// initialize the data in slow regular code
_vertices[i] = ... // complex unity code
}
for (int i = 0; ...) {
// only read _vertices here and run fast parallel code
jobs[i] = new RasterizeJob { vertices = _vertices }.Schedule();
}
JobHandle.CompleteAll(jobs);
problem is, I get an error ```
InvalidOperationException: The previously scheduled job RasterizeJob writes to the Unity.Collections.NativeArray1[Unity.Mathematics.float3] RasterizeJob._vertices. You are trying to schedule a new job RasterizeJob, which writes to the same Unity.Collections.NativeArray1[Unity.Mathematics.float3] (via RasterizeJob._vertices). To guarantee safety, you must include RasterizeJob as a dependency of the newly scheduled job.
I should note, the `RasterizeJob` _does not_ write to the array, it only reads it ... but from what I understand unity can't tell that there's no other job writing to it, and that the write happens from a regular monobehavior beforehand?
Are you using the [ReadOnly] attribute on the NativeArray field in the job?
yeah I tried adding those but still getting the same error
oh interesting, so looks like if I remove all my writes from the job it stops showing the error on read 👀 hmmmm, I thought if I passi n a 1 element slice that would fix any issues with this, e.g. resultPositions = new NativeSlice<float3>(_resultPositions, idx, 1),
but I guess that doesn't really work that way 😅 going to look at the parallel for thing instead
If you know that you're not writing to overlapping indices you can add the NativeDisableParallelForRestriction attribute to the collection in the job
Weird that you said you only read and now are saying you write 😛
I read from one NativeArray and write to another, I was getting errors for both, even for the one I read from even with the ReadOnly annotation
hmm, re-read the docs for the job system, I'm still a bit confused how I'm supposed to solve this ... so lets just consider the following scenario:
// main thread
write_to(A);
for (...) {
// reads A, writes B[i]
jobs[i] = new Job(A, B).Schedule();
}
JobHandle.CompleteAll(jobs);
// main thread again
read_from(B);
it feels to me that this should "just work", but it also seems the tracking of who's writing/reading is somehow wrong ... note that both A and B are allocated with Allocator.Persistent, they're not just temporary memory
turns out if I remove all the writing to B from the job I get no error on anything ... but if I add back the write, I get an error on both "reading from A" and "writing to B" 
even with the NativeDisableParallelForRestriction
going to try just making this into a parallel for I guess
oh crap
I have a compute shader that uses the same NativeArrays 😅 ...
I'm debugging some compiler/editor issues and trying to tail the editor log, but it appears to.. not flush to the log all that often. Is there any way to force it to do so during builds? I've been looking at these lines for the last 10 minutes, and I can't tell if the build is hung:
Opening scene 'Assets/Scenes/LoadingScene.unity'
Unloading 74 Unused Serialized files (Serialized files now loaded: 0)
Loaded scene 'Assets/Scenes/LoadingScene.unity'
Deserialize: 2287.833 ms
Integration: 242.398 ms
Integration of assets: 1.432 ms
Thread Wait Time: -0.344 ms
Total Operation Time: 2531.319 ms
Unloading 2561 unused Assets / (16.6 MB). Loaded Objects now: 7162.
Memory consumption went from 307.4 MB to 290.8 MB.
Total: 26.931400 ms (FindLiveObjects: 1.410300 ms CreateObjectMapping: 1.159100 ms MarkObjects: 17.064500 ms DeleteObjects: 7.296600 ms)
(just thought of that because of this thread: https://forum.unity.com/threads/editor-progress-bar-stalls-request-for-bug-reports.1137817/)
i've definitely gotten stuck at that exact point before
got it working
turns out I had so many things wrong, one being I spawned a parallel job in a loop instead of just calling Schedule(n) once ...
thanks for the tips! (using jobs to rasterize the visibility area and apply it to the fog)
do you guys know if it's possible to get debug break point to only activate on a selected gameobject? in Rider
Add a conditional breakpoint
Not sure about rider, but it's probably the same as in VS: add a condition with the name or id check.
yeah I tried that and it doesn't stop
ops! it does, i hadn't match the case
ring vs Ring
Some devs seem to want to prevent their assets from being extracted. I've seen two games that used AES to encrypt their AssetBundles. However when I tried to decrypt their games, I find their encryption keys as strings in their il2cpp metadata relatively easily.
If I was to make a game and I want to further ensure people don't decrypt my assets, what actions can I take? (obfuscate the encryption key itself?)
you can only make it awkward, you can't make it impossible
How can I modify the Texture compression format value in Player Settings via code? I can see it under m_BuildTargetDefaultTextureCompressionFormat in ProjectSettings.asset, but I don't see where to access it from code
Are you trying to do it at runtime or edit time? I don't think it's possible at runtime because it's more or less something that happens at build time.
I'm building an editor tool to swap a bunch of values
I have 3 types of items which I wanna spawn, they have circle colliders and box colliders. Now I want a system to be developed such that no item should spawn very close to each other or touch each other (or appear on top of each other). The system should be aware of all items instantiating and be responsible to have a distance between every item respective of each item's size. How do I approach this?
definitely not an advanced question, and please don't crosspost
depends
if he want a deterministic algorithm to do this.....(not while(fail==true))
Looking for ideas.
I have a client with a game that takes a long time to load. They wanna know why. I've written a lightweight application context class that's a DDOL, sits high in the script execution order, and is in their loading scene.. Hopefully it's one of the first things to Awake() in the game - which is important because it sets the load time then.
When I start the game in the editor, there's about 8 seconds of untracked time between my first Debug.Log (from the EditorSceneManager.playModeStartScene assignment to scenes[0] and the initialization of my application context).
I know I could tack on the Time.realTimeSinceStartup but I was hoping to have functionality during this window (the idea being I could call into this static class from anywhere in the codebase to observe how startup is going). I'm not quite sure what's causing the slowness in mobile builds.
Any ideas on how to get this DDOL/singleton injected earlier in the startup sequence?
any luck hooking in with the profiler?
I haven't tried that but my very first log message comes from the EditorSceneManager.playModeStartScene = AssetDatabase.LoadAssetAtPath<SceneAsset>(bootScene); call, in my editor [InitializeOnLoadAttribute] class
I mean.. Maybe I could just do something hokey where my application context "subtracts" the real time since startup:
private void Initialize()
{
Load();
_isActive = true;
_lastResumedUtc = DateTime.UtcNow - TimeSpan.FromSeconds(Time.realtimeSinceStartup); // Capture the "dead" time before we init.
}
but I'm not sure this is helping me figure out why our app takes so long to load
I haven't done profiling on-device before.. does that work well?
yeah, that's why I mention the profiler, cause if you can just see everything that's happening that seems simpler to me than trying to hook in only where you're allowed
no idea, never made a mobile game 😄
heh
i have some issues with my device in particular (google pixel 6 - connecting via USB seems to simply not work.. windows plays the new device/disconnected device chime every second repeatedly while plugged in) but maybe I can.. explore this
lemme see what the profiler says is happening at startup in the editor
something buried under a UniTask unfortunately.. i'll use the unitask profiler window thingy and see if i can figure that burp out
700ms
now i'm running of out memory, which is probably confounding my results 😛
hm, maybe there's leads here.. I'll keep poking. Thanks
hey guys does anyone know anything about raycasting in 3d with triggers and colliders?
Yes, lots of people do. This is probably a #💻┃code-beginner question, and be sure to just state what you need help with. The common saying is:
https://dontasktoask.com/
Kinda feels like a recursion.🤔
After a few hours of digging I've found something - slow (and unnecessary) newtonsoft json deserialization.. which was hidden under a UniTask that wasn't on a cancellationtoken
it wasn't failing so no issues there, but it was definitely slow as molasses
ah nice! I think you can turn on verbose serialization logging in newtonsoft and see if maybe it's spitting out anything useful?
using UnityEngine;
public class BuildWallScript : MonoBehaviour
{
public GameObject buildingPrefab;
public float buildDistance = 25f;
public float gridSize = 55f;
private bool hasBuilt = false;
private const string buildTag = "PlayerBuild";
void Update()
{
Vector3 playerPosition = transform.position;
if (Input.GetKeyDown(KeyCode.C) && !hasBuilt)
{
Vector3 buildPosition = CalculateSnapPosition(playerPosition + transform.forward * buildDistance);
if (!IsPositionOccupied(buildPosition))
{
GameObject newBuilding = Instantiate(buildingPrefab, buildPosition, Quaternion.identity);
newBuilding.AddComponent<BoxCollider>().isTrigger = true;
Renderer renderer = newBuilding.GetComponent<Renderer>();
if (renderer != null)
{
Material material = new Material(Shader.Find("Standard"));
renderer.material = material;
}
newBuilding.tag = buildTag;
hasBuilt = true;
}
}
if (Input.GetKeyUp(KeyCode.C))
{
hasBuilt = false;
}
}
private Vector3 CalculateSnapPosition(Vector3 position)
{
float x = Mathf.Round(position.x / gridSize) * gridSize;
float y = Mathf.Round(position.y / gridSize) * gridSize;
float z = Mathf.Round(position.z / gridSize) * gridSize;
return new Vector3(x, y, z);
}
private bool IsPositionOccupied(Vector3 position)
{
Collider[] colliders = Physics.OverlapBox(position, Vector3.one * gridSize / 2f);
foreach (Collider collider in colliders)
{
if (collider.gameObject.CompareTag(buildTag))
{
return true;
}
}
return false;
}
}
Can anyone help me with why random extra builds will randomly be created?
Like around the spots of already placed builds extra ones will be placed when I place a new one
What I usually look for is:
- First Scene. (As light as possible) No text, nothing except potentially 1 scrip with no reference.
- Resources Folder. Do not use.
- Shader Prewarm
Hey guys any idea why my inspector variables arent being displayed? This only happens now on my remote access to the machine
This script was supposed to be full of variabls to config on inspector
(its a linux os )
There's some weird rendering stuff going on - likely related to your remote access client and/or unity not rendering components.. like I see no play/pause button? and there's a gap in the toolbar (right above the hierarchy)? maybe minimize/restore the window and see if it forces the components to re-render
Maybe, the weirdest is that it used to show before and ive no idea what changed
The cursors changes when the mosue is over the float values .... its really a rendering stuff. I got no idea of how to fix it tho
Restart unity
Already did it a few times, even the desktop. Other components show normally, but apparently all scripts are being displayed like that
Do you have any editor inspector plugins? Like Odin inspector? Disable or uninstall those temporarily maybe
It could just be a failure to render specific graphics components with your remote software if it works fine locally
No I don't, guess It could be physics or some entities related package
Although analyzing the fact that when I access the desktop physically I got no problem Im supposing that might be something on the vpn or something like that
Although Ivent changed nothing, and it used to work just fine.
Take a screenshot of unity from your desktop (not your remote client computer) and paste it. No components= problem with your remote software
I swear I have not even considered that O.O gota try it !!! Thanks!!!
It doesnt enable the paste values button on the other side... guesws I need some rest btw, appreciate the help
Thanks a lot. Would this only work for updating the assets directly though? I'm hoping to change the option in the android player settings page
hi. does anyone know why Unity's SerializeField class has no Attribute postfix?
Maybe the developer who made it wasn't aware that most attribute types have that and that the C# language has special handling for it to make it optional to type.
but Tooltip has it, Header has it
Unity has more than one developer.
but then some (I guess older?) attributes like RequireComponent dont
They're probably newer
that's very short-sighted... but i guess thats it, just an old compatibility thing
This is just how software development works
Anyone has a clue since when the debugger is attaching to a separate process in the editor? If I just break and look at the parallel stack, main thread is nowhere to be found
I have this exact same problem
I wish C# could have user-defined optional postfixes. I would use them for all my ECS components, to name them HealthComponent, PositionComponent, but be able to reference them as GetComponent<Health>, GetComponent<Position>.
I figured it was a bug in vscode debugger
Is it? There seems to be another process of unity running and it has the main thread.
no... that's how shortsighted software developers work :)
Maintaining backwards compatibility is shortsighted?
They don't use the Attribute suffix? Okay.
no. making an issue and not fixing it is
No, it can't be changed
Renaming the type would introduce other problems.
That would break all existing projects
yeah of course, probably too late, or else they'd have done it by now
This is what I meant by how software development works. They probably could update it using the codemod tool, but it's not a problem so why would they
Honestly I feel like having Attribute be an optional suffix is the mistake in C#, and that also obviously can't be changed. It's such a weird feature.
Anyways, the editor seems to freeze on Domain/Scene reload sometimes... Anyone has any clue? Seems to be stuck in some windows input/output from AssetImporter😭
Updated to the latest 2022 LTS in hopes that it was a bug in a previous version, but it still happens...
true, the root of the problem goes back there
At times like this I really appreciate access to source code that we have at work(Unreal though)
You might be able to check the editor log and see what is being imported
When it freezes
Good idea
And get a clue of which importer is choking it
Maybe you've got a specific asset that is triggering a bug
Hmf... Seems to be stuck before some final task is started/completed?
That's the end of the log:
running zzzUnity.Burst.CodeGen.BurstILPostProcessor
[750/752 0s] CopyFiles Library/ScriptAssemblies/Assembly-CSharp.pdb
[751/752 0s] CopyFiles Library/ScriptAssemblies/Assembly-CSharp.dll
*** Tundra build success (2.40 seconds), 6 items updated, 752 evaluated
Or not..? It does say that 752 are evaluated.
Well, it does, not as you want it, but a global using would work, just not in this Unity version
apparently that's actually a feature. to distinguish a ClassAttribute and a Class, for some weird reason some projects seem to use that pattern
if someone has different Unity versions than 2022, can you confirm that SerializeField attribute actually doesn't have Attribute in its name? by decompiling it using Rider, Visual Studio or vscode
Raw source code, not decompiled
I'm having an issue with event listeners execution order. In both classes I'm subscribing to OnConsoleToggled event in Awake method but the execution order varies in editor and in a built application. Is there a way to fix this? I've read on some forum that a problem like this might be a consequence of bad design, but how can this design be improved then? And why is it wrong? I tired changing the DefaultExecutionOrder on both scripts, but with no effect
(pictures below show that the order of event delegates is different in editor and build)
//method from the first class
private void OnConsoleToggled(bool toggled)
{
if (toggled)
ClearAndSelectInputField();
Debug.Log("ConsoleInput class is now listening to OnConsoleToggled event!");
}
//method from the second class
private void OnConsoleToggled(bool toggled)
{
_consoleGUIParent.gameObject.SetActive(toggled);
if (toggled)
{
_consoleContentField.text = ConsoleProcessor.Content;
ResizeContentRect();
ScrollDown();
}
Debug.Log("ConsoleVisuals class is now listening to OnConsoleToggled event!");
}
//method where the event is invoked
public void Toggle(bool toggle)
{
IsToggled = toggle;
OnConsoleToggled?.Invoke(toggle);
CheckFirstToggles();
}
The order it is invoked in is the order of the invocation list. It is a design problem though if the order really matters. Listeners are meant to be independent of each other, so they shouldnt really care if another has finished running. Anyways it is not guaranteed that the order is kept and it could change in the future (although probably wont). You could just call these methods in the order you want or do something like store a list of delegates which you handle yourself.
Im surprised the default execution order doesnt work though, that should be fine. If you log something from awake, does it not follow the correct execution order?
I will test the DefaultExecutionOrder again, but I just though that I might declare another event in ConsoleVisuals class like “OnConsoleVisualsToggled” and listen to this one instead
I would probably opt for explicitly calling them in order anyways. I'm not a major fan of changing execution order for little stuff like this
Execution order does tend to be different between editor and builds (for behaviours of the same order) - it's one of the more common things I encounter that causes build-only issues, which are highly annoying
I personally use an event implementation that allows you to specify a magic order/priority number when subscribing to an event, and then I execute the event handlers based on this
Is it somewhat of a hack? Yes. Has it solved all my (rare) problems with such things? Yes. 🙂 Of course, sometimes it does make sense to actually reorganize things, if something has meaningful separate stages.
Here are the results of the execution order experiment
how is the object instantiated? is it something that exists on the scene or?
is it a c# feature or your own? Seems like a perfect solution
both are MonoBehaviour on one prefab in scene
my own... give me a second, I'll see if I have the code around to share, it's not anything too magical, just works 😅
that does sound weird... because the execution order should indeed work for such things 🤔 I'm actively using it, so seems weird
Here it is: https://gdl.space/tiharanaxu.cpp
Usage is - you make a public Event<ArgsType> SomeEvent {get; private set;} = new(); somewhere and then when you wanna subscribe you do obj.SomeEvent.AddHandler(obj or method, order); (higher order means execute later)
great, thanks a lot! Will tinker around with it
Hey everyone, I'm having the problem with my large Unity project that git has corrupted itself for the third time within less than two years.
I'm no longer confident that git is stable enough for large projects.
What version control system do you recommend for large long-term projects? Something without the possibility of corruption?
I've never heard of git corrupting itself
Have been using it professionally for a very long time, it's the gold standard in the software industry for version control
even if your local repo became corrupted it should be pretty trivial to pull a fresh copy from your remote
I do host my own git, I don't trust the 'free' implementations
I also host my own git using Gitlab. The problem is that the remote gets corrupted. It could be due to Git LFS.
The host machine is already really old so there is also the slight chance that its harddrive is failing.
Are you not using a Raid configuration?
One prefab was suddenly broken (invalid script references)
It was the in-game debug console from the unity asset store.
I re-imported the prefab file from the unity asset store which fixed the issue, but worryingly git status didn't show any change
so on second thought I doubt that its due to hard drive failure
No
Linux hosting OS?
yea
which drive format?
Ah, that could be the problem. Have you recently done a Kernel update?
No I haven't updated anything
that, in itself, is not good. which OS?
Ubuntu 20.04.4 LTS
I doubt very much if this is a hardware or git problem. I would recommend backing up everything and updating all of your middleware then reinstalling git and restoring the backup. I would also recommend that you invest in at least Raid0 or 1 if you really value your data
I think the most likely problem is that I changed Git LFS settings a while back.
The previous git corruptions were also after I changed Git LFS settings.
Investing in a Raid system is probably a good idea though 👍
I am extremely paranoid about backups, we lost decades of work last year due to a fire inside a fire proof cabinet which housed our backups, so excuse me for being over cautious
Oh damn. You're not being overly cautious at all!
I have a custom firewall set up so I don't really worry about security upgrades. Do you still think there are some updates that are somehow essential?
Kernel updates on a Linux OS more than anything, we switched to Unix as our main backup system as it requires less maintenance
What are they needed for? Better security?
I'm always paranoid about updating stuff. I'm always afraid it might break my software somehow 😅
well always multiple site backup, if its important enough to backup its important enough to have in multple locations
What drive format do you use for your backups?
true, that works well and we do for 'work in progress' and 'client work' but we had 50 years of software development on the backup drives and to host all of that in the cloud was just not cost effective, we've got the floppies and the hard copies though
we use NTFS for everything
That makes sense.
basically Kernel updates will ensure that at least the basics of your system is up to date so, for example, if there are problems in your base system they are addressed. A Kernel update should never break anything because if it did Linus would get a very nasty email from me and I'm even more aggressive than he his
Two years ago I installed BackBlaze and it's freaking amazing. For consumer-grade local backup it's everything you want - passive/silent backup, really easy restore (they mail you a USB), etc. It's not great for industrial use (ie, git) but I can't recommend it enough. I went down the route of doing my own server closet with a bunch of NAS devices but that completely misses the point because you're still at risk of location-specific issues (fire, flood). This is nice because it just works.
(also in my old age I just sorta appreciate software & hardware that just works without needing to be a wizard and niche expert in some trivial technology.. that shit was fine when I was younger, for now I'm just too busy to be required to learn something new)
for our new system, to replace the burnt out one, we installed 3 HP Proliant servers running HPUX in the US, UK and Spain which each Raid to each other, the theory being, short of nuclear war, we are covered
Yep, that's fine.. just saying for "consumer" use (ie, I wanna back up my computer/laptop with the least amount of hassle) it's pretty solid in terms of price-per-effort-per-functionality
BackBlaze is pretty expensive though. For my non-git needs I prefer Google Drive.
Maybe, although google drive is a lot more micromanagement.. ie, making sure to do the backup, or add folders locally to the gdrive folder (which means they're a pain in the ass to work on since they're "network" directories).. which increases the risk that you just won't back something up because of the hassle factor
In that case you and I differ, I'm pushing 70yo and I still delight in learning new stuff
BackBlaze literally just aims at my local drives and backs up everything.. excepting some blacklist stuff that you specify
Google drive can do that too
though the software is pretty buggy (bad memory leak)
It backs this stuff up automatically without being in the GDrive folder
Oh don't get me wrong, I like learning too.. I just mean, I have kids, have a job, have a side hustle, have lots of technologies already that I need to get mastery of.. I just sorta want my computer & data to "just work" and "just be backed up" without needing to devote @misty glade -CPU time to that task
tbh writing custom backup software is pretty trivial, however doing that on top of a Git system is less so
90% of my days on average are .. learning something to get something to "just work". :p
Yeah but I mean, I can already see that you're only backing up those two folders..
the SFX folder is huge
I use 1.3 TB on google drive
Uploading and downloading files is quick and free
That's sorta my point.. needing to manually add directories to be backed up is either.. a hassle or straight up impossible because of the effort.. At the end of the day the question is this: if your computer/house/office burnt/drowned would you be able to recover or would it be a life changing setback? I mean, aside from the other already-life-changing setback of being burnt or drowned. 🙂
that's my backblaze panel
907k files
No way am I gonna be importing that stuff manually into backup software
the folders are automatically synced in the background though. i don't need to manually upload files every time I change something
lol, I gave up on that hope the day Microsoft introduced MSDOS and then compounded the error with Windows 1.0
As long as they're under "Steam Page Assets" or "SFX" 🙂
For me.. as long as it's under "D" (which is a pooled drive, not a physical drive) then it gets to where it needs to be
(this tech is kinda cool too, if y'all aren't using it and are on windows)
raid for dummies
anyone having work on addressable bundle
you were told yesterday not to post in multiple channels, you're not exactly making friends atm
What do you mean i face error on my code so i ask community its my right whats your problem
do your work
Server rules, one question one channel
i don't know about this rule but i apologize for my behavior
iirc you posted a few error messages but absolutely nothing else, you might want to correct that if you expect to get any help, you might also consider making a thread
And, btw, my 'work' does not include answering anyone if I don't want to
Does a boxcolliders layer inclusion or exclusion setting override the project settings collision matrix? Or vice versa? or does it work in a different way
Test it.
It appears it does
Was double checking because im having this issue: "So i have 3 box colliders on seperate children, 1 small and 2 big ones. Both are a child of the same parent. When big box collider 1 gets triggered, the small box collider somehow also gets triggered. When big box collider 2 gets triggered, the small box collider also gets triggered. The big box colliders do not trigger eachother. The small box collider is not touched for sure. Does anyone know about this problem or can help me figure out the cause?"
So to not allow overrides, i should set both to nothing?
i mean, yeah if you don't want any overrides, then do not assign any overrrides to the collider
So with that in mind and every override set to nothing. Do you know why a collision with the big hitbox is triggerering functionality of a smaller hitbox?
collission matrix properly set up
you've not shown relevant code or even how these objects are set up in the hierarchy and inspector. so i could only guess at what it happening
its a few pictures, ill send them
Don't send it as pictures
Use !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
also none of this is advanced code related
Its mainly pictures of hierarchy
Oh, well the other parts are fine as pictures
yeah but its not a code issue
OnTriggerEnter2D is being called when its respective hitbox is not collided with
This is #archived-code-advanced so I am unsure what point you are making by saying it isn't a code issue
The pictures show a big hitbox, which has class playertestcollisionhandler. The small hitbox has playerbodycollisionhandler. The code in playerbodycollisionhandler is being called when the testcollisionhandler hitbox has been interacted with. Thats my issue here
could be a code issue, thats why im asking here or me misunderstanding code runtime
Perhaps you guys have a clue as to why this is happening?
don't colliders share collisions if they are in the same hierarchy or something? it's been awhile
they forward collision events to the first parent with a rb if one exists
I have multiple children like the playertestcollisionhandler. They all seem to not trigger eachother except for the playerbodycollisionhandler, which is also a child at the same level under the same root.
My parent does have an Rb, but no colliders attached. So my question is basically why is one specific child receiving all trigger messages from any boxcollider on my children objects.
Let me try this out, might be onto something haha
Fixed it.... turns out a stray duplicate script was hidden on my parent....
ffs
5 hours of my day poof
Occam strikes again
Tell hariedo haha
yes good that you say so
ill apologize to him real quick
Oh it's all good. I just think it's always nice to find out when something is resolved
I'm chasing down small allocations today. I noticed something very strange: foreach is producing garbage.
This produces garbage:
foreach (var el in prev)
res = agg.Invoke(res, el);
This produces no garbage:
var enumerator = prev.GetEnumerator();
while (enumerator.MoveNext())
res = agg.Invoke(acc, enumerator.Current);
prev is a RefLinqEnumerable<T, TEnumerable>, which is from RefLinq -- https://github.com/asc-community/HonkPerf.NET/tree/main
I eventually discovered this old documentation that talks about how using foreach requires some boxing:
Newer versions of the documentation don't mention this, and I indeed haven't seen this happen when iterating over lists, arrays, etc.
Is this just something that happens with custom enumerator types?
The Unity Manual helps you learn and use the Unity engine. With the Unity engine you can create 2D and 3D games, apps and experiences.
The first code block produces 32 bytes of garbage
Ah, I suppose this is because the enumerator is a value type, isn't it
That just clicked after I typed all that out 😉
I suppose I can rewrite this library to replace foreach with equivalent while loops.
ah, and in the same file, there's an example of the author doing exactly that
fantastic
hmm 32bytes, guessing due to some boxing with the access of it via IEnumerable<T>
thought that would be smaller though
Yeah.
That was a pretty big win on the GC front (:
now I just need to figure out how to stop allocating massive piles of garbage in the AI system
lots and lots of objects I allocate, use a few times, and then discard in the same frame
i'm getting a pooling feeling here
Yeah, because they're polymorphic
To plan its actions, an entity asks all of its modules (each of which provides a "thing" the entity can do) for PlannerActions
These actions get thrown out immediately after the planner has figured out a plan
yeah not hit a perf problem yet
the winning plan is resolved into BrainActions and handed to the entity's brain to carry out
so that's persistent
but assuming the npc beahviour systme in my game causes a good bit of garbage each time a new behaviour is choosen
I've already reduced the garbage by not re-allocating immutable stuff