#archived-code-advanced

1 messages · Page 191 of 1

red osprey
#

Dameon is recommending that you break it up into smaller steps... that way you don't have to deal with threading at all.

cunning grove
cunning grove
red osprey
#

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.

cunning grove
#

That seems relatively simple. I'm already firing off an event once it's done

cunning grove
red osprey
#

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.

cunning grove
red osprey
#

But you need to make sure that the push and pull are done correctly.

cunning grove
#

except Vector2Int

sly stag
#

I'm thinking GenerateChunks would be the spot to split it up

red osprey
#

Vector2Int is your data.

cunning grove
#

I don't understand what "my data" is

sly stag
#

Easiest thing to do would be to turn your loop into a coroutine and yield in your loops

red osprey
#

Like -- don't touch any game object, etc.

cunning grove
#

Oh, yeah it doesn't do that

#

the final result is a 2d array of enums

red osprey
#

Yup. It's common that logic just works on abstract C# stuff.

#

Not actual gameobjects, etc.

cunning grove
#

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

red osprey
#

That returns whatever the gamethread needs to make the map.

cunning grove
#

With the coroutine method, would I be able to have an animated loading bar or something?

red osprey
#

Yeah. When the coroutine does a yield return, Unity renders a frame.

cunning grove
#

So it would just have to be placed strategically to yield around every frame

sly stag
#

Nah

red osprey
#

It's basically telling Unity "Okay that's enough for this frame. Start me from here next time."

sly stag
#

Just yield at the end of every loop

cunning grove
#

I'm thinking the coroutine method sounds the simplest

red osprey
#

It's quite simple, yes.

#

Also handles cases like cancelation, etc.

cunning grove
#

Oh that's true, so if you want to quit the program mid-generation

urban warren
#

Worth noting that threading it will make it considerably faster though

red osprey
#

Then the gameobject managing the coroutine goes away, and the coroutine stops.

sly stag
#

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

red osprey
sly stag
#

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

red osprey
urban warren
sly stag
#

Yeah, but it's a lot of traps for a beginner to threading

red osprey
sly stag
#

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

cunning grove
#

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.

red osprey
#

Depends... if you yield 10,000 times, and it takes 10ms to render a frame, then that's 100s extra lag.

cunning grove
#

I'll have to figure out where to put my yields

sly stag
#

Or cut it into chunks that are a reasonable amount per frame

red osprey
#

Yup.

urban warren
#

You can limit it n ms per frame

cunning grove
#

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

red osprey
sly stag
#

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

cunning grove
red osprey
#

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.

cunning grove
sly stag
#

Check the system time in milliseconds when you start and when you finish, subtract

red osprey
#

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.

sly stag
#

Easiest way is to just use the profiler though

red osprey
#

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.

cunning grove
red osprey
#

Unreal.

cunning grove
#

okay

#

So what you're saying is that you kept it simple and it worked way better?

red osprey
#

But yeah it's a good thing to be like "Wait... does this order of magnitude time actually make sense?"

cunning grove
#

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

red osprey
#

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.

sly stag
#

Nothing wrong with starting with the greedy solution and optimizing to get the optimal solution

red osprey
#

Yup.

cunning grove
#

There's probably a better way to do it, I just don't really know how unfortunately

red osprey
#

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."

cunning grove
#
//* 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
red osprey
#

You can profile it and see.

cunning grove
#

That is very true, I should really use the profiler more

red osprey
cunning grove
#

oh shoot that's a thing?!?!

red osprey
#

That will tell you exactly how much time that block takes.

#

Yup.

cunning grove
#

holy crap

sly stag
#

Yeah, the profiler is one of Unity's most powerful features...there's good reason it was a paid feature back in the day

cunning grove
#

my mind is blown

red osprey
#

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.

sly stag
#

Definitely check out the API reference for the profiler, there's more handy features you can work into your code

cunning grove
#

I'll do that when I get home, but basically I should use yields if it can't do any more calculations, right?

red osprey
#

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"

cunning grove
sly stag
#

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

cunning grove
#

