#archived-code-advanced
1 messages Β· Page 151 of 1
hmm yeah I think it doesn't
are we allowed to create topic conversations?
yes
Do you know any other way to achieve something like this? Editor Scripting ?
deifnitely possible with editor scripting, yes
For example I think you can use this https://docs.unity3d.com/ScriptReference/AssetPostprocessor.html
Oh great, thanks. I will look into it
Grid System with ExecuteInEditMode
My game just got stuck in an infinite loop (very hard to reproduce bug that players report, it rarely crashes/freezes). I'm trying to use the Visual Studio for the first time and I can't seem view the source while debugging/stepping (but I can see the Disassembly). I can't close Unity since it's hard to reproduce (I see this extremely rarely)
I get the error "The current stack frame was not found in a loaded module. Source cannot be shown for this location." when I try "step".
is your Visual Studio configured properly?
I attached to my game process (Unity.exe - Game is the title).
Do you get IntelliSense?
Like the auto suggestions as you type code
Yeah I got those
It's attached I think (Unity.exe - Game) because if I unpause I hear the music, if I pause it stops the music
but the Unity editor is frozen, so it's inside an infinite loop of some sort I believe
Something's off about your debugger
you should be able to just set breakpoints in your source code, and when you hit play it should attach to unity automatically, you shouldn't have to select a process
unless you're debugging a build
I.e. it should look this way
I'm debugging my Unity editor in play mode
then you shouldn't have to select a process
nope, I just looked into debugging the first time my game froze on me
you need to set breakpoints in the code
it's really hard to reproduce
oh
It happens extremely rarely, like once every few days of development hmm
so without breakpoints, I won't be able to view the source code?
then the debugger will stop there when the game reaches that point in the code
Mmm, I can take a look at that but I don't know where it freezes, could be anywhere
so not sure where I can put this breakpoint if I don't know where the loop is
How many loops do you have π
what are you doing in your game when the freeze happens?
Well, it could be infinite recursion or anything, no idea π I'll set some random breakpoints in
and hit play
no
infinite recursion will not freeze the game
you will get a stack overflow exception
oh yeah true
I'll search "while" and set a breakpoint for each while
Possibly something wrong with my project, I'll do a quick search
something seems weird about your Unity <-> Visual Studio connection
probably yeah. I tried attaching to unity instead of via process, but it's a bit odd. I think I'll mess around with a debugger tutorial or two to make sure I'm ready the next time I come across the hard to reproduce bug
Thanks anyways for the help, I'll prepare myself. The debugger looks really nice on YT, should've learned it earlier
P.S. I managed to find the cause of the infinite loop by forcing an exception to be thrown by changing a value in the register (credit: https://blog.unity.com/community/breakout-how-to-stop-an-infinite-loop-in-a-unity-c-script). Now to learn the Unity debugger properly so I can debug things properly in future
damn that's even cuter that what I normally do (just throw an exception from the immediate window)
I have a project compiling to a 4.7.2 framework DLL that contains all my domain models and utilities. I was considering putting my services here since I now have another project (Blazor admin tools) that needs these services (ie - Cosmos DB). However, I have a Unity project that doesn't need those services (and in fact specifically might have issues with it).
Should I make a second shared project for these services?
Current structure:
1) Shared (models are here currently)
|
+ -- 2) C# Server (services are here currently)
+ -- 3) Admin tools (new project that needs services & models)
+ -- 4) Unity client(s) (existing project that needs models but not services)
quick q about rpcs in unity netcode
for something like stats, only the player who has the stats will ever need to know what they are - if the stat variables are made into network variables on the player object, Iβm assuming theyβll be updated for every client, right?
if so, are rpcs also sent to every client, or just the client version of that script?
RPCs can usually be targeted to a specific client when supplied that client's ID in the method signature, Network-/SyncVariables are usually not targeted as their main purpose is to sync state rather more persistently (i.e. data that would be relevant for clients that join later). Think of RPCs as transient and vars as persistent and their respective features being motivated by this classification.
You can however put certain sync vars on a network object that is only visible to a subset of all clients. Then those sync vars will only be updated on clients when the object is visible. This behaviour may depend on the implementation of visibility/syncVars in your chosen networking library/framework.
I got stuff to randomly spawn within a 1000x 1000 area, now how to i make it so it only spawns on a tile
@hexed bay like aligned to a grid, or only on specific types of tile objects?
a grid is easy.
int gridsize = 2; //size of tiles
Vector3 pos = transform.position;
float newX = Mathf.RoundToInt(pos.x/gridsize)*2;
float newZ = Mathf.RoundToInt(pos.z/gridsize)*2;
float newY = pos.y;
//float newY = Mathf.RoundToInt(pos.y/gridsize); //if you also wanted to align vertically.
transform.position = new Vector3(newX,newY,newZ);
//example: 5.5; 5.5/2 = 2.25. 2.25 rounded is 2. 2*2=4; had it been 5.6, it would've been 6 instead.```
Does anyone know why public delegates and events might not get recognised when using DLL in Unity, but works just fine in regular .net project.
I'm not sure what I should be looking at here, the delegates are declared in the top window, but I don't see the relation to it in the bottom window
Also you have invalid syntax in the bottom one, the constructor must declare a body
The bottom is the metadata unity has generated for the dll.
Ah, alright
Are they only absent in the metadata, or do you get compiler errors when trying to reference them?
Yeah, the compiler generates errors based on the generated metadata IIRC.
I can't find any similar issues on the internet, and delegates get decompiled well on my end (using https://sharplab.io)
You could use a real decompiler, or enable the one in Visual Studio (settings, navigate to decompiled sources) to see if they got generated
Yeah, that's what i'm messing around with right now as well.
It doesn't seem to be represented in the dll at all?
But I am able to use it on my other test project without errors.
It must have something to do with compile settings since my other non-unity test project is using visual studios reference system; this is the only thing I can think of.
Ahhh
It was optimized away...
That's weird, the delegates and events are public and contained in a class that is public. If they were internal to the assembly and nothing used them it would have made sense to optimize them
Just anywhere on a tilemap
Oo
Idk why, but disabling optimizations helps.
hello, i have a little problem with unity event
i have an event (event1) i want to copy the event of this event1 in an other event2 from the inspector, so i've made a button
The problem is that, when i copy the event1 to the event2 (juste like event2 = event1), it copy the data, but now event 1 is link to event2, so if i modify event2, it modify event1 too
does anyone know how to solve this ?
i didn't understand it clearly but
try using a temporary variable so the main ones can't connect directly
already tried temp vars, it didn't work
to my mind, it copy the memory adress of the unity event, not the unity event
you are correct, you are just setting t he "memory address" of the variable to the event (it's called a pointer, but we don't really use that term in c#)
If you want to "copy" the event then you need to create a clone of it
(which you usually don't do for things like events)
what are you trying to accomplish?
i have make my own "timeline signals", because the unity signals was not really good for my use
So when i copy paste one of my marker (i call it like that), it copy past the data too, and the data is unity event
so i need to create a clone of the copied marker"s unity event
I don't think there's any nice way of copying UnityEvents without using reflection
yeah, after some research, every topics was speaking about reflection, don't really know what it is but i think i'll have to learn this
UnityEvent has two lists of callbacks - one is the AddListener method that uses a non-persistent C# deelegate, and the other is the persistent callbacks list. You can only add persistent callbacks from the GUI
You can read persistent callbacks data from the UnityEvent, but not add one
okay, thats a good infos to know
2 hours later... Reminder: don't ever move script assets around outside of Unity (and delete the .meta files) because Unity won't be able to tie those scripts to prefabs/objects and you'll have to manually readd them all.
Also always use version control and commit / checkin frequently so you can undo your own dumb mistakes
or be like me and have your production game backed up in a zip file on onedrive and nothing else
in that case, try to subscribe those delegates in the dll itself once to an empty function, do a compilation once(with optimizations) and then check if that works. It should most likely
Is it reasonable that there are errors in build that do not show up in editor
for following conditions:
- I'm running exact same C# code
- I'm running on a well supported platform Windows/Linux
- I'm not using IL2CPP (added)
No. Runtime errors can occur because of stripped code, which could be because of IL2CPP or various other reasons. I'm sure there's more.
well good you mentioned IL2CPP, if I add that to the list of restrictions: see edit ^
what "other various reasons" are there?
I would like to get a build to a point where I can say "the code is supposed to behave almost certainly like the code in the editor"
It would be easiest if you just describe what error you're having and the scenario it occurs in instead of covering all possible bases.
who says I'm having an error
If you make a build send it to someone they test it and get an error
wouldn't it be great if you could send another build that is "supposed to work" as a methodology for narrowing down?
You would know what the error is so you would go from there
even if you have a clean stack trace available
that does not mean you know the reason of the error
There are many differences between the many different target platforms that Unity supports
the goal for me is narrowing it down
That is one source of errors
exactly
Sure, but not knowing anything about it at all doesn't help narrow anything down, asking for an exhaustive list is unreasonable. Maybe someone else can be bothered, but I certainly can't.
that's why I'm figuring whether there is one that is closest to "ground truth"
Another source of error is different framerates, resolutions, and device capabilities of the running hardware as well
not sure if anyone could give an exhaustive list, but if the mentioned would include 99% of cases that would already be a win for me personally
I make no guarantees of that
You will never be able to make 99% visible to debug against. By the time you include the current state, which will give you months to years of work, there is new stuff coming up which will again add up. Thats some romantic belief, that we can avoid any circumstance in development, but not reality π Find your target audience, find the most used devices/platforms or what not, and go from there.
if i include a dll i made in net5.0, should unity have no issues with it?
okay thanks
...I'm really starting to hate the unity compiler.
Ah yes, I sometimes get the same. VS is like "hey use this nice syntax to simplify", but it fails to compile in Unity because it somehow can't get the .NET version being used
I've had that be weird before with ternaries. This is making me do it differently though. Either with remainders or replacing the whole switch with a chain of ifs. Really thought it'd have this.
Maybe with a switch expression if you can adapt the code
Yeah, I thought pattern matching was only valid in switch expressions, not statements? I've not found an authority on that, though.
The ms docs seem to show it as fine.
Ah, no, I've found an example in the docs for statements too.
Yeah, just found that one. I guess it is fine, I just haven't seen it anywhere else.
I'm also wondering why you have to use constants, since it seems to say that was only in version 6 and earlier.
I think the values must be constant because of the limitations of the IL code, where it branches (jumps) if some condition is true.
But it was fixed in later versions maybe? I don't remember
Oh yep, the issue being that Unity doesn't use the same runtime as dotnet, and some features are unsupported
Non-constant values might be one of them
Relational patterns were introduced in 9.0 iirc
2022 might have access to that syntax, but I'd have to give it a go. I also thought it only worked in switch expressions
Ah, you're right, they're on the 9 spec. I guess I was just confused since they're in some examples that seemed to be specifically talking about how patterns with introduced in 7.
Fortunately unity is in works to update the runtime for net 6.0. release is probably soon-ish
Ah good
Was about to ask if and when they'll eventually drop Mono for the mainstream .NET, since it's now open source
They'll first update to latest mono. Then after a few more months they'll also bring experimental coreclr support
unity can't handle standard 2.1, only 2.0
Yes it can
IIRC 2.1 support was added around 2020
2021
Oof, that late?
anything thats not in LTS is kinda pointless to argue about
Why
Late as in netstandard 2.1 is quite old
And most serious devs are on LTS unless they're still early in dev
Yeah. But even Roslyn itself only targets net standard 2.0
Even if they target netstandard 2, doesn't mean you shouldn't support later versions...
unity was stuck on really old .net APIs for over a decade, their support for new stuff in NET has improved by leaps and bounds... so i'd stop complaining so much, their focus on stability is commendable
That doesnt work. You can target a later version and can write things in standard 2.0, but it doesn't work the other way around
I feel like there's some miscommunication here
Unity as well as net itself is unfortunately plagued with 'backwardscompatibility' bullshit. I'd rather have my whole project break because I am using old ways of doing things rather than having it still work even if my coding approaches were flawed.
Wdym then?
Hi, does anyone know how 2d Platformers such as Towerfall or celeste, handle Actor-Actor collisions? Do they use a grid and check all possible collisions? do they check collisions while moving like they do against solids? do they sweep check collisions after moving ? thanks β€οΈ
probably with regular colliders?
Typically a physics engine will do a broad phase check to gets lists of bodies that are potentially close enough to collide, then do different kinds of specific collision checks depending on how those bodies are set up. But I'd say it'd be relatively rare for a 2D platformer to write its own physics simulation these days, since Box2D is free and very time-tested.
(To be clear, Unity's 2D physics uses Box2D internally.)
yeah, i guess my question is when are the collisions calculated and who calculates them
the Physics system in sync with FixedUpdate
Yeah, as far as I know 2D physics will do it in the "Internal Physics Update" step, same as 3D physics: https://docs.unity3d.com/Manual/ExecutionOrder.html
so then i should move using physics.velocity, and try to get the contact points to move back the actors to where they collided
Why is this sounding like you are using physics but still want to create your own physics
Well in the end you will do the same as Unity is already doing
if you use a kinematic character controller you probe for collisions manually and resolve them via the collision info you get from the collision tests you do/receive... they are basically resolved in that data but not applied yet.
if you have two kinematic actors, you have to enable kinematic collisions between them in physics settings and deal with the collision separation manually... or let the physics engine handle that temporarily if you want simulated physics for that response
So lets say like in super mario, you squash the goomba when jumping on it
goomba and mario, at a basic level, are just movable platforms to each other, with some extra features
during on collisionEnter you would get the contact points, see if mario was on top, then move mario back to where they made contact the first time and then kill the gooba and make mario jump?
Or just do a rigidbody.AddForce to it so it jumps up after collision tag == "Goomba" for example. lots of ways, depending on your game mechanics
I'd simply put a collider at the top of the goomba to cause it's destruction and players bounce.
hollow knight does its movement largely with physics and some tweaking of the forces on certain events to get the right 'feel', better jump curves etc.
Where the body of the goomba's collider would hurt the player instead.
the problem is when 2 objects move towards each other and they collide but go through eachother
the "collision point" becomes unreliable
raycasts may help
Well you either use collision from physics to prevent that or when on collision, get their directions and prevent them from moving in that direction, but I would just go with physics. still depends on your usecase
it depends on how you want your game to feel really
so in this case each object check for collisions in the direction it is going?
They ought not be going through each other unless they're traversing as great speeds.
yes, and you define explicitly how they respond to it, if that response is just how they would respond with regular collision sim, then use that
they are kinematic at this point
even if they are not traversing they end the frame at different points each time
that may be because physics aren't deterministic
Ah, Kinematic (jumped in without the full disclosure - reading past posts).
it boils down to this: kinematic == total control, simulated physics == easier to get things moving.
yes, it will in any case be kinematic
the question is> use physics and resolve what happens during OnCollisionEnter
or
raycast and resolve as we are moving
in both cases you can use physics of course, but i just mean "OnCollisionEnter"
well, onCollision gives you info what has happened, and raycasts give you information what will probably happen relative to input and your knowledge of your game-design... you design your system from there
But oncollision is not a thing with kinematic bodies, right
ofc it is
yes
you can make kinematics receive collision information... just have to enable it in settings
"Collision events are only sent if one of the colliders also has a non-kinematic rigidbody attached" is wrong then? π
you have to set in settings
Is it the static pairs setting?
yes for 3d
i don-t know if it-s enough with "Use full kinematic contacts" for 2d
on the rigidbody2d component
well, raycasts are more useful anyway
yeah, i already do that, so it would make sense to use that method
i do it for level geometry
the problem with that is that the actor that gets processed first, gets to move more than the other
π
well, you can work around that... you don't have to process the data right when it arrives, you can collect it and resolve 'later' when all info is available
the physics engine internally resolves collisions iteratively... there is really no other way since collisions resolution can't be calculated by a closed formula in the generic case
but you can create a special case for your game where that might be possible, as you can control all the constraints
ok, i'm gonna try both approaches, and see which one feels better and is easier to implement
thanks for the help @compact ingot @midnight violet @orchid marsh @small badge
β€οΈ
I'm running into a search-wall.
I'm generating prefabs from FBX files using an editor script.
If the FBX has been updated, I want the editor script to check if there's a previous prefab for that FBX, and copy its components onto the newly generated prefab (to handle changes made to the prefab since it was generated from the FBX). I have this working, but with one problem: internal references become null through the copy.
Simplified version:
Create a gameobject with a child gameobject. Make two separate prefabs of that object. On one of the prefabs, add a script to the parent that references the child. Copy that component from the prefab and paste as new component to the other prefab. The child reference will be null.
I want to use an editor script to perform this copy, and preserve this child reference, by using the gameobject names figure out what internal prefab references should go to what thing. When I convert the component on the first prefab to json, its references say instanceID:0.
Any ideas?
I'm assuming instanceID hasn't been set because the objects aren't in a scene. They're just in a prefab. But there's got to be some way to check the internal references in the prefab and reproduce them in another.
Hi there, does anyone know a way to make an "create asset" menu for scriptable objects?
Like if I right clicked on one of mine it would say something like "create clone"
You have to add an attribute to it. CreateAsset or something.
aight, Ill check that out
Suppose a shooter game. We have two types of states, states related to logic and states related to animations. To make a decision or doing something based on (preconditions), sometimes we need to know the states in logic and sometimes in animations.
An example:
A player can be equipped or not (armed/unarmed). When the player is equipped, the logic related state changes instantly but the animation state changes to equipped when the equipping animation ends.
Now, imagine a situation that the player would like to fire. The precondition of shooting is equipping. Here, we should consider equipping animation state (After equipping finishes completely, now the player can fire)
They can be non synchronized. Do you prefer to synchronize them?
How do you distinguish between them?
Scripts which are views, should interact with animation states not logic related states?
Scripts which are views, should interact with animation states not logic related states?
what do you mean by this?
I agree, it is vague, forget about it
In my example, when equipping is a precondition to do something, I think almost always, I want to work with animation state when equipping animation completes then do ...
im kind of confused because it sounds like you have it figured out already
Hello I am working on procedurally generated terrain using a marching cubes algorithm, and while my alhorithm seems to work when I go to actually create the mesh unity seems to refuse to draw more than 4 triangles am I missing something or doing something wrong I've tried searching all day and could not find any information
here is the code where I assign all the vertices and tris (I also create sphere primitives at the vertex's positions for testing)
void UpdateMesh()
{
mesh.Clear();
mesh.vertices = vertices.ToArray();
mesh.triangles = triangles;
foreach (Vector3 v in mesh.vertices)
{
GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
sphere.transform.position = new Vector3(v.x, v.y, v.z);
sphere.transform.localScale = new Vector3(0.1F, 0.1F, 0.1F);
}
mesh.RecalculateNormals();
}
here's what it looks like in game
I've tried many different arangements and no matter what it will not draw more than 4 triangles
Make your area a lot smaller
Like 2 grid slots
And reason about the vertices and triangles
Are they correct?
like this ?
Yes
correct in what way
Are all triangles correct
well yes as you can see
Well, what's wrong in your triangle array?
Something must be
I feel stupid now this definitely looks wrong I looked at it earlier this is not supposed to loop
well thank you I know what I'm doing wrong now
moved some code around forgot to change that line...
the only issue now is that the normals are reversed is there a simple way to fix that ?
nevermind I just had to invert a condition
thank you for the help
This seems like more of a question of game design than code? I think it depends on the type of game. Personally I think most games feel better to play when they use the logic state to determine what the player can do without forcing them to wait for the animation to catch up, but sometimes slower-paced games will want the opposite. Obviously in the first case that means your animation state needs to be able to cope with receiving logic changes faster than it can handle them.
The initial post said it was marching cubes (i.e. implicit surface to trimesh), so no, not a triangulator (which would be set of points to trimesh).
I didn't read the whole thing
Hello. To get a list of all objects of a certain type, active and inactive from the current scene the Docs says you can use Resources.FindObjectsOfTypeAll https://docs.unity3d.com/ScriptReference/Resources.FindObjectsOfTypeAll.html
They are filtering objects in scene like this:
if (EditorUtility.IsPersistent(go.transform.root.gameObject) && !(go.hideFlags == HideFlags.NotEditable || go.hideFlags == HideFlags.HideAndDontSave))
objectsInScene.Add(go);
The problem is that the EditorUntility is in the UnityEditor namescpace and the script wont compile for a final build unless moved to the Editor folder which would remove it entirely from the build
So how can I go around this?
Thanks
what type of objects are you trying to find?
a specific type
like all Gameobjects or all "MyEnemy"
then myClass could put itself in a static list of MyClasses when is spawns and then eveyrone can acces the list
as a way around i mean
because it has to be active and inactive
is it spawned?
is loaded but not active in the scene
by something or just exists in the level?
thus Awake nor Start wont get called
how is it loaded?
Player input that will create a specific type of object based on Player's hardware
and it loads in a thread
so I cannot immediatelly know if it loaded
ok, i'm not sure i understand sorry. I would guess that in this thread at the point where the class is loaded you would have a reference to this class and thus could put it in a list. But i probably don't understand how it is working
it is a closed API in a dll
All I can do is call the API and it will generate the objects in scene
i see
I do get a callback which is where I am hooking the logic to find all of them
but some of them are inactive, and I need to add them to the list too
and you get the callback for all of them or just the active ones?
I get a callback when it finished creating all of them, but I dont get any params in the callback
Hence I need to find them myself
but why cant u use this? https://docs.unity3d.com/ScriptReference/Object.FindObjectsOfType.html
use FindObjectsOfType with the includeInactive bool to true
yeah thats what I am using
but it returns objects not in the scene but also in the project files, like the prefabs
mmm it says it shouldnt return prefabs
oh my bad, you said Object.FindObjectsOfType
arent u using Resource.
yeha I tried that one too
yeah
what
but the flag is only when parents are inactive but the object itself is active
if the object itself is inactive it wont be returned
FindObjectsOfType takes a boolean parameter. Passing true will return inactive objects aswell
it will return active and inactive objects. Are you saying it can't find children in inactive gamobjects? (Znel)
it works for me
Im trying it again to check what is the issue with it
also about the callback, what parameters are passed in it? if it's a good library it should surely have some sort of reference to the gameobject(s) or behavior(s)
everything inactive both script and gameobject and still finds them
indeed is returning all the prefabs
nice
but I dont want the prefabs
ahah
just objects in the scene
yeah
it doesnt return it on my pc
I also tried:
if (go.hideFlags == HideFlags.NotEditable || go.hideFlags == HideFlags.HideAndDontSave)
continue;
if (go.gameObject.scene.isLoaded) continue;
To filter them
but still get returned
yep
not possible.
Show us the code and also tell us how you're so sure it returns a prefab
I mean for this
don't use Object, nvm it's just extra specificity, still returns Object[]
and how are you sure that a prefab is being returned?
I hope by Prefab, you mean a reference to a prefab in script, and not a prefab which is already in scene
Then after this runs I check the list on the inspector, I click in one of them and it points to the project folder and selects the prefab
The list is popullated with almost triple objects that are actually in the scene
sorry im jumping into the convo late, what do you mean you want the prefabs and not the objects?
If true that would be an editor bug, as the docs specifically say that Object.FindObjectsOfType() will not return assets. You're probably not going to find an alternate function that doesn't return assets because that is the function that doesn't return assets.
Its backwards, I only want to find objects of type in the scene but not the references to the prefabs in the project files
I know is a prefab because when you right click on it in the inspector list
there is an option to copy the path if it is a prefab
when you copy the path it copies the actual path to the prefab
versus if you right click on the item when it is not a prefab, the copy path option will be grayed out
what editor version are you at?
yeah that code looks right to me
2020.3.19
pretty much unlikely to be an editor bug.
one way to confirm it is by checking parents name recursively until null
let me write some code for it
but anyway
im not sure what you mean about copy path
but if you right click on it, it has the prefab context menu as well?
if u use: gameobject.scene.isLoaded it should tell you if it is a prefab, so that is strange
yeah and that function explicitly says it will not return that stuff
another way to confirm if it's an asset is by calling Destroy function. unity throws an error.
you can also try to reparent the prefab from the reference. unity throws an error if it's a prefab.
have you tried asking it nicely
Or go right to the source, PrefabUtility.IsPartOfPrefabAsset().
Alright, good news is that it works and it was a false alarms, Object.FindObjectsOfType(true) only returns references to objects in scene as expected
The bad news (not really bad) is that I wasted your time due to a VS issue, I hate VS that sometimes it wont sync immediately the code with Unity
but all good now, thanks everybody
glad it works
I see, so the includeInactive was introduced in Unity 2019.2
That is why when I tried Object.FindObjectsOfType back then it wasn't working for me
and now that I am revisiting this code I can use the new includeInactive flag, that is great
@cosmic basalt Don't post off-topic images.
I'm trying to understand 2D Collisions. Namely i have 2 BoxColliders moving Through each other and i want to find what position they are at when colliding
if i call OnCollisionEnter it only returns the position at the end of the frame (when they both have passed each other)
you don't call OnCollisionEnter, and its the position after the last physics update, physics are frame independent
if i use contacts i have the contacts but i don't know how to get the position of the objects
you get the position via Collision2D.transform.position
how would you go and find the position? i tried raycasting but it has the same problem
where do i get the collision2D
?
MonoBehaviour.OnCollisionEnter2D(Collision2D) https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionEnter2D.html
you get it automatically when the collision event method is invoked
but the transform position is after the objects have moved
it returns the end position of each object not the position when they hit each other
or rather it returns the position at the end of the frame
if you want to disable the collision resolver, then make the objects kinematic
but they hit before reaching the position and i don+t know where
yes they are kinematic
enable kinematic pairs, and resolve the positions manually
i do all that but i donΒ΄t know where the collision happens
i know what frame and where the objects are at the end of the frame
it happens between the last position and the current position
there is no more accurate position than that
you have to "guess" or calculate one based on their relative velocities
those are contacts, and they are not really accurate
accurate enough maybe
the collision contains ContactPoint2D.separation, that together with the contact normal, and all other contacts also gives you a clue how the collision can/should be resolved and where it happened.
i guess, i hoped there would be a more straightforward way, thanks
maybe when you re-think your system design you find a solution that achieves the same goal by more conventional means which are supported by the unity API out of the box.
You could cast your collider between the frames to get contact points.
yes, this works against a static object, but against another moving object i would need to cast both at the same time against each other i think
If you do the cast in fixed update, both of the objects should be in the expected position and a cast would work.
i-ll try, thanks
yeah, it mostly works, thanks for the suggestion!
The thing is i am just trying to make a simple super mario clone where mario jumps on the goomba to kill it. I understand that it will work with OnCollisionEnter, but if the goomba is moving up and mario is moving down the collision will be accurate enough but not really accurate. I thought there was some common practice to solving this kind of situation since it is a fairly common mechanic.
if both of the objects are controlled by physics and interpolate, then there shouldn't be any problem Imho.
but i am using kinematics
Then you've got to handle it on your own.π€·ββοΈ
yes π i just thought there was a "100 years old method" to do this π
i don't want to reinvent the wheel
The recommended workflow is to let physics handle it. That's the 100 years old method. Otherwise you handle it on your own which is also a 100 years old method.
usually using casts of different type.
Is there any way to combine a [Tooltip("")] with XML automatically? I'm using doxygen to auto generate documentation but it does not pick up the Tooltip attribute, so any time I want information displayed both in the editor and in the generated docs, I have to write a <summary> and a tooltip.
The question has been raised before but haven't found any solutions out there, I suspect there might be some way to use a custom attribute or preprocessor but don't know where to start with those
Afaik no not really
This would be possible with IL post processing/IL weaving, which Unity unofficially supports. Burst and the ECS package use IL post processing to modify the compiled assemblies and it's possible to make your own IL post processor, but it's not documented and could suddenly stop working.
Here's some information about it:
https://forum.unity.com/threads/how-does-unity-do-codegen-and-why-cant-i-do-it-myself.853867/
ty @sage radish , will check it out now
ILWeaving won't let you generate <summary>, it'll let you generate the attribute though but finding the docs might be non trivial
I've looked into it in the past and it wasn't as simple as you'd hope
(also when I did it, Unity didn't generate the docs output file by default)
it is a complete non-issue, you are probably over-thinking it
Hey, I'm developing an app for android at the moment
I know when developing with android studio it's possible to add widgets to the app which can be added to the home screen
Does anyone know of ways this functionality can be used in a unity game?
Because I would need to have support for home screen widgets with the app
not sure if this is "advanced" enough but... how do people typically implement textual player notifications? through direct calls (e.g., `notificationmanager.notifyplayer("message")), through callbacks (e.g., notification manager will add its own notification methods to various game entity callbacks), or through polling (e.g., notificati/on manager holds references to various game objects, periodically polling them to check values, and notifying when some event occurs)? or through something else?
probably all valid approaches depending on the situation, probably wouldnt do the polling one though unless it's a multiplayer game taking something from a server though
thanks
I'm working with compute shaders programming Conway's Game of Life, and for some reason, it escapes stable patterns.
I'm going with a 2D grid of cubes that read their data from the structured buffer.
struct Cell
{
int2 position;
uint isLiving;
};
RWStructuredBuffer<Cell> cells;
int dimension;
uint liveOrDie(Cell cell)
{
int x = cell.position.x;
int y = cell.position.y;
int pos = (x * dimension) + y;
//0-->L, 1-->BL, 2-->TL, 3-->R, 4-->BR, 5-->TR, 6-->B, 7-->T
int indexes[] = { pos - dimension, pos - dimension - 1, pos - dimension + 1, pos + dimension, pos + dimension - 1, pos + dimension + 1, pos - 1, pos + 1 };
indexes[0] = (x != 0 ? indexes[0] : -1); //not on left
indexes[1] = (x != 0 ? indexes[1] : -1); //not on left
indexes[2] = (x != 0 ? indexes[2] : -1); //not on left
indexes[3] = (x != (dimension - 1) ? indexes[3] : -1); //not on right
indexes[4] = (x != (dimension - 1) ? indexes[4] : -1); //not on right
indexes[5] = (x != (dimension - 1) ? indexes[5] : -1); //not on right
indexes[6] = (y != 0 ? indexes[6] : -1); //not on bottom
indexes[1] = (y != 0 ? indexes[1] : -1); //not on bottom
indexes[4] = (y != 0 ? indexes[4] : -1); //not on bottom
indexes[7] = (y != (dimension - 1) ? indexes[7] : -1); //not on top
indexes[2] = (y != (dimension - 1) ? indexes[2] : -1); //not on top
indexes[5] = (y != (dimension - 1) ? indexes[5] : -1); //not on top
int livingNeighborCount = 0;
for (int i = 0; i < 8; i++)
{
livingNeighborCount += (indexes[i]!=-1 ? cells[indexes[i]].isLiving : 0);
}
return ((cell.isLiving == 1 && livingNeighborCount > 1 && livingNeighborCount < 4) || (cell.isLiving == 0 && livingNeighborCount == 3) ? 1 : 0);
}
[numthreads(128,1,1)]
void Conway (uint3 id : SV_DispatchThreadID)
{
Cell cell = cells[id.x];
cell.isLiving = liveOrDie(cell);
cells[id.x] = cell;
}```
Does anyone here have experience using a UPM package sourced from a git repository, with a particular revision specified? I've tried following the documentation for it in the manual (for version 2020.3), but UPM keeps saying it was unable to clone to repo because the revision (a tag in this case) was not found. The tag is definitely there, and when I reviewed the set of git commands that UPM is using to acquire the package source, it seems like the problem is that it's creating a shallow git repo, at least that's what I was able to confirm with someone in the official Git IRC channel.
Has anyone else had this setup work for them, and if so what version of Unity and Git were you using? Thanks!
Hi!
I'm working on creating an insanely accurate aerodynamics system
I already have a custom object with a mesh
My problem;
I need to gather all the outer surfaces of that mesh, then get their surface area and orientation (rotation)
Apart from that I also need to apply a force in the center of all of them
How would YOU go about doing it? I can't seem to find anything on the internet or in the docs
Meshes are made up of vertices and triangles. The Mesh object contains data about all of the triangles, and you can infer their direction from the order of the vertices in each triangle. You can get the normal of a triangle from new Plane(pointA, pointB, pointC).normal
What PB said. Find the normal vector (https://mathinsight.org/forming_planes if you want to do it by hand, or .normal above) and surface area of all of the triangles (https://math.stackexchange.com/questions/128991/how-to-calculate-the-area-of-a-3d-triangle), multiply each normal times the SA of the triangle, add all of them up and that should be your total drag on the system. I'm no scientician, though, so.. you know, check your work with someone smert. π§
Is there a better way to write the following? if (hoverCount <= 0) { isFlying = true; hoverCount = 10; } else if (hoverCount < 5) { hoverCount -= Time.deltaTime; isFlying = false; } else { hoverCount -= Time.deltaTime; }
well you could use a state machine...
if you want to be really nitpicky, you repeat the -= Time.deltatime, so you could do
{
isFlying = true;
hoverCount = 10;
}
else
{
if (hoverCount < 5) isFlying = false;
hoverCount -= Time.deltaTime;
}```
but it's arguable if that's 'better' or not
Oh cool. I thought that there may have been a way to count back up to 5, to reset the counter instead of just a 10-5-0 check
technically, setting it directly to 10 will cause small inaccuracies to add up over time. Doing hoverCount += 10 instead would get rid of the small inaccuracies.
assuming this is constantly looping every 10 seconds
Yeah it depends on the length of the path and if it's killed or not. Are you talking about the 100th's of seconds etc..? I have a few counters like this so assume I should change them all?
well, thats for you to decide, but the issue is simply that: let's say you had a lag spike when the timer was at ~.01 (basically zero) seconds left. As soon as the game recovers from the small lag spike, deltaTime will be larger than usual, and you will subtract much more from the timer at the end of the frame. Lets just say that timer is now at -2 seconds. Then, when the next frame starts, you will basically just ignore that lost time because you are setting it directly to 10, whereas adding would put the timer at 8 seconds which is more accurate since you spent 2 seconds with the game lag spiking
I used two seconds as an exaggerated example
Awesome explanation, that makes sense and I will update it everywhere since it is actually appropriate - it will likely fix issues with my guns I haven't noticed due to the minute timings
usually yeah, it's 100ths of seconds
I just upgraded a project from 2020 to 2021 and now I'm getting "does not exist in the current context" errors on Cinemachine as well as Input System...
I tried adding assembly references, removing and re-installing the projects, etc. but it is telling me the namespaces do not exist. Does anyone have any idea how to resolve this?
Do the errors exist in Unity's console, or just your IDE
In my IDE, Visual Studio Code
Are they not in the console though?
They were in the console until I added assembly references
Now those errors are gone.
I am able to make builds, and the input system and cinemachine seem to be working
Then it's gonna be an issue with VS Code. You may have some luck if you tick this box on the external tools preferences
The Regenerate project files button under it should also help
and you hit the regenerate button?
Tried regenerating project files but no luck. If I open a project in 2020 it works perfectly fine in VSC.
No idea then. If you're not seeing errors in Unity's console but you are in an IDE, then the IDE is the one that's wrong
If you're a student JetBrains Rider is free and I highly recommend it. Otherwise installing VS Community via the Unity hub is the easiest and most reliable option
The liveOrDie decision needs to be made based on the status cells had after the last update, but right now every time you check a cell's isLiving in liveOrDie it's going to be arbitrary whether you get the previous update's value or the new update's value. You need to have two buffers, one with last update's data that you read from, and one for the new update's data that you write to.
This is a bug with VS Code integration version 1.2.4; I recommend just going back to 1.2.3, which works fine.
That's what I was thinking. I haven't implemented it yet but I'm glad my suspicion was correct!
Yeah I know some people do but I still don't understand the preference for vs code over vs if you're coding in c#
They both have pros and cons for me? Code is much faster to start up and reload solution changes, but it's missing some of the automation of mainline VS.
If I had an infinitely powerful PC I would probably generally pick mainline.
jetbrains also just released their new IDE
Which doesn't support C# yet
Did they announce pricing?
Nope. It's not available outside of preview yet.
@small badge I wanted to thank you again. My program is working perfectly :))
Hopefully someone here can help... I'm currently using Python for Unity 4.0.0-pre1, and am trying to get Python to communicate with C-Sharp. At the moment, my Python code creates a list based on a input field, but I'm very stumped in terms of how to go about receiving the data from Python in CS, and assigning it to an array.
The built-in PythonRunner.RunString is set up a void function, so it doesn't seem to return anything.... Maybe someone her knows of a way to assign to a Unity variable directly from Python?
If this is in-process API, it looks like the Python side can access game objects and scripts. You could have the python code place the result into the appropriate variable.
That's the issue, though... there's no immediately obvious way to write to external variables, so far as I can tell, and both versions of the API have very little documentation.
you can use sockets or piping. I'd recommend piping since it's very fast and is actually meant for inter process communication.
In windows you can make use of file mapped object as well. It allows you to read same memory location without having to clone data from python to c# everytime.
I did not realized that I wrote "void" there. Oh my gosh! how on earth π
Hey!
I try to get values from DynamoDB through Lambda by using API Gateway.
I managed to get data defined only if they are string.
When I make nested classes and try to get the whole structure, I could not define.
public class Restaurant
{
public string Id { get; set; }
public string RestaurantName { get; set; }
public string Phone { get; set; }
public string City { get; set; }
public string RestaurantSlogan { get; set; }
public string Email { get; set; }
public List<Catalog> Catalog { get; set; }
}
public class Catalog
{
public string CatalogName { get; set; }
public string CatalogID { get; set; }
}```
public async Task<Restaurant[]> GetAllRestaurants()
{
ScanResponse result = await _amazonDynamoDb.ScanAsync(new ScanRequest
{
TableName = "test"
});
if (result != null && result.Items != null) {
List<Restaurant> restaurants = new List<Restaurant>();
foreach (Dictionary<string, AttributeValue> item in result.Items) {
item.TryGetValue("Id", out var id);
item.TryGetValue("Catalog", out var catalog);
restaurants.Add(new Restaurant()
{
Id = id?.S,
Catalog = catalog?.
});
}
return restaurants.ToArray();
}
return Array.Empty<Restaurant>();
}
}```
How should I define the 'catalog' class?
I could not write .M ("Map"). It gives an syntax errror.
well for one your restaurant class wants a list of catalogs
Stop crossposting please
is there a way i can fix this
Even if you could, it wouldn't do anything; you're getting a copy of the object's position and changing the copy's Y value; that won't move the object. If you want to change the object's position you need to set a new Vector to transform.position.
transform.position is a property
So, I am making a grand map strategy game, but something is wrong with my text overlay code where for some countries it isn't done correctly but for others it works perfectly, screenshot:
In depth screenshot of UK:
Code:
@buoyant lantern use one of the code sharing sites in the read me plz, dont rly wanna dl + look at a txt file lol
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.
thats not one of the sites lol but ill look at it
as long as its colored
so the UK is the only one it isnt working for?
and germany is a bit offset, since down isn't assigned for some reason
But in general, the uk is the biggest problem
uks assigned territory is the block in the top left
i would think an easier way to implement that would be to have your country prefab and give it a textmeshpro element in the center
and then in your script you can say like country.SetNameText() or something and it would always be in the center
but its a map strategy game, where the text and borders shift because of war.
the countrys size will change midgame
and the text's position
the text's position can be relative though
and it's relative to the exact center by default anyway
but the text meshpro wont scale with the country
the country is an empty gameobject
storing variables
it can, there is an auto size checkbox on the tmp component
the country stores the provinces belonging to its territory, it itself is empty
These are just empty
Apart from the country script
oh right but the text could be on the province object right
There are multiple province objects making up one country
A basic explanation each country has states, the provinces get assigned based on these states, which hold the provinces.
These are the provinces
oh ok
is there any way to move the game window? i found something about doing it on windows but im using a mac so i need cross platform stuff, and the amount of info ive found based on it barely even there
@buoyant lantern the logic looks ok to me, try setting debug logs in the different conditionals
I have that was my second screenshot showing how the rightmost and downmost objects arent assgined.
This one
Hi guys. Does anybody know why this doesnt deserialize ?
this is my class ```cs
public class SpinnerValues
{
public List<int> spinnerValues { get; set; }
}
- Unity cannot serialize a class unless it is marked with
[Serializable] - Unity cannot serialize properties. (your list is a property because of the get/set syntax)
I have tried without get/set and with Serializable cs [Serializable] public class SpinnerValues { public List<int> spinnerValues; }
continue to the next line in the debugger...
that line hasn't run yet
Oh wait also you're using Newtonsoft my bad thought you were using Unity's JsonUtility. So the advice I gave before may not have been necessary π
I have tried both
You are right. Its not empty
looks good to me
You know what would make my life using Unity so much easier?
Being able to click and drag scripts into Lists of interfaces with the SerializeReference attribute. Would make it possible to compose data, like you would with a GameObject.
I'm making a dialogue system. I wanna be able to arbitrarily cause certain actions to happen at different points in a line, and no matter how I slice it, the problem I keep running into is that I need to be able to populate a list with a generic type from the inspector, which just isn't possible without getting lost in PopertyDrawer hell.
It's certainly doable; OdinInspector (paid) lets you select types from a dropdown for any list of serialized references. I don't know whether any of its free competitors have the same function yet, though.
{
LinkedResource res = new LinkedResource(filePath, MediaTypeNames.Image.Jpeg);
res.ContentId = Guid.NewGuid().ToString();
Debug.Log(res.ContentId);
string htmlBody = "<img src=\"cid:" + res.ContentId + "\"'/>";
AlternateView alternateView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
alternateView.LinkedResources.Add(res);
return alternateView;
}
I'm having an issue using smtp to send an email with a inline image in Unity. I am almost certain the issue lies within my body composition line. I only get a broken image when I send out the email. Any ideas?
you probably shouldn't make language features an integral part of your dialogue system. In particular generics/interfaces aren't the only way to achieve composition.
How to implement Flare Layer in a custom scriptable render pipeline? Here's someone asking the same question with no answer https://answers.unity.com/questions/1580707/lens-flare-in-scriptable-render-pipeline.html Seems like Lens Flares arent supported in the new render pipeline system?
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
that's from 2018. we now have 2021
also: no code problem
So do you know how a flare layer is implemented in a custom SRP?
Well for a custom SRP you pretty much have to code your own lens flares
Hello everybody! I can not trigger the second function from my funciton named "FUNTCION HANDLER" do you have any idea why?
public async Task<APIGatewayProxyResponse> AddRestaurantAsync(APIGatewayProxyRequest request, ILambdaContext context)
{
var restaurant = JsonConvert.DeserializeObject<Restaurants>(request?.Body);
restaurant.Id = Guid.NewGuid().ToString();
restaurant.CreatedTimestamp = DateTime.Now;
context.Logger.LogLine($"Saving restaurant with id {restaurant.Id}");
await DDBContext.SaveAsync<Restaurants>(restaurant);
await FunctionHandler("dsfdsf",context);
var response = new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.OK,
Body = "Test",
Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" } }
};
return response;
}```
public async Task<string> FunctionHandler(string input, ILambdaContext context)
{
try
{
context.Logger.LogLine("Selam");
using (AmazonLambdaClient client = new AmazonLambdaClient(RegionEndpoint.EUCentral1))
{
JObject ob = new JObject { { "param", "hello" }, { "param1", "Lambda" } };
var request = new InvokeRequest
{
FunctionName = "SaveToOpenSearchDomain",
Payload = ob.ToString()
};
var response = await client.InvokeAsync(request);
using (var sr = new StreamReader(response.Payload))
{
return await sr.ReadToEndAsync();
}
}
}
catch (Exception ex)
{
return ex.Message;
}
}```
I can not see "Selam" in my AWS Log.
this function is never called for some reason. and I do not know why.
Elaborate? I don't want to have to make a custom class for every combination of components.
... Which, now that I think about it, would also require generics.
How would you do it if you had neither generics, abstracts or even objectsβ¦ itβs possible with just structs and procedures. You are building a data driven system, so worry about the data, not the language features you have available.
the best shortcut available is using generics with non-generic base class and βconcretizisingβ them at the end just like you would with MyTypeEvent : UnityEvent<MyType>
So... Every line has a list for every type of component?
how does the editor script for button work?
I want to be able to replicate the onclick part of the button script for another object
You looking for UnityEngine.Events.UnityEvent?
When a variable of that type serialized, it lets you hook up functions from other objects in the inspector.
yea I think that was it.
I ended up opening up the button script in unity and used that as the basis of what im trying to implement
There are some git packages that have gone through the property drawer hell for you, like this one:
https://github.com/mackysoft/Unity-SerializeReferenceExtensions
Oooo, free, open-source, and exactly what I'm looking for. This should work great, thanks.
@regal olive This is advanced code, if you're asking about basic concepts, use the appropriate channels. And also just ask your question, we don't need a ramp up.
@humble leaf it is movement controls i cant figure it out i am trying to make the perfect movement controls it was 5 years snce i have used unity
Then you're free to ask in one of the beginner coding channels, as you've already done in #archived-code-general. π
okay
but how do i exactly do it
can you help
with the coding
look at YouTube tutorials for Character Controllers...
okay @regal olive but what is the best one for it
No such thing as the "best one", they can vary and some may not suit your needs. You need to put some effort into actually researching this yourself though
question about target framerate
if a game has a tick rate of 100 ticks per second with no interpolation, and the monitor is 144hz, is there a difference between setting the target framerate to 100, 200, or 300 [assuming no framerate drops]?
yeah without interp there will be frames where nothing moves
yes
if the game actually gets above 100
but I'm saying would there be a difference then
between 100, 200, and 300
I'm thinking no right?
yes you have a weird understanding
I'm not too sure how the target frame rate even works - does it limit the amount of frames the screen shows or the amount the game calculates?
the principle stays the same, framerate limiter is just limiting
so if you have 144hz you are limited to 100 frames, and the result should be same
it limits amount of update cycles
only visually right
nope
unity is tied, update loop reflects render loop
if you are writing a variable framerate ticker, you have to support that
so according to the scenario I gave, even if I had a 300hz monitor and set my target fps to 300 [assuming no fps drops], it would look the same as a 144hz monitor set to 144fps?
i dont understand the question, so lets try from another end
what do you expect not to work properly
what is the actual concern
the actual concern is I don't want the user to waste gpu setting the fps to something really high if it is indiscernible from a lower fps that uses less gpu
so if 300 target fps and 150 look the same I want to just limit the user to settings the target to 150 max
then set to screen rrate by default and thats it
allow unlimited as well
its up to user to burn their gpu
but they might set it really high thinking it does something
when in reality there's no difference
then call it for what it is
when there could be no difference that is
"Framerate limiter"
they can call it that, but its functionally a limiter
thats all it does basically as it cant do anything else
ok but if the game has no interpolation and has 100 ticks per second, is there a difference between 100fps, 200fps, and 300 fps?
I just need to know that
in games typically when you actually have a real "target framerate" parameter it implies that the game also has some means to dynamically adjust the settings to maintain it
unity doesnt have that
depends on your code. if you allow input to be polled independently of tickrate if the fps is higher, players will experience less input lag
yes input is independent of tickrate
I'm trying to create a package following the steps for "Create Embeded" on this page of the docs..
https://docs.unity3d.com/Manual/CustomPackages.html but when I get to the last step of opening up unity to see it in the package manager- I get this pictured error: Any suggestions/thought on what I might be doing wrong?
then yeah, thats all the difference that comes to mind atm
oh ok
so then actually 200fps would be twice as fast when showing input compared to 100fps
and processing input
right
not really
well the time it takes to show the input I mean
like if the user opens a menu
it will take .01 seconds for one and 0.005 seconds for the other?
for the menu to pop up
in both cases it can take both amounts
it depends on how close the input was in time to the tick
i think its related to input window
but i cant formulate it, ill go smoke and try to picture the graph in my mind
interesting topic
ok it makes sense only if the input processing and input reaction locally is independent of the tickrate, like its done in online games, where server has a tickrate, but client reacts to input in update loop, then the perceived input lag is reduced due to prediction
i think that if the game locally processes input completely in the tickloop, there will be no difference, whatever the framerate is
you can possibly decouple certain systems from tick, like camera movement and ui
hmm ok
"it will take .01 seconds for one and 0.005 seconds for the other? " No- if programmed correctly, it would take X frames at 100fps, and 2X frames at 200fps... which SHOULD be the same amount of time on both systems @lofty inlet
it can even introduce more issues with ignored inputs, if you dont buffer input between ticks
my advice would be to design it for both lower fps and higher fps without making concrete assumptions
tick loop has to run several times a frame if fps is low, and input has to be buffered for cases where its high
I'm not sure why Bolt doesn't have a channel here, seeing as it's been purchased by Unity, as far as I'm aware. At any rate, I'll throw this here. I'm wondering if anyone has experience writing custom units for Bolt, and if so, how to get a text area to show up in the unit inspector.
look at #763499475641172029
Hey guys i have question for you, my goal is to get true or false when i give x and y and frequency, this need to be sync with the seed
my first approach is
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum SeedOffset
{
TREE = 0x01,
EVENT = 0x02,
}
public class RandomSeedTest : MonoBehaviour
{
float timer = 0x0A;
[SerializeField]
int seed = 0xAEAA;
[SerializeField]
float frequency = 0.9999f;
public bool randomByPositionFrequences(int seed, float x, float y, float frequency, SeedOffset offset)
{
Random.InitState(System.Convert.ToInt32(seed + ((float)offset * x) + ((float)offset * y)));
return Random.Range(0f, 1f) > frequency;
}
void Update()
{
timer += Time.deltaTime;
if (timer > 0.1)
{
for (float x = 0; x < 0x64; x++)
for (float y = 0; y < 0x64; y++)
if (randomByPositionFrequences(seed, x, y, frequency, SeedOffset.TREE)) Debug.Log("Tree at " + (new Vector2(x, y)).ToString());
timer = 0;
}
}
}
Is there a way to assign multiple materials to a procedural mesh?
I have it made and ready, but I need a way to properly use submeshes with it, and it doesn't help that the error just says "Failed getting triangles. Submesh index is out of bounds."
I set the subMeshIndex to 2, and am assigning geometry to 0 and 1.
Essentially, I am trying to assign this material only to the bottom, flat face of this procedurally generated road.
Any ideas?
where exactly ?
do you mean subMeshCount? if you have 2 submeshes, valid indices are 0 and 1. To assign multiple materials, just use the plural of the renderer material (.sharedMaterials or .materials). Each material is applied to each submesh of the same index
yes
I did that. In the MeshRenderer, I assigned two materials, one for each submesh.
confirm that your mesh does actually have submeshes
"Failed getting triangles. Submesh index is out of bounds." == try to get one object not allocated
a = array[60]
a[60] == error index is out of bounds
ref byte[] tempByte = ref Unsafe.As<float, byte[]>(ref newstuff);
Console.WriteLine(tempByte[0]);```
How do I use Unsafe.As? This is failing because it's trying to do unsafe pointer stuff on a managed array
I only specified in the code to use submesh 0 and 1.
VS unity project don't allow unsafe pointer no ? but no too mutch ref ? x)
@static patrol the 2 submesh exist? or are created?
I am creating a mesh from a bunch of individual points, and am trying to separate a few faces into their own submesh. They don't exist before hand, and are created.
public void changePointer(ref float ptr)
{
ptr = 0x01;
}
int main()
{
float myfloat = 0x00;
changePointer(ref myfloat);
// Debug log (myfloat)
return 0x00;
}
@plush hare ?
@static patrol send code or picture where you get submesh[x]
its possible your submesh didn't create
I'll send the GenerateMesh function thati'm using
@plush hare |= x << ^2 π if you want to work on bits
This is what I normally have. I've removed the actual submesh generation part because I couldn't test anything as it wouldn't run because of compile-time errors.
{
mesh.Clear();
List<Vector3> verts = new List<Vector3>();
List<Vector3> normals = new List<Vector3>();
List<Vector2> uvs = new List<Vector2>();
for(int ring = 0; ring < edgeRingCount; ring++)
{
float t = ring / (edgeRingCount - 1f);
OrientedPoint op = GetBezierOP(t);
for(int i = 0; i < shape2D.VertexCount; i++)
{
verts.Add(op.LocalToWorldPos(shape2D.verticies[i].point));
normals.Add(op.LocalToWorldVec(shape2D.verticies[i].normal));
uvs.Add(new Vector2(shape2D.verticies[i].u, t));
}
}
List<int> triIndicies = new List<int>();
for(int ring = 0; ring < edgeRingCount - 1; ring++)
{
int rootIndex = ring * shape2D.VertexCount;
int rootIndexNext = (ring + 1) * shape2D.VertexCount;
for(int line = 0; line < shape2D.LineCount; line += 2)
{
int lineIndexA = shape2D.lineIndicies[line];
int lineIndexB = shape2D.lineIndicies[line + 1];
int currentA = rootIndex + lineIndexA;
int currentB = rootIndex + lineIndexB;
int nextA = rootIndexNext + lineIndexA;
int nextB = rootIndexNext + lineIndexB;
triIndicies.Add(currentA);
triIndicies.Add(nextA);
triIndicies.Add(nextB);
triIndicies.Add(currentA);
triIndicies.Add(nextB);
triIndicies.Add(currentB);
}
}
mesh.SetVertices(verts);
mesh.SetNormals(normals);
mesh.SetUVs(0, uvs);
mesh.SetTriangles(triIndicies, 0);
}```
hard code x)
c is faster
Trying to separate those 2 flat faces near the bottom into their own submesh
but it's the best ^^
@static patrol need to separate edge of this flat faces
Index it with
https://docs.unity3d.com/ScriptReference/Mesh.SetIndexBufferData.html
and
https://docs.unity3d.com/ScriptReference/Mesh.SetIndexBufferParams.html
for final use that
https://docs.unity3d.com/ScriptReference/Mesh.SetSubMesh.html
or
simply
int[] triangles_index_0;
int[] triangles_index_1;
mesh.subMeshCount = 2;
mesh.SetTriangles(triangles_index_0, 0);
mesh.SetTriangles(triangles_index_1, 1);
hey yall, I'm trying to write a custom importer to auto-generate TMP files when otf or tff files are imported, but I'm getting this error that I can find nothing about, and I'm not sure where I went wrong code-wise: "The asset is loaded, but not tracked. source hash='e297be892e5f61012d3aee81b5ef64a9'"
this is my first time working with the import pipeline so I don't super know what I'm doing but I don't think I'm too off-base code wise
ImproveSeedByPosition
whats the best way to approach rendering cards in the players hand for a card game ? Not sure if I want to go with Raw Images or if objects work or if theres possibly a better way
From what I know, ScriptableObjects are god tier for this kinda thing
You will still use raw images for the card art, but it will be way better.
I mean, is a raw image not an object?
Welp apparently my entire issue was that I had unnescecary UVs on the other faces.
Works now.
nice π
put it in #archived-works-in-progress for anyone interested
now to work on the rest
hi, i'm trying to use an animation event to call a function but it only works once, then I have to relaunch unity for it to work again (once). resetting the "play" session doesn't make it work again.
any idea what I should be looking for as the problem? I don't usually have issues like this when there's something wrong with the code so I thought maybe it could be something else.
Please don't spam all of the chats
I waited before moving up the chain. thought that'd be okay. figured maybe it was more advanced than beginner or general code. maybe i'll just delete the old messages?
I actually think you'd actually be better asking in #π»βunity-talk since it doesn't seem like code π
Hey, i hope that somebody will have an answer or something
I want to know if a component contains variable of type "unityevent", does somebody know how to achieve this ?
why do you want to do that?
i think you could do it using reflection but i'm not sure that's the best solution
yeppp, by using reflexion i can, i have find the solution : https://forum.unity.com/threads/get-public-variables-of-an-unknown-component.252934/
are you using this for a custom editor or for runtime code?
alright cool
not sure if this goes here, but having an issue with C++ plugin im making for calculating battle stats in my game
C++ Code: https://pastebin.com/AqPNygwN
C# Code: https://pastebin.com/niyB9Hk2
It craps itself when i run it, i just want to call the CalculatePlayerStats function.
Crash Log: https://pastebin.com/rwiJPkrr
Can someone lend a hand with this, maybe a few pointers as to what I might be doing wrong or what Unity is doing wrong please?
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.
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.
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.
Not that I know what the error is, but any particular reason you're leveraging an external C++ lib instead of just a C# script directly in unity, or at least a 4.7.2 framework DLL in C#?
(just to remove a moving part from your system)
soo any big brains knows how to check if x mesh is made to convert to cube/plane object? like i have mesh and i want to check if its possible to use there plane or cube like amount of verticles is same or if that can be plane used
aka convert map which is made from just single mesh and convert everything to primitives only
The error is also pretty unhelpful π¦ "Got an UNKNOWN" - maybe throw some logging in your C++ lib if able, even out to the console if you can't hook the debugger into it
noob question here, but how would one do that? normal C++ std::couts?
yeah
I'm trying to mentally step through your code atm
It looks fine enough, but still, I'd just do this in C# if you're able
ie - I don't see anything special in the C++ lib that can't be done in unity, unless you're specifically needing a shared lib of some sort
The dev team im part of is experimenting with performance of doing the math for our game in C# or C++, we are also looking to make our own plugin at somepoint for internal use so this is also good practice for us
sure, fair enough - but just recognize that you open yourself up to a whole class of interop bugs by doing that.. dev time is real π
but unfortunately I've never done this so I don't have any really helpful advice, sorry
i'm still looking at the code just to see if there's any obvious issues
oh yeah defo, it's kinda what im prepared for
I tried std::tuple but because of the extern C, it hates it
aye
I wonder if there's an issue in the conversion from "your" class to the C++ struct
that's what im wondering too
i have no idea how that would work, but it doesn't seem like you're doing any specific conversion
and you're leaning into the C# "var" use to do the lifting there so.. yeah, might be an issue with that
I shall see if changing from var fixes, was there for quickness when typing lol
perhaps you need to explicitly declare/use the C++ type
Anyway, I'd probably take this issue as a singular data point expressing a "con" (in the pro/con sense of the word) against leveraging C++ and C# in the same application. You might get some benefits from C++ for really heavy duty hot paths, but ... you should probably demonstrate that in whatever benchmarking environment you can put together separately from working on the interop. My personal gut feeling says that C# is pretty fast and should be comparable in terms of performance, and if you really wanna get into the heavy wizardry, you can always explore the unsafe world and do the pointer/memory operations directly
Like, there might be better solution paths to getting the performance you need out of C#, and you eliminate the whole class of interop bugs - it's a pretty specific skillset that might be a lot of "pioneers get the arrows" type work.. ie, stepping through c++ to debug issues
whereas the collective knowledge of working within one framework is pretty deep, so.. you know, that might be a better class of future problems to solve
sorry that's not more helpful
it's ok π
i've tried explicitly telling it the type instead of var, to no avail
you might need to wrap the struct in a managed class in C++
my light googling tells me that C++/C# interop using pinvoke is supposed to "just work" but.. i don't know if mapping the C++ object to a different object (even though the floats are both 4 bytes and fields all share the same name, even though one is a class and one is a struct) "just works".. you might need to use the C++ object
thank you, i shall have a read through and see if anything can make any headroom
this looks like a lot of work π
In any case, it looks like you need a bit more explicit work to sustain the interop - you probably need a specific class that can marshall in/out calls to your C++ code and objects
including just getting the raw pointer and constructing the equivalent C# object
maybe someone smarter than me can say if that's the case or not, but ... that's what this looks like (and opinion: i would be a grumpy developer doing it π )
I got this strange error. I download the nuget package but when I return to the IDE, the reference misses with no reason
you have any idea? thanks
btw, both the project and the nuget pack are dotnetstandard 2.0
At the very least your C# class should have an attribute like [StructLayout(LayoutKind.Sequential)] and maybe change it from a class to a struct as well. I also prefer to pass the object as out parameter and assigning it in C++ rather than returning it. The C++ function should take that struct type as a pointer then
I have a menu extension that will call a method to add a gameobject to the hierarchy. That gamobject will be a supplied prefab with a monobehaviour DLL as part of it.
A GO with a script always has the values with it, but I want to convert this to a menu generated and DLL based GO to avoid the play mode.
I thought I would ask this before heading in that direction to make sure of 2 things:
Is this feasible/allowable?
and
If this is the best approach will the gameobject in the hierarchy retain the variable settings of the public input variable types, i.e. selected GOs, floats, bools?
In the previous effort the problem I could not devise a way to menu generate a GO and the settings would store with the GO.
Thanks in advance.
Don't nuget packages outside of unity - it's really fragile or just not functional... unity manages its own references to packages and in fact, regenerates the csproj and solution files
There is a nuget for unity, but I didn't have a lot of success with it
What I typically do is simply download the actual DLLs or source code and put them directly in unity (DLLs go in /plugins, source goes wherever in your /assets)
A DLL? I'm not sure I understand this question
If you want a prefab game object, maybe you want a ScriptableObject
(You can also add items to the editor/right click menu to create new game objects of whatever type you want.. if that's what you're asking)
Yes. I want to create a DLL from my script to attach to a prefab. Then generate the GO from a prefab with the DLL attached.
Then go to the inspector, fill in variables and add more gned GO to that prefab
I do not want to distribute the source code through an asset.
I already the GO with the script.
hm, ok, interesting (and imho not a great policy, but that's your choice)
I don't think you can do that
DLLs have to go specifically into the plugins folder, so you might be able to make some editor methods that move the files there and trigger a recompile
but as far as attaching a DLL to a game object... i don't think so, because a DLL is a class library, not just a single class
(it might only contain one class, but that's not constrained)
Unity's editor would also need to know what the class is that you're trying to attach to a given game object, and I'm not aware of any method of .. uh.. using DLL/plugin classes in the editor to attach a specific component to a game object
Opinion mode: it sounds like what you're trying to do is protect your source code from theft, but to be honest, you reduce the value of your asset by doing so - people want access to your source code so they can debug what's busted about it when things go sideways, and offer bugfixes/bugs to you. I would personally never use something that's not open source for this reason, and I don't think most companies/organizations suffer from a loss in revenue from what they're producing by making it open source
you're making it a lot more complicated for yourself and your users by trying to do it that way
Thank you for this guidance. I had gotten this idea then it turned into things to try with the system instead of just GOs and scripts. There are always boundaries to see.
Hello! Is there a way to perform something like this with overlapping textures in parts?
"stamping" the texture onto one gameobject and combine them so they dont glitch out?
is it possible to put a custom setter on an int that's exists only as dictionary value?
give context
I want to trigger an event call whenever a dictionary value is changed. I guess I could put a setter on the entire dictionary?
extend the dictionary
thats called Observable
as an example
are you asking about z fighting? like if two items overlap and the texture glitch back and forth? might be able to fix with sorting orders? Or are you trying to make something in unity that you can do in most graphics programs? Like is this a game mechanic? or just layout of the game?
Exactly, the overlapping textures keep glitching out. So itβs with roads, they are the same texture but they highly detailed so itβs not one solid color of course. And when Iβm laying then out and they overlap the texture glitches back and forth from one to the other
#π»βunity-talk message
Anyone have any knowledge how to solve this? or a way to reset webgl input from javascript or any other source? The code problem is if webgl canvas loses focus in anyways, webgl dont return input value to 0 until you press the button again. Any other html element on page or other things causes the same problem.
Someone know how can i avoid huge memory increase after setting the same array of DetailPrototype to multiple TerrainData? When i comment single line with assignment 'terrainData.detailPrototypes = detailPrototypesArray;' memory is fine. For 2 details and 256 terrains memory increases by 2.5GB just by this line. Tested only in unity editor
Fixed my z fighting! Thanks it was a simple solution
Just adjusted the height of it by .0001
I had asked earlier about DLLS and now have a more refined one:
Can I use calls from an EditorWindow class DLL to call methods in a Monobehaviour class dll with the correct assembly references added?
Got a bit of a networking question for unity
Sometime in the future I'd like to implement a sort of noticeboard for my project (What's New, Personalized Messages, etc.), similar to the one used in Genshin Impact for example.
Right now my project works strictly with a PHP server, which is good for quick one-shot requests like pulling user data, but what would I use if I want my game to actively listen to messages from a server? Like say I just released some new batch of news, how would I make it so anybody currently online would instantly have these updated in their noticeboard? And also obviously anybody offline would also see these news when they log in.
Is this noticeboard always visible on the user's screen or are you going to have a notification appear? It's always going to be simplest to have the client poll for news when they check the noticeboard.
i was hoping for something like have a noticeboard icon somewhere in the UI and just have a little ! sign or something to let the user know there's something new
i thought about polling every X time, but I wasn't sure if it's the right move in terms of efficiency
There aren't really many other options, but some are listed here:
https://en.wikipedia.org/wiki/Push_technology
Push technology, or server push, is a style of Internet-based communication where the request for a given transaction is initiated by the publisher or central server. It is contrasted with pull/get, where the request for the transmission of information is initiated by the receiver or client.
Push services are often based on information preferenc...
I'd poll whenever the user does something like open an in-game menu. They probably don't want to be bothered with news while they're playing.
i mean yea, it's all meant to be stuff running in the background and the players would only see the noticeboard if they actively decide to open it
this Push tech seems like what i'm looking for, thanks
I have a question regarding assemblies and asset bundles. We have a build system in place for building plugins for our product which works well. I was now playing with plugins/assemblies that depend on another plugin/assembly instead of a plugin only depending on the assemblies in our product itself
for that , in TestChild, I referenced the second assembly, TestParent, in the asmdef of TestChild and attempt to build and package it
the compilation works well and a dll file is produced. however building of the asset bundle fails
"Error building Player because scripts have compile errors in the editor" is the error from the assetbundle building step. There does not seem to be a way to view these errors though
there are no errors building the child assembly
Do I need to have the TestPArent Assembly in binary form and loaded in the editor? right now that source only lives as source in my project
What's the most elegant way to take a list of transforms and return the transform whose distance to the player's transform is the SMALLEST/GREATEST?
transformList.Min(t => Vector3.Distance(t.position, transform.position));
This uses Linq and almost does the job, except it returns the smallest float/distance, instead of the transform that results in the smallest float/distance
I'm an idiot, isn't it just "Where" if I'm using Linq? ugh
Using distance squared and a for loop is how I'd do it. Make an extension method for it if you need it often
You don't need to do the square root in the magnitude if you're just comparing. You just care about the relative distances
(b - a).sqrMagnitude
damn..
Vector3.distance -> (b-a).magnitude
instead of comparing that to some float
I should do
(b-a).sqrMagnitude, and compare THAT to "some float" * "some float"
in a for loop!
wow
Thanks for the tip!
What book would you recommend to learn unity's DOTS?
I'm comfortable with c# and reading a book on .NET to extend my knowledge.
(Also, i'm currently using a initializer script that FindObjectsByType().each(o.Initialize()) so i can make certain everything is initialized in proper order.
Is this bad practice?
I know there's Awake() and Start(), but i find micromanaging it leads to less headache.
no book. online docs.
Turbo Makes Games is a DOTS-Focused YouTube channel that might help
I'll check this out
I'm loosing my mind. How is it possible for a list of scriptable objects references to have SOME values lost. When the list is deserialized, I loose 90% of the references but a few remain???? The files exist in my folders and the container serialized file contains the guid of these SOs. I imagine it might be because I create and save them from code but... I seem to do every step necessary
did you set the game object that contains the list to dirty before saving or did you change the list via SerializedProperty?
if its prefab, did you record the changes?
does anybody know how to access the private field of components?? is it even possible??
Im trying to make a runtime quicksave type mechanic and I dont want to have to program it for every single component
are they just blocked off from use?
is there any simple way around it? like for example to store the location/rotation/scale of a transform
It is possible with reflection, but in general it's better to use public fields in the first place. The whole point of a private field is that you should be able to write code in the class with the assumption that those fields will only be changed in ways and at times that you control. If external code is accessing the class's private fields then that assumption is broken, which is likely to result in bugs.
The location, rotation and scale of a transform, for example, are all public, not private.
those are properties though right
I think that should work fine for most things but it would be most robust if it could store the exact state of the object
if its possible with reflection lmk how bc using .GetFields(BindingFlags.NonPublic | BindingFlags.Instance) doesn't get anything
Even with reflection you won't be able to store the internal state of Unity components that aren't implemented in C#.
thats annoying
and disheartening
but I should've remembered that they aren't c# objects
You can get the property values though
you should just manually implement which properties are relevant though
as many will not be
hmm
maybe im biting off more than I can chew
my plan was to only save properties that change
yeah properties just completely break everything
to answer your original question
the way you retrieve a private field, is by creating a secondary public field, with { get; private set; }
or just use that public field itself
that 2nd thing is a property, not a field... fields store state, properties don't.
oh I was asking about the existing built in components anyway
so you want a script to read another object's component's properties?
I basically want to be able to save the exact state of an object
kinda like creating an animation on the fly and then being able to play it back
there are a few ways to achieve that
I wonder if I can use unitys animation system
im listening
well, theoretically. I can't say I've done this exact thing.
One solution, is perhaps* to instantiate a copy of the object and disable it - might be enough, but not sure if ideal
The other thing that comes to mind - is JSON serialization
oooo
storing GameObjects as JSON
that could work for what I want to do actually
but
given I dont have to make that json myself and im using some library
cuz if I was it would just be the same thing over again
interesting
we will see if it actually works lmao
Good luck :)
If JsonUtility doesn't work like you want it to, there are some other alternatives, though I'm not up to date on which is good or not
I have a inkling that it will just do what my code already does and not actually save the relevant data
but I can probably find something better
Try searching for Unserializable Properties or something
if it can be serialized, it can be stored in JSON
which is?
just save what properties are changed
is it a predictable data set? if so, you can probably just make a function to store them manually
what type of data do you need to store, and also important - why `?
its too much data
alright ill bite
its probably overambitious but I want to make a rewind mechanic
that ones a little basic
indeed
Like
Is there a way to do a shorthand version of the one above? I'm just learning about ternary operators
I could pretty easily make every major relevant system rewind properly but I would lose the ability to make complex effects at all
now, I believe you've said two things
- Quicksave Feature
- Rewind Time (includes animations etc)
I would really want the full rewind time feature but if I can only manage quicksaves it would still be ok
First - look into how to Save a Game State in general - do the same, but don't exit
And I haven't done this, but here's an idea:
Sorry, I don't see what ternaries have to do with this code. ?. is the null-forgiving op, which means the instructions on the right of the op won't be run if the instructions on the left evaluate to null.
List of Vectors for each frame, point in time OR build an input framework based on System Input Events, using the same mechanic to move forward, as well as back.
For animation - can it be played in reverse?
I have no idea I might just not both with animations
Right, my apologies, I did mean null conditional. But is there something similar if i'm trying to increment values? Like only += 1 IF != null? but nice and clean like "?"
or make my own simple system
using the input event approach would potentially reduce the amount of points in time you'd need to store, if the game is deterministic and Not probabilistic
yeah I wish but I've already made the main mechanics of the game
I dont think that its possible to rewind time like that tho π€
What error message are you getting on that line?
I haven't tried rewinding animations, but worst case you could generate them yourself
I basically need to make a multiplayer game
+= someObj != null ? 1 : 0
but instead of sending the game state I just save it
Local Multiplayer?
I need to save every relevant part
Yep, that's the shortest you can get to.
Beautiful, many thanks
Ill probably have to make the part of the game where you "rewind" not be 100% true to what happened
cuz there are some things I can't really rewind easily
Unity doesn't have built-in support for rewinding particle systems from an initial offset time. Particles systems will ignore attempts to set any negative simulation values and clamp all properties to 0. We can add support
like if I use a particle effect or trail renderer or any similar effect
Trail might be difficult
but let's think like a confidence man for a moment
what if you just Snapshot each frame and replay them backwards.
that was my original idea lmao
it wouldn't solve the main issue anyway
actually yeah
id still have to reset the actual gamestate at some point
ill need to store every relevant factor inside scripts then
its not that big of a deal tbh
yes, but you'd only have to store the values at fewer points in time
and if you really want to use smoke and mirrors, you can add a "coming back" effect, to null out any animation discrepancies
the rewinding will take care of itself at that point
righttt
just flash the screen white or something
smart
the hardest part is gonna be projectiles and other instanced objects
π€
trying to wrap my head around the best way to do that
position and rotation is simple enough
more the spawning and deleteing
wait
im pooling them
that shouldn't be hard then
+1
just need to store for each when they enable and all that
It's another scriptable object instance that contains the list of scriptable objects. It is set to dirty and saved in the adb
just in case you need this bit of inspiration
bricks.AddRange(grid.GetComponentsInChildren<Brick>(true));
whats the true do