#archived-code-advanced
1 messages ยท Page 98 of 1
it's a factory game written fully with structs & jobs so it goes fast.
I'm rendering all belts with rendermeshinstanced no matter what. as for buildings, either I use graphics.rendermesh to render the factory buildings too (ideally with a way to animate) or i make some system that spawns gameobjects purely to render the buildings, nothing else.
not sure what path to take because i don't know what my options are for animation with renderMesh
texture scroll is good for belts, not sure how i could use it for buildings. *or what i could use it for rather
is this a 3d game?
yes
hmm, I would look into skinned meshes first, and only after reading about them more trying to look into other things.
Does someone have experience to disable warnings with a csc.rsp its about the warning UNT0011 can i disable this somewhere?
why are you creating an instance of a scriptable object by calling its constructor manually?
Hi, would anyone happen to know how to set the "rendering layer mask" when using Graphics.DrawMesh?
It's trivial to set it on a UnityEngine.Renderer, but I don't understand how to do it when rendering things manually.
I've looked around online but I've found no obvious way to do it.
Any help is appreciated!
Is programming a functional inventory system that complicated or am I that stupid?
i programmed everything its just that when I drop an item which is at index 0, the item at index 1 goes back to index 0
inventory systems like that usually have numbered inventory slots
example: minecraft
Sounds like you're using a List. Lists shift elements back when an item is removed.
If you have a fixed number of slots in your inventory it would be better to use an array
(this also isn't exactly an advanced code topic)
A list still could work, just give it an ID that indicate it as empty
I guess but it's super awkward
You would have to manually populate it with empty elements to begin with
inventory is one of the more difficult concepts imo
well, depends how complicated you make it, but once you start mixing types it becomes logic heavy
then comes the ui :)
yeah I only have 4 slots so an array would work
type of inventories you mean?
i will look into that option as well and see whats easier
thanks people, I almost felt like I am so dumb
Just general inventory logic such as stacking, hotbar, equipment screen UI stuff
and passing between these container types. It can be quite overwhelming
aha I see, well I will just continue searching online because I would need stacking too, thank you
Sorry to ask again, but does anyone have a lead on this? I still have no clue how to solve it.
it's not really the number of slots that matters, it's whether the number is fixed
although isn't the int layer parameter in DrawMesh calls what you are looking for?
No, that's different. There's Layers, and then there's Render Layers. I'm interested in render layers. They're completely separate from the normal type of layer you set on gameobjects and so on.
render layers deal with lighting and shadows
Seems like it's related to the Renderer system.
Since DrawMesh skips the whole Renderer system, I doubt there's a way to involve it.
Then the question is how I could hook in to the rendering system earlier...
Is there some way to play nice with the rendering system then?
The end goal is just to render a lot of meshes without needing to have the overhead of a gameobject, mesh renderer and so on for each one.
Well have you looked at https://docs.unity3d.com/ScriptReference/Graphics.RenderMesh.html ?
the RenderParams seem to have some option for rendering layer masks
https://docs.unity3d.com/ScriptReference/RenderParams.html
that does seem promising... i'm currently looking into it...
That does seem to have solved it! Thanks for the help, it is very much appreciated!
When using unity.properties package https://docs.unity3d.com/Packages/com.unity.properties@2.1/manual/index.html
- can I reuse
Property/IPropertyand cache it? - can I simply get a property value if I know the property type and it's path, but the object (i.e. TContainer?) defining this property is only refrenced using it's based type
Base? (i.e. can something likePropertyContainer.GetValue<Base, int>(someComponent, propertyPath)work?) - when I use
[Unity.Properties.GeneratePropertyBagAttribute], is there any generated companion with generated paths to properties?
Does anybody know why IDragHandler would not work?
wdym by "not work" exactly?
Well I have a project I haven't worked on for a couple weeks, and before I stopped working on it my inventory system I had was working normally. Now that I have reopened the project recently, the inventory system has decided that nothing should work including dragging an item.
This is not the finished code for items but what I have so far:
what does "not work" mean though? Is the code actually running?
Also !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.
How can I know if the script is running in the first place then?
Basic/standard debugging techniques apply as always.
does unity.Properties package work with SerializedProperty ?
Looks like the file is running
wdym "the file" is running?
is OnDrag running?
what I mean is the overall file that im having issues with is in scene.
and how would I know if OnDrag is working if I cant get it to work?
If you put Debug.Log in it, does it print?
yes
dragging an item
in what way is it not working?
it doesnt react to my mouse clicks whats so ever.
But you just said OnDrag runs
so it does react
Are OnBeginDrag, OnDrag, and OnEndDrag all being called/running when you expect they should?
well the way i got the script to debug.log is i quickly put in a start method inside
So you still haven't actually checked if OnDrag is running
ya, so how would i check that>
We don't care about Start
i know
Didn't we already go over this??
Well my item just doesnt react to any mouse click so im just entirely lost
I don't understand the confusion here
Check if the code is running
with basic debugging techniques
if it's NOT
then we learned something
but you have to first make that effort
Well ive been trying
i have debug.log's in each of my interfaces
Ok so can you answer the simple question I asked here?
like ibegindrag, idraghandler
those are interfaces
you can't add logs inside the interface
you can add logs inside your methods.
i know i mean the methods
ok sooo....^^^ ??
and none of them seem to work
so they're not running
yup
So don't tell me they are like you did before ๐คฆ
Do you have an event system in the scene?
Wow... I must have somehow accidentally deleted that lol. Thanks ๐
sorry for making you lose brain cells๐ข
I'm looking for a super cheap / free option to collect some simple telemetry for my app (a puzzle game with hundreds of levels). I basically just one a single API endpoint that unity can call to log information. Ideally this API endpoint can write/append the data in the call to something like a google sheet.
Faster/simpler/cheaper is better. I do have azure infrastructure but I'd rather not spin up a web service and database for this single data point of telemetry. Azure databases are kinda stupidly expensive.
Any ideas?
Maybe google firebase..?
(Or has anyone used the new unity cloud stuff? is this the same as the old unity gaming services?)
super cheap / free -> look into oracle always free tier... buuuut... not sure if they have preemptive containers. Probably very inappropriate if you try to use it for actual prod, but good enough on prototype stage or something... Just be aware of their preemptive containers
beside that Firebase, maybe self-hosted supabase
I dunno, I'm also interested in answers to that question ๐
Maybe this if you can apply for indie developers program: https://gameanalytics.com/indie-program/
I'm gonna try out the new (old?) unity services analytics.. seems pretty shiny and quick and easy to setup.. I'm just sorta cringing at the pricing (since it's a low-LTV mobile product so high MAUs = really expensive costs)
But since we haven't launched yet.. we'll swap it out later if it isn't what we're thinking
Does anyone know how to make a simple AABB collision box around a rotated collider?
I've got a struct called Segment, formed by two Vector3 variables. To make things simpler, imagine I want to calculate the length of this Segment variable. I have two options of doing this, either like this
public struct Segment
{
public Vector3 Start;
public Vector3 End;
public Segment(Vector3 start, Vector3 end)
{
Start = start;
End = end;
Direction = (End - start).normalized;
Length = Vector3.Distance(start, end);
}
or like this
public struct Segment
{
public Vector3 Start;
public Vector3 End;
public Segment(Vector3 start, Vector3 end)
{
Start = start;
End = end;
}
public Vector3 Direction()
{
return (End - Start).normalized;
}
public float Length()
{
return Vector3.Distance(Start, End);
}
}```
Which of both would you recommend me to use? As far as I know the former would store the data forever while the latter would calculate it on the fly. For such a simple struct I'm unsure of which would be best
the first use case will be correct if you're accessing it more than once or twice over the lifetime of the struct; the second use case will be correct if you're creating/deleting these en masse and only using direction/length once or twice - ie, what is your constraint, CPU or memory
also I'd change Direction() and Length() in the second to properties (methods should be verbs, and property-ish methods should just be properties):
public struct Segment
{
public Vector3 Direction => (End - Start).normalized;
}
Right, I always forget about lambda expressions
exact same thing, tbh, but then it's easier to remember externally ("is it .Direction or .Direction()?")... whereas if you really want to remember that you're doing an expensive calculation, you could name it GetCalculatedDirection() or something.. a bit more verbose but then clear in the name of the method that it's doing some shit
Does anyone know how the assembly is called which I need to reference to use Unity.VFX?
Or more generally, if it says assembly is missing: How do I find out what I have to reference?
com.unity.visualeffectgraph no?
Stream stream = new MemoryStream(file.bytes);
BinaryReader br = new BinaryReader(stream);
int dataVal = br.ReadByte();
BitArray bitArray = new BitArray(dataVal);
Debug.Log(bitArray.Length);
for (int i = 0; i < bitArray.Length; i++)
{
Debug.Log(bitArray[i]);
}
Hi, im trying to use bitarray to make an array of bits of a byte, but for some reason instead of working how i expected it to (an array of bools of length 8) it makes an array the size of the binary number, with every value being false
IE hex of FF would make an array of length 255 with every value being false
did you look at the documentation? it's working as intended based on your description
the documentation doesn't have everything as false surely every value being false is kinda pointless idk
how would i achieve what i want then?
I don't know what you want because your code doesn't make sense. You allocate a bit array to hold dataVal bits which are all initially false, exactly as described by https://learn.microsoft.com/en-us/dotnet/api/system.collections.bitarray.-ctor?view=net-8.0#system-collections-bitarray-ctor(system-int32). But then you don't do anything or assign anything to them
is the byte being read from readbyte not what's assigned to bitarray?
we're back at the documentation now. No
i wanna make a bitarray with the values of the byte read from readbyte
you probably want to use the constructor that takes a byte array and use https://learn.microsoft.com/en-us/dotnet/api/system.bitconverter?view=net-8.0 then (or parse yourself)
this is still getting bytes though how do i convert that to an array of bools
how were you going to do it with the BitArray? How are you packing the data in the first place? You could just convert a bit at a time
like i wanna read the first 8 bits and get an array of [1, 0, 1, 0, 1, 0, 1, 0]
idk i thought that's how i was meant to it looked like what i wanted
so create a bool array of length 8, and check each bit
Loop the bits and bit shift the byte value to get each bit value.
I have a question, I know you can't have multiple inheritance.
I have two asset packagaes: MoreMountains TopDown Engine and Databrain
How to have a class that inherit from Dataobject (Databrain) and InventoryItem (TopDown Engine) at the same time?
public MyClass : Monobehaviour
{
public DataObject DataObject;
public InventoryItem InventoryItem:
}```
Sorry I forgot to mention both are from Scriptable objects
Similar idea, just make a class of ScriptableObject
So,
If I inherit from DataObject (I can view that scriptable object in Databrain editor window)
If I inherit from InventoryItem (I can use the whole inventory engine with that scriptable object item)
If I do it like your suggestion, I can't see the object in the Databrain editor window and I have to still have the InventoryItem scriptable object item created
I was thinking how to merge both so that I can handle the InventoryItem in the Databrain editor window
not sure what these packages are, but if this Databrain is some standalone asset that works on other assets, I wouldn't expect you to have to actually restruct the package data
I was thinking of going in the asset package and doing this:
public InventoryItem : DataObject
But I can't because the asset packages are like isolated? You can only build on them through inheritance
So I have a silly: I am currently using the Unity Rendering Pipeline. I am currently first rendering a "mask" which is saved to stencil. This mask is just a rendering layer so everything on it is part of the mask. I want to add some blur to this effect to soft out rough edges. Is there any way to apply a blur to one layer? I am working in 2D
Example Object that renders the mask
Render passes(in order)
Shaders and post processing / camera deals more with that
stencils for pixel replacement and rendering order specifics (also used for discarding pixels)
Hello, I have a small programming question: we are given a shape(polygon made of squares) like in the picture, the goal is to find its corners like highlighted in red. the squares are described by a list of int tuples that desribe its location in the grid. what's the best way to get the coordinates of the corner points in red?
check if each point has at least 2 adjacent black faces and at least one white face. also check if the black faces are not on the same axis if it is just 2 black faces that are touching, because otherwise it'll consider a straight line of blocks to have corners.
Hey all, anyone know a way that I could disable ENABLE_UNITY_COLLECTIONS_CHECKS in the editor?
thanks I'll try that
simplified convex hull walk (take the idea is rotate the line anti clockwise) should work, dfs and find a random outermost cell and generate the coordinate of one corner, then try to always walk in one direction, if fails, rotate the direction by 90deg anti clockwise
very nice idea, but what if there are white spaces on the inside?
like a ~~9x9 ~~3x3 where number 5 is a white square and everything else is black
sorry i meant 3x3 lol
afaik you can't ๐
i understand, the algorithm is the same (for each current corner point detect the next corner point by checking if there is a cell blocking it), but now the problem become how to detect the "hole" inside
yes im not sure how that would be implemented inside of a convex hull algorithm
maybe another algorithm just for this issue in particular ๐คทโโ๏ธ
not convex hull, i just take some idea from it
time taken should be O(2* number of tile)
not "walking" on the tile but walking on the corners of them
@plush pasture you should take a look at this because this is prob much better than the solution that i gave
damn I would never have thought about that thanks @tiny pewter
btw the "next corner" calculated depends on the direction you walk
or simply coordinate+ direction*tile length
but you should look at this too because this is an issue that'll arise #archived-code-advanced message
ah yeah no worries, in my application that is not gonna happen
detect "holes" is some way harder, i only come up with a solution done in O(size of AABB of the shape), ie floodfill
consider each 2x2 block, the middle is a corner if there is 3 of one colour, and 1 of the other
think it should work in all cases
beautiful and concise, how did you come up with this?
just noticed the pattern, but it's quite similar to how marching squares/cubes works as well
genuis! thanks
I think it depends whether this should be considered corner, I assume it should. In that case only the check for opposing colors should be added which wouldn't be that much harder tho
Does anyone know how to hook into the generation of the csproj file to modify it?
in what way are you trying to modify it?
this is beautfiul
The contents of the file
To change options that unity doesn't support
I don't think it really matters for the question. Basically unity will regenerate the file and I want to hook in and modify each time.
Then I advise taking a look at the C# FileSystemWatcher class
That's what I said!!!!!
Lol I noticed that too
Sorry your idea isn't beautiful
Beauty is in the eye of the beholder
I'm not afraid to admit you're right ๐
Hahaha
I'm joking
I actually read through the responses to see why it was so beautiful and was laughing that it was just your immediate answer
But phrased slightly differently
Oh well, at least you know you were right
Mine involved a few extra brute force checks but the other one simplified it perfectly
Ugh. That seems like the hackiest option. I'd sooner just use the compile callback and defer a few updates as required. I just thought there might be a "right" way to do it.
I guess English is the hardest part when it comes to coding ๐
I'm not sure if watchers would survive a domain reload anyway
how you think you are going to get a callback from something outside of the Asset folder I do not know
There is a callback from unity
But I thought maybe someone would know if there was a more specific API
but what has that to do with changing the csproj file?
Csproj is regenerated on compile
no
No what?
It's also generated when you click the option in the external tools panel
But that's pretty rare
csproj is not regenerated on compile, it is regenerated before compile, you need to hook into the space between the regerate and the compile, the api you linked will not do that
Ah I see. Well it's just for the IDE anyway so that's fine
I can use csc.rsp for unity compiler
It just doesn't respect it enough to add it to the csproj
And ide doesn't respect csc.rsp
what you are suggesting will only work for batch build, not for compile in the editor
I don't know what batch build is sorry. I just want to have the same settings in the IDE as I have in unity via csc.rsp.
Specifically I want warnings as errors and nullable refs
Very easy to enable in the unity compiler, but asmdef itself doesn't expose any options for them
So the options don't get baked into the csproj
There's a callback for csproj
Meaning that we get completely different handling between IDE and unity
Oh yeah?
Oh shit, so there is!
https://forum.unity.com/threads/editor-call-back-after-generate-visual-studio-files.508061/#post-3316048
OnGeneratedCSProject.
In that callback you can just use typical file IO and do whatever.
Yeah perfect
It's just an XML file so it should be relatively easy to modify I think
Instead of csc.rsp, have you tried using additional compiler arguments instead? I can't remember if the IDE integration packages have special handling for those, worth a quick try.
It's not something I've looked into, no.
Not something I was aware was an option tbh
I thought csc.rsp was compiler options for mono
Actually I found so little info about what it even is from googling
I came in the conversation late and it's too far for me to scroll up on mobile, what compiler option are you changing?
I want to set warnings to errors and enable nullable refs. I am able to do this for unity via csc.rsp but I don't have parity in our IDEs because unity generates them.
Actually there is a way to create a special file called directory.Build.props that augments the csproj, but annoyingly it applies to all csproj in the folder, which is every single csproj
So I'm hoping to just modify ours each time they generate
Honestly I think that callback is the answer
I might write a program that parses the csc.rsp and converts them into csproj options
Worth looking into additional compiler arguments regardless, it's somewhere in project settings, and if IDE integration packages know how it works then that saves you the trouble with having to deal with modifying csproj.
Okay. I'll Google it tomorrow. Thanks for the tip
Really appreciate it
I'm not by my computer atm, but my project also uses nullable reference type and I remember removing all the csproj modifications a while ago, so there's probably a way to do it. I'll check how my project is set up later.
Legend. Pls let me know! At the moment we just have #nullable enable on every file ๐
I need to sleep, but thank you.
@kindred tusk if you're still awake - I had the exact same question a couple days ago and there's an undocumented event unity fires after generating the csproj that you can hook into and manually add/rewrite what you need to into the files
lemme see if i can find the event name for you to google up
https://discussions.unity.com/t/change-visual-studio-solution-generated-by-unity/17448/3
AssetPostprocessor.OnGeneratedCSProjectFiles()
hahaah sorry didn't read yours
I have a private Vector3 with a [SerializeField] attribute named m_Size in a private class. This class inherits from MonoBehavior and is a component on a GameObject. How can I utilize FindProperty() to modify the variable m_Size? It is possible, right?
Oh yeah, nice. So many options.
what do you mean, how? that should just work ๐
I figured it was possible, but FindProperty("m_Size") returns null. I assume there's an entire path system of properties, and I don't know how it works.
which object are you calling FindProperty on?
The full line is: new SerializedObject(gameObject).FindProperty("m_Size")
aha, do it on the component, like new SerializedObject(gameObject.GetComponent<YourComponent>())
I would, but the component is a private class. I can't reference the class at all.
you should still be able to use the overload of GetComponent that takes a string type name then
is it your own script that you can't access from an editor assembly? you could always make it internal instead and use InternalsVisibleToAttribute
That worked, thank you! I wan't aware of passing in a string to GetComponent. Also, the component is ProBuilderShape, from Unity's ProBuilder plugin, so I wasn't able to modify the class.
string typing it is then ๐ฅฒ
Checked my project setup, it simply uses additional compiler arguments, with a Directory.Build.props at project root with:
<Project>
<PropertyGroup>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
Tahnks @scenic forge, that's what I've got now. But it's applying to every csproj, including libraries etc, which is causing unwanted errors from other libs.
You can override each directory with their own Directory.Build.props.
but all csproj files are in the same directory
in Unity
Ah.
This is what I tried:
<Project>
<PropertyGroup Condition=" '$(MSBuildProjectName)' == 'Game.Runtime' ">
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>True</TreatWarningsAsErrors>
</PropertyGroup>
</Project>
but for whatever reason it's not respected, so I gave up
But yeah, essentially enabling nullable on all your upm packages wreacks havoc on the project
like it's okay, but jump to next error can have some unwanted consequences in VSCode
Well you can always fallback to doing the csproj modifications in callback.
Yep, that's what I'm going to try
this is my plan...
wait for them to be generated, search for each asmdef
then find the relative csc.rsp
I feel like surely you can get conditions to work with Directory.Build.props though.
then convert each of those optinos into options
One would hope! But even still it's a poor man's solution
Because I can only have one directory.build.props Actually you can have multiple blocks, it could be the right move if I can get it working.
I did try for a few hours
I was asking on C# discord and, predictably, they were like 'why don't you just modify the csproj" at which point I had to reveal that I was a unity dev.
They don't like when you do that!
Yeah I moved away from modifying csproj because it's just kind of fragile, if modification breaks it's silent because obviously you don't check Unity's csproj files into source control so you have no idea, and the breakage can manifest in weird ways and waste your time making you think it's something else.
Ah right. You know what would be great? If unity had an option to not generate a csproj so we could just use our IDE.
Or if it exposed an API for modifying it safely
oh well, bitching never solved anything
It'd be nice if Unity was consistent with rest of the .NET world in general yes, hopefully the Core migration would help with some of the pains even if not this specific one.
Is this an upcoming update?
I haven't been keeping tabs on things. Hopefully we get the latest version of C# soon. I want those memory utilities for span.
Not sure when, but it's something that's been actively worked on for a while so I'm hopeful.
Well thanks for following that up @scenic forge!
I might try messing with directory.props some more
It's sadly not soon, but it's coming fast.
not coming fast enough to LTS so it's largely irrelevant for me
If we're lucky there'll be a preview within the year ๐
but I'm glad there's a nice future for my skillset
GOT IT
<Project>
<PropertyGroup Condition="$(MSBuildProjectName.StartsWith('Game'))">
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>True</TreatWarningsAsErrors>
</PropertyGroup>
</Project>
All our asmdefs start with Game
If you have people using Rider in your team, might want to check with them to make sure things are also working there. I've heard there were bugs with Rider's support for Directory.Build.props but they might already be fixed, but good to check regardless.
We do, thanks for that
oh no... trouble in paradise!!!
I used this as our csc.rsp
-warnaserror+
-nullable+
it's respecting warnings as errors but not respecting nullable
strangely this is working in another project, I must be doing something wrong
Okay, got it all working. This is great :-)
So is there a "method to the madness" of creating a new object in async (not coroutine, actual async Tasks) that causes Unity to not just crash, but disappear ๐ป
Should probably give some code for context, my bad:
function.CallAsync(request).ContinueWithOnMainThread(task =>
{
if (task.IsFaulted)
{
// blabla bla checks
}
FSLog($"GetAllMessages - ResponseMessage: {response["content"]}"); // all good
var serializedJson = JsonConvert.Serialize(response["content"]) // Works fine
var finalObj = JsonConvert.DeserializeObject<ObjType>(serializedJson); // Finishes? Probably not, since stepping over nukes Unity
callback(response);
}
And on this topic, even creating the new object without the Deserialize wrapper nuked it:
function.CallAsync(request).ContinueWithOnMainThread(task =>
{
if (task.IsFaulted)
{
// blabla bla checks
}
FSLog($"GetAllMessages - ResponseMessage: {response["content"]}"); // all good
var myObj = new ObjType(); // Nuked :D. When I removed all code and left just properties, it looked like it worked.
}
what is the class declaration for ObjType?
{
[JsonProperty("Read")] public List<SupportMessage> Read { get; set; }
[JsonProperty("Unread")] public List<SupportMessage> Unread { get; set; }
}
what does ContinueWithOnMainThread look like?
That is Firebase own extension method. Getting a sample one sec (but it doesn't seem firebase related, just async in general)
i can't think of a way async would make this crash somehow unless there's some weird compiler bug, but sudden unity crashes are often stack overflows and stuff like that
{
continuation(t);
return true;
})))).Unwrap<bool>();
It's a bottomless pit of running on main thread calls lol, it should work well, and I don't think the bug is with that, it has something to do with my own setup. Any general rules I should follow? Not exactly an async champ here ๐
I just now that sometimes when I allocate new mem on the heap with new() in async methods it just sends the whole thing to oblivion. Was hoping there was a known scenario where that might happen that I can take measures to avoid
assuming your call starts on the unity main thread in the first place, can you change your code to the following? just in case there's something unexpected going on with their method
await function.CallAsync(request);
var serializedJson = JsonConvert.Serialize(response["content"]);
var finalObj = JsonConvert.DeserializeObject<ObjType>(serializedJson);
The solution currently was to use the Firebase snapshot.ConvertTo<SupportMessageCollection> using deserialization with FirestoreProperties. Pretty sure that's doing heap allocation internally but maybe it's doing it in some special way? It doesn't nuke itself at all, I must be missing something
.... That's a good point. I'll try to find a slot to run that and see what happens, maybe with a Try Catch and hope it doesn't just disappear again ๐ซ
i don't know if it'll fix it but it takes some extra layers out of the mix for debugging at least
there should be nothing special at all about allocating in a task continuation
So no risk of the thread trying to access memory that it shouldn't, causing the OS to insta kill the entire process tree? That was my assumption. But I also recall that exceptions inside threads can fail silently if not awaited and may bring the whole thing down suddenly
not really, in this case (both with the await and their method) it's supposed to be running on the main thread, so it's no different to allocating in Update or something
... True
exception handling can be a problem, await might help with that
๐ค I guess more debugging as per your suggestion is the best course of action. ๐ Thank you very much simon!
good luck ๐
is there no better alternative to using AnimationEvents ?
im trying to create a Hitbox function that can be called via animation events with args about the boxcollider to use, the damage, knockback type and amount but i cant seem to find any easy way to do this
What part are you finding difficulty with?
It is a bit hard to test this so iam going to ask here.
I am using dotween library and want to release that package onto unity asset store.
I would like to make package to use assembly definition which requires me to reference dotween assembly definition and that is handled through dotween utility package.
If i reference it within my package and release it, my guess is that reference would be broken and user would have bunch of errors until he fixes references right? Is there solution to this?
ive found a solution, but i just struggled with passing multiple parameters to an animation event
you don't need to
just call a parameterless function
and have that function call your other function with all the parameters you want
but i want the parameters to be in the animation
the way ive done it is my component holds an array of structs that provide data, and the animation event simply calls a function and passes the index of the struct it wants to use
esp since some structs may be used multiple times within a single gameobject and their animations
This is usally what we do, alternatively, you can use ScriptableObject.
i worry that scriptable objects might take up more overheard
that's a nebulous concern
Hi would could be causing this problem?
as you can see it disables the box colliders but doesnt switch the tile when i jump
Is there a way to get PropertyPath from Property during visitation in PropertyVisitor from Unity.Properties package?
Hi all!
One of our colleagues already helped me connected to this. So I know that I can reach the shadowmap from the shader directly, but I am still curious.
Can I access the shadowmap in the builtin pipeline on the c# side?
That sounds like a thing you shouldn't do because it'll be horribly slow
Why would you want to do that
what's the end goal?
if your game mechanic depended on things being or not being in shadows, often times raycasting from the surface towards the direction of the light source would give you good enough estimation with less performance impact (basically ray tracing in CPU against the colliders in the scene)
I just want to visualize it in screenspace. I am gonna use a shader to do it as I can access the shadowmap there, however I just wonder if it is accessible on the c# side. For simply curiousity. ๐
In urp, it is in the rendering data class as far as I know, but I am not sure if built-in let us access these buffers at all.
So this way I won't have to use the shaders just some raycasting.
Good to know, thanks! ๐
If you worry about overhead on Animation Trigger, you should not use them because they are not performant. Also, there is no difference between a call towards a component or a scriptable.
Personally, I use scriptable object for Animation Trigger such as PlaySFX or PlayVFX. It is easier to edit scriptable object than to edit component in those situations.
sure. though for something like visualizing the shadow map that you talked earlier raycasts won't perform well enough assuming you are not sticking with some 10x10 resolution but for checking whether given point is in shadow or not, raycast would be a good idea. note that raycast can only check against colliders, not the actual 3d geometry (you can use mesh colliders for the objects of course)
hi guys
I currently develop a multiplayer big-world game with physics of some objects like iron ingots which can be pushed around with your body, or picked up
My current multiplayer approach in-game is pure tcp with a server running on somemone's machine
So, one player hits Create Lobby, Sets world name, difficulty and other stuff, and then player limit from 2 to 4(rn it's just 4 players), and after that creates a lobby
UDP and TCP clients are starting on his machine, where udp is for displaying info in serverlist when somebody from lan network hits "refresh list" or just opens up list of lobbies
or well, if i add a master server, it would send the data to the server and transfer it to the user
so when player decides to connect, he enters password, passes modcheck and gets added to the lobby
When all players are joined, host presses start and new world gets created with own serverside save folder and stuff
And well, players should get switched to Game Scene, where they all create their characters with race/gender and so on
And after all guys finished(like in for the king, for example), they get to the game and spawn in different chunks according to their race/biography pick
So well, i need to make some kind of serverside player's control so server tells player to spawn on chunk 0;0, or 99;14 or other
and player, using that information, gets tossed to this location and starts rendering it
after spawning static objects like terrain, trees and stones/mountains/buildings and so on, server should tell players which physical objects should spawn around them
For example, several NPC's and a set of armor lying on the ground
and well, server should somehow control physics of all this so dynamic objects don't drop through the floor
any clue or link to how this can be achieved?
I use HDRP/NavMesh/Terrain(with Terrain Tools to make terrain based on heightmap)/TCPClient/Unity Physics and running on Unity 2023 latest
And in order to load objects I use AssetBundles and ScriptableObjects, along with a custom ModLoader and serverside PluginLoader(which currently does nothing since it's for a future API to let users make plugins for the game)
and that's what i'm trying to achieve for all players in the world, depending on their location and mod set
i don't plan adding quests or dialogues, but would like to learn how to make physics and npc's
so players could just walk around, see each other and NPC's, and their would should look 100% same if modlist is matching
this is more of a learning project to get understanding of TCP, ModLoading, c# reflection and physics
go to #archived-networking and scroll up a bit, people were linking video tutorials
netcode is one of the official unity ones, if you're not using DOTS it's probably the one you want
otherwise there's similar 3rd party ones
I'm planning on using DOTS ig
netcode for entities then!
netcode for gameobjects is the one people were talking about but netcode for entities is the DOTS one
i never used DOTS before, but as i see it, it's a stack of stuff which optimizes both code and scene processes
am i right?
it's a totally different architecture from gameobjects, you have to write your game differently if you use it
Yeah, yeah
But well, it will definitely help players to load my large-scaled world with lots of trees, grass, terrains, static objects and physical objects with more performance, right?
or this is not what i'm looking for and i should stick with default unity stack
gameobjects, rigidbodies, colliders and so on
it could, but it really depends heavily on what's in your game, so only you can really decide that
tho, DOTS work fine with HDRP?
and does dots support terrain features?
well, my current prototype is classic
but it lacks the chunk loading part
no idea about the specifics but i imagine so
i mean terrain itself and terrain tools extension
since i'm planning to use heightmaps which are only supported in TerrainTools
alr, time to spend another week learning DOTS
I want to achieve the same effect that SpriteShape package gives, but I want it to render on the canvas instead of world space. Any ideas?
Render on a camera then take the render and put it on a raw image ?
yeah that's plan B.
Hello, I made this code that moves the UI a little bit based on the mouse position. How can I make it so if the screen size changes the UI changes with it? Thanks for the help ahead.
using UnityEngine;
public class UIMover : MonoBehaviour
{
[SerializeField] private float smooth = 5f;
[SerializeField] private float maxOffset = 20f; // Maximum offset from the initial position
private RectTransform rect;
private Vector3 initialPos;
private bool canMove = false;
void Start(){
rect = GetComponent<RectTransform>();
initialPos = rect.position;
Invoke("setCanMove", 1f);
}
void Update()
{
if (canMove){
Move();
}
}
void setCanMove(){
canMove = true;
}
void Move()
{
// Check if the mouse position is within the screen bounds
if (IsMouseWithinScreen())
{
// Calculate the normalized mouse position (-0.5 to 0.5 range)
Vector3 normalizedMousePos = new Vector3(
(Input.mousePosition.x / Screen.width) - 0.5f,
(Input.mousePosition.y / Screen.height) - 0.5f,
0
);
// Calculate the target position based on the max offset and the normalized mouse position
Vector3 targetPos = initialPos + (normalizedMousePos * maxOffset);
// Smoothly interpolate towards the target position
rect.position = Vector3.Lerp(rect.position, targetPos, smooth * Time.deltaTime);
}
}
// Helper method to check if the mouse position is within the screen bounds
private bool IsMouseWithinScreen(){
return new Rect(0, 0, Screen.width, Screen.height).Contains(Input.mousePosition);
}
}
nvm i fixed it
Why ask a question when you already fixed it?
Well, you see, they actually asked the question BEFORE they fixed it. Messages that are higher up are earlier in time.
Wdym?
It's often the case where you SAY the issue, then end up figuring it out just by trying to frame is as a question
Well, time is linear in the human perspective. So things can happen before or after other events. The question was asked BEFORE they figured it out
Then, after posting the question (later in time) they figured it out
Ah, so you are referring to the theory of time linearity?
Cool
I mean you always learn new thing in your life.
Today I learned about event chronology, tomorrow I might create nuke.
I agree, they should've went back in time and prevented themselves from posting that question if they already figured it out.
Some people canโt even go back in time to fix their mistakes smh. This generation is doomed am I right guys ?
I had a dream last night that I wrote a function that executes code from the top of a script to the bottom in sequential order ๐
Unity has rotted my brain to its core
Can I somehow make SerializedProperty work with properties marked with [CreateProperty]?
I need a potential undo support and multi-object editing
Hey guys, TMPro -> sprite's from rich text via TMP_SpriteAsset that is in TMP_Settings. When i change the default sprite asset in TMP_Settings in runtime, my sprite's refresh only after scene reload, i can bypass this by calling TMPro_EventManager.ON_TMP_SETTINGS_CHANGED(); but that works only in editor. Do you know any other way to refresh settings in build version?
How do I stop my player and enemy to be blurry using cinemachine?
I guess this really depends on how they are rendered. SpriteRenderer? MeshFilter+MeshRenderer? something different?
(Are you sure you're inspecting them through the game view i. e. not through the scene view?)
If it is a sprite/texture: make sure that the base image is large enough. Make sure that the mas resolution is high enough. Check the current quality settings.
If nothing of this helps, it might be good to get some more details, e. g. a few screenshots. (What does it look like? What are the settings?)
Anyone know how could I achieve the same as Unity's SerializeField attribute in Non-Unity c#? I want to import a DLL and make an attribute in there to be able to serialize private fields in editor. For Json Purposes I am using Newtonsoft.Json.JsonProperty but i'm not sure how to achieve the editor aspect
I'm building a script which allows the developer to choose a Scene to load after a "Loading" scene has completed. An Editor script allows the developer to hit a button which regenerates and enum. A public field allows the developer to pick a value from the enum. The trouble I have is finding a way to wait until the enum is regenerated before selected a new default value, since the chosen inspector value for the scene might now be invalid, after generation. Does anyone know how I can wait for Unity to stop compiling the script before the rest of the code is executed?
Using enum for this is not a good idea. Read on Primitive Obsession (https://refactoring.guru/smells/primitive-obsession)
Ideally, you should use Scriptable Object.
Use of primitives instead of small objects for simple tasks (such as currency, ranges, special strings for phone numbers,ย etc.)Use of constants for coding information (such as a constant USER_ADMIN_ROLE = 1 for referring to users with administrator rights.)Use of string constants as field names for use in data arrays.
I have to say that is a complete and utter load of crap
You are entitle to your opinion. That would be cool if you could elaborate a bit more though.
well let's just take one thing he says
'If you have a large variety of primitive fields, it may be possible to logically group some of them into their own class. '
And this reduces the number of primitives used by how much? Zero. All you have done is added another level of complexity.
What he is effectively saying is bad design basically stems from no design. So go and design your code properly rather than trying to stick a band aid on it
Hmm I don't see why I need a ScriptableObject since I don't need any of its features, unless I am missing something
Scene is a ScriptableObject. If you want to select a scene, why go through an indirect enum that describes the scene, instead of referencing the scene itself?
I.e. if you are doing scene <-> enum mapping, and in the editor script you are doing selection by scene enum, then you can just display a list of Scenes directly (SciprableObjects) and use that. What's more, if you just use a Scene targetScene, then you get for free a default inspector field that automatically lets you pick up the scenes from the project
I think it's more how would I create a picker for selecting from a list more than anything. Scene targetScene doesn't show a field to pick :/ . That would be far simpler if it would ๐. Thanks that sounds much cleaner, il take a look
then you are most probably looking for a custom property drawer for scene asset types
similar to this: https://forum.unity.com/threads/how-to-link-scenes-in-the-inspector.383140/ (just be aware that it's using older GUI system)
NasughtyAttributes has an existing implementation of [Scene] attribute you can use
you could then use something like
[Scene] public string bootScene; // scene name
[Scene] public int tutorialScene; // scene index
another "scene picker" implementation is even in the official docs, so you wouldn't need to depend on external packages: https://docs.unity3d.com/ScriptReference/SceneAsset.html
Primitive Obsession, as most design principle is a "guiding" principle. The idea is to increase maintainability by regrouping field with high cohesion together. Obviously, in some scenario it is overdesigning such as when you are using regrouping primitive in a already highly cohesive class.
In this situation, it is clear that you might add additional data per scene such as Level Name, Level Assets, Loading Screen, Spawn Points, etc. A scriptable object enable you to serialize all this information together.
I think I found the simplest way and works perfectly. No File reading or hard work needed
What's happening with buildSettings there? I dont see how it's used
thats an SO iirc
This is my cameracontroller. I have two camera methods. One allows me to follow the player while being able to zoom in and out with the scroll wheel. Pressing Y key toggles methods. My 2nd method is a free form method that allows me to move the camera with the edges of the screens. The problem is that zoom does not work during the 2nd method. If I scroll wheel during the 2nd method the variables do change. I can tell because if I'm zoomed out during lock, swap to free form, zoom in (no visual change shown), then swap back to locked cam, it snaps to all zoomed in like I wanted it.
Code is attached. Please help ๐
Hey guys - I'm trying to write a script that will convert a skinned mesh renderer to a static mesh per frame of animation.
I'm running into an issue though where I'm also trying to capture all the static meshes attached to the skinned mesh renderer... but they're not being translated in 3d space.
I'm a bit of Unity Noob though so I'm probably missing something. I am looping through all the regular meshes and trying to translate them into localspace... but i might be missing something ?
https://pastebin.com/B2jeLEEb
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
intended outcome:
What's being generated:
ignore the box - it's a hitbox where i forgot to remove the mesh
I based the script off https://www.youtube.com/watch?v=Hh5zcT2IkaQ
In this Unity tutorial you will learn how to bake animations as a series of "snapshots" of meshes. These snapshots can be taken at a configurable framerate that suits your game.
The concept here is attacking a similar problem as Animation Instancing: https://blog.unity.com/technology/animation-instancing-instancing-for-skinnedmeshrenderer, but ...
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Sorry it's not very clean ๐ญ
well you say it's translated into local space, but that's not true. And according to the docs, BakeMesh bakes the mesh using the position and rotation of the skinned mesh renderer's transform so seems like line 142 would be wrong at first glance
once you fix that, fix the static mesh transforms so they're in local space of the skinned mesh renderer's transform also
oh derp
combinedMesh.CombineMeshes(combineInstances.ToArray(), true, true);
i had the last argument as false
useMatrices
so.... when combining them of course it was not going to work
have set it to true now
looks closer, but still need to fix the static mesh transformations
Can anybody help me? I think its probably just a small oversight.
doesnt this: if (Input.GetKeyDown(KeyCode.Y)) freeFormCameraEnabled = !freeFormCameraEnabled; basically flip the freeFormCameraEnabled ON and OFF every frame the Y key is pressed?
an alternative, if I may suggest, look into Cinemachine package, because what you seem to be trying to implement, they have basically out of the box
I will check that out thank you
Hey guys, does someone know how I could proceed to fill a cell with a pavewalk or other to place my houses on?
( procedurally )
the cell generated would take form of a large polygon
What I'm thinking would be to make a mesh from the polygon and apply a material to it
Can someone explain what's going on here?
public class TestAlloc : MonoBehaviour
{
// Update is called once per frame
void Update()
{
NativeArray<float> test = new NativeArray<float>(1000*1000*60, Allocator.Persistent);
test.Dispose();
}
}
If i run this the memory in the profiler keeps increasing
I thought dispose was supposed to free it????
try to allocate it other than persistent?
tempJob can only be used for 4 frames, i need persistent because it can sometimes be an expensive job
and temp only works inside jobs
try raw malloc and free? i doubt that after you freeing the large block of memory unity get some memory internally by new causing heap fragmentation
Sorry for the late reply, but it's rather simple:
We cache the EditorBuildSettingsScene settings. If, when we trigger OnInspectorGUI(), the build settings have changed since last checked:
-> Create a temp list of strings to store the names of only enabled scenes
-> Assign the strings according to the latest settings
-> Set the string represented by the index
I just need to add validation checks
I don't know if someone responded in the meantime. I could be wrong (or maybe it's due to the video compression), but the enemy doesn't look blurry to me. You should make sure that it's not just your screen that has difficulties properly displaying moving things (e. g. due to a low pixel response time). Since you have a recording already, make sure that the recording doesn't contain to many compression artifacts. Make sure that you can observe the issue in the video when playing it at normal speed at the correct resolution (i. e. if you record at 1920x1080, the playback should be 1920x1080 i. e. fullscreen for most people). Then, reduce the playback speed and observe if the issue persists. You might also want to step through the video frame by frame. If you don't see the issue this way, there's a good chance that the rendering is fine.
hello everyone
I created a library for myself, but in the code on the editor I did not put it in the editor tag and I created it as a dll when building in unity it got an error, if I tag the editor on visual when creating the dll then It will lose the code on the If unity_editor tag, so how should I do it?
sorry, but your question is unclear. Could you show what you mean
this link sir
I want to do that but in 1 dll
or somehow include it in the project so that other people won't see my source code
This is how to do it
put the non editor dll into Assets/Plugns and the Editor dll into Assets/Editor/Plugins
Is there any other way to hide my source code?
no
thanks sir
already fixed it but now i have another issue, I placed sounds in an enemy and activated spatial blend and configure distance but it doesnt matter how much i run away i still hear it
Do you have any way or can you give more details? I tried it and it didn't work
that forum post explains exactly what you need to do, the post after the one I screenshot
I made 2 parts, 1 part only has external code like this
and a class I call as follows
But when I build it, it cannot call the class that I tagged if unity editor
did you make 2 configurations in your VS solution
yes
This is a class without the if unityeditor tag
public class GroupAttribute : PropertyAttribute
{
public string Name;
public Color Color;
public GroupAttribute(string name, string color)
{
Name = name;
switch (color.ToLower())
{
case "red":
Color = Color.red;
break;
case "green":
Color = Color.green;
break;
case "yellow":
Color = Color.yellow;
break;
case "brown":
Color = new Color(0.65f, 0.16f, 0.16f);
break;
default:
Color = Color.white;
break;
}
}
}
and This is the class with the if unityeditor tag
but propertyattribute is editor only
[CustomEditor(typeof(MonoBehaviour), true)]
public class GroupedInspector : Editor
{
private class Group
{
public string Name;
public Color Color;
public List<SerializedProperty> Properties = new List<SerializedProperty>();
}
public override void OnInspectorGUI()
{
serializedObject.Update();
var groups = new Dictionary<string, Group>();
var noGroupProperties = new List<SerializedProperty>();
var iterator = serializedObject.GetIterator();
iterator.NextVisible(true); // Skip the "m_Script" property
}
So what happens when building?
it will error untagged unity editor
you get 2 dll's one with editor+runtime code and one with runtime code only
I just tend to make 2 VS projects anyway, one for editor code and one for runtime
yes so wrap ALL editor code in a #if define
When I build it, it crashes if I don't tag unity editor
I use the following set up in VS
Solution
ProjectA
references UnityEngine
contains all non editor code
builds to Assets/Plugins
ProjectB
references ProjectA, UnityEngine, UnityEditor
contains all Unity Editor code
builds to Assets/Editor/Plugins
@eager willow
Sorry for the late reply, it was very late for me yesterday, can I text you to ask more clearly?
Any idea why i cant set scene active even though my loaded prints before the error?
Even with a yield return new wait for seconds it doesnt set the scene to active, no idea why
before what error?
Here's some example code for how to handle async loading and scene activation in a coroutine. I recommend following their example.
https://docs.unity3d.com/ScriptReference/AsyncOperation-allowSceneActivation.html
otherwise - unless you're setting allowSceneActivation to false it should activate the scene automatically afaik
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Assimp;
using System.Linq;
public static class AnimationImporterForAI
{
public static AssimpContext importer;
static AnimationImporterForAI()
{
if(importer == null)
{
// *loads something that is big in memory here*
}
}
}
this causes memory leak to me since every enter to play mode or modification of a script, the domain gets reloaded without disposing the old stuff stored in memory. what do i do?
First one pretty much explains issue every chunk loaded the graphics memory usage increases but chunks gets unloaded as well("destryoing gameobject"). However that doesnt reduce graphics usage in any way. The other screenshot shows the code that sets the mesh.
Can anyone help? Because i have no idea why this is happening (and no i am not using compute buffers in my project)
Does anyone have thoughts on Initializing Singletons? In the past, I had a "Manager Scene" which had all the Singleton manager objects -- and loaded the game scenes after (the manager scene is always running and booting other scenes)
That's how I do it.
I know it's common to just DontDestroyOnLoad and set the instance in Awake but I'm concerned I might try to access a Manager during Awake elsewhere
(I also use this scene to download addressables, prompt the user for privacy/data tracking, and that kind of stuff)
track the initialization with a flag then
Awesome, just making sure I'm on the right track
init on awake, check if it's init'd already and early-out if so, elsewhere if you call into it and it's not initialized, then init it
It does kind of suck that you lose the ability to start a particular scene, you'd need to hack something together.
private bool _isInitialized = false;
private void Awake()
{
if (instance != null)
{
Destroy(gameObject);
return;
}
instance = this;
Initialize();
}
private void Initialize()
{
if (_isInitialized) return;
_isInitialized = true;
// do stuff
}
}```
this is my pattern
and then anyplace that needs init (that could happen before awake) just pre-emptively call Initialize() .. just be careful of circular dependencies
since this is obviously not resilient to that ๐
MetaXR Spatial Anchors
Excuse my noobishness but this is my first time interacting with the unity job system. I am attempting to parallel process a potentially large number of targets using a threaded task but I am running into an issue. The issue I am running into is that the targets seem to be being managed incorrectly somewhere along the line but I'm just struggling to see what I'm doing wrong here. I've tried a number of things but I still can't seem to quite figure out what the issue is.
The issue I am running into is that the targets seem to be being managed incorrectly somewhere along the line but I'm just struggling to see what I'm doing wrong here.
"managed incorrectly" is extremely vague
what are you expecting to happen and what's happening instead
Also please share your code via !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.
Ah you got it, gimme a minute and I'll reformat the post to give 1. Better info 2. A more in depth explanation
https://gdl.space/wurutakuri.cs
The issue I'm experiencing is that when an enemy exits the collider, I begin to see the gameobjects in the list show up as a type mismatch. This only seems to happen upon exiting the sphere collider in charge of registering and deregistering targets. I reckon it's something with my threaded code though
The reason I reckon that is because upon reverting to my commit before attempting to thread the code, The system worked fine
Not seeing anything in that normal critical path that could cause such an issue.
What's the multithreaded code do?
ooooh wait you're modifying the list in the job?
I thought that was the point of IParallelJobFor. I could be way off base though.
well...
you can't actually even TOUCH managed memory
in any job
and I don't think you are here
This is a little weird/inefficient but I don't see how it would break things:
for (int i = 0; i < RegisteredTargets.Count; i++)
{
RegisteredTargets[i] = new TargetData(RegisteredTargets[i].TargetGameObject, RegisteredTargets[i].TargetRB, RegisteredTargets[i].IsEmpty, scoreResults[i]);
}```
pretty sure you could just do RegisteredTargets[i].TargetScore = scoreResults[i];
wait nvm it's a list
not an array
The job itself writes to some lists then the job does work on the lists then the results of the calculation are added to the struct value so I don't think I ever write to managed memory from inside the job itself. I could convert the list to an array and pass it into the nativearray constructor
that might be more efficient
no no. What you have is the way
That list -> Array -> nativearray thing is the same as what you have with an extra unecessary step
Is there any way to check if GPU instancing is supported by the hardware at runtime? I have a release build that I've tested on a few machines that works, but on one particular machine, all the stuff I'm rendering with DrawMeshInstancedIndirect() just doesn't show up and I see no indication as to why?
I believe I've also tested the same gen GPU previously, but a slightly different model so I'm not sure if its a hardware thing or not
Awesome, thank you! ๐
So those both return true on that machine.... Anyone have any ideas as to why DrawMeshInstancedIndirect() would not render on one machine but not others?
If you can inspect the issue with the frame debugger it might provide some clues.
Otherwise the dedicated graphics debugging tools for the platform(pix for windows for example)
Does anyone have tips for dealing with native crashes in production? Native Crash - KiUserExceptionDispatcher
I've enabled Cloud Diagnostics but the stack traces aren't helpful.
All I see is: 12 GameAssembly 0x00007ffef67c2cc0 <symbols missing for uuid: 1D6DFAF74FFD46869A365F2FE7A16491d>
I've uploaded the pdb file with the corresponding UUID but the logs aren't being updated.
I'm getting lots of refunds over this issue, appreciate any help ๐
Can you not download the crash dump file and debug it?
I was not aware of that option. Let me look into it a bit.
I don't know much about cloud diagnostics, but it would be weird if you can't get the crash dump file.
I can download a json file and I have the pdb file for the build. Is it possible to see which line of code is correlated to the following stack trace locally?
12 GameAssembly 0x00007ffef67c2cc0 <symbols missing for uuid: 1D6DFAF74FFD46869A365F2FE7A16491d>
13 GameAssembly 0x00007ffef6555701 <symbols missing for uuid: 1D6DFAF74FFD46869A365F2FE7A16491d>
14 GameAssembly 0x00007ffef6211704 <symbols missing for uuid: 1D6DFAF74FFD46869A365F2FE7A16491d>
15 GameAssembly 0x00007ffef621a201 <symbols missing for uuid: 1D6DFAF74FFD46869A365F2FE7A16491d>
16 GameAssembly 0x00007ffef6210eee <symbols missing for uuid: 1D6DFAF74FFD46869A365F2FE7A16491d>
17 GameAssembly 0x00007ffef6017726 <symbols missing for uuid: 1D6DFAF74FFD46869A365F2FE7A16491d>
18 GameAssembly 0x00007ffef60171c9 <symbols missing for uuid: 1D6DFAF74FFD46869A365F2FE7A16491d>
No. Crash dump should have an .dmp extension or something similar.
Ah ok. And if it exists I can use WinDbg or Visual Studio symbolicate the crash dump?
Yes.
It seems like cloud diagnostics doesn't collect the crash dump.
You might need to contact a user that experience the issue and ask them to provide crash dump.
Also, just in case you don't know, this is not the official unity support, but a community server. You should contact the actual support, seeing how it's a native crash.
Ok thanks for your help โค๏ธ
I've contacted Unity but technical support requires a Pro license atm.
You can still open bug reports etc
hey so i have an issue where
i have a gameobject with an animator
and i sometimes disable the gameobject but
if an animation is running and i disable the gameobject, then re-enable it
yes
#๐ปโcode-beginner -> show the code
i was going to ask if theres a way to make an animator reset to its defualt statethrouygh code
Hello guys. Kinda need some advice on not creating a whole bunch of spaghetti code here.
So.. In my project i want to able to to select the enemy i'm attacking on mouse click, but i am also using composition and it would be cool to make a reusable attack component that would be able to be attached to the Player Character and the Enemies.
Both the Character and the Enemy inherit from an Actor class.
So far, whenever i click on an Enemy, i set a static variable Enemy enemyTarget to the clicked enemy, and in my attack component(for the player) i'm checking on trigger stay to see if other == enemyTarget.
For the enemy im just checking on trigger enter and on trigger exit for the player.
Then i need to be able to call the TakeDamage method inside the HealthComponent of my target, but i dont really have acess to it as Actor doesnt have the HealthComponent, but the Player Character and the Enemy does.
Should i create another class that inherits from Actor and will be the base class for Player and Enemies?
Should i just add an interface to the Player and Enemy classes, i didnt really want to have to write a TakeDamage method in those classes, i wanted to be able to let the healthcomponents deal with all that
Any advice someone can give to this situation_
I think this is more a question for #archived-code-general but anyway: There's multiple approaches and in theory there's no good or wrong. But by following a set of pre defined rules it makes it easier for everyone (Including yourself) to understand the code and not make spaghetti out of it. Have a read of the SOLID principles. I usually fall back to this Medium article as it explains exactly how to implement it in Unity: https://medium.com/@alejandrodiazjllo/s-o-l-i-d-principles-for-unity-a1556ee99e7c
A good video to fall back to: https://www.youtube.com/watch?v=QDldZWvNK_E
Yeah, im familiar with the SOLID principles but in this specific situation I'm having some trouble. I think i might go with the inheritance route
Then i need to be able to call the TakeDamage method inside the HealthComponent of my target, but i dont really have acess to it as Actor doesnt have the HealthComponent, but the Player Character and the Enemy does.
Use GetComponent or make an interface IReceiveDamage and try to cast your actor.
Get component seems like a decent route too! I have my components inside an empty gameobject inside my prefabs so it stays organized. But i might just add all of it to the prefab parent
Should i just add an interface to the Player and Enemy classes, i didnt really want to have to write a TakeDamage method in those classes, i wanted to be able to let the healthcomponents deal with all that
Use Composition to be able to reuse the "component" through your classes.
public class Player : ITakeDamage
{
private DamageHandler damageHandler;
public TakeDamage()
{
damageHandler.TakeDamage();
}
}
Yeah, i didnt really want to go that way because i think thats really ugly. I'd rather call take damage directly on the damage handler
One thing you might need to note, is that "Health" is usually used by a considerable amount of system. Making it in a seperate component might work for simple game, but if your game start to be a bit more complicated you realize that your health componenet needs a considerable amount of "Customization". By example, you might have modifiers, you might invulnerability period, you might complex interaction for the damage taken.
In any circumstance, I believe the easiest way to handle simple scenario is to have a "Character Class" i.e. god class. As long as your game is relatively simple, it might be more than enough.
Obviously, that would means that you are vulnerable to the same issue, but in a different way, then what I described with using components.
I've gotten to the point where if I'm not using singletons to grab references, then I'm using bi-directional references to reference upwards the hierarchy.
Large reason for this is a lot of stuff that I want to be grabbing components from should be its own gameobject, for quicker component accessing instead of convoluting a single gameobject. All my objects with colliders will have some script that's composed of just properties that point to their respective script.
Yeah.. i might go with a bit more inheritance to solve that
this seems to work, i wonder what might be the issue
Can someone explain the differences between Allocation Types in the scope of using UnsafeUtility.Malloc?
I understand TempJob being for jobs, Temp of 4 frames, and Persistent to be more persistent. But none of those warnigns are thrown with UnsafeUtility.Malloc, so what's actually happening behind the scenes with those allocation types?
only persistent actually allocates real memory, the others go to a faster bump allocator that gets cleared 1 or 4 frames later
Ah good to know
also, to have a list of pointers
is this a good approach?
public unsafe struct MapPointerHolder{
public float4* pointer;
public int Length;
public void Dispose(){
UnsafeUtility.Free(pointer, Allocator.Persistent);
}
}
and then list of that struct?
or could that bring problems
i don't think there's exactly a safe way to do that, so it depends how it's being used? you could maybe improve it a little by making pointer get-only and setting it to null on dispose to avoid double frees
Alright
I transformed it to this
public unsafe struct MapPointerHolder{
public float4* pointer{get;}
public int Length{get;}
public NativeArray<float4> array{get;}
public void Dispose(){
UnsafeUtility.Free(pointer, Allocator.Persistent);
}
public MapPointerHolder(float4* pr, int Lenght){
this.pointer = pr;
this.array = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<float4>(pr, Lenght, Allocator.Persistent);
this.Length = Lenght;
}
}
and it breaks unity, great
that seems a little redundant now if you convert it to a native array - NativeArray already does everything your wrapper does ๐
buuuuut that's where the issue is
Im doing this because for some reason, native array. dispose doesn't really free all the memory
it seems to generate some garbage that I cant delete
example here
using System.Collections;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine;
public class TestAlloc : MonoBehaviour
{
// Update is called once per frame
unsafe void Update()
{
//Normal way
/* NativeArray<float> test = new NativeArray<float>(1000*1000*60, Allocator.Persistent);
test.Dispose(); */
//Manual way
var ptr = (float*)UnsafeUtility.Malloc(1000*1000*60,UnsafeUtility.AlignOf<float>(), Allocator.Persistent);
NativeArray<float> newtest = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<float>(ptr, 1000*1000*60, Allocator.Persistent);
UnsafeUtility.Free(ptr, Allocator.Persistent);
}
}
if you uncomment and test the normal way you will see that memory starts increasing, while the second, the manual, doesn't
are you sure? you're allocating a lot of memory (240MB in the NativeArray) every frame. You could be causing a lot of fragmentation, and Unity never releases heap memory once acquired. It looks like your Malloc is only allocating 60MB btw, assuming Malloc is in bytes
also had to add an atomic safety hadnler
im not sure at all, but it's what I saw. but im gonna check the difference between 240mb and 60mb
yeah so i tried now with 240mb (adding sizeof(flaot) into the method of manual) and it stil stays consistent
i tried it and it does level out after a while, i think it might just be unity not bothering to free memory until a certain point to save time
that could be but when doing testing on a bigger scene (before getting to this point) my issue was that memory keept increasing while exiting and entering play mode, and I wasn't getting any reports of memory leak anywhere
Editor profiling can be misleading and outright wrong due to extra stuff it does. You tested in an actual build right?
i did not
lets see
interesting, it doesn't happen in an actual build
But then its problematic too, because im doing a unity tool and therefore it should work fine on the editor and not accomulate memory
are you sure dispose is always being called in your tool? assuming it's not just disposing immediately after allocating like your example ๐ normally i'd try to avoid using persistent allocations in editor because of how easy it is to create a leak
i was quite sure! but I will check again. I'm not allocating anything in the editor that i'm not doing in build too, and they need to be persistent since sometimes it takes 5-6 frames instead of 4 ๐ฆ
How can I make unity release heap memory?
Or check if that's the problem?
Ah no, heap memory seems to be fine
I have a bit of performance issues in my game, and I think I've narrowed it down to local material creation on an object that I'm sometimes creating several (N=2-10) per "move" (typical moves are 1 per 1-3 sec).
I have this prefab that has a number of special effects on it, and in order to not have materials "collide", i create a copy of the material at Awake time.
Could I use object pooling for something like this?
you certainly could - but also are you using .material or .sharedMaterial?
.material
usually like this:
private void Awake()
{
Tile2Image.material = new Material(Tile2Image.material);
_shineMaterial = Tile2Image.material;
}
then I do some tweening and animations and shader nonsense on the _shineMaterial
you you might even be making two copies of the material like that
use .sharedMaterial
because accessing .material tends to create its own copy internally
right - that's what I want, though
Basically I think you can just get rid of that first line
like, if I use shared material, won't the effect on one item affect all the items?
private void Awake()
{
_shineMaterial = Tile2Image.material;
}```
this will already create a copy
oh? ok.. this is a bit of cut and paste coding from the uh.. shader component thing i have
private void Awake()
{
Tile2Image.sharedMaterial = new Material(Tile2Image.sharedMaterial);
}
``` this would _also_ create one copy
just more verbosely
k, trying it out.. tbh i was raising my eyebrow at that code too
I think in both cases you also will need to Destroy the copy when you're done with it
oh, also good to know, i wasn't doing that
ok - so commented those extra ctors out and functionality is ๐ .. will profile again
ah but it does this nonsense:
ie, just entering play mode modifies the .mat file in the repo
(which is super annoying both for me and all the designers)
uhhh what code did you end up with? That shouldn't happen ๐ค
if you're using .material it should definitely make a copy
I would expect that if you modify the material returned from .sharedMaterial directly
Oh, i wasn't using shared material sorry
well hang on.. maybe i'm not understanding something.. lemme just paste code, sec
well you shouldn't use sharedMaterial if you wish to create a copy to modify
private Material _shineMaterial;
private void Awake()
{
_shineMaterial = Tile2Image.material;
}
// elsewhere:
_shineMaterial.GetFloat(_shineId);
seq.Append(_shineMaterial.DOFloat(1, _shineId, 0.3f).SetEase(Ease.Linear)); // dotween sequence
seq.AppendCallback(() => _shineMaterial.SetFloat(_shineId, 0));
basically i'm setting the float on a shader on the material.. when i don't make a copy of it, it affects every sprite in the game that uses that material
that should have worked without modifying the asset ๐ค
Tile2Image is... a renderer or what?
or is it a UI Image?
just a UI image, yeah
Ahhhh
i am using a custom component for this, btw, so the problem might be in there - All In 1 Shader
that explains it
Yeah you'll need to manually create the material like you had before then. Sorry for the misunderstanding I thought it was a Renderer
k.. no worries
I don't think UI Image actually has a separate .sharedMaterial property
yeah it doesn't
yeah i .. recall going down a rabbit hole trying to get shared materials in UGUI things and it just not working
I would think if you manually point multiple Images at the same material instance it should be shared amongst them
this might not even be the problem with my frame stutter anyway.. the profiler isn't really showing me any bad offenders, just .. a lot of shit going on in this frame
maybe a lot of shit going on in the UGUI render pass
You may already know this, but in case you don't, duplicated/created materials, whether it's with .material, Material constructor, or Instantiate, do not get cleaned up automatically unless it's no longer referenced anywhere and Resources.UnloadUnusedAssets() is called, which Unity will also call for you if you load a scene in Single mode. Until then, it will hang around in memory. This applies to all Unity objects. To unload them manually, you need to Object.Destroy them.
The two OnGameStarted callbacks seem pretty hefty
Thanks - good to know, I'll clean that up now.
Yeah, digging into them but it doesn't seem like there's any obvious low hanging fruit. ๐ A game start does a lot of shit.. spine animations, sprite loading, object instantiation, particle effects, etc
is there a better tool to navigate a single frame from the deep profiler? this is a little.. not great
Also FWIW I get this hiccup only once at the start of a level.. but normal gameplay is several hundred moves (for a level) and is super fast. I'm not sure why the hiccup in this frame exists
well it seems to be doing a ton of initialization stuff right?
yeah.. I'm digging.. the tile init seems to take 12-17ms, which is a lot but.. this is a 200ms frame so it's not like.. the worst thing in the world
i suppose i need to clean that up some because it's not unexpected to create 5-10 tiles per turn
like here's a "normal" turn:
is that a single instantiate taking 12ms??
the tile init takes 12.92ms but .. the bulk of that is those 2 material copies - 5.35+5.27
yeah ๐
most of that seems to be the editor drawing the material property drawer in the inspector though no?
oh, good call
Close the inspector window and see ๐
well, i don't have the inspector open on that specific tile
or does that not matter?
i assume that's the problem - this particular library has like... hundreds of editor knobs
wow.. i drill down and it's filled with String.Equals stuff.. i'm assuming the library has some sort of string property lookup nonsense
that's actually reassuring though - this shouldn't be the case on-device
Yeah I think that MaterialEditor stuff can be handwaved away
closing/disabling inspector didn't have an effect on the instantiate time unfortunately
i haven't done any on-device profiling in the past.. not sure if I'm gonna need to but this 200ms hiccup is annoying
aye.. i've been putting off learning how to do it basically forever
premature optimization and all that
you could start with a PC/Mac build if that's at all feasible with your game
but really it's not that bad to do on-device profiling
nah i have a good CICD pipeline for device based builds but.. just have never profiled before so I'd have to read up on how to do it
there's a .. feature that you can connect a unity instance to a device instance to profile, yeah?
the 3 object.instantiate() calls in the 75.79 OnGameStarted call in the middle seem like the worst offenders atm
This has all the info you need https://docs.unity3d.com/Manual/profiler-profiling-applications.html
k, thanks, i'll give it a shot
oh.. this is interesting.. i have a 250ms frame a bit after the level start that's doing some .. FMOD stuff..
I can't tell what LoadFMODSound() is doing - there are thousands of calls to SyncRequest()
https://forum.unity.com/threads/soundmanager-loadfmodsound-causes-a-critical-spike.1182781/
This might be the solution - loading in background for audioclips
That fixed it. Preloaded all audio and it's peachy now. Still need to improve my tile instantiate time ๐ but hopefully that's not an issue on-device. Thanks for the help PB
Hi
I want to somehow block login to my account on the second device (due to lack of data synchronization)
there are 2 options
- a popup is shown on the new device with a message that if you want to log into your account, log out of your account on the old device
- auto logout on the old device and login on the new one
Option 1 requires session tracking
Option 2 seems like it can be done, but then there is a question about implementation
ala request to the server every couple of seconds โtell me which device you logged into your account fromโ, and if the deviceId matches then everything is ok, but if not then we automatically log out the user
2's better, if that's your question (ie, if you left yourself logged in in another physical location but want to play, you shouldn't need to go home to log yourself out)
if you have a server already, track your sessions in a dictionary with device id & connection id, and if someone logs in with a duplicate userid, log out the existing device id (also make sure your client doesn't have auto-reconnect functionality, or at least build functionality to disconnect a user with a reason why and for "logged in from another device" as a reason, prevent the auto-relog)
But wonโt there be a heavy load on the server if I, from a device that has already been logged in, for example, poll the server every 3-4 seconds to automatically log out to check for the presence of another login?
i use firebase auth with my own server (store accounts)
Depends on a million things like how often you poll the server, whether or not the server is maintaining connections and you have some way to identify users based on connection id or whatever. If you are just having some sort of stateless server that takes webapi requests for things that happen in game, then make a login API and don't accept calls unless they're from the most recently logged in device
the only thing my server does in terms of logging into firebase is tying the user's firebaseId to the user's server account
but for a game I made last year, it was tcpip & stateful - users had to maintain connections, and we allowed cross platform play so .. I'd look up the userid from the deviceid (we had some features to link devices so a user could have multiple device ids), and stored connections in a dictionary of connection ids. If a user connected but was already connected on another device, we'd disconnect that device.
i'm not super familiar with firebase but i'm assuming a firebase id is a unique id "per person"? ie, i could log in from my computer or my phone with the same firebase id? And I'm assuming you're concerned about duplicated/desynced user data?
I'd say you should just ignore (and logout the client from) subsequent "save" requests if they originate from a deviceid that isn't the last logged in device
Iโm not very strong in client-server interaction yet, and I want to understand how the server will inform my old client that he should log out of his account? Constantly listening to the server every few seconds and checking some flag??
well i mean, what else are you doing? I guess I don't understand.. if the client is just auth'ing to firebase (and nothing else), what's the problem with multiple copies of the user being logged in?
Like.. I'm assuming you have a client/server architecture for a reason.. like save state persistence or .. just allowing people to play together? There's something your server provides to users, right? ๐ What I'm getting at is .. whatever your server is providing to the users - you have an opportunity to handle all the "who's who" at that surface
If your server stores save files, the client has to ask the server to save it - the server can reject it if it's not the correct device.
If the server handles matchmaking - and a client asks for a game, the server could reject it if it's not the correct device.
If the server has a persistent world, clients will need to ask the server for the state, which again.. the server could reject if the client is making that request from an incorrect/old device.
this is simple chat with bot
i save my messages on server
and i dont have sync when I use two account in one moment
ok so every chat with the bot is going to have some text payload.. just include the device id with it
yes, we have an account linked to deviceId
Is this way normal?
- when you log in on the second device, the server automatically goes through all the accounts from which you need to log out and sets some flag (you need to log out of the account)
- the client represented by Unity polls the server every few seconds and checks this flag; if it is set, then it is necessary to exit
This probably isn't an advanced question FWIW (and I have to go in a moment), but basically you'll need to keep track of the users "last logged in device" (since I'm assuming you're using the firebase ID as the primary key) and .. any requests into your server should include the device id and firebase id with the request - and your server needs to track the state of the most recently logged in device
No, this isn't normal
You haven't really told me about your connection architecture - if you have a stateful/permanent connection thing, then when someone logs into a second device, find the original connection and just log it out.
If you don't, then each and every request should come with the device ID. When a user logs in successfully, you save the "last known device ID" to their user, and you only accept requests from a device id and firebase id that match (ie - users can use multiple devices and devices can allow multiple users to play).
My ML agent does not want to train. and only half of people AI agents start to move (10 out of 126). I attached all of the separetly. Also in Heuristic mode lights does not switch on on pressing on G.
Need your help!
Given a generic mesh made of of a grid of points (and enclosed by a spline) and a getHeight(x,z) function... I want to take that 2d closed spline and fill the space between the area represented by the spline toward the grid of points. Anyone have suggestions how to accomplish this?
Or perhaps, conversely, is there an algorithm to find and fill holes in a mesh with tris?
I have a teammate who deleted a cs file out of the /Library/PackageCache folder and committed it to their PR. The entire directory is in gitignore so I'm not sure how deleting it made it but.. how can I resolve this? Is there a way to force the package cache to be rebuilt? Should I just send him the cs file and have him drop it in his directory?
Just tell them to close Unity, delete the entire Library, and reopen. Unity will rebuild it.
(And of course, fix that commit)
k.. not sure if this is a unity question, even, but I'm puzzled at how it's in the PR when the entire folder is in the gitignore
Yeah that's weird, might want to make sure nothing in Library got accidentally checked in in older commits and no one caught that.
my profiler is showing these spikes is it because of the behavior updates?
I currently have around 200 zombies that use a* to find the player
looks like animation is tanking the most, not scripts
@shy nebula which part says that
Pretty sure this is scripts. Animation has a slightly different color. Also looking at the hierarchy, it's clearly scripts.
You'll need to dig deeper into the hierarchy, but yeah, it's your scripts. It could be the a*, but without seeing the details it's just a speculation.
what? dark blue is scripts and light blue is animation.
No. Bright and dark blue is the same category. It's due to them having selected something in the hierarchy. The selected category is getting highlighted.
Animation is more of a turquoise color.
Anyways, it would be clearer if they share more details
ah ok, sorry for the confusion @outer barn
No worries
I'm getting strings from a JSON (using Newtonsoft JSON), but the trailing zero's are being removed. How can I maintain the trailing zeroes?
What does it look like in jsonArray?
you'd have to write it as a string in the JSON if you wanted to preserve the exact format as written, numbers don't have any inherent format, just a value! if you want to store it as a number, read it as a number in C# and use a format specifier it when you print it like $"{jProduct["Price"].Value<float>():F2}"
It still logs the same value, if this is what you're asking. Sorry, new to this ๐
Thanks il try it
Wouldn't String.Format()work for this too? String.Format("{0:0.00}", 0.8); should make 0.80
the bottom most brown color is Editor. You can see EditorLoop takes 75% of the frame time
!code this isnt viewable on mobile. Also more likely a beginner or general issue based on the description
๐ 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.
What kind of topics would go onto the advanced channel out of curiosity?
usually something slow enough that only a handful of people know
It is hard to classify, you can scroll up and see but if you're not familiar with c# then it's likely at most a general issue
Got it
I always consider it more about the level of the questioner. Are THEY advanced? Then they likely know how to debug and research. If it is a kind of novel or ambiguous issue that thorough research isn't answering, it is likely advanced.
so a mobile build should be more performant as compared to the editor one
Always
It is the same thing, EXCEPT the build isn't also running the editor
Now, the device running the build could be less performant than the one running the editor...
@half swan I added a profile marker and I can see that the path calcualtion is taking up too much resources, since I am using A*
Allocating a 100mb definitely sounds like an issue.
Probably contributing to that cpu time quite a bit.
But you'd use the hierarchy view to see what exactly is the issue. The marker doesn't really help in that regard.
Say, if you guys had to make a dynamic system of weapons attachments, how would you go about routing the references to the main part of the gun?
I have the FirearmAttachment, and it goes on an AttachmentMount, which could be on a FirearmAttachment of it's own, so on and so forth
Actually just pipe a reference to the main body of the gun through those chains? Seems bulky. Let me know if you guys can think of a better way.
And what if, for example, you had a barrel (attachment) and a muzzle device on the end of the gun that reduces recoil. The muzzle device has a reference to the reciever, and then if the barrel gets disconnected then there is just a muzzle in the world still reducing recoil not attached.
Those attachments would all just be toggles on one big script modifying a set of parameters of one an abstract gun. Unless the guns are actually very different, Iโd avoid multiple scripts to โcomposeโ them. But ofc, if thatโs the main focus (instead of stat modification), components is the way to go. Possibly tied together via IOC from a root-gun-system.
Hello, anyone who has worked with Oculus lipsync here?
do unity sub-assets have some kind of key?
when I add something with AssetDatabase.AddObjectToAsset(...)
then when I later want to retrieve a sub-asset I can use AssetDatabase.LoadAssetAtPath<SomeType>(...)
or GetAllAssets and similar
but they only return by type
I'm lacking some kind of mechanism to ensure that there is only one sub-asset with, let's say, key currentSomething
Only the object.name
Hey! One of my students tried building a project where the build failed(got stuck for an hour and then failed, as she explains it) for some reason(my guess is lack of HD space, but since I wasnt there and all the logs are gone I cant confirm) She tried several more times and then tried to troubleshoot by doing a full project reimport. After the reimport, she tried building again, and during that failed build all of her scripting assets and most other local assets simply disapeared without a trace.
Since then, before I was told, she's done a bunch of troubleshooting togheter with her partner, commendable, but it also means I have no logs to go off of an a lot of the cache files have been overwritten by new ones. Anyone have any idea what might have happened, and if there is any binary, dynamic library or similar I can do black magic on to try to get her work back?
They are using version control, but since this was quite a crunchy weekend for them noone thought to commit anything since saturday. I feel so sad for them, but I cant find a fix
Or even know what happened
I dont know if/ how to get back the progress
But good learning experience none the less, version control doesnt do anything if you dont use it ๐คทโโ๏ธ Simply having something installed is not "using version control"
At least now they know for next time i guess?
It's a good story to tell new students and get them to use vcs
If it was out of disk space, I guess it could've written partial corrupt files
And then deleted them after
Yeah in the long term its a good learning experience. I just hate seeing them so down. ๐ญ
Several days of work, a shame indeed, but also a good lesson for the future. Now that they know and remember roughly what they did, they can treat it as a "burned prototype" they can build more solid foundation on though.
possibly investigating Library/Artifacts could yield something
Yeah, the real kicker is that they were aiming for a contest deadline yesterday and were actually building the final submission. But get burned once like this and it never happens again I supposed
This body is made from infinite swords etc
I have a python library that I'd like to use for my Unity-made Android app. Is it possible to run python code on Android via Unity?
Doesn't need to be massively performant
Looked into Android Unity-python interop and it seems a little rough(with the caveat that I could easily be missing a good solution). Could you perhaps run the python library in a separate app(which starts through the same app icon) and then do interop through shared local state cache or something?
Hmm, possibly, but since the output is an audiostream I'm not sure the result would be particularly good. I guess it depends on the bandwith I could get between the two apps using that method ๐ค
In that case my gut reaction is to have the python app do playback and then sync output via timestamps in some way
maybe give visual output a bit of a delay and then just have the unity program write the audio events it wants to a file
or sumthing
then you dont have to worry about bandwidth
its a messy solution
I think I could get away without sync, as it's essentially a text to speech library. A small delay is perfectly acceptable, as long as the audiostream isn't choppy. I could try to just output a .wav file and then read that from Unity, no need to read it as a stream. I'd need a way to clean up the files so I don't bloat the storage, but that should be doable.
I was hoping to find a way to do this via the unity app though, it's a little messy to start a secondary app on the side
Yeah, I'll keep looking ๐
in you own machine, you can start a new python process=>io redirection=>call python process=>listen to stdout=>done
but i am not a android developer and i dont if android os provides such functionalities
so keep waiting....
Hey can anyone help why this eroor keeps occuring, even tho i check if its completed, it still throws this error, is it because if noise job is finished the iscompleted becomes true even if surface job has jus started or wasnt finished
which filename and line number is the error happening at?
how often you call Schedule Job, seems like two instances of GetMeshJob()? write to the native list at the same time
Ye so i've looked and first i was sometimes calling verticeslist.clear write the schedule was being called i've fixed that, there was a second one where i was scheduling another task while the previous was still running fixed that as well, but kinda since it currently just ignores the the following job
But i think thats possible to fix with queue system.
So thanks, for now its fixed ill say
I have used IronPython once in the past for python-unity interop perhaps it will suite your needs too. It was quite some time ago so donโt ask me about dedails haha
I did find some stuff about it, so I'll probably give it a try!
Anyone know why this is taking so much time when I async load a new scene in ? Deep profiling does not show anything else. Is it loading in the audio for the scene ? It does not have that much audio. And if that is the problem how can I check ?
are you loading many scenes in parallel?
xd
what's your loading type on audio files?
Streaming or Decompress on Load?
if you don't have Streaming you may check it out
if it's working for you ofc
(the setting on the audio importer)
try to use Streaming on clips and see if it helps
I should first check the memory profiler maybe to see what audio gets loaded in
I know about the streaming option I believe most of our bigger audio like long running ambiences etc are set to that
I have an admin tool exe (built in unity) that my level designers use. It's got a whole bunch of logging content that is kind of a pain to view in real time - the admin tool doesn't have a lot of visual space (I already have a "console" in it that the users can press to view the log, but the functionality is really rudimentary and clunky). I know that the logs already go to the player.log file but it'd be nice to have it visible in realtime.
Any ideas for .. opening a cmd/terminal window and hook into stderr/out on windows for logging?
I think you can follow the same techniques you would use in a normal C# app. Like this:
https://stackoverflow.com/questions/4362111/how-do-i-show-a-console-output-window-in-a-forms-application
how do people have game logic asynchronously request player input without undue coupling to the UI system? do you have some request queue or something that is processed by a ui manager?
for example, i have a calendar that is executing game events at given times. some of these game events require player input. i don't want the calendar to call the ui. should i have the calendar have access to some sort of "player request queue" that stores events with possible choices and a callback?
The calendar should just fire off events. Your queue thing can listen to the events
As stated already, your calender should trigger events. Depending on how you want to implement it, it could be beneficial to also take a step back: your calender UI is displaying the state of the calendar data i. e. which "apointments" there are (even if not all are displayed to the player), what the current time is, how many and which activities are pending and mandatory, etc.
once the current time reaches an appointment, an event about this state change would notify other systems in your game about this. Maybe this means that a time stopping popup appears to get the player to do something, maybe there is another notification. The Calendar icon (assuming you have one) could now indicate that there is a mandatory activity in the calendar (if there is one) so that the player can click on it.
In the calendar, the appointment could be highlighted to indicate pending input from the player.
Keep in mind that I made a few assumptions about how this could look like, and your game might look different from this.
The way it's implemented right now, the calendar records GameEvents (custom class) into a SortedList and pulls them off and executes their "execute" method when the time comes. What it appears you guys are suggesting is that, in addition to this, I should also fire off a "GameEventExecuted" C# event every time this happens. The GameEventExecuted event can have signature (delegate) Action<GameEvemt> and thus pass the game event that was executed so that anybody who cares about this GameEvent can examine it and determine what to do.
Hmm, connecting some sort of UI manager/filterer to this singular event and filtering all events based on whatever desired criteria is probably a good way to delegate the events to appropriate UI elements without having the engine know about the UI.
Thanks guys.
I'm .. experiencing something weird, and not sure if I'm missing something obvious.
I'm instantiating this prefab and fiddling with local position, scale, etc. Sometimes it works, and sometimes it doesn't. I seem to have narrowed it down to whether or not the parent is active, which is weird, because there's no layout/fitter stuff in this object or anywhere up the hierarchy.
Any ideas what would cause the following code to place this object in a different place based on whether or not the object is active when this code runs?
_spineCrew = Instantiate(SpineCrewDatabase.GetSpineCrew(crewType), SpineCrewContainer.transform);
_spineCrew.SetState(CrewState.Idle); // animation stuff - doesn't touch location
_spineCrew.transform.localScale = Vector3.one;
_spineCrew.transform.localScale = Vector3.one * 1.6f;
Vector2 pivotedPosition = _spineCrew.GetPivotedPosition(); // code pasted below
RectTransform newActorRT = _spineCrew.transform as RectTransform;
newActorRT.anchorMin = new(0.5f, 0.5f);
newActorRT.anchorMax = new(0.5f, 0.5f);
(_spineCrew.transform as RectTransform).pivot = new(0.5f, 0.5f);
_spineCrew.transform.localPosition = Vector2.zero - pivotedPosition;
_spineCrewLocalPosition = _spineCrew.transform.localPosition;
// Gets a "center" of this object based on the pivot - I use this to focus on the "nose" of the character
public Vector2 GetPivotedPosition()
{
Vector2 diff = (_originalPivot - new Vector2(0.5f, 0.5f)) * transform.localScale.y;
float y = diff.y * 350;
float x = diff.x * 175;
Vector2 ret = new(x, y);
return ret;
}
nothing in the above block seems like it should depend on the game object being active or not
wait.. i'm dumb, I have some init in the prefab that sets _originalPivot. ๐คฆโโ๏ธ
thanks rubber ducks :p
does Camera.rect get temporarily set to 0,0,1,1 while rendering? I'm trying to read it in RenderPipelineManager.endCameraRendering but it always returns 0,0,1,1 even though I set it to different value before
Hi All, I've implemented a function to check if four same colored(tag) crates form a winning pattern Diagonally, the win condition should be met, the problem I'm facing here is that, I have a 7 column and 6 rows grid array, the win condition is perfectly triggering in " \ " this diagonal direction. However, it's not triggering the win condition on " / " this direction, can someone please look into the code below and tell me what could be the possible reason behind?
private bool CheckForDiagonalWin(string crateTag, int startX, int startY, int startZ)
{
// Check diagonal
if (startX <= gridSizeX - 4 && startY <= gridSizeY - 4)
{
for (int i = 0; i < 4; i++)
{
if (gridArray[startX + i, startY + i, startZ] == null || !gridArray[startX + i, startY + i, startZ].CompareTag(crateTag))
return false;
}
Debug.Log("Diagonal \\ Win Condition Met!");
LogWinningCrates(crateTag, startX, startY, startZ, 1, 1, 0);
return true;
}
// Check diagonal /
if (startX >= 3 && startY <= gridSizeY - 4)
{
for (int i = 0; i < 4; i++)
{
if (gridArray[startX - i, startY + i, startZ] == null || !gridArray[startX - i, startY + i, startZ].CompareTag(crateTag))
return false;
}
Debug.Log("Diagonal / Win Condition Met!");
LogWinningCrates(crateTag, startX, startY, startZ, -1, 1, 0);
return true;
}
return false;
}
!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.
thats why i dont recommend early return
Is this for me?
I'm sorry, I'm new to this channel and don't understand too much of coding words.. Please accept my apology. Please help me with the issue I'm facing
Might wanna stick to code-beginner then. Btw dont cross post. Have some patience
private bool CheckForDiagonalWin(string crateTag, int startX, int startY, int startZ){
// Check diagonal '\' pattern
if (startX <= gridSizeX - 4 && startY <= gridSizeY - 4){
for (int i = 0; i < 4; i++){
if (gridArray[startX + i, startY + i, startZ] == null||!gridArray[startX + i, startY + i, startZ].CompareTag(crateTag))
return false;<--early return...
}
//other codes
}
// Check diagonal '/'
//other codes
return false;
}
Do you want me to create seperate methods for both? // Check diagonal \ && // Check diagonal /?
yes
if first one fail then it will check the second
if both fail then there is no '/' or '\'
Thank you so much
I've been stuck with this problem for a long time today , you have been my savior ๐ฅฒ ๐ฅน ๐
Apart from the suggestion you gave to use two methods, was there any other issue with my code or is all good?
if (gridArray[startX + i, startY + i, startZ] == null||!gridArray[startX + i, startY + i, startZ].CompareTag(crateTag))
```to
```cs
GameObject obj=gridArray[startX + i, startY + i, startZ];
if(obj==null||!obj.CompareTag(crateTag))
```to prevent you forget to change the way of calculating coordinate in future, eg
```cs
if (gridArray[startX + i, startY + i, startZ] == null||!gridArray[startX - i (not + i), startY + i, startZ].CompareTag(crateTag))
I'm learning on my own and making game projects to become a professional game dev and it's overwhelming to see and understand coding language but I've now completed two game projects successfully and help from you kind of people is huge for me, thank you so much once again for everything ๐ฅน
Please be my mentor, guide, guru and guide me ๐ฅน ๐
you can ask for help from the others in other coding channels
what did your research turn up?
All I can do is create a dll file but still be able to view my core code
It sounds like you haven't started the "try to answer your own question" part of the research
I don't think it's polite to ask a person to be your mentor, simply because they helped you once
As in, if somebody decompiles your project, you want him to have a hard time figuring out what you've done?
The term your looking for is Obfuscation, probably
thanks bro
You be clear, it's impossible to hide anything. You can only make it slightly more difficult for people.
You're welcome, I never researched anything in that direction, but I know there are some assets for that (read reviews first xD)..
Also, this doesn't make your project "secure" by default, people with the skills and the motivation will still be able to reverse engineer your project without a doubt
Sorry, maybe my English is quite poor and I will try to improve it in the future
I looked for it, but it seems to be the part I want
You had no issues with your English, I'm just letting you know that if someone wants to modify your game, they can
I'm trying to find the problem I want, specifically I have created a function and people who code in the same project as me will be able to use it but I don't want them to see it, what should I do?
Oh, that's a whole different thing..
Why wouldn't you want the people that work on the same project to see your work?
That's probably harming their productivity
I want my code to be protected from others when developing games, I don't want them to see it
Yes, I understood that, but why..
I'd almost guess you're not using any version control?
There are some functions that I developed for a long time and I don't want them to know about them
It took me a lot of time. If they found out, the values โโI worked on would be taken away in a way that made me uncomfortable.
Dude.... Please.... Give me the why .
If they work on the same project as you do, they should be able to see your stuff
I doubt that it's that big of a thing as you think
Well, maybe I didn't make it clear, I did create modifiers on the editor, changes for the attributes, it's quite flexible and I don't want it to be stolen.
Idk if it's possible to obfuscate a single .dll and include that obfuscated .dll in the project and have it still working
But that should be your direction of research, if you're serious about that
Sounds.. suspicious. If you are working on a project with people, theres nothing you can really do about it. And I doubt people would wanna work with such style where their team members are hiding functionality.
But, if they work on the same project as you, you should just trust those people or let them sign a contract
100% this ..
Imagine the chaos when theres a bug and you cannot even check stuff like the editor scripts or attributes that may be affecting it
The editor codes that I code, I think maybe after the project they can use them without me being able to do anything
Yes.... They can't do their own troubleshooting when something interacting with your specific functions doesn't work, you gotta do the troubleshooting and understand their code and intentions
Even if you obfuscate it, they can still keep a copy paste of that .dll and use and/or sell it, they just can't modify it easily
And even if you put some kind of copyright comment or whatever into the files, doesn't matter because 1. It's obfuscated and 2. Probably stripped from build anyways
The best advice here is probably, don't take this as an insult.. Do not work with people
I think I should adapt to it
if you're paid for that work, creating artificial obstacles like that sounds malicious
and if it's something you developed in your own time and you want recognition or compensation, best way to go is making it open source (for recognition) or publishing it in an asset store (for compensation) imo
There is only one way to do that. Do not share the code. Do not use it at all in any project that you are doing with other.
stop naming variables and use alphabetic naming like in competitive programming to obfuscate your code
i sometimes dont even understand what my code does
is there a way to do this in one line without using &&?
GameObject object = transform.Find("X").gameObject
if(object) object.SetActive(false)
You would not WANT to do it jn one line
And don't use Find
- no I don't think so (in any clean way)
- don't use Find
why no find?
ok yeah that's what I thought rip
- it's slow
- prone to typos
- relies on names (doesn't work if you change the name of the object later)
are you referring to gameobject.find or transform.find for your first point?
actually I thought you were using GameObject.Find but I think it applies to Transform.Find as well
I think both of yall thought I was using gameobject.find lol
I don't think it would apply to transform.find
should be the same speed as getcomponent
only searches the children of the transform
I was not
that I'm pretty sure isn't true
yeah true string comparison
but not nearly as slow as gameobject.find
which I never use
why shouldn't I use transform.find
genuinely curious
just the string comparison making it super slow?
Logic relying on names is generally gonna be an anti-pattern.
Is the child added at runtime?
no
yeah, I wouldn't say string comparisons are necessarily that slow or bad coding practise but relying on gameObject names isn't usually very good practise
Then do a serialized reference
yeah that might work ๐
If you can, it is always the preferred choice.
If you cannot, at least try to pass the reference via the instantiate return.
the thing is there's a lot of gameobjects with that script
so if I set a reference at on start/awake, I feel like that might decrease overall speed (load time) versus if I just do the 2 liner every couple seconds max
If it was a non Unity Object, you could do:
transform.Find("X")?.gameObject?.SetActive(false);
(You could also do that if you know that your object will never have a reference on a destroyed object)
Serialized reference is drag and drop
ok thanks a lot
yeah I thought there was some sort of exclamation mark thing for this
I'll try that
No. Don't...
You clearly do not know what could go wrong.
I know that
but when I have over 100 gameobjects with that script that isn't ideal for me
what can go wrong
Unity is overriding the null operator. If you destroy an object, you still have a reference to the object but unity will says that the object is no longer valid.
what if the object is never destroyed?
You could create an extension method
public static GameObject FindAndDeactivate(this GameObject gameObject)
{
//Beware that you could have a null exception with you current code if you do not find the object and that object is not a valid name.
GameObject object = transform.Find("X").gameObject
if(object) object.SetActive(false)
return object;
}
Yes, but no. The only time that the object will be destroyed you will lose 1 week of your life.
what
The error is not obvious, when you are going to hit it, you will probably search for a long time.
I'll roll that dice ๐
What have I done.
Why even risk it with string based names? Serialize field here is the best option by far.