Okay, all of the stuttery loading screens in games make so much more sense now

red osprey
#

Yeah... a lot of it is that this industry is messed up and people don't question things.

#

To be blunt lol.

cunning grove
#

I've always thought that that was just a "thing"

sly stag
#

Well that and actually calculating how long something will take to load anywhere near accurately is pretty near impossible

red osprey
#

Here's another funny story.

cunning grove
red osprey
#

In Unreal, if you leave the oculus SDK's default splash screen thing, it will add like 20s load time to every level load.

red osprey
#

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.

cunning grove
#

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.

red osprey
#

Yup

#

(Bottom of page)

#

Er... once... and was about to a second time?

#

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.

torpid swift
#

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...

▶ Play video
next kayak
#

awesome

honest hull
#

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

honest hull
#

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

kindred tusk
#

Yeah tmp handles this

red osprey
#

Yeah, Unity's tooling is pretty good.

regal olive
#

Yeah 😮

red osprey
#

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.)

short junco
#

Physics methods creating GC always ?

short junco
austere jewel
#

Yes. Though that allocation you're looking at is the array being created and returned to you

short junco
#

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 😄

austere jewel
#

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

short junco
#

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 👍

bitter elm
#

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

untold moth
#

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.

bitter elm
#

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?

untold moth
untold moth
#

If you're using a rigidbody, then yes, you also need a collider.

bitter elm
#

well rigidbody cant do slopes or stairs

untold moth
#

Why not?

bitter elm
#

Are you saying it can?

untold moth
#

Depends on what you mean by slopes and stairs, but you can add that behavior yourself if needed.

bitter elm
#

I thought the point of the CC was slopes and stairs

untold moth
#

I'm not sure. I barely ever used CC.

bitter elm
#

And I cant find anything on how to make the rigidbody use stairs

#

or slopes

untold moth
#

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

bitter elm
#

oh

rocky mica
#

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

untold moth
#

True that, but you can get a CC kind of behavior with rbs as well.

rocky mica
#

rigidbodies arent in my experience, snappy enough to create precise and snappy movement systems unless you do a lot of workarounds

untold moth
#

Just make it kinematic and move manually.🤷‍♂️

rocky mica
#

yeah but they are very erratic, in my experience at least

#

for 2d platformers I always had some kind of issue

#

specially with collisions

rocky mica
#

he hits a wall and stops?

bitter elm
bitter elm
#

which isnt what i would call realistic

#

I wonder if dusk/ultrakill used either cc or rigidbody

rocky mica
#

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

bitter elm
#

for physics?

#

the fixed update?

short junco
#

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 ?

maiden turtle
#

what do you mean exactly by anchor proportionally?

somber swift
#

dynamic? 🤢 theres not many reasons why dynamic should exist on C#

weary stag
#

@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.

brittle wharf
#

how do i have a overlay 2 cameras, each rendering a different layer in hdrp?

fresh basalt
#

anyone familiar with mirror commands?

rotund citrus
#

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...
sly grove
#

But no I've not been thinking about your problem since then.

weary stag
#

Well, if you can write one fully, I can benchmark it alongside the existing algorithm and we can see which one performs better?

sly grove
#

I wish I had the free time for that sir. Good luck.

marble drum
#

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

wooden cedar
undone coral
#

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

weary stag
undone coral
#

the actual cards you probably want to lay out in 3d if you want zoom

undone coral
undone coral
#

for common linq behaviors it should suit you well 🙂

#

NoAlloq, LinqFaster, Hyperlinq, ValueLinq, LinqAF, StructLinq all do stuff like this

marble drum
copper nexus
#

how to made in game programming (i.e. scripts)?
how to made support for mods?

cunning grove
#

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.

honest hull
#

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)?

#

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?

versed slate
#

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

honest hull
#

hrm ok
if it helps at all
if I do BakeMesh(mesh, true) I can get a proper, but if false its still improper

honest hull
#

I do not understand why this offset exists...

topaz ermine
azure ibex
#

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?

inland delta
#

