#archived-code-advanced
1 messages · Page 191 of 1
https://pastebin.com/tuEMPEi2
There are like for loops inside of foor loops
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.
Ah I see, and then just update the loading screen in between
Yup. Could be a coroutine that yield return null a bunch
Note that you need to balance that because the more you call it the longer it'll take.
That seems relatively simple. I'm already firing off an event once it's done
Yeah it would have to be in logical places
Alternatively, if it's 100% your data, then you could create a background thread, give the background thread all the information it needs, wait for the background thread to complete, pull all the completed information from it, and hide the loading screen.
It's pretty much 100% my data.
But you need to make sure that the push and pull are done correctly.
except Vector2Int
I'm thinking GenerateChunks would be the spot to split it up
Vector2Int is your data.
I don't understand what "my data" is
Easiest thing to do would be to turn your loop into a coroutine and yield in your loops
Like -- don't touch any game object, etc.
Yup. It's common that logic just works on abstract C# stuff.
Not actual gameobjects, etc.
So, the two methods I'm seeing is to A: turn it into a coroutine
or B: turn it into a background thread that returns the map
That returns whatever the gamethread needs to make the map.
With the coroutine method, would I be able to have an animated loading bar or something?
Yeah. When the coroutine does a yield return, Unity renders a frame.
So it would just have to be placed strategically to yield around every frame
Nah
It's basically telling Unity "Okay that's enough for this frame. Start me from here next time."
Just yield at the end of every loop
I'm thinking the coroutine method sounds the simplest
Oh that's true, so if you want to quit the program mid-generation
Worth noting that threading it will make it considerably faster though
Then the gameobject managing the coroutine goes away, and the coroutine stops.
It's the easiest, since once you step out of Unity's main thread you have to also develop a method to communicate with Unity's main thread
hmmmm that's true
If you can break it up into more than one thread.
And then you get fun stuff like deadlocks
Also you can't use most of Unity's types or methods once you're in your own thread
Which are easily avoidable if you don't do messy crap. Just two SPSC queues, one in each direction, or something.
I mean just putting it on its own thread should lower the time between start and completion. No?
Yeah, but it's a lot of traps for a beginner to threading
Depends on how many frames it takes.
Also just putting it in its own thread won't really speed it up much, you'd have to do a full conversion to multi-threading to really get a nice performance increase
I think for now I'm going to use the coroutine method, that way I don't screw anything up too bad. If, in the future it seems too slow, I might try threading.
Depends... if you yield 10,000 times, and it takes 10ms to render a frame, then that's 100s extra lag.
I'll have to figure out where to put my yields
Or cut it into chunks that are a reasonable amount per frame
Yup.
You can limit it n ms per frame
yeah. Either way, thank you all so much for the help. I realized that I had no idea what the heck I was doing, so this has been amazing
Yeah... do a time check before you yield and see if you can still squeeze in another iteration or two or twenty before said yield.
I do recommend getting into threading and learning to do it, once you understand it it's not hard, and being in the habit of thinking async is good
Yep. I'm going to try to convert my pathfinding to the jobs system
Here's actually a funny story.
Back in 2014 - 2017, I was working on a chess game.
When I did the AI, I did a pathfinder algorithm. Never bothered multithreading it, but it was a background thread because AI.
How would I do the checks if I have no idea how long the code will take to run? Answer me after your story though, I'm interested in this
Check the system time in milliseconds when you start and when you finish, subtract
And to validate the paths, I ran the code through all my game logic, etc. etc. etc. It was unreal so those were UObjects... etc etc etc it was slow. I was only able to do dozens per second.
Easiest way is to just use the profiler though
And I was like "Ugh this is bad." Stressing about it I was like "Hope about I just try rewriting the logic with raw game objects and cut down code."
Went 1000x faster.
So I stressed for a few hours but then I was able to optimize it 3 orders of magnitude faster... in like an hour.
Was this a unity project? Just to be clear
Unreal.
But yeah it's a good thing to be like "Wait... does this order of magnitude time actually make sense?"
I think the order of magnitude for mine does make sense. It's doing some pretty stupid math, sooo
Mostly just each room iterating over every other room to figure out which is the closest
I'm more saying that the intuition of "wait, why is this taking 10s of milliseconds per path?" instead of worrying (like I did) would have pointed me to the real solution.
Nothing wrong with starting with the greedy solution and optimizing to get the optimal solution
Yup.
There's probably a better way to do it, I just don't really know how unfortunately
But it's good to develop that intuition too... that a memory fetch is ~200 cycles, and a if statement is ~2-20 cycles depending on branch prediction, etc.
Then you can think "If I'm doing X on 5,000 objects, I should have (4 billion / 5000) cycles to do it per second."
That sounds rough
//* Here We're getting a distance and assigning it a weighted value. The closer the point, the higher the probability it will be chosen.
List<KeyValuePair<Vector2Int, float>> distances = new List<KeyValuePair<Vector2Int, float>>();
foreach(Vector2Int distancePoint in midPointsCopy)
{
float dist = (float)Vector2Int.Distance(point, distancePoint);
if(dist <= 0)
{
// Skip over iteration if the distance is on itself
continue;
}
float weightedValue = Mathf.Exp(-(pathWeight * dist));
distances.Add(new KeyValuePair<Vector2Int, float>(distancePoint, weightedValue));
}```
I think this block is the biggest problem
You can profile it and see.
That is very true, I should really use the profiler more
Put a https://docs.unity3d.com/ScriptReference/Profiling.Profiler.BeginSample.html and EndSample before and after it
oh shoot that's a thing?!?!
holy crap
Yeah, the profiler is one of Unity's most powerful features...there's good reason it was a paid feature back in the day
my mind is blown
Then keep dissecting until you find the specific line that's effed.
Then try to figure out why "Memory lookups? Blocking call into something?" etc.
Definitely check out the API reference for the profiler, there's more handy features you can work into your code
I'll do that when I get home, but basically I should use yields if it can't do any more calculations, right?
yield says "Okay I'm done Unity do your stuff, pump the message queue, draw a frame, then get back to me when it's my turn again"
yep, so when I can't do more calculations in a single frame, then yield, and then come back and continue to do more calculations
Anywhere there's a yield statement in a coroutine, it returns control back to Unity until the next frame, and then starts from there next frame
Okay, all of the stuttery loading screens in games make so much more sense now
Yeah... a lot of it is that this industry is messed up and people don't question things.
To be blunt lol.
I've always thought that that was just a "thing"
Well that and actually calculating how long something will take to load anywhere near accurately is pretty near impossible
Here's another funny story.
Yeah, unless I do multithreading I will probably have a stuttery loading screen.
In Unreal, if you leave the oculus SDK's default splash screen thing, it will add like 20s load time to every level load.
that's kinda crazy
I figured it out and told a couple VR studios that I knew -- and they had no idea. They were just living with the load time.
Without that bug, load time was in the fraction-of-a-second range.
20 second load time for a splash screen is pretty crazy
Alright, well I'll stick with the coroutines and see how that goes.
I can't stress it enough but ty all so much for the help.
Yup
Lol oh no apparently this one guy (robcardiv) formatted their drive twice thinking that it was their PC causing the lag. :X https://forums.oculusvr.com/t5/Unreal-VR-Development/Splash-screens-hang-the-editor/m-p/770989
(Bottom of page)
Er... once... and was about to a second time?
I think this might be the issue??? https://forums.unrealengine.com/t/open-level-taking-a-really-long-time-strange/421871 Been a while.
Anywho -- yeah. It's surprising how many people just put up with that load time thinking that's what video games take to load levels.
Hi! I need some help with using my own model for this spider project. I'm hoping one of you worked with it and could help me with it, i'll gladly compensate a little since it's kind of important. https://www.youtube.com/watch?v=4Ff9XeACUH4
Find the Spider on my GitHub: https://bit.ly/3ifahan
A Unity Engine Project in which a controllable wall-walking spider uses inverse kinematics (IK) to position its legs to its surroundings in a smart fashion, such that is moves realistically. The user can freely control the spider, which is able to walk on any surface: walls, corners, ceilings...
awesome
Hey so ive figured out how to handle skinned mesh transforms when all the components are on the same layer
but how do I handle skinned meshes that are embeded in the armeture?
this is what its making rn wiht my current system
because if all the meshes are attatched to the same animator, it works fine, but as soon as theres another animator atatched to a bone with its own mesh it screws up
Yeah tmp handles this
Ok this is literally insane
Yeah, Unity's tooling is pretty good.
Yeah 😮
Of course a lot of the time it's not going to be a script that's out of whack. It's going to be things like physics objects, how things are rendered, etc.
But the profiler will help you see that -- especially the timeline view, which shows you what "every" thread was doing at each point inside a frame.
Practically every thread.
I think the only time I saw a conspicuously missing chunk of time was when I was loading an asset bundle... I'd see the file read/write and then a chunk of nothing, which ended up being where LZMA decoding happened.
I mean I guess it could have been a worker process for that matter. I didn't really look too far into it. (I obviously didn't care at the time lol.)
Physics methods creating GC always ?
thanks a lot also I guess I need to avoid .Where or .Cast methods right 😅
Yes. Though that allocation you're looking at is the array being created and returned to you
return ResultContacts.Where(x => x != entity.EntityCollider).ToArray(); this line still creating a minimal stable garbage is there any linq expression that doesnt create a temp 😄
ToArray creates a new array with the results
Which of course allocates the space for the array
and the lamda you're using is capturing entity, which will allocate the closure structure
hımm so i think the best way returning the same array without touch then adding something to the other section to handle that thanks again @austere jewel 👍
Im having this issue with explosion velocity where, the velocity still pushes the player even when touching a wall causing this to happen
For the explosion script
if (pm != null)
{
Vector3 forcedir;
forcedir = pm.transform.position - transform.position; //distance from explosion
pm.velocity = (forcedir * ccforce);
}```
this is what pushes the player
and in player movement
Controller.Move(velocity * Time.deltaTime);
so what do i do to fix the issue?
Also for some reason the player is launched farther if they are farther away from the location of the explosion
For that you probably want to normalize the force direction before multiplying it with it's magnitude, since the further away from the explosion, the bigger the initial direction vector is.
Since you're not using physics you'll need to handle the velocity dying out manually. Detect a collision with the wall and reset the velocity at that point.
im not sure if i should use a rigidbody for player physics or not cause it didnt work when i tried
or maybe i got something wrong
do i need a collider other than the character controller if i wanna use the rigidbody?
You can use either one. The difference is if you're using an rb, you're at the mercy of unity's physics system(although you can limit it's effects depending on the settings), while of you use a CC, you have to implement your own behaviour for things that physics usually does for you.
Cc and RB are not compatible. You should use one or the other.
If you're using a rigidbody, then yes, you also need a collider.
well rigidbody cant do slopes or stairs
Why not?
Are you saying it can?
Depends on what you mean by slopes and stairs, but you can add that behavior yourself if needed.
I thought the point of the CC was slopes and stairs
I'm not sure. I barely ever used CC.
Well, it should behave the same way as in real life
if you're using a box collider it will of course get stuck at the stair, but if you use a sphere or a capsule it might be able to go up the stairs depending on it's radius, the amount and direction of the force applied and the friction between the collider and the stairs
oh
CC > RigidBody for basically any movement system
EXCEPT if you want realistic physics
which you never want unless you are doing a physic simulation game like QWOP or stuff involving accurate forces
True that, but you can get a CC kind of behavior with rbs as well.
rigidbodies arent in my experience, snappy enough to create precise and snappy movement systems unless you do a lot of workarounds
Just make it kinematic and move manually.🤷♂️
yeah but they are very erratic, in my experience at least
for 2d platformers I always had some kind of issue
specially with collisions
Sorry but, whats the issue with the behavior
he hits a wall and stops?
the wall stops the player but once the player is no longer is touching the wall the force moves the player
Im trying have quake/tf2 style movement
which isnt what i would call realistic
I wonder if dusk/ultrakill used either cc or rigidbody
That sounds like an issue with your code rather than CC
CC dont move
unless you call move
with a speed
if you arent handling your speed correctly you might get issues
usually the strategy is to separate speeds into different forces
so you have normal movement forces, gravity, platforms/threadmills, etf
and at the end of your physics update you add eveerything together and get a final speed
then use move
you should be using fixed update btw
Game run on editor as expected but in android it gives these because in some scripts i have dynamic variables in my scripts
Scripting backend = ILL2CPP
StripEngineCode = On
ManagedScriptingLevel = Low
Any idea to fix that without break my structure in script ?
remove dynamic. Not supported in il2cpp https://docs.unity3d.com/Manual/ScriptingRestrictions.html
what do you mean exactly by anchor proportionally?
dynamic? 🤢 theres not many reasons why dynamic should exist on C#
@sly grove Were you ever able to write an iterative version of the algorithm?
(I'm not saying it can't be done, just that it seemed a lot of work)
I'm aware of the Church-Turing thesis.
how do i have a overlay 2 cameras, each rendering a different layer in hdrp?
anyone familiar with mirror commands?
Hey, I am trying to pushback a characterController. (in a similar way to rb.addforce)
How should I do it?
private void PushBack(GameObject Player)
{
CharacterController cc = Player.GetComponent<CharacterController>();
cc.Move(force * time.deltatime);
}
``` will only work once...
I did write one you rejected it because it used heap allocated data structures.
But no I've not been thinking about your problem since then.
Well, if you can write one fully, I can benchmark it alongside the existing algorithm and we can see which one performs better?
I wish I had the free time for that sir. Good luck.
Trying here since no one had an answer for me in code-general. Does anyone know how to work around "onmouseexit"/"onpointerexit" not triggering appropriately? You can see in my video here that I have coded a hand of cards that nudge each other out of the way when you mouse over one. The issue is that if I run the cursor over them too quickly they get jumbled. Any advice would be appreciated
If you didn't like what he wrote, why not write a better one yourself?
ah yes, you are discovering how hard this is
the collider for the touch events must not be the same as the collider for the cards
you have to make an even, regular row of rectangles
that do not move
in 2d
What? Did you read the context before answering?
the actual cards you probably want to lay out in 3d if you want zoom
but heap allocated data structures on computers purpose built to allocate things on the heap is blasphemy
you can try this package https://blog.devgenius.io/like-regular-linq-but-faster-and-without-allocations-is-it-possible-3d4724632e2a
Who didn’t use LINQ? But you must’ve also heard that it imposes some performance hit. Can we do better?
for common linq behaviors it should suit you well 🙂
NoAlloq, LinqFaster, Hyperlinq, ValueLinq, LinqAF, StructLinq all do stuff like this
so the collider moving is the issue?
how to made in game programming (i.e. scripts)?
how to made support for mods?
I'm going through my code, and I'm having huge memory leaks. It appears to have something to do with the LOH (Large object Heap) and the fact that these objects are not being collected by the gargabe collector (I think). I'm using a 2d array of enums like so: Enum[,] name and I'm doing lots of stuff with it inside foreach loops and for loops and whatnot. I've tried manually calling the garbage collector, clearing the arrays, and nothing seems to clear the issue. I would appreciate any help you can give.
So I figured out that with a single animator at the top of a skinned meshes, in order to get from graphics buffer to the proper world space position, I have to multiply each point by the hip bone of the armeture's world to local matrix, then multiply it by the parent of the armeture in the hierarchy's localtoworld matrix, then take the of the hips parent(so the armeture object in the hierarchy) localtoworld matrix multiplied by the hips local position, then multipled by the armetures worldtolocal matrix, and add that to each point, and that gets me from the vertexbuffer output to the correct world space positions
What do I have to do if instead now its an animator with a skinned mesh that is attatched to one of the bones, so like in the image instead(where tail is the skinned mesh attatched to the animator in OniTail)?
https://cdn.discordapp.com/attachments/377557956775903232/977334943120252958/unknown.png
because without changing anything this is the shit I get
any help is appreciated, its driving me insane again
like do I now need to multiply the vertex's by every single bone going up to the origional hips?
There is probably an array of weights [boneNum] that is part of the vertex data
if you can reconstruct what the combined matrix is, of bonematrix[1,2,3,...] multiplied, then thats the transform for that vertex
each bone that can potentially affect the vertex has a 'weight'
this is all general info and i unfortunately know next to nothing about the details in unity
hrm ok
if it helps at all
if I do BakeMesh(mesh, true) I can get a proper, but if false its still improper
I do not understand why this offset exists...
Hello everyone. I have gif image url. Now I wanna replace the raw image with this using unity c# code. I guess the gif image should be split to the frames. Please let me know how I can do this in unity c# if anyone knows. Thanks
here is the gif image url
https://ipfs.fleek.co/ipfs/bafybeia5f7ropf4mocemkkqsni6ympg7eoinquonczj54afjffvydytktq
Don't crosspost
So since a physicsMaterial2D's properties can't be changed during runtime, or cant be applied during runtime, how do i make my player bouncy sometimes and not bouncy other times, without needing multiple rigidBody2Ds?
it can be swapped during runtime for other material
just create one physics2d material with 0 bounce and other with full bounce
and do Collider2D.sharedMaterial = thePhysicsMaterial
I did, it didn't do anything
gimme a min
I gotta check smth
Yep, thank you. I was changing the RigidBody2D's material without changing the collider's material.
no problem
What's the actual error message?
Full message
typeof(type) doesn't make sense
You'd just use type directly there
typeof() only works with literal type names like typeof(MonoBehaviour) for example
typeof(Something) gives you a Type.
You already have a Type so you don't need it
var DeclaringMembers = type.GetMembers().Where(x => x.DeclaringType == type);
could this work ?
Hey, guys. Trying to Google something, but I’ve forgotten the actual name of this type system. It’s a technique for managing positions in large-scale games, think real-scale solar systems. Involves breaking the space into cubes, breaking those down into smaller cubes, repeat until you can maintain floating point accuracy. Does anyone know what this system is called?
Bit of a brain fart.
Floating Origin is what i have see used
its moving the world origin around the stuff that you actually need to render and calculate
Yeah, have a system for that.
@marsh oak do you need to keep only the fields whose type that derives from scriptable object, is what I'm gathering by glancing over the conversation
but you only want to keep your types
yeah so:
- create an attribute that this logic needs to apply to, and mark your classes with it (its more flexible than subclassing something). Another way is to implement a tag interface, also works, but you can put more indo into attributes
- you can just iterate fields already with GetFields
fieldInfo.FieldType.GetCustomAttribute<YourAttributeType>()will give you your attribute
attributes of the subclass?
what attributes do you have in mind?
[TheseOnes]?
System.Attribute
In what class? what fields? what do you consider to be attributes there?
CreateAssetMenu is the only attribute there
these are fields / properties
ok so your so's getting dirtied at runtime, which you essentially want to roll back when you exit play mode
you might be able to use some logic in SerializedObject, so that you don't have to reimplement most of this stuff
I haven't done this, but it might be an option
or I guess you can just clone obejcts
yeah
does CustomScriptableObject have common fields?
for the subtypes
or is it just a marker
yeah then I'd use an attribute instead, or an interface
[RestoreAfterPlayMode]
class SO : ScriptableObject {}
the usage would be sort of like taht
or on individual fields
depends on what you need
you can get set field values with fieldInfo
that you get from GetFields
Whenever you use one of those sorts of tools, you’re posting plain text. When you hit save to get a link, it tries to guess what language it is. It’s not always accurate, but what’s important in that case is the code proper, not the extension.
you can define custom attributes and then query them via reflection
and the fieldIngo
fieldInfo.SetValue(objectOnWhichToSet, fieldValue)
and
fieldInfo.GetValue(objectFromWhichToGetFieldValue)
your scriptable object instance
and the fieldInfo is what you get from GetFields (you get an array, a filedInfo for each field)
yep, it's correct
the tyoe of test will be object
and then you can set it on the onstance
you've probably got some other code not commented out completely or something
I can't spot it on mobile
GetFields also takes binding flags
you may want to specify those too
yeah
filters what it should query
static vs instance fields, private, public
by default it only returns public fields
yes
but I'd try using SerializedObject instead anyway
it should be simpler and faster in the end
- it takes care of figuring out whatever needs to be serialized
Unity also has [NonSerializable] which can force a public field not to be serialized
so you'd ideally need to take care of all this too
= reimplementing logic already existent in SerializedObject
no problem
of course
you're telling it to only fetxh the static fields
it has all categories within
yes, you do tell it to get either
but by category
static goes with isntance
and public with non public
I'm pretty sure that's how it works
so if you wanted instance fields that are either private or public
you'd do Instance|Public|NonPublic
no
like if you wanted just instance fields, you'd do just Instance|Public|NonPublic (you don't care about visibility, it can be either), but if you wanted either static or instance fields, you'd do Static|Instance|Public|NonPublic
so one of either Static or Instance has to match with the one of the fields (the staticity) and one of the access modifiers has to match with that of the field
you kind of have two independent search criteria that both have to match at least one of the specified options
if that makes sense
I'm sorry if I'm explaining it in a complicated way, i probably am, I'm going to bed rn
good night
realize this question may be better suited here, but what would be the best way to send lots of textures to a compute shader, but still be able to modify how many textures are sent in real time? I need a replacement for doing PackTextures every time something needs to update
the collider below your mouse changes as it moves
send i out of N possible textures
so choose a number of textures max you can send
ok yeah I know the max amount of textures
but that will change
otherwise worse case could be like 100
of 8k
since I cant make a 16k packtextures work in real tiem
wait that sounds like a shitton of memory
ok fine so one massive atlas may be my best bet then, is there any way to speed it up to not take like 3 seconds for a large texture?
if the textures are loaded in the GPU already you have ways of accessing them without copying
it sounds like they are not though
what part is being slow?
no
they are atlas's that I create for each object
Currently I then create an atlas from those atlas's to make a max of a 16k texture
this freezes the program for a bit, which is bad since I need to redo it every time I spawn a new object
no
they are different objects
and they are actually many objects merged together usually, with 1 atlased texture which is fine
again whats not fine is when I need to remake the main atlas, as that freezes the main thread for far too long
quick question, this has basically already been answered by unity, but then again, the answer is 9 years old..
https://issuetracker.unity3d.com/issues/t4-templates-disappear-from-monodevelop-project-after-refreshing-solution
Is there any way to stop unity from removing T4 templates from the project solution, and if not, what is this monodevelop add-in unity was referring to here? 😅
While editing scripts in MonoDevelop, user has created text templating "T4 Template" file, which was successfully added in file hier...
@undone coral heap allocations in hot code is never good. it's why the stack exists.
I'm not trying to get a mere 2M nps. With current optimizations and utilizing the stack, I've been able to get speeds up to 147M nps (Stockfish 15 is at 242M nps).
a what
you should create a separate solution outside of unity for these maybe. otherwise write a custom importer for the extension and set it to do nothing
yeah, that's what the page says as well
it just seems weird to me to create a different solution file just for something so simple
am i really to create a separate solution for one file?
I'm not sure whether two solutions can be in the same directory either so that's going to be fun for git if i do that
nvm, in between all the spam comments, there is a fix on the second page for it
I basically have this code to generate and regenerate a map in the editor, but the clear part of the script isn't working. Any idea why? I'm not able to reset and destroy the previous objects fom my scene in editor mode
Try DestroyImmediate(map.transform.GetChild(i).gameObject)???
it seems like he's lefting some behind
it's deleting some now at leats, that's progress
Er I guess that would fail if you forward-iterate.
for (int i = map.transform.childCount - 1; i >= 0; i -= 1)
{
DestroyImmediate(map.transform.GetChild(i).gameObject)
}
Ideally you'd just make a generic algorithm that reverse-iterates.
worked perfectly, ty
Hello :), I've been trying to solve this problem forever so I figured I'd ask here. I'm making a game where to teach ppl to code, you can write code in game and run it, I'm using https://github.com/aeroson/mcs-ICodeCompiler to compile at runtime and it works but I want to restrict what the user can do. I tried following this tutorial for sandboxing: https://docs.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/bb763046(v=vs.100) but it gives me an error PlatformNotSupportedException: Operation is not supported on this platform when I try to define the fullTrustAssembly, which I assume is because Unity doesn't have a strong name but I can't remove it since it's required as per the tutorial. What is the best way to go about this?
hmm
Any other ideas for this by chance? I need a way to have an array of textures of dynamic length that I can update in real time to send to a compute shader
I’m really stumped about this, but I know I need a replacement for packtextures if I want to get far with this
yeah heres why I need to change
If I drop the atlas texture size down to 1024 object loading is litterally seamless
but thats not ideal for like 40 2k textures
Hi there!
Is there a best practise for implementing sequences right in Unity?
My initial Idea was having some instructions consisting of n AudioClips and *one *IEnumerator which then get stored in a List and get executed, so that the sequences are modular and easy replaceable. So I created a class which does exactly that, but the Handler object I intended to use for executing the list of these sequences doesn't Work as expected...
Do you have an Idea how to split the Sequence properly in some chunks and use them later?
Thank you very much!
Greetings gentlemen, would anyone happen to know why JsonUtility.ToJson returns an {} (empty string) upon serialization?
_data and _state are ScriptableObjects, BUT they serialize nicely due to ODIN extension. So I can serialize both of them separately (tested)... but when I serialize InventoryItem as a whole it returns empty string.
[Serializable]
public class InventoryItem : IInventoryItem
{
[SerializeField, OdinSerialize] private readonly IInventoryItemData _data;
[SerializeField, OdinSerialize] private IInventoryItemState _state;
[SerializeField, OdinSerialize] private readonly Type _type;
public IInventoryItemData Data => _data;
public IInventoryItemState State
{
get => _state;
private set => _state = value;
}
public Type Type => _type;
public InventoryItem(IInventoryItemData data)
{
_data = data;
State = new InventoryItemState();
_type = GetType();
}
}
JsonUtility and serialization in the editor aren't the same
They don't support the same things
Both _data and _state serialize into JSON files, as well as being editable in the editor. That's what causes my confusion. Basically, 1) all parts of this class are serializeable, 2) they serialize independently, but 3) whole class serializes as empty string.
Currently working on isloating _data and _state in separate data-holder class, will see if that works. (but that's an extra serialization/deserialization steps which is not really pleasant)
They're interfaces though and JsonUtility probably doesn't support that
And readonly might also be a problem
Removing it doesn't help, although might break de-serialization, but I'll address it later
Yeah, I figure it has something to do with interfaces, will test it. thought it would support something like that
Hello to everyone, I have a question to a more experienced developers. So I making a game very similar to a tetris, but in my version i have only horizontal blocks which can move by player only horizontally (there is already games with this mechanics, so nothing special) The game already working if i setup the level and you can spawn next block from top of the board when you have cleared some of the lines (like in tetris) buuuuut... the problem here is that I need to change spawn point from top to bottom (when we clear a line, we spawn not one next block but a 2 mb 3 from bottom) and I need somehow to show what would be the next blocks.....and of course I can create a method that would calculate the next block and his spawn position on the line based on board width (for example with width of 8 we can create two blocks with sizes 3 and 2) and... its ok..... but problem here that how could I know(calculate) if this newly created line of blocks is good for a board with width of 8 and there would be no situation where the player has no more chance to continue. I messing up with this and try to look at similar games and found that in those game they for example have only 1 block with size 4 in one loop, so they dont spawn next before this one (size4) would be destroyed.... who can help to get me out of this stack ? Guide me please in a right dir. Thank you!
and of course sorry for my English.
Anchors are percentage based, so you can say, for example...
layout:
Container:
- Top: anchor: min=(0, 0) max=(1, 0.5)
- Bottom: anchor: min=(0, 0.5) max=(1, 1)
Then it will scale up
I recommend watching some UGUI tutorials, it's not super obvious how to use it properly.
I know how they work, I've used them to position the header and the content container correctly
Great!
So what are you stuck on?
You need to use TMP
If you want the text to resize
It's just an option on the TextMeshProUGUI component
Set the max size high and it will expand up to fil the box
and parent the image to the text?
exactly to the right of the text
I typically don't add children to text or images, I just create empty layout boxes for positioning things.
Do you want the image to resize?
Okay, cool. In that case you need an aspect ratio fitter IIRC
So it would be something like this:
- HorizontalRow
- TextMeshProUGUI (set anchors to left)
- AspectRatioFitter (set anchors to right)
the last problem is that it may go beyond the cobtainer if it's parented to the text
Yeah, you shouldnt' be parenting it to the text.
If you want to control its size.
Unless you want it to overlap the text
That sounds difficult or maybe impossible.
Is there a neat way to start a Coroutine at a certain point?
for example:
public IEnumerator Sequence(){
yield return StartCoroutine(A1())
yield return StartCoroutine(A2())
yield return StartCoroutine(A3())
yield return StartCoroutine(A4())
}
Now you are noticing that A1 and A2 worked just fine. But you want to start Sequence() at Coroutine A3()
Is that possible?
You can pass in parameters to that coroutine and optionally run or not run any of those other coroutines with simple if statements
yeah I thought about that, but I really don't see a clean way to implement that. And I would like to avoid an endless if-else chain ...
but maybe I could use switch cases without breaks x)
Hi!
Someone could help me clarity this? I have a GameObject that reference a ScriptableObject istance. How can I inspect the instance values?
An array of bools and a for loop? Or a list of ints describing which ones to run or which to ignore.
the ScriptableObject instance is in-memory, so I cannot select it in the project window
can somebody help me out with this issue im having? the drawn mesh is not following the position of the object or the input position at all.
foreach (MeshFilter filter in meshFilter)
{
GameObject currGO = filter.gameObject;
Mesh currMesh = filter.sharedMesh;
for (int i = 1; i <= _propInstances.intValue; i++)
{
Vector3 finalPosition = _propPosition.vector3Value * i + currGO.transform.position;
Quaternion finalRotation = currGO.transform.rotation * Quaternion.Euler(_propRotation.vector3Value * i);
Vector3 finalScale = _propScale.vector3Value;
// Create a translation, rotation and scaling matrix
Quaternion rot = Quaternion.Euler(_propRotation.vector3Value * i);
Matrix4x4 m = Matrix4x4.Rotate(rot);
Vector3 rotatedPos = m.MultiplyPoint3x4(finalPosition);
matrix = Matrix4x4.TRS(rotatedPos, finalRotation, finalScale);
_previewMaterial.SetPass(0);
Graphics.DrawMeshNow(currMesh, matrix);
}
}
by watching the video, you should see that the drawn mesh are moving at a different direction and isn't following the input position
you want them to move in the same direction the main object goes?
they're on the same axis so moving something on the X axis will move the farmost left one left, the upmost one up and the furthest one right one right
yea that's what i'm doing with this code here: Vector3 finalPosition = _propPosition.vector3Value * i + currGO.transform.position;
currGO being the main object
but i want the drawn mesh to move together with the main object like this
get what im trying to do?
It's been a while since i've done matrix transformations, so if i'm wrong, please correct me
but what i think you want to do is:
- scale
- translate: to assign the offset
- rotate: so the blocks are in the right direction (like you have now)
- translate: again, so the matrix is back together (as shown in your second video)
Is it possible to replace a component with a component of a child class, you have "parent" on an object, you replace it with "child" that keeps all the values of "parent"
hmmm so i should do all these 4 steps before drawing the mesh?
you need to do a deep copy yourself
what's the offset you're talking about btw?
yeah, i'd recommend having a look at https://catlikecoding.com/unity/tutorials/rendering/part-1/ if you haven't already
but like he demonstrates here:
Normally you scale first, then rotate it, and finally you translate it
But in your case you want the "offset" to be applied before you rotate it, so it is included when you multiply it (offset is just another translate)
you should get something like this, if you use (scale) matrix * (offset/translate) matrix * (rotation) matrix * (worldposition/translate) matrix
and for demonstration purposes, this is what you want to achieve right?
https://i.imgur.com/g4UC06T.mp4
@kindred tusk 👋 - I hadn't seen you in this discord in a while and meant to mention that I had the same issue you did recently.. but dammit, I can't remember what the issue was. It was some github issue comment.
It might not have even been unity related.. I wish I remember what the hell it was.. I believe I had found a solution to it too 😐
Ha, found it. https://github.com/Demigiant/dotween/issues/539
I was getting spam from this same error but for something entirely different - I was setting some rect transforms of a prefab in OnValidate, and I solved it by not doing that in OnValidate but instead subscribing to UnityEditor.EditorApplication.delayCall and doing it there. 🤷♂️
hold up so i can't just use Matrix4x4.TRS() ?
hmmm alright will try
How would I add a timer to my first person controller so when there is no input after 60 seconds it takes me to a scene?
literally just set up a timer which reset every time some event occur (in this case inputs)
you can do
public IEnumerator Sequence1(){
yield return StartCoroutine(A1())
yield return StartCoroutine(A2())
}
public IEnumerator Sequence2(){
yield return StartCoroutine(A3())
yield return StartCoroutine(A4())
}
Oh nice!
You should chuck that solution in the GitHub issue
not sure it's related, TBH - when I went down the rabbit hole, it was some sort of unity thing that they either didn't want to fix or .. was in place for some other reason
you need to represent your board logically, not in game objects. then, since there are a finite number of positions you can spawn the block, check each one until you find a valid placement
Lol "illustrious"
Shucks
I bump into your comments on github everywhere it seems :p
honestly if I could do the shit you do, I'd consider myself a success, I'm just a grasshopper
Probably just been doing it for longer than you :-)
and harder
your "every day has activity" streak from mid nov to mid jan is impressive
hehe
i've wanted to write a bot that draws pretty pictures on github activity logs but i've got enough side projects (and to be honest I'm sure one already exists)
Honestly a better use case would be to make it look like real work and then apply for a job
Hahaha
haha
my workflow is currently a bit stunted, tbh - local work for days and github as a backup repository.. dozens of commits with the message "WIP" for days/weeks at a time
@undone coral the board its a 2 dimensions array of transforms, each block knew his size of tiles. So when block is moved or fall he rewrite his position on grid like in tetris, but i still don't know how to create new blocks that would guarantee the board has some ways to be cleared
I read your problem, briefly.. seems like just brute forcing it is fine? IE, if you have a block, check if it clears a line if dropped in position 1 (all the way to the left), then 2 (one block from the left), 3, 4, 5.. If any any point it does, break out of the "isValidNextBlock()" check. Then rotate it 90 degrees, repeat 3 more times. Then do that for all the blocks you have, and if none make a line, game over or whatever you decide is appropriate.
Or, alternatively, do this for all the block types, add those valid "next blocks" to a list and select the next block randomly from that list.
@misty glade i understand you're thinking but.... I must see what would be the next spawned line before i clearing one, so the code doesn't known what blocks would disappear. I think maybe i need some method that would be called after line was cleared, and this method would sort all blocks from a board and count how much blocks we need to create more than one line, but in theory. I think i need to dig this better to found good approach. I know the maths but how to found right answer.
@misty glade if i dont found i just implement a method that would check all possible ways to make a line and if it have not one would be game over
@misty glade there is a game slidey in this game is way im looking
hey so is there a better way to do this that doesnt use so much memory?
If I make a variable that is new uint[8], and replace all the new uint[8]'s with that, memory use halves, but it doesnt work I assume because they are getting linked(same thing happens if I make an instance of BVH8Node and set all BVH8Nodes to it)
for(int i = 0; i < BVH2NodesCount; ++i) {
BVH8Nodes[i].e = new uint[3];
BVH8Nodes[i].meta = new uint[8];
BVH8Nodes[i].quantized_min_x = new uint[8];
BVH8Nodes[i].quantized_max_x = new uint[8];
BVH8Nodes[i].quantized_min_y = new uint[8];
BVH8Nodes[i].quantized_max_y = new uint[8];
BVH8Nodes[i].quantized_min_z = new uint[8];
BVH8Nodes[i].quantized_max_z = new uint[8];
}
Not sure if you have posted something before this, but you might want to look into other datatypes like uint8, depending on how big the values are that you insert
That should divide the space by 4 times
I do it like this so I can send it to the GPU
they used to be bytes but I cant send bytes to the GPU natively
and my attempts at packing and modifying it did not work
Aha you should've mentioned that
Look into bit shifting and make your own format if possible
I did
didnt work
How did that not work?
idk
just didnt
values in and out were not correct
but still is there any way to not do the new uint[8] so much? this is for thousands of things and consumes a ton of memory
ArrayPool?
My guess is that you didn't do it correctly
I've done it before and it worked just fine
yeah
i know
but still new short[8] isnt performing much better than new uint[8]
same with byte
Are you sending it to the GPU and back every frame?
Hmm.. not sure if I can provide any ideas in that case
Why do you need an array of 8 of ints/shorts anyway?
you can think of it as a compressed version of an octree node
so each one is the AABB's in a compressed format of the 8 child nodes
even converting it to chars dont help
nor do bytes help
I think you should first try to get the algorithm to work before you try to optimize it
oh it all works
problem is this part is taking up 2-4 times more memory than it should be
and if I remove all the news, suddenly its taking up the proper amount of memory
i've seen and ignored that issue for years
i've been thinking about this and i think the only thing that went wrong is the endianness of your packing
oh?
but still what im talking about now is on the CPU
yeah it was packed little endian
ohhhh
and you really needed it packed big endian
seems weird though
since you are the one interpreting it
i mean you should send it little endian but read the 4 bytes in reverse order in your shader
does that make sense @honest hull ?
yes
its layout in memory is backwards to what you expect because your platform is little endian
ok
okay
here is how you should decode
uint Encode(byte b1,byte b2,byte b3,byte b4) {
return ((uint)b1 ) |
((uint)b2 << 8) |
((uint)b3 << 16) |
((uint)b4 << 24);
}
decode, adapted from :
https://github.com/keijiro/Pcx/blob/ffc344756b9320584a02a738c8b9d328090e1bc3/Packages/jp.keijiro.pcx/Runtime/Shaders/Common.cginc#L15
half4 Decode(uint data)
{
half b1 = (data ) & 0xff;
half b2 = (data >> 8) & 0xff;
half b3 = (data >> 16) & 0xff;
half b4 = (data >> 24) & 0xff;
return half4(b1, b2, b3, b4);
}
@honest hull
Is there a Math wiz in the audience?
Don't ask if anyone knows XYZ, ask your question directly in the relevant channel.
ah I see ok
I figured it out a different way but I may try this
But currently still on the memory train, is byte[] A = new byte[8] not taking up the space as 8 bytes in memory?
it should definitely take up 8 bytes of space in memory
provided it's aligned
hmmmm
just wondering because my code is taking drastically more than it does in C/C++
driving me nuts
hmmmmm
I'm not an expert but have you set the layout?
no not yet
requires unsafe
and that requires setting all my functions to unsafe last time I tried
and that requires others who use this to enable unsafe
No it doesn't..?
https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.layoutkind#system-runtime-interopservices-layoutkind-sequential
It goes without saying that you'd want LayoutKind.Sequential
As noted on the page the default pack size is 0, so that's good
Well, you can use explicit if you want to calculate everything for yourself
You might even find micro optimizations to pack things better
Refer to https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-packing-rules for that
ye I am find with explicit but getting an error where Reference typed field 'e' has explicit offset that is not pointer-size aligned
it comes after a Vector3
I'm having trouble with this code for intercepting a target ```internal float3 Intercept(float3 targetPosition, float3 targetVelocity) {
var speedRatio = math.length(targetVelocity) / this.maxSpeed;
var distanceVector = this.position - targetPosition; // inverted
var targetAngle = Vector3.AngleBetween(targetVelocity, distanceVector);
var myAngle = math.asin(math.clamp(math.sin(targetAngle) * speedRatio, -1, 1));
var distance = math.abs(math.length(distanceVector));
var prediction = distance * math.sin(myAngle) / math.sin(math.PI - myAngle - targetAngle);
var target = (math.normalize(targetVelocity) * prediction) + targetPosition;
return this.Seek(target);
}``` It works awesome, but only on in the -x and +z quadrant. In the other directions it looks like the target is a mirror image of what it should be
so I did the explicit layout
its still the same
so I initialize an array of that now expliticetly defined sized struct
thats fine thats the expected memory use
Then I do the New's and suddenly its double
Are you still referring to this code here with "the new's"?
yes
SO
I MADE IT FIXED SIZE
WHICH MEANS EVERYTHINGS NOW UNSAFE
BUT ITS HALVED THE MEMORY USE
but I cant have it unsafe
so I have confirmed that its the news basically eating up half of my memory usage
because if I declare the arrays inside the struct fixed size(which requires unsafe which I cant keep) my memory use is halved
You're probably doing something weird
I also don't see why you need unsafe
Can't you assign the arrays without unsafe in the constructor?
no
I need them to be fixed size
fixed reuiqres unsafe
this took 17 gigs without the fixed size
it just took getting rid of the news
so going backk
is there a way for me to do this without declaring the arrays fixed size in the struct?
or is this just not possible without unsafe?
End of the day, I NEED to get rid of these new's
Hey guys, i was trying out A* and was wondering how i could convert this code into one using sqrMagnitude instead of distance
void FindNearestTarget()
{
GameObject[] targets = GameObject.FindGameObjectsWithTag("Player");
GameObject nearest = null;
float distance = Mathf.Infinity;
foreach (GameObject obj in targets)
{
float d = Vector3.Distance(transform.position, obj.transform.position);
if (d < distance)
{
distance = d;
nearest = obj;
}
}
target = nearest;
}```
``` currentTile.h = Vector3.Distance(currentTile.transform.position, target.transform.position); ```
distance = sqrt(pow(a,2) + pow(b,2))
not sure why you would want to do that tho, since you're basically throwing away performance
Yuk, pow(a,2) instead of a*a
I was under the impression that using square magnitude was better for performance
Guess not
Vector3 difference = obj.transform.position - transform.position;
float d = difference.sqrMagnitude;
you're right :p
Ah thanks
and yes, this should have better performance than using Vector3.Distance or magnitude directly. As long as you don't care about the actual distance and just which one is nearest/farthest, it is a good choice.
Squared one is slightly faster. Find method youre using may be more of a performance problem tho
@gray pulsar @somber swift @wary swift Thanks!
i'm looking at the source code, and it's quite odd how that isn't a method in the vector3 class itself
it seems like something you would want to use more often 🤷♂️
Vector3.SqrDistance? yeah, that seems like it would make a nice extension
Just use (v2 - v1).sqrMagnitude lol
sure, but if Vector3.Distance is worth having, why not SqrDistance?
but that constructs a new vector3?
Distance also does
- its not a class, its a struct 2) Its not very useful on other cases than optimization 3) its micro-optimization anyways, on pc youre gaining pretty much nothing by using squared distance 4) feel free to make your own extension method if necessary
It's literally that inside, without the "sqr"
And yeah, Vector3 being a struct creating one won't harm your computer since it'll be on the stack ie. dropped when execution exits the block it's declared in
I just like it because it makes the intention of the code crystal clear. Constructing (v2 - v1) adds a little bit of muddiness that it could clean up. But yeah, def not a big deal either way
i'm not sure if you intend to come over as aggressive, but that's how i interpret it since you're basically just throwing bullet points at me
but sure, you're right on that it's a struct, not a class, i overlooked it for a second, thanks for correcting me
and sure, i could make that extension if i wanted it, i'm just saying that i'm surprised that it isn't already there
It being a micro optimisation, i find an irrelevant argument, vector3 is used everywhere in unity, so it not having some well performing methods seems odd to me
regardless whether you're on pc or not, unity is a cross platform game engine, and just because pc might not benefit a whole lot from it, doesn't mean mobile can't
especially when you're comparing a lot of variables
Sorry, i didnt mean to be agressive, i just wanted to list few things why I think unity havent implemented that. Only platform I have tested it is pc so I dont know of the others but atleast on pc, that would be unnecessary in terms of performance these days. It is actually bit weird that Distance, magnitude and sqrMagnitude exists but not SquaredDistance. Maybe they are trying to keep the amount of functions at minimum and they didnt see that too useful (as its quite easy to do the same using sqrMagnitude. I think think the whole point of sqrMagnitude is that you can use it to optimize certain things)
ive noticed something extremely strange...
i normally get 300+ fps
but then i select something in the inspector
and the FPS drop to 30
is that normal?
Doesnt sound normal
how do i start to go about figuring out why thats happening
Profiler could probably help on that
i have no idea how to read that thing
unless he activated deep profiling in the profile, and that's why it's slow 🤔
click on it ^^
the inspector does potentially a lot of work every frame, if you've selected something "heavy" I wouldn't be surprised to see the frame rate tank like that
oh and go from timeline, to hierarchy (on the center-left)
Yup
it seems like everything is fine, minus the 1.9kb of garbage that you're generating that frame
is that a lot of garbage?
i would consider 2kb a lot of garbage, if it happens every frame
alright
but i'm also quite nit-picky
still ill get on fixing it
thanks
ah that was the reason
i was still in debug mode
disabling it fixed it
Anyone here familiar with Mirror Networking?
It's been a while, but I have used it commercially.
I've got odd behavior going on, don't really know how to describe it. You got a minute?
I am back-and-forth from the computer, but I can try.
#archived-networking or join the mirror discord server
Pretty new to coding, hoping to find someone with a good amount of experience I can throw some money at to chat with me for an hour or two and give me some direction on this project.
Not to say I'm not up for the offer, but you may not need to throw money to get attention if you need it.
I'm up for a couple hours if you need; you can keep your pocketbook closed.
Hello, is it possible to change the projection matrix of a VR camera on single pass mode?
@old swallow Don't cross-post. Pick a channel
sorry
how do you get native plugins up and running for IOS? in short I want to create a native plugin of the stockfish chess engine source code that is in c++, to do so I need to make a dynamic library of it, but im a bit confused as to how to do that on Mac os for IOS
I am using Voice Recognition from https://docs.microsoft.com/en-us/windows/mixed-reality/develop/unity/voice-input-in-unity
Therefore I've created a class
public class KeywordRecognition
{
private KeywordRecognizer _recognizer;
private readonly Dictionary<string, System.Action> _keywords = new();
public void AddKeyword(string keyword, System.Action action)
{
_keywords.Add(keyword, action);
}
public void RemoveKeyword(string keyword)
{
_keywords.Remove(keyword);
}
public void ClearKeywords()
{
_keywords.Clear();
}
public Dictionary<string, System.Action> Keywords => _keywords;
public void Start()
{
_recognizer = new KeywordRecognizer(_keywords.Keys.ToArray());
_recognizer.OnPhraseRecognized += OnPhraseRecognized;
_recognizer.Start();
}
public void Stop()
{
_recognizer.Stop();
}
private void OnPhraseRecognized(PhraseRecognizedEventArgs args)
{
System.Action keywordAction;
if (Keywords.TryGetValue(args.text, out keywordAction))
{
keywordAction.Invoke();
}
}
}
and added it to an example class to test it
public class ExampleBehaviour : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Debug.Log(("Recognition started"));
KeywordRecognition recognition = new();
recognition.AddKeyword("blue", () => { Debug.Log("Blue"); });
recognition.Start();
}
}
but it wont recognize the keyword for some reason....
Hi guys, i've been struggling the whole afternoon with this. I'm trying to create editor script that will reset all overrides on all selected Prefabs in my scene, except a certain type of component (could be transforms, could be meshrenderers, materials...) But i rly don't understand the PrefabUtility workflow. The closer i got to it was finding the property path of each PropretyModification via GetPropertyModifications() and comparing it with a string list of avoided propreties that i manually set. But it doesn't seem solid. And it's only resetting the propreties, not the added objects or removed objects and so on. Basicly all what i need to do is select a bunch of prefabs (hundreds in my scene), and revert everything to the original prefab except for their transforms, static attribute and scale in lightmap. Any explaination about how to go about doing this kind of stuff would be very helfull !
What about ..
https://docs.unity3d.com/ScriptReference/PrefabUtility.RevertPrefabInstance.html
?
Just make a copy of an object, revert the original then copy & paste the components/objects/values you want to persist and then delete the copy.
Pseudocode:
copy = Instantiate(original);
PrefabUtility.RevertPrefabInstance(original, InteractionMode.AutomatedAction);
var addedComponent = original.AddComponent<PersistMePls>();
CopyValues<PersistMePls>(copy.GetComponent<PersistMePls>(), addedComponent);
DestroyImmedate(copy);
void CopyValues<T>(T from, T to) {
var json = JsonUtility.ToJson(from);
JsonUtility.FromJsonOverwrite(json, to);
}
Hey, is it possible to somehow get the axis to bend the object based on hit normal? Like in this image, if I hit the rod from above I need to rotate on the Z axis. But if I would hit from the right side, I would need to rotate on the Y axis
do I need to map my axises to normals? like if normal is 0,1,0 then I should rotate on 0,0,1
not sure how universal this would be
if I have this:
RenderQue.Add(BuildQue[i]);
BuildQue.RemoveAt(i);
where RenderQue and BuildQue are lists with a type of class
Does this copy all the data in the class, temporarily taking up double the origional RAM that it took to store this for a brief period?
If so, how can I have it not do that? trying to solve why on start memory usage can spike from 13 gigs to 20-24 gigs for a second
I have a procedurally generated mesh, and I need to know the "area" of a face. The meshes are always convex geometric shapes, so I can assume anything with the same normal is part of the same face. How would I go about getting the area of a portion of a mesh bound by vertices with the same normal?
Generate face normals for all tris, Bucket sort the normals, then sum the areas of all tris in a bucket?
are the faces convex? (seems intuitive that a convex 3d shape would have convex faces to me, but I'm not sure) https://www.mathwords.com/a/area_convex_polygon.htm
I managed to do something similar to this. I iterated over each triangle, and did some math to get the area and normal of the triangle using the positions and normals of the vertices.
This worked out, I was able to find the small faces and eliminate ones with an area less than 1. Now I'm dealing with a slightly different edge case than the original edge case: Some of these faces are very long and very thin, like 0.01 units wide and 100 units tall, that aren't being thrown away by the area check. I'm really not sure how I would go about fixing this one, at least before I had a semblance of what geometry I could do to solve it but I don't really know where to begin with this one
Maybe I could find a way to get the rectangular bounds of the face perpendicular to the normal? How would I go about that?
Guys, quick question! I'm instantiating a skinnedMeshRenderer from a prefab. When instantiated I update the rootBone and the Bones to match the prefab ones. Do I need to copy/modify the bone weights as well?
I'm getting this behavior
Well that's terrifying
there's one bone that it's not referenced by the skinned meshes, yet it seems to have impact on the rendered mesh :/
when I'm saying it's not referenced is because none of the skinnedMeshRenderers.Bones contains it
Maybe merge vertices that are close together and discard faces with 0 area or just 2 vertices
That could work. In the function where I compute the area of a triangle, I can just get the min distance between any two points, and if they're within a threshold, I could set the area of that triangle to 0. That way it won't show up on the list of faces with area greater than 1
Let me see how that looks
if you have a robust edge collapse function, I think you can solve most of those edge cases. But marking them in your preprocess sounds like a workable solution too.
Is it possible to save data to a scriptable object from the editor?
My goal is to procedurally generate a bunch of maps with an editor script, but I wanted to save them somewhere so I though about SO's. I know I can't create instances of it during runtime but is it viable to do it in the editor? Do you think this is the best approach?
what kind of maps?
tower defense maps, in a grid like style like this
wip
whats the data
basicallly the cells and path
it is a bunch of gameobjects stacked in a grid like style
don't know if it's understandable
why not use a scene or prefab?
by a mile, yeah
😅 thanks ahaha dumb me
but
if you want to save it in a minimal way, a texture asset is the way to go
you just have to come up with an encoding scheme on your own
I got you
this is a project for my dissertation so optimization won't be the focus here but thanks for the approach
other than that, if you want to exchange the map and easily use it external tools, a json file works well for complex data
yeah json seems good too but I think i'll go with prefabs it's quicker and saves me everythingm cells, path, waypoints, etc
ty so much
so think about how a hammer on an anvil works. what you're doing is making the surface normal at the point of impact conform to the surface normal of the anvil
i hope that helps
a 2d byte array would give you the most lightweight configuration for a map configuration, and supports 256 unique tile types, so it's pretty flexible
Of course you can, all you have to do is add the MenuItem tag to a method that creates the ScriptableObject
if you modify a scriptable object via script you have to make sure to flag it dirty or it won't actually save
Anyone familiar with the "new" input system? I'm looking for the easiest way to filter actions by control scheme (c# Input Actions)
GUI.Box(new Rect(0, y, Screen.width/2, Screen.height/2),"");
GUI.backgroundColor = new Color(0, 0, 0, 0);
input = GUI.TextField(new Rect(10, Screen.height/2, Screen.width / 2 - 10, Screen.height / 2 - 15), input);```
im trying to create a box of text right below the initial box
an input box
but when i put the following values for input, which should put it in the middle of the screen on its y axis, it disappears...
Nvm i figured it out
It was invisible since i set the bg color before drawing the text box
what would be the best way to impleemnt a chess engine into unity for an ios app?
having a board guard which resolves the states your board is going through
while blocking non allowed behaviour
and interavtions
Hello, how get a rotation from surface normal to camera look rotation ? I already have Quaternion.LookRotation(-raycastHit.normal) it works but it I need the Z rotation of that, to match the camera(FPV) , so if I'm looking down rotated quad on surface reflects this-
here is a drawing.. A is the quad. , so the Red is the current result, but green is the intended Result.
hope it was clear, pls @ me a suggestion to this. thanks!
hi there, ive got a tricky problem over in editor extensions, wondered if one of you expert guys might want to take a look at it since im a little stumped
hello i am trying to make a peer to peer game, and i have the authentification working, but when i test with 2 different pc, the connection between them to connect together fail, i got the ip of the host, i also use lobby and relay service, so i can join a lobby by joincode or random join, but nothing work, it throw http not found error, or it just doesn't connect without trhowing error :/
Local or public network?
So they are both on the same network, and p2p is not working?
yup
Have you checked that the firewall on the PCs aren't blocking anything?
but i did a custom network manager using mirror service
so maybe my code has an error ? or smtg wrong
it is currently testing
My first guess is that the firewall is blocking the connection. I would just turn it off to test first. If that's not it, maybe something is wrong when you set up a connection. Check that the addresses are correct etc, maybe hard code it first. Else I don't know either... 🤔
yeah, but an other guy tell me that mirror and relay use different relays system :3
Might be some incompatibility between them, which means rewriting networking code 🙃
yup
Can anyone please say How can I modify terrain from scripts?
Hello how get a rotation from surface
how to play 2 videos - one after another - but without any frame skipped between them? VideoPlayer.LoopPointReached or checking VideoPlayer.isPlaying on Update and playing next video doesnt work
Are you sure the next one is already loaded into memory?
If it's only starting the loading at the end then it makes sense that it's skipping some frames
i call VideoPlayer.Prepare() before anything
then just
""if (!videoPlayer1.isPlaying) videoPlayer2.Play();""
I need help writing a state machine that has a core of states which are shared by all monsters,
but which still allows for exclusive states which are only used by some monsters
it's a shame scriptable objects cannot contain specific logic... else they would be perfect to create a drag and drop style statemachine
😩
Anyone?
I'd rather check the frame manually (frame >= framecount - 1) if I need to seamlessly switch between video, maybe even playing both video at the same time at awake then pause the second video, just to 'pre-warm' it.
how i can make conveyor belt like satisfactory conveyor belts?
Plenty of tutorials for this, even one from Brackeys
I have asked on #💻┃code-beginner and #archived-code-general but apparently question is too difficult. So I ask there too.
I operating on Euler Angles, and my values are clamped between -180 and 180 degrees, so basically character can rotate freely on any axis, and I dont have crazy values like -2460 degrees etc. But I facing little problem now. When my character is in space and for example Z axis (Q/E) is -45 degrees, and I trying rotate character on Y axis (Left/Right) I need rotate it with Z axis degrees offset, how I can do it?
Someone knows answer?
tbh, I have read the same question on both of those channels but I wasn't able to figure out what your question means. you should probably add some examples/visualizations to make it more clear what you want
You could start with that in first place then!
I dont know how to explain it way you will understand, but I can show it.
maybe, but answering on questions I don't quite understand sometimes leads to awkward conversations, I usually just ignore them and hope someone other understands the question better
Yes thats right.
To avoid gimbal locking issues I use quaternions for doing all my rotations. I sometimes describe directions with with Euler angles, sometimes with a forward and up vector.
Well yeah but Since I dont fully understand quaternions I just stick to euler angles, I have gif explaining problem.
I got more comfortable using quaternions once I stopped tried to understand how they worked internally and instead just focused on their usage
So basically I need my character rotate on Y axis when Z axis is 90 degrees, there must be formula for it.
Instead of X axis ofc.
pretty much all you need to know about quaternions is what quaternion * vector and quaternion * quaternion multiplications does, you don't need to understand why it works that way or what happens under the hood
Yeah I have watching video about quaternions and imaginary nature.
you can forget all of that, you don't need that in game dev
But eulers seems so simple for me, you want 90 degree ok do it, not 0,85x 0,25y 0,11z and 4242141242W
Ok then I will make more research on quaternion topic and implement it instead.
again, you don't need to understand quaternions. You never need (I have never had to atelast) to give values to quaternions using x, y, z and w components
Use the API to convert to and from Euler angles. You can do your reasoning in Euler angles and do the actual rotations with quaternions.
Your gif does look like a loss of dimensionality which is an indicator of gimbal locking. If it truly is gimbal locking then solving the problem purely by using Euler angles is much harder.
guys
a general
unity question
Im making a freelook camera
GetKey(RightClick) SwitchToFreeLookCamera(true) GetKeyUp(RightClick) SwitchToFreeLookCamera(false)
when coming back from free look camera
if i look to the right it works accurately and get back to 0
from 40 to 0 it tweens
but when i look to the left
< 0
it rotates the whole round
-40 to 0, rotates 360
{
transform.localRotation = Quaternion.Euler(xRotation, value, 0f);
}).setOnComplete(() => comingFromFreeLookMode = false);```
code
would someone be able to tell me as to why with this code, the collider cannot call the "TakeDamage" function on the gameobject? I may just be confusing myself at this point since its multiplayer
whe i tried to actually see if the tag of the collided was a "Player", it was actually giving me an error as for some reason my Player prefab seems to lose its Player tag. Not sure if this relates to then not being able to grab the gameobject from the passed in "collided"
just debug log the object and i guess you'll have the answer no ?
shouldn't you be looking for a Player tag?
yeah i see that for some reason its taking the furtherst child of the Player gameobject ://
yyeahhh i was just going the ground thing to test things out sense my player tag wasnt working, however ive found the issue now
thanks!
mesh ?
maybe two colliders
yeah thats exactly what was happening
wellll not quite (:
so here my collider is on the "Standing" game object
then when my function is triggered i get this error
do i have to manually grab the parent gameObject of standing?
ive never had this issue before
doesn't look like your object has a Player script on it
so GetComponent<Player> will return null
if the Player script is on the parent you can either do:
collided.GetComponentInParent<Player>(); or collided.transform.parent.GetComponent<Player>()
ahh gotchaa, thanks!
hmm yeah im really not sure why even returning the tag of the player gives me an "Untagged"
pain
print out the name of the object too
it's probably one of the children of the player
or something else entirely
this would be to correct way to do that right?
print stuff outside the if statement
do you even need a tag? can't you just do
if (collided.transform.parent.TryGetComponent(out Player player))
{
player.TakeDamage(100000, -1);
}
im thinking the issue is that I need to maybe reset tags or something, since I imported this project from my github and had to reinput a lot of the tags
lets see 🤞
Accidentally pressed enter, one sec editing
I think im also kinda braindead rn cuz im working with photon as well, and multiplayer just makes these things so much harder lol
sadly doesnt seem to trigger the if
then either that transform.parent has no player component or you aren't colliding in the first place, but you can add debug logs to find out
well i am colliding
then that leaves one option
and from the looks of it I have the Player script and component as the parent
hmm
well thanks for the help tho
There is likely a simple answer to this, but I am stuck on it. If anyone could help, I'd really appreciate it!
I have 2 Quaternions, a and b in 3D space.
Right now, b is facing in ➡ this direction, and a is facing in ⬅️ this direction.
I need to get a bool, f telling me if a is facing in any direction ≥ d degrees away from the opposite of b (which would currently be ⬅).
For example: if a rotated ≥ d degrees upward (or in any direction), while b remained stationary, f would become true.
Another example: if b rotated ≥ d degrees in any direction, but a did not, f would become true.
When you talk about these Quaternions facing different directions, are you ignoring how they are twisted along that axis? If so, you can convert the Quaternions into directions and compare angles that way.
The twisting is irrelevant yes.
Then it would look like this:
public static bool IsFacingOpposite(Quaternion a, Quaternion b, float d)
{
Vector3 dirA = a * Vector3.forward;
Vector3 dirB = b * Vector3.forward;
return Vector3.Angle(dirA, -dirB) >= d;
}
Ahhh yes, that makes sense! Shall give this a shot. Thank you!
Is there a method so that I can make a function that can take in any number of arguments without making like a hundred overloads. Example:
public void SetSequence(float args...)
{
// Access args like an array
}
// However, when calling the function, instead of:
SetSequence(new float[]{...});
// or something, instead just do:
SetSequence(1f, 8f, 5f, 8f, 0f, 3.5f);
even a tuple-like structure could work
Yes.
public void SetSequence(params float[] args)
{
}
It has to be the last parameter
unless i fill in an integer inbetween
ahh
and i don't need to do new float[]{} or something
No, the compiler will do that for you
what is your desired behavior
all i see is a capsule floating between two surfaces
or what might be a sky and a terrain
are you saying your are trying to make a capsule where the player uses the mouse to drag rotations?
the camera is obscuring what is going on
Have you played space game where you can move character in deep space?
yes but usually that is with a gamepad
Does not matter.
are you trying to rotate a capsule using a mouse?
Does not matter.
I want rotate it correctly, I mean when you are rotated on X axis and you rotate on Z axis, you must rotate with X axis offset.
I dont know how to achive it.
unfortunately this is a long journey
when you say lobby by joincode, etc. etc., are you using a framework / package to achieve multiplayer?
mirror and relay use different relays
hmm... you have 100% of the code to this game, you should be able to look at this and see what's going on. what's your objective? are you working with someone on a project, and you're responsible for implementing networked multiplayer?
you should use cinemachine and new input system, using its input provider.
also, when you say free look camera, what do you mean?
okay, so you're trying to rotate a capsule using your mouse
by dragging
i'm not sure why you're being such a stickler on telling me what the user interaction is
what is it?
Wait.
is it keyboard presses? mouse drags?
how are you rotating the capsule?
it's essential to know what is being translated into what
gamepad inputs?
Wrong gif.
So basically my character acts like I moving it in Global Space.
And I want achive local space rotation efect.
effect
it's going to be a lot harder to solve this problem for you without knowing the answer to my question
because i'm trying to avoid saying quaternion or euler right now
But inputs does not matter man. xD
know i use mirror with epic relay, so its working, but ty ^^
Who cares how I move my object, it can be whatever I want, even banana.
My inputs are Mouse X Mouse Y and Q and E
okay i think maybe go to #💻┃code-beginner and ask there
Q E = Clockwise
Mouse X = Left Right
Mouse Y = Up Down.
oh
you finally answered
sorry i have been blocking you, because i wasn't sure why you were being so stubborn on this
Cuz you asking me about input system and it is irrelevant.
the first problem is that you haven't really articulated the rotation here correctly
and it is exactly the problem between "local" and "global" rotations (even though that's not really what we're strictly talking about)
like i get what you mean colloquially by clockwise, but there's no method called rotate clockwise in unity
first try to express the desired 3 rotation inputs as "rotate by amount "T" along (object or world) axis V"
so for example, Q sounds like "rotate by -k along object vector3.up"
btw I think you could just use Transform.RotateAround(transform.position, transfrom.up, amount)
then those expressions will translate directly to what you will do in your code
as you can see, people already understand a million times better what you're trying to do
because you answered my question
and can sort of jump the shark here
that said, you will not be using transform.rotatearound
@cunning grail it sounds like you do not want to try my approach
the words i'm using translate directly to a quaternion operation. the reason you have to use quaternions is because you are trying to turn small changes of something in one space (input space, mouse space, etc.) into small changes of another (rotation space)
I want but Im not native english speaker and its taking time to understand what you saying.
okay
But you said you understand my goal.
you're going to do stuff of the form
transform.rotation = transform.rotation * Quaternion.AngleAxis(+or-smallAmount, Vector3.up or Vector3.right or Vector3.forward);
in response to your inputs
which you can read as
set my rotation to
my previous orientation changed a small amount
about a local axis
the order that you multiply rotations matters
in short that's how you express local versus global rotations
does this make sense @cunning grail ?
so for "clockwise" which i assume you mean "about my local vector3.up"
Probably yes, but still I need test it out and check how I can apply it to my needs.
Clockwise for my purpouse is vector3.right.
no...
that doesn't make sense
so i think you have to rid yourself of these words
like clockwise
and up and right
those aren't orientations
so just don't say them anymore
Nah man its make a lot of sense for me.
that's good
i know
i think a lot of htis was just using the right words 🙂
Input.Player.RotateClockwise.action.performed += _ =>
transform.rotation = transform.rotation * Quaternion.AngleAxis(smallAmount, Vector3.up);
@cunning grail let's say clockwise meant rotate the capsule about its longest length, like a top spinner.
this is sort of what it would look like
i would suggest switching to input system too
how do you convert two screenspace vector 2's into a worldspace vector3?
what's your objective in terms of gameplay?
find an axis to rotate an object around
what's the gameplay?
@cunning grail as you can see everyone needs to find words sometimes
literally pick up an object and rotate it as you do in the inspector
Yep.
i think it's got an interesting style @cunning grail 🙂
it'll be good
clamping is a little more challenging - i saw that's something you want to do
This is why I have Vector3.right as clockwise.
So you turning like clock going.
Or counterclockwise.
So I moving on Z Axis.
Rotating*
clamping is challenging because you really want to say that "the object can only be oriented within this shape that resembles a spherical sector" which you're never going to find in a tutorial
ii found that word by searching "a piece of sphere" lol
Well but I dont need clamp anything.
Its space game, you can rotate as much as you want.
Nothing limits me.
alright well good luck out there 🙂
well this happens to be what we're talking about right now
you can read the conversation
it's there
the first thing you should realize is you need to express how an input translates to a rotation 🙂
don't worry yet about the translation of spaces
@rose hearth
like
mouse drag X => what effect on the rotation of the object?
mouse drag Y => what effect on the rotation of the object?
@undone coral well Its working.
did you try subtracting one quaternion from another
sick
Funny how creating spherical gravity is easier than creating character rotation.
lol
looks good
hi hi, having a bit of trouble with programmatically creating a quad mesh. What I'm doing: for each point in array of points on a straight line, I add 2 vertices (I refer to them as left and right) that are a specified width away from each other. The problem is that edges of the completed mesh are uneven (see picture). The only difference between the left and right points is in the z component(width). I'm assuming there needs to be some change for the x component as well so that the edges are slanted like that, but I'm not too sure how I should be getting that.
hey how i get the display id in script im trying to make it so my script disables if im not looking in that camera in editor but i cant seem to get it working
lol sorry bout that. Here's a screenshot of how I calculate and set the position of the vertices:
{{ description }}
so your picture doesn't seem like there's anything wrong to me
it's a bit zoomed in so i can't see if something is like an axis line or what but it looks like you made a quad no?
Umm the brackeys one focuses on creating a fully random map. But What I want to do is I want to create a terrain myself and during runtime I want the player to create roads(grid based) and wherever there is a negotiable but a noticable up or down I want to adjust the height of that terrain part at which the road mesh is colliding equal to the height of the road in world space.
You might find some stuff online, I know Seb Lague has a path creator which you could use for roads
so yea, its a quad, but I need the outermost vertices of the quad to line up more like this:
what are those grid lines?
it looks like you're incrementing the vertices world position along an axis instead of incrementing along their local axis
using world axis points. Here's a more zoomed out picture for context. Z-axis is top to bottom, X-axis left to right
okay
so don't use world coordinates, use local coordinates. or calculate the direction as orthogonal to the direction of your line
does that make sense?
what frame of reference are you using to build your quad points?
so you know the direction that you want to build your mesh right? so obviously you have some vector, and in order to get a vector orthogonal to that vector, you need another vector to establish which plane that orthogonal vector gets projected on
like... can you boil this down to a method makeQuad(origin,axisZ,axisX) ? then the other stuff with velocity and ball radius and so on can be separate.
in your case, you want to use the local z-axis since you're building your mesh on the xy plane
one idea per method, please! 🙂
Vector3.Cross(growthDirection, transform.forward).normalized * distanceFromoriginalPoint will give you a position vector as an offest from the original point
so you would add that value to your origin point and that should give you the result you're looking for
you're the best, using the perpendicular direction from the mesh's line direction worked! I was using the vector3.forward without really thinking about how the line is actually oriented
Hi there. I am basically making a car game and wrote this script.
using System.Collections.Generic;
using UnityEngine;
public class WheelController : MonoBehaviour
{
[SerializeField] WheelCollider fr;
[SerializeField] WheelCollider fl;
[SerializeField] WheelCollider br;
[SerializeField] WheelCollider bl;
public float acceleration = 500f;
public float breakingForce = 300f;
private float currentAcceleration = 0f;
private float currentBreakForce = 0f;
public float maxturnangle = 15f;
private float currentTurnAngle = 0f;
private void FixedUpdate()
{
currentAcceleration = acceleration * Input.GetAxis("Vertical");
if (Input.GetKey(KeyCode.Space))
currentBreakForce = breakingForce;
else
{
currentAcceleration = 0f;
}
fr.motorTorque = currentAcceleration;
fl.motorTorque = currentAcceleration;
fr.brakeTorque = currentBreakForce;
fl.brakeTorque = currentBreakForce;
bl.brakeTorque = currentBreakForce;
br.brakeTorque = currentBreakForce;
currentTurnAngle = maxturnangle * Input.GetAxis("Horizontal");
fl.steerAngle = currentTurnAngle;
fr.steerAngle = currentTurnAngle;
}
}
For some reason, the wheels go into the plane and there is no movement.
Please help if you want
ok.... if you comment out FixedUpdate() does the car still sink?
i'm wondering when the wheel collider is created and if it's active at all. idk unity physics.
i will try
Hi team, do you guys use Try Catch statements in unity? I am wondering as i dont, unless its an operation like load or save. I am sure that you shouldnt use try and catch in unity but i may have been totally wrong ?
do your wheels have wheel colliders and are they orientated the correct way? when unity changed from 4 to 5 they used physx2 and it nerfed the original wheel collider from physx 1 which was a wheel that acted like a real world wheel. new wheels only have contact point on base really and so dont really act like a real world wheel.
see the orientation in the picture and the up arrow https://docs.unity3d.com/Manual/class-WheelCollider.html
further to this if you need a wheel that acts like a wheel... this implementation was great for me and still acts like a wheel should act...
https://assetstore.unity.com/packages/tools/physics/universal-wheel-physics-41456
i've read that a lot of games outside of Unity don't use exceptions, opting only for Assertions instead. i.e. for the performance, since exception handling is pretty expensive
but i'm a mobile studio and we don't need to optimize to that degree, so we use them when it makes sense. but either way, as a general programming rule of thumb: don't use exceptions for control flow, so they should be pretty rare either way
(to clarify: outside of file and network IO, i can't really think of any place i'd use them)
Thanks Joey, i was unsure, i thought it was super expensive and dangerous i.e if you get a try catch in FixedUpdate... So i have never done it. i stumbled onto this.. but its so old and unity has developed much since 2013
https://forum.unity.com/threads/c-try-catch-doesnt-seem-to-work.24743/
When you do any I/O you should.
E.g. reading/writing files or making network requests
why do you need to do a try/catch in a loop?
what operation needs to be done on a fixed step that needs exceptions?
Yeah there's no call for it in FixedUpdate ever
that would just be a mistake that ended up in fixedupdate
like have 0 try catch's apart from I/O in any of my games so far... just working on my first PC game and was thinking maybe i should do some more error handling around stuff... even just handling core sprites etc
that seems strange to me.. unless you're doing network stuff via addressables to load your sprites?
what could reasonably go wrong with loading sprites?
well i was going to allow some modding somehow ? i am new to that
ah
well.. yea. that sounds like I/O for files outside of your built-in ones so it makes sense i guess
thanks man, i will keep on just checking for nulls and disabling scripts if there any...
keep on coding bros
lol np, good luck bud