just create one physics2d material with 0 bounce and other with full bounce

#

and do Collider2D.sharedMaterial = thePhysicsMaterial

azure ibex
#

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.

inland delta
#

no problem

sly grove
#

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

humble onyx
#
 var DeclaringMembers = type.GetMembers().Where(x => x.DeclaringType == type);

could this work ?

ocean raptor
#

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.

humble onyx
ocean raptor
maiden turtle
#

@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:

  1. 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
#
  1. you can just iterate fields already with GetFields
#
  1. 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

ocean raptor
#

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.

maiden turtle
#

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

maiden turtle
#

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

honest hull
#

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

undone coral
undone coral
#

so choose a number of textures max you can send

honest hull
#

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?

undone coral
#

it sounds like they are not though

#

what part is being slow?

honest hull
#

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

undone coral
#

why do the objects need distinct atlases

#

are they instances of something else?

honest hull
#

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

wary swift
#

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? 😅

weary stag
#

@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).

undone coral
#

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

wary swift
#

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

wary swift
#

nvm, in between all the spam comments, there is a fix on the second page for it

regal olive
#

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

red osprey
regal olive
#

it's deleting some now at leats, that's progress

red osprey
#

Er I guess that would fail if you forward-iterate.

regal olive
#

ahhhh true that migh be the problem

#

with a foreach maybe?

red osprey
#
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.

sharp blaze
#

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?

undone coral
#

hmm

honest hull
honest hull
#

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

stuck crane
#

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!

lone elk
#

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();
        }
    }
flint sage
#

JsonUtility and serialization in the editor aren't the same

#

They don't support the same things

lone elk
#

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)

flint sage
#

They're interfaces though and JsonUtility probably doesn't support that

#

And readonly might also be a problem

lone elk
# flint sage 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

wraith rover
#

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!

wraith rover
kindred tusk
#

Then it will scale up

#

I recommend watching some UGUI tutorials, it's not super obvious how to use it properly.

maiden turtle
#

I know how they work, I've used them to position the header and the content container correctly

kindred tusk
#

So what are you stuck on?

maiden turtle
#

I just don't understand how they can help me with the text

#
  • image next to the text
kindred tusk
#

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

maiden turtle
#

and parent the image to the text?

kindred tusk
#

Probably not.

#

Where do you want the image?

maiden turtle
#

exactly to the right of the text

kindred tusk
#

I typically don't add children to text or images, I just create empty layout boxes for positioning things.

kindred tusk
maiden turtle
#

yep

#

but keep the aspect ratio

kindred tusk
#

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) 
maiden turtle
#

the last problem is that it may go beyond the cobtainer if it's parented to the text

kindred tusk
#

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.

stuck crane
#

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?

sly grove
#

You can pass in parameters to that coroutine and optionally run or not run any of those other coroutines with simple if statements

stuck crane
#

but maybe I could use switch cases without breaks x)

steep robin
#

Hi!

#

Someone could help me clarity this? I have a GameObject that reference a ScriptableObject istance. How can I inspect the instance values?

sly grove
steep robin
#

the ScriptableObject instance is in-memory, so I cannot select it in the project window

wild furnace
#

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

static mountain
#

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

wild furnace
#

yea that's what i'm doing with this code here: Vector3 finalPosition = _propPosition.vector3Value * i + currGO.transform.position;

#

currGO being the main object

#

get what im trying to do?

wary swift
#

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:

  1. scale
  2. translate: to assign the offset
  3. rotate: so the blocks are in the right direction (like you have now)
  4. translate: again, so the matrix is back together (as shown in your second video)
fickle robin
#

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"

wild furnace
tough tulip
wild furnace
#

what's the offset you're talking about btw?

wary swift
#

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

wild furnace
#

yep!

#

ill read through the link you sent, this... is too much for me to handle haha

misty glade
#

@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 😐

#

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. 🤷‍♂️

wild furnace
wary swift
#

nope

#

well, you could multiply it with another translate, that could work i suppose

wild furnace
#

hmmm alright will try

lethal matrix
#

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?

dark crow
#

literally just set up a timer which reset every time some event occur (in this case inputs)

undone coral
kindred tusk
misty glade
#

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

undone coral
kindred tusk
#

Shucks

misty glade
#

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

kindred tusk
#

Probably just been doing it for longer than you :-)

misty glade
#

and harder

#

your "every day has activity" streak from mid nov to mid jan is impressive

kindred tusk
#

That is insane

#

I definitely went out on nye

#

And stayed up all night

misty glade
#

but you still at least did something 😛

kindred tusk
#

Hahaha

#

My wall of shame

misty glade
#

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)

kindred tusk
#

It does exist

#

I've seen someone with a checkerboard

misty glade
kindred tusk
#

Honestly a better use case would be to make it look like real work and then apply for a job

#

Hahaha

misty glade
#

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

wraith rover
#

@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

misty glade
#

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.

wraith rover
#

@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

honest hull
#

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];
        }
wary swift
#

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

honest hull
#

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

wary swift
#

Aha you should've mentioned that
Look into bit shifting and make your own format if possible

honest hull
#

I did
didnt work

wary swift
#

How did that not work?

honest hull
#

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

flint sage
#

ArrayPool?

honest hull
#

?
also I converted the uints to shorts
didnt do much

#

maybe a 2% improvement

wary swift
honest hull
#

yeah
i know
but still new short[8] isnt performing much better than new uint[8]
same with byte

wary swift
#

Are you sending it to the GPU and back every frame?

honest hull
#

no?

#

this is all preprocessing

wary swift
#

Hmm.. not sure if I can provide any ideas in that case
Why do you need an array of 8 of ints/shorts anyway?

honest hull
#

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

wary swift
#

I think you should first try to get the algorithm to work before you try to optimize it

honest hull
#

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

undone coral
undone coral
honest hull
#

oh?
but still what im talking about now is on the CPU

undone coral
honest hull
#

ohhhh

undone coral
#

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 ?

honest hull
#

yes

undone coral
#

its layout in memory is backwards to what you expect because your platform is little endian

honest hull
#

ok

undone coral
#

okay

#

here is how you should decode

#

from
encode: https://github.com/keijiro/Pcx/blob/ffc344756b9320584a02a738c8b9d328090e1bc3/Packages/jp.keijiro.pcx/Runtime/PointCloudData.cs#L78

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

modern storm
#

Is there a Math wiz in the audience?

fresh salmon
#

Don't ask if anyone knows XYZ, ask your question directly in the relevant channel.

honest hull
undone coral
#

provided it's aligned

honest hull
#

hmmmm

#

just wondering because my code is taking drastically more than it does in C/C++

undone coral
#

hmmmmm

wary swift
honest hull
#

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

honest hull
#

wait it dont??

#

ok hang on

wary swift
#

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

honest hull
#

not explicit?

#

The type or namespace name 'StructLayoutAttribute' could not be found

wary swift
honest hull
#

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

modern storm
#

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
honest hull
#

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

wary swift
honest hull
#

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

wary swift
#

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?

honest hull
#

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?

honest hull
covert rain
#

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); ```
wary swift
#

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

somber swift
#

Yuk, pow(a,2) instead of a*a

covert rain
#

Guess not

gray pulsar
wary swift
gray pulsar
# covert rain 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.

somber swift
covert rain
#

@gray pulsar @somber swift @wary swift Thanks!

wary swift
#

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 🤷‍♂️

gray pulsar
fresh salmon
#

Just use (v2 - v1).sqrMagnitude lol

gray pulsar
#

sure, but if Vector3.Distance is worth having, why not SqrDistance?

wary swift
#

but that constructs a new vector3?

fresh salmon
#

Distance also does

somber swift
fresh salmon
#

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

gray pulsar
#

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

wary swift
# somber swift 1) its not a class, its a struct 2) Its not very useful on other cases than opti...

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

somber swift
# wary swift i'm not sure if you intend to come over as aggressive, but that's how i interpre...

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)

meager kite
#

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?

somber swift
#

Doesnt sound normal

meager kite
#

how do i start to go about figuring out why thats happening

somber swift
#

Profiler could probably help on that

meager kite
#

i have no idea how to read that thing

wary swift
#

unless he activated deep profiling in the profile, and that's why it's slow 🤔

meager kite
#

heres the output

#

what do the spikes at the top represent

wary swift
#

click on it ^^

long ivy
#

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

wary swift
#

oh and go from timeline, to hierarchy (on the center-left)

meager kite
#

that gives me this, what now?

#

i see EditorLoop is extremely high

#

is that normal

wary swift
#

Yup

#

it seems like everything is fine, minus the 1.9kb of garbage that you're generating that frame

meager kite
#

well then ill just avoid clicking on my object ingame

#

thats rather strange tho

wary swift
#

i would consider 2kb a lot of garbage, if it happens every frame

meager kite
#

alright

wary swift
#

but i'm also quite nit-picky

meager kite
#

still ill get on fixing it

#

thanks

#

ah that was the reason

#

i was still in debug mode

#

disabling it fixed it

ocean raptor
#

Anyone here familiar with Mirror Networking?

violet valve
ocean raptor
violet valve
zenith ginkgo
solid tide
#

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.

violet valve
violet valve
old swallow
#

Hello, is it possible to change the projection matrix of a VR camera on single pass mode?

frozen imp
#

@old swallow Don't cross-post. Pick a channel

heady bane
#

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

hidden sphinx
#

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....

uneven crypt
#

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 !

manic orchid
#

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);
}
nova gust
#

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

nova gust
#

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

honest hull
#

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

plain abyss
#

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?

compact ingot
gray pulsar
plain abyss
# compact ingot Generate face normals for all tris, Bucket sort the normals, then sum the areas ...

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?

azure hinge
#

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

plain abyss
#

Well that's terrifying

azure hinge
#

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

compact ingot
plain abyss
#

Let me see how that looks

compact ingot
#

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.

regal olive
#

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?

regal olive
#

wip

compact ingot
#

whats the data

regal olive
#

basicallly the cells and path

compact ingot
#

colors?

#

you could just save that as a texture asset

regal olive
#

it is a bunch of gameobjects stacked in a grid like style

#

don't know if it's understandable

compact ingot
#

why not use a scene or prefab?

regal olive
#

well that's not a bad idea actually simply saving the prefab

#

i was overcomplicating

compact ingot
#

by a mile, yeah

regal olive
#

😅 thanks ahaha dumb me

compact ingot
#

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

regal olive
#

I got you

#

this is a project for my dissertation so optimization won't be the focus here but thanks for the approach

compact ingot
#

other than that, if you want to exchange the map and easily use it external tools, a json file works well for complex data

regal olive
#

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

humble loom
#

i hope that helps

humble loom
# regal olive

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

sly stag
humble loom
#

if you modify a scriptable object via script you have to make sure to flag it dirty or it won't actually save

soft hawk
#

Anyone familiar with the "new" input system? I'm looking for the easiest way to filter actions by control scheme (c# Input Actions)

meager kite
#
        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...

meager kite
#

Nvm i figured it out

#

It was invisible since i set the bg color before drawing the text box

heady bane
#

what would be the best way to impleemnt a chess engine into unity for an ios app?

buoyant vine
#

having a board guard which resolves the states your board is going through

#

while blocking non allowed behaviour

#

and interavtions

warm mica
#

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!

whole badge
#

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

white arrow
#

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 :/

white arrow
#

on the same connection

lucid girder
#

So they are both on the same network, and p2p is not working?

white arrow
#

yup

lucid girder
#

Have you checked that the firewall on the PCs aren't blocking anything?

white arrow
#

but i did a custom network manager using mirror service

#

so maybe my code has an error ? or smtg wrong

white arrow
lucid girder
#

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... 🤔

white arrow
lucid girder
#

Might be some incompatibility between them, which means rewriting networking code 🙃

wraith cove
#

Can anyone please say How can I modify terrain from scripts?

warm mica
#

Hello how get a rotation from surface

true cosmos
#

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

flint sage
#

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

true cosmos
#

i call VideoPlayer.Prepare() before anything

#

then just
""if (!videoPlayer1.isPlaying) videoPlayer2.Play();""

lucid girder
#

the functions isn't async so it should run sync

#

do you prepare both players?

hexed meteor
#

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

#

😩

somber tendon
burnt wave
#

how i can make conveyor belt like satisfactory conveyor belts?

shadow seal
cunning grail
#

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?

somber swift
# cunning grail 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

cunning grail
#

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.

somber swift
#

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

cunning grail
#

Yes thats right.

errant plinth
#

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.

cunning grail
#

Well yeah but Since I dont fully understand quaternions I just stick to euler angles, I have gif explaining problem.

errant plinth
#

I got more comfortable using quaternions once I stopped tried to understand how they worked internally and instead just focused on their usage

cunning grail
#

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.

somber swift
cunning grail
#

Yeah I have watching video about quaternions and imaginary nature.

somber swift
#

you can forget all of that, you don't need that in game dev

cunning grail
#

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.

somber swift
errant plinth
#

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.

cunning grail
#

Yeah 100% its gimbal lock.

#

Thanks a lot for pointing problem.

hoary plover
#

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

twin belfry
#

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"

white arrow
sly grove
twin belfry
twin belfry
#

thanks!

twin belfry
#

yeah thats exactly what was happening

white arrow
#

so you got the issue

twin belfry
#

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

sly grove
# twin belfry

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>()

twin belfry
#

hmm yeah im really not sure why even returning the tag of the player gives me an "Untagged" disgui2Feels pain

sly grove
#

it's probably one of the children of the player

#

or something else entirely

twin belfry
sly grove
#

print stuff outside the if statement

twin belfry
#

yeah untagged

#

hmmm

#

i wonder what I messed up

gentle topaz
#

do you even need a tag? can't you just do

if (collided.transform.parent.TryGetComponent(out Player player))
{
  player.TakeDamage(100000, -1);
}
twin belfry
#

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

gentle topaz
#

Accidentally pressed enter, one sec editing

twin belfry
#

I think im also kinda braindead rn cuz im working with photon as well, and multiplayer just makes these things so much harder lol

twin belfry
gentle topaz
#

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

twin belfry
#

well i am colliding

gentle topaz
#

then that leaves one option

twin belfry
#

and from the looks of it I have the Player script and component as the parent

#

hmm

#

well thanks for the help tho

strong dove
#

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.

sage radish
strong dove
#

The twisting is irrelevant yes.

sage radish
# strong dove 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;
}
strong dove
indigo kiln
#

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

sage radish
indigo kiln
#

O::

#

hidden c# juices

#

wait so is it the only parameter allowed

sage radish
#

It has to be the last parameter

indigo kiln
#

unless i fill in an integer inbetween

#

ahh

#

and i don't need to do new float[]{} or something

sage radish
#

No, the compiler will do that for you

indigo kiln
#

O:::

#

c# param keyword is beautiful

#

thank you very much!

undone coral
#

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

cunning grail
#

Have you played space game where you can move character in deep space?

undone coral
#

yes but usually that is with a gamepad

cunning grail
#

Does not matter.

undone coral
#

are you trying to rotate a capsule using a mouse?

cunning grail
#

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.

undone coral
#

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?

cunning grail
#

This behaviour.

#

I need this.

undone coral
#

also, when you say free look camera, what do you mean?

undone coral
#

by dragging

cunning grail
#

Nope.

#

I rotate in third person.

#

Using Inputs.

undone coral
#

i'm not sure why you're being such a stickler on telling me what the user interaction is

#

what is it?

cunning grail
#

Wait.

undone coral
#

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?

cunning grail
#

Wrong gif.

undone coral
#

🥺

#

are you trying to rotate a capsule using gamepad inputs?

cunning grail
#

So basically my character acts like I moving it in Global Space.

#

And I want achive local space rotation efect.

#

effect

undone coral
#

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

cunning grail
#

But inputs does not matter man. xD

white arrow
cunning grail
#

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

undone coral
cunning grail
#

Q E = Clockwise
Mouse X = Left Right
Mouse Y = Up Down.

undone coral
#

oh

#

you finally answered

#

sorry i have been blocking you, because i wasn't sure why you were being so stubborn on this

cunning grail
#

Cuz you asking me about input system and it is irrelevant.

undone coral
#

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"

somber swift
# cunning grail

btw I think you could just use Transform.RotateAround(transform.position, transfrom.up, amount)

undone coral
#

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
#

@somber swift its not working.

#

I have tested it.

undone coral
#

@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)

cunning grail
#

I want but Im not native english speaker and its taking time to understand what you saying.

undone coral
#

okay

cunning grail
#

But you said you understand my goal.

undone coral
#

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"

cunning grail
#

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.

undone coral
#

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

cunning grail
#

Nah man its make a lot of sense for me.

undone coral
#

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

rose hearth
#

how do you convert two screenspace vector 2's into a worldspace vector3?

undone coral
rose hearth
#

find an axis to rotate an object around

undone coral
#

@cunning grail as you can see everyone needs to find words sometimes

rose hearth
#

literally pick up an object and rotate it as you do in the inspector

cunning grail
#

Yep.

undone coral
#

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

cunning grail
#

This is why I have Vector3.right as clockwise.

undone coral
#

i see

#

yes as long as the three choices are distinct

#

it will work well

cunning grail
#

So you turning like clock going.

#

Or counterclockwise.

#

So I moving on Z Axis.

#

Rotating*

undone coral
#

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

cunning grail
#

Well but I dont need clamp anything.

undone coral
#

oh

#

okay

cunning grail
#

Its space game, you can rotate as much as you want.

undone coral
#

if you did you would use the distance between two quaternions

#

it's very simple

cunning grail
#

Nothing limits me.

undone coral
#

alright well good luck out there 🙂

undone coral
#

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?

cunning grail
#

@undone coral well Its working.

undone coral
undone coral
cunning grail
#

Funny how creating spherical gravity is easier than creating character rotation.

undone coral
#

lol

undone coral
#

looks good

full pike
#

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.

humble loom
#

that's definitely a picture

#

can we see the code

hot tendon
#

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

full pike
humble loom
#

could you use a paste link if you don't mind

#

so i can manipulate the text

humble loom
#

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?

wraith cove
# shadow seal Plenty of tutorials for this, even one from Brackeys

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.

shadow seal
#

You might find some stuff online, I know Seb Lague has a path creator which you could use for roads

full pike
humble loom
#

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

full pike
#

using world axis points. Here's a more zoomed out picture for context. Z-axis is top to bottom, X-axis left to right

humble loom
#

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?

plucky hound
#

what frame of reference are you using to build your quad points?

humble loom
#

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

plucky hound
#

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.

humble loom
#

in your case, you want to use the local z-axis since you're building your mesh on the xy plane

plucky hound
#

one idea per method, please! 🙂

humble loom
#

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

full pike
vagrant magnet
#

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

plucky hound
#

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.

vagrant magnet
#

i will try

last sandal
#

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 ?

last sandal
# vagrant magnet ```using System.Collections; using System.Collections.Generic; using UnityEngine...

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

lethal nimbus
# last sandal Hi team, do you guys use Try Catch statements in unity? I am wondering as i dont...

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)

last sandal
sly grove
#

E.g. reading/writing files or making network requests

lethal nimbus
#

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?

sly grove
#

Yeah there's no call for it in FixedUpdate ever

last sandal
#

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

lethal nimbus
#

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?

last sandal
#

well i was going to allow some modding somehow ? i am new to that

lethal nimbus
#

ah

#

well.. yea. that sounds like I/O for files outside of your built-in ones so it makes sense i guess

last sandal
#

thanks man, i will keep on just checking for nulls and disabling scripts if there any...

#

keep on coding bros

lethal nimbus
#

lol np, good luck bud