#archived-code-general
1 messages · Page 257 of 1
no I think he was refering to calling methods
literally last week, a feature in Unity was broken because they had a string that said “ScrollTextSeachBar” vs “ScrollTextSearchBar”. Which made a whole range of UI features totally unusable because some dumbass used a string, and a separate dumbass made a spelling error.
I make a non-generic abstract parent when I want concrete methods to be inheritted by all children, and maintain internal variables . Interface otherwise.
my spawnpoint has a ton of machinery, so I saw it was greatly beneficial to make an abstract base class
hahah
@left violet agree with Loup 100%.. my rule of thumb: compiler errors are better than runtime errors.
I was not saying anything against his suggestion 😄
Clearly it is better practice to not use Strings
sorry, didn't mean to imply otherwise.. was just giving a reason WHY
How do I check what layer my navmesh agent is currently walking on? I've got two so far:
- Walkable
- Wall
however it seems to only always return walkable?
why is your agent walking on walls
to simulate the AI wallrunning
which is why I need to be able to check the layer / area the navmesh is currently walking on, so I can rotate the mesh
probably can do it with the navmesh raycast but I'd expect there's another method
rider 100%
ye its a lot faster with compiling maybe bc its live... and also auto complete seems to be faster too
rider auto saves right?
mhm
ah thats why
ive seen there has been a unity script editor... what happened to it?
or is this just vc?
This one got discontinued. Your mainstream options are now Visual Studio, Visual Studio Code, Rider
alr... yeah i think u dont even call them mainstream seen a graph where other was at 0%
for used programs for unity
Some still want to suffer, we've seen a few use Notepad
I saw a student using Word once
xD
(in a class I was TAing)
best ide has typing function
I mean how do you even compile code in Word, that thing is stored in XML
Let's do it in Excel instead. It has tabs, one sheet per file
._.
btw. when using shaders would u rather do it in unity or in blender
still stuck on this..
private void CheckLayer()
{
if (_navMeshAgent.SamplePathPosition(NavMesh.AllAreas, 0.1f, out var hit)) return;
Debug.Log((hit.mask & _wallMask) != 0 ? "On Wall" : "On Floor");
}
it always prints "On Floor"
Blender has a completely different rendering system. You must create shaders and materials in Unity.
materials are often imported tho
shaders dont carry over though
also the materials rarely come over fully correct, generally just the names of them and the slots and where they apply comes over
Some info can make it over, yes
then you edit those in unity to have the correct shader and textures
It can work if you use the Principled BSDF shader in blender and directly collect image nodes to its inputs. But arbitrary materials aren’t going to survive the FBX export
Yeah, I've given up importing anything but general mesh datas
alr. well ill learn how to do shaders in unity then
I just create materials in Unity and then assign them in the model importer
Shaderlab is dumb easy if you like visual scripting
i kinda dispice visual scripting
You mean shader graph?
shader graph right
Shaderlab is the text based format
I do too, but visual editing works way better for shaders
I use both styles depending on what I’m doing
I dont like visual scripting either, but shader graph is really good. Visually let's you even see what happens in intermediate steps
majority of special shaders you'd make is just copy pasted code anyway
Writing HLSL works better if you need to do really elaborate stuff
no reason to reinvent the wheel
I am trying to get a system going where a creature's legs go the the three closest points (basically just the second point in a linerenderer) but I am running into some issues
The script is kinda lengthy so I will put it in pastebin but I am not totally sure what isn't working here
you will have a easier time with shadergraph since it does alot of the work for you. you need to implement more yourself if using hlsl and shaderlab with urp
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.
hlsl is also just a bunch of unity methods and macros
mhm mhm noted.. but visual coding for other functions are often a mess...
im getting an issue where two legs are going to the exact same spot (same coords not just visually) and some just go through walls
examples:
unsure what the issue is here
I ended up doing this in a kind of hacky way, by somewhat abusing serialized static nested structs inside an editor window
hey guys, i need help with unity 2d, i have jump code that works fine, but i want to make the character jump only when is in the floor collider so i made something like this :
void OnTriggerEnter2D(Collider2D other) {
if (other.CompareTag("Floor")) {
JUMP;
}
why doesnt it work ?
A:
include ```
before and after you enter your code
and B:
what tf does "JUMP" mean
like what is your actual code
i just wrote JUMP as a short term for the jump code i wrote
so i dont have to type that much 😅
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class jump : MonoBehaviour
{
public float velocity = 1f;
public Rigidbody2D rb2D;
void Start()
{
// rb2D = GetComponent<Rigidbody2D>();
}
void OnTriggerStay2D(Collider2D other){
if (Input.GetKeyDown(KeyCode.UpArrow) && other.CompareTag("Floor"))
{
Debug.Log("Gibtu");
rb2D.velocity = Vector2.up * velocity;
}
}
void Update()
{
}
}
this is the code
why do you have rb2D's assigner commented out?
its also transform.up not Vector2.up
and idk how "ontriggerstay" is evaluating but it is a lot better to use an overlapbox with layers
IsOnGround = Physics2D.OverlapBox(transform.position - new Vector3(0, 0.8f), new Vector2(0.5f*transform.localScale.x, 0.21f), 0, Ground);
if(IsOnGround && Input.GetKeyDown(KeyCode.Space)){
IsOnGround = false;
body.AddForce(new Vector2(0, JumpPower*15));
transform.localScale = new Vector3(1.5f, 0.5f);
}
like this
(Ground) is a layermask
i see, thanks man i will try this
anyways, anyone have any idea whats up with my code?
is there some glaring issue I am not seeing
How do I stop player from clipping into walls/other colliders?
hmm
I was going to say continuous collision but you already have that
maybe the colliders just don't line up right?
you could always make it so that object are not moved when pushed, but I don't think that is what you want
It also happens slightly with the wall so I don't think pushing is the problem (though it does exaggerate it)
well this is prob whats happening. fixed update isnt fast enough for the player speed
My code is in Update() not fixedupdate
that doesnt matter update isnt simply fast enough for its speed
I see, does that video have a way to fix it?
this is why physics code is usually in fixed update
but the collision is set to continuous doesn't that usually fix that issue?
no sadly not... he says he covers it in another video
but this should fix it
Ok I'll try it
did it work?
Continuous collision detection means that the rigidbody actually sweeps out a volume in space, rather than just checking if its new position is occupied
It's more expensive, but also more accurate
Thera are a few different modes you can use. https://docs.unity3d.com/Manual/ContinuousCollisionDetection.html
(well, two of the modes sweep out a volume in space)
sweeps out?
I had to change the interpolation to none, now it's significantly better but still a bit there
Interpolation just makes the physics system change the position of the object each frame
instead of only in physics updates
it shouldn't be affecting the actual behavior
hmm tried Continuous collision still clips through
It is for some reason
Oh it's possible it's just a visual thing if that's what you mean
blue light filter
anyways, still unsure what is causing my issue
genuinely stumped
this
i think theres still a way to fix it maybe with apply force
yes that works
I've implemented a pause button in my space simulation by setting the timeScale to 0 when its clicked. When you click on a planet in my game, I want something to appear, but if the timeScale is 0 will this prevent it from appearing?
or does it just stop update()
eh as long as there is no lerping it should work I think????
Idk
Setting the time scale to zero won't stop Update from being called.
deltaTime will simply be zero.
also at a high enough speed it would
show us your code.
using AppCore;
using UnityEngine;
namespace Game.PlayerComponents {
public class PlayerMovement : MonoBehaviour{
[SerializeField] private float movementSpeed = 5f;
protected Vector2 _currentMovement;
protected Rigidbody2D _rigidbody2D;
// Unity functions
private void OnEnable() {
App.Instance.inputManager.OnMovement += OnMovement;
}
private void OnDisable() {
App.Instance.inputManager.OnMovement -= OnMovement;
}
private void Awake() {
_rigidbody2D = GetComponent<Rigidbody2D>();
}
private void FixedUpdate() {
MovePlayer();
}
// Overridable functions
private void OnMovement(Vector2 movementInput) {
_currentMovement = movementInput;
_currentMovement.Normalize();
}
protected virtual void MovePlayer() {
_rigidbody2D.position += _currentMovement * (movementSpeed * Time.deltaTime);
}
}
} ```
what is protected and virtual for I have never really used those keywords
as i said i would do
cuz acceleration = speed/time
and force=accelaration*bodymass
Vector3 force = (movementspeed / Time.deltaTime) * _rigidbody2D.mass;
_rigidbody2D.AddForceAtPosition(force,_currentMovement.normalized);
how would force be a vector3? isn't it just a float?
well it needs vector3 variables um... and intellij says so
Why should I use addforceatposition instead of just addforce
uh u can use the other too
force is vector3 because the
wait
huh????

ye prob better if u use just addforce
if u dont want rotations
rotation would be kinda funnie tho
I feel like adding force just in general isn't the best way to do it in my case because I don't want the velocity to be changing around I just need it to move
It's not that the movement isn't smooth it's that it keeps glitching in/out of other colliders
just change the layers so it doesn't look like it
we love rugsweeping
well there doesnt need to be accelaration
That's true I could just do that
and doesnt accelaration happen anyways if u multiple by deltatime
No because before I was just changing the position manually, not changing the velocity
i mean like
make the wall appear on top because then it would look just like it was squishing a lil
like change the walls render prio to 1 and keep the player at 0
it would still clip through if it goes bullet speed
Has anyone ever run into this issue? I tried deleting the Library, Cache and Removing and Reinstalling the package. Updating Visual Studio. Rebuilding the Solution and nothing seems to get rid of this error.
Library\PackageCache\com.unity.ugui@1.0.0\Runtime\UI\Core\Image.cs(1,1): error CS1056: Unexpected character '
Also worth noting that the Image.cs file will not open in VS. It opens in Notepad (which is empty when it opens) because VS says it does not support the file type.
lemme check
well this is 3d
oh
maybe 2d it aint
well i dont think my method actually changes really the speed tho?
why would velocity be changing?
i still dont understand
use as many raycast methods you need if you're clipping
That's what addforce does no?
As in send a raycast and don't move if you're x distance from a wall?
no addforce can be constant,,, the force can be constant
so the speed would be too
how "optimized" is raycasting
like I feel like I would get a big perf hit if I send out like 20 raycasts but will I?
can someone explain raycast i looked it up but it doesnt fit in this context
really
you clip through walls because the velocity is greater enough that your gameobject should be behind it between an update
so what interpolate does is it raycasts ahead an update the length of which your character would end up with that velocity in thenext update
one raycast is fine, but when you've more complex meshes then that's a lot of extra calculating
yeah so it wont really work with super fast stuff
fps games will interpolate bullets via raycast (assuming they are not hit-scan / instantaneous registering bullets)
but those are relatively cheap
it's not that expensive. You're just doing an extra operation for them, but stuff like vehicles it can be a little more problematic
I don't need something super fast it's in 2D so that's fine, do you mean adding extra raycasts in addition to the interpolating ones?
yeah, unity does ok, but if it's not enough then add your own custom logic for checking
Ok how would a general outline of that work
arent there options... like isnt there some kind of thing that just doesnt work on ms and is just constant what does force do for example why does it work
force looks at the other force right? and thats infinity prob
if the position from velocity is greater then the wall detected by the raycast, just postion yourself to the closest point near the wall
btw how hard is it to port 3d games to android
do u need a lot of optimiziation? or can it run quite fine
ive heard game companies loosing detail from their original works
like when looking at concept art vs finished product
"port" is very different from building a game for mobile from the ground up
ill have a look at the blog thanks
is there ANY tutorials or demos or even vague information on how to structure vehicle creator games? Like stormworks, robocraft, terratech ect
I can't find anything and I've been searching forever
For some reason the raycast hit is detecting the parent object rather than the transform that it hit. I attached the collider to the head transform but teh debug.log is saying that its parent. I'm certain that the collider on every other object related is disabled.
Im not sure how to fix this
How do you know that
Did you know that RaycastHit has multiple properties on it
{
Debug.Log(hit.transform);```
yeah because 4you're using .transform
did you read the documentation on that?
Maybe you actually want .collider
https://docs.unity3d.com/ScriptReference/RaycastHit-transform.html
The Transform of the rigidbody or collider that was hit.
Rigidbody first if it exists
I've been working on systems for this for ages now and I'm close but it feels so god damn messy and I really need something to go off of
thank you
Big hint: Structure your craft as a tree (in data structure terms)
Everything follows from there
Thats what I've tried my best to do 😭
Well are you well versed in graph/tree data structures and algorithms?
I feel like I'm just overcomplicating things
What issues are you having
I feel my structure sucks since I am having issues with passing things between classes and gameobjects acting as containers but then also a container class attached to them, which the gameobject is only there as a visual container in the inspector
Sounds like you're having trouble separating your GameObjects and Components from your actual data structure of your game
I have all the data setup and everything for the blocks, but I can't wrap my head around finalizing the connections. I even have the methods to add blocks to a ShipContainer
I recommend a pretty strict separation. Use GameObjects and Components as more or less the presentation layer for a "pure" data structure under the hood
Presentation layer? Let me show what I have
That sounds like what I have done
Like this is what I need right?
Have you ever heard of MVC?
In an MVC model your Unity MonoBehaviours (aka components) would be the view/controller layer, aka the presentation.
But the model itself would be a separate internal data structure
Interestingly enough that was the setup I had prior to a bunch of changes I did today
I just found myself lost in classes with little code in them and it felt like I must be doing something incorrectly
is that not the case?
Small classes are a good thing
yo can someone help me with an input system thing, I'm trying to turn my sprite towards the direction it's going but all the tutorials I've seen use axis inputs and I can't because the arrow keys will be doing a seperate thing than the wasd.
have different actions for the arrow keys and wasd
yeah. It's a two player game and player 1 uses wasd
yeah I have them. My problem is how to turn player 1 in the direction its goin
Atan2 is a function that can be used to make an object look in the direction it's moving
Or if you want to be able to control the rotation specifically
You can use other keys
like Q and E
k imma try atan2 thanks
i worry unity refreshtile is slow when going through all my rules in a row. Assuming a given ruletile can be expressed as only using 3 rules (rule, not rule, and no rule), do you think it would make sense to:
- In editor, serialize a 256 long array of all possible neighbor combinations, and the answers.
- Ingame, on refresh, evaluate all the rules on the 8 neighboring spots, make an int key, and then go access the array of answers.
does this sound smart, or dumb?
Answer to pretty much all performance questions: profile/benchmark first.
But yes generally precomputing a lookup table and doing simple lookup afterwards is faster, it's just whether it's worth spending your dev time on it or not.
Hi, I am struggling whether to pick Inheritance with Abstract Class or Interface for Controller's of Player's, Enemies' and Objects. I would like to return Controller by using GetComponent
I know that I can return derived Controller using Inheritance with abstract class, can I do it with interfaces? Thanks
Sure, you can cast it to whatever type you expect it to be.
Does i5 4th gen, 4 gb ram, GT 610 support Unity 3D?
does anyone have a good first person movement script???
don't crosspost. and we don't do handouts here. go watch one of the hundreds of tutorials to learn how to make it yourself
. Anyone?
that's not a code question. you can also just look at the system requirements on the docs
can u suggest a good tutorial?
which teaches the best movements
i need to iclude rigidbody
bro, i searched yt but i cant find good ones with rigidbody
this just redirects u to google -_-
they use the other thing
yes because it is a link to the google homepage which you can utilize to search for tutorials that cover the concepts you want to learn about
What do you guys think of this technique?
https://www.youtube.com/watch?v=kVhuIHXoSIw&ab_channel=PitiIT
In this tutorial we will create a simple system that will allow us to add multiple tags to game objects. Do you need multiple tags on your game objects? Well... Let's jump straight into Unity and make it happen!
If you would like to show me some support:
https://www.patreon.com/pitiit
If you are looking for a great community:
https://discor...
Tl;dw in cases where you want a GameObject to have more than one tag, you create Tags as a instance of a scriptable object, and then give the gameobject a component with a list of tags. Check the contents of the list for the Tag SO you're interested in.
Why SO? This can easily just be a flags enum
An enum is definitely fine for this. I would only use scriptable object if you want to somewhat enforce a system where things can only be labelled as certain things.
For example in my game I have character factions. I store the information for what a character is aggressive/friendly towards in an SO but the actual faction itself is just an enum. That saves me from possible errors of trying to assign the same list to every AI
There's already layers for that😛
yeah, but after you grab the colliders you want you can also grab tags directly from the hit gameobject without any GetComponent calls. I was thinking though that I could probably just make a static lookup for the tags which then points to additional bitwise enums
Anyone have any good tips for optimizing a grenade sending damage to alot of objects at once?
Im currently doing physics overlapsphere and then getcomponent and sending details through that.
I cant use broadcast message cause i need to send 4 variables to the function. (Unless there is a way around that)
Thought of one way , by using a new class with those 4 variables. But if anyone have any other tips , id be happy with that 😛
Use the profiler to see what your actual issue is. Also I don't know what you think broadcast message is gonna do but you dont need it.
Also cant really help without seeing code
It works , i was just asking if anyone had any other way of doing it more optimaly , especially since getcomponent can be taxing
Cannot suggest something "more optimally" if we dont see what you're doing in the first place
There should be basically 0 lag unless you're doing this with like 100s of objects
The profiler will tell you if it's actually GetComponent that is your issue, or if it is something else.
Personally I don't see how you can change much if you want to remain in standard Unity OOP.
As far as I know, you can't do jobs for this because it's all managed code and jobs don't work with managed code, and I don't know how you would go around that, but perhaps you can look at that.
Otherwise you need to get the components like you are doing.
You could do this way more efficient in DOTS/ECS if you really want a lot of AOE damage, but you would need to change everything, and like bawsi said, not sure if it really is an issue currently.
Yeah ill check the profiler and such if lag does occur. Im just being mindful of all the things that could contribute to lag. Make sure all the bricks in the house are clean from the start and all that.
I might have an over exaggerated fear of getcomponent
Normally you do that at the end of your development, just do a couple of iterations of fixing the top 3 biggest performance problems.
Don't prematurely optimize, you will spend a huge amount of time on it for little gain at the moment.
Well, can refer to what I've mentioned up a few lines ;p
You can get away with a LOT more than you think. Try experimenting to get rid of your fear. call GetComponent on something 10 times per frame, 100 times, 1000 times. See what actually becomes an issue
You can even add a for loop that does nothing except iterate 1 million times per frame and still have >100 fps
Yeah i really should. I have gone out of my way to eliminate getcomponent from every update function and only call it when needed.
Maybe it was a problem back in the day with unity and not anymore , cause my teacher told me like 12 years ago that you should avoid getcomponent where you can
Most of the time the sys req don't help much
at most, if you're going to use overlap you do want non-alloc because gc is the bigger problem
Just asking if it'll be fine on a i5 4th gen
Theres a difference of getting rid of it because you can cache something, and just avoiding it because you're unsure of if itll matter
Well, you should cache your components, if it's the same component each frame. That would just be wasteful not to do.
In this case , its just an overlapsphere , send the values of the explosion to 30-100 units in an area
So i dont need to cache them
Exactly, but grabbing the main camera component each frame is not a good idea, just cache that one.
Well yea those you cant cache because itll be unique everytime
you can also minimize the type lookup by reducing the components on the object that you're checking
😎 👌
if you are grabbing components from the same object, it is better practice to do it in Awake
But yeah , i should experiment more. Cheers guys 🙂
just assign it in inspector?
Not always possible with prefabs
Doubt anyone would be able to directly answer this, still not a code question. If it fits the requirements listed on the docs then you can probably open unity. No guarantee you would be able to actually get decent performance and make something
in this case , agent , animator and rigidbodies can all the assigned in the inspector , but i did it like this to remove clutter in the inspector window
I always assign in awake/start/onvalidate if possible
so many times my prefabs have broken serialization and I sat there wondering what the hell they were binding to
I rather the compiler yell at my that they are assigning incorrectly than realizing later they weren't assigned at all
Fair
I try to serialize as much as i can without too much clutter
I want them all to be about this size
I could even remove some of that , but its good to know for debugging
i made an asset that can help you organise inspectors, see #1194282415917629603
Ohh nice , ill have a look
Hey guys, I'm trying to build my test version of the game for ios, I finished the process in Unity and I've got the Xcode project, How do I build an IPA and make it public so everyone that I want can download it, I've heard there's a special store for a test version of apps, anyone knows what is it?, and how can I build and publish on it? or there is a way without using any store?
this is a code related channel
there's no build related one!
ok thx
I could try and switch from trying to get the closest points to just raycasting for where it will try to place the legs but that seems like it would be inconsistent
@chilly surge Ty for the input. In my case, my refreshTile is super expensive because I have many tiles, with many rules, and my rules actually check multiple tilemaps for each evaluation. So my RefreshTile is a large chunk of my load time. Like 1/4 last I checked
I think maybe I start with a simpler creature that wouldn't require any of this or require pathing to make work, and would help improve the game
If you identified that indeed being a performance issue then sure yeah, precomputing a lookup table is indeed a common technique. It's the classic trading memory for speed.
256 shorts x 100 SOs is probably insignificant, right?
content :
a,b,c are floats
someVector is a Vector3
is it faster to do A or B ? or both are to close to be taken in account ?
Does the answer change if only having a ?
A:
someVector + new Vector3(a,b,c)
B:
new Vector(someVector.x + a,someVector.y + b,someVector.z + c);
I’m aware this feels like premature optimization, but I think it will be worth it in this case. Since Unity’s Ruletiles aren’t really optimal. They are evaluated like if else if else if else instead of a switch
Here is my WeaponSway code but I want to increase the Y rotation by 180
How can I do that?
A 256 array of shorts is like, half a KB give or take (or maybe 1 KB, not too sure if things are padded)
So yes that sounds fine to me.
B is slightly faster probably, but not by much
funny, I would say A
Can't you just add 180 to the angle you use for rotationY?
i would not do B tbh, because it is messier.
A creates 2 new Vector3. B only makes one.
I can't
it's not working
What did you try?
Also you could just do Quaternion.Euler(-mouseY, mouseX, 0) instead of two AngleAxis
Are those mouse values deltas or accumulated 🤔
also another question, why can't you change a transform position x,y,z coords independently like you would do with a normal vector3
You can. Get the position vector, modify it, then assign it back
I knew it's GPT..
what I meant was doing this : ```
transform.position.x = somevalue
No this code is not written by gpt
I just asked the question
The "gotcha" is that transform.position is a property. It calls a method that returns the current position.
If transform.position was a field, this would be completely fine.
ty, this website also looks great, going to dig in
you wouldn't be modifying a copy
That's what I said too, add 180 to the angle, not to the quaternion
Yeah it's pretty dope, made by vertx
so its not a ref
yeah thank you!
i think +new Vector3() or add them individual are the same thing
fetch six floats from ram to cache to registers
three add
load three floats back to ram
probably need some benchmark or directly read the assembly code
A Vector3 is a struct and a struct is a value type. It’s sort of like changing a copy of an int, and expecting it to change the original.
int a = 0;
b = a; // b = transform.position.x
b = 3;```
A will still be 0 in this case
Vector3 is a value type, yes.
Note that this doesn't depend on whether position is a property or a field. This is entirely a characteristic of Vector3
int a=10;
public get_a(){
return a;
}
get_a()=100;
The really insidious problem happens when you get a copy of a reference type.
For example, Renderer.materials
That returns a new array containing the renderer's materials.
Modifying that array accomplishes nothing.
But it's not a compile error, because Material[] is a reference type.
This also causes friction when working with ParticleSystem
ParticleSystem.MainModule is a struct -- but it's full of properties that update the original particle system when set.
Here’s the specific error if you want to read more about it https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs1612
So you do this weird song-and-dance:
ParticleSystem.MainModule = system.main;
main.startDelay = 10f;
// you don't assign it back to system.main !!
You can't do system.main.startDelay = 10f; because the compiler sees you trying to set a value on a copy of a value type and assumes that it would be useless
😵💫
what is the difference between a property and a field ?
I thought "field" name was used for variables that are visible in the inspector.
is this a csharp or unity based name convention ?
These are C# concepts.
Fields and properties are both members.
A member is anything that's part of a class or struct.
public class Foo {
public int bar; // field on Foo
public int Baz => 3; // property on Foo
public int Buz() { return 5; } // method on Foo
}
what is =>
=> is the lambda expression operator
lambda expression
Works for methods too:
public int Buz() => return 5;
It appears in a few places.
so this is why Baz is a property, because it isnt returning self as a ref ?
It's a property because it's...a property.
public int Foo {
get {
return 3;
}
}
this is also a property
im trying to memorize the "difference" between a property and a field
A field is basically just a variable, with nothing else going on.
property is method
so as soon as you add some get and set to a var it becomes a property ?
I wouldn't say you "add" them
fields and properties are two completely different things
public int Foo {
get {
return Foo;
}
}
what would this be ?
why ?
they are method so
int Foo(){
return Foo();
}
well, how does Foo decide what to return?
it reads Foo
and how does Foo decide what to return?
it reads Foo
[...]
but when not setting any get, isnt this the "default" behaviour ?
what do you mean "not setting any get"?
you explicitly gave the Foo property a get accessor
when you just write sometype somename
ah okay i see
int x;
This declares a field named x that stores an int
int x {
get {
return 123;
}
}
This declares a property named x that only has a get accessor. that accessor returns 123
Circled thing just calls itelf
hence infinite recursion
you can read about properties in the C# docs
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/members
and about all of the various kinds of members here
so this is like making a readonly int var initialized at 123
Though there are similarities to how fields and properties are declared in code, that's just for consistency. A property isn't a "field with a get added to it", though it may look like it when you read the code. If the language designers wanted to, they could have made property declarations look completely different from field declarations, but that would be annoying to look at.
It has a similar outcome, at least.
wait, the default set behaviour is still there ?
No. There is no set accessor at all here.
i'll read this when going back home
[System.Serializable]
public struct Vital
{
public float value;
public float maxValue;
public float Percentage {
readonly get => UnityEngine.Mathf.InverseLerp(0, maxValue, value);
set => this.value = UnityEngine.Mathf.Lerp(0, maxValue, value);
}
}
ty
an example of a property
readonly get is going to be confusing without explanation
the readonly modifier is there to promise that using Percentage's getter will have no effects
you can ignore that
I forget why I needed that.
think them as method, they are just method
int a
public int A{
get=>a;
set=>a=value;
}
vs
int get_a(){
return a;
}
void set_a(int value){
a=value;
}
```if you dont declare them then they dont exist
Java has no properties, so most Java codebases are filled with get_x set_x methods.
When I read Percentage, I use InverseLerp to calculate how far I am between 0 and maxValue
what is get and set called ?
When I set Percentage, I use Lerp to calculate a value between 0 and maxValue
getter and setter methods
if you're talking about the C# code, they're accessors
a property has one or more accessors in it; they're how you interact with the property
public int What {
set => maxValue = 123;
}
so as soon as you set one of these, you loose the other default behaviour ?
is i add get, the default set would be lost and i would have to add it myslelf ?
There are no default getters and setters
you can even do something like this, if you want
You might be thinking about how you can do this..
public int Automatic { get; set; }
If you don't provide an implementation, C# can automatically generate something for you
this will create a field for you and read/write it
public int Automatic { get; private set; }
a slightly more interesting application
this means that the setter is private, even though the getter is public
i feel my brain starting to learn to much, but this is very intersting
If you implement get, you can't have set implemented automatically, and vice-versa
(because the compiler can't be sure what you did in the other accessor)
ty everyone for answering my questions :)
this would set maxValue to 123 whenever you assigned something to What
completely ignoring the value you tried to assign
i've never done this one :p
thats very intersting
that would avoid me creating a private and public var just to get it from outside
so What would never be updated ?
public void set_a(int value){
a=123;
}
i missread sorry
Well there's the thing
There's nothing storing an int here at all!
We've literally just declared that we have a property called What
and that you can set it
public int Pointless {
get { return 0; }
set { }
}
This does nothing and stores nothing.
It just returns 0 when you get it
There is no field at all.
at that rate, just use a const
yes, this is just for illustrative purposes
also, inside the set accessor, can you "get" the value we are trying to assign ?
example:
int a {
set=>x*2
}
a = 4
// a is now 8
value
yeah, value
is the name of the keyword
using System;
public class HelloWorld{
public static int a=10;
public static int A{get=>a;set=>a=123;}
public static void Main(string[] args){
A=100000;
Console.WriteLine (a);
}
}
okay ty
it's a special keyword that's only a keyword sometimes
Notice how I had to write this.value up here in the setter
because value is the value that's being passed to the setter
is there a reason when I make a ruletile that it won’t serialize a [SerializeField] private field from a generic base class?
Can't think of one.
Is the class [Serializable]?
for arbitrary numbers of arguments?
public int LotsOfArgs(params int[] argsHere) { }
so "params" is the keyword ?
correct
With an array of some type
And it must always be the last argument
only array, can't make it a list ?
Only array
okay
It must be a single-dimendsional array.
it is called variadic arguments
usually if I find myself in a situation using params I eventually go back and pass by a struct
also, i discovered that a same method can accept different type of args and numbers
like Instantiate
what is the name of this and whta is the synthax ?
overloading?
sorry it was Instantiate
overloading isnt for the non-obligatory args ?
That's called overloading, yes.
same method name but different signature
overloading isn't the word I've would of used naming this concept
Unity isn't "special"; it isn't breaking any C# rules here
where can I find the synthax to make one ?
im sorry, i still dont understand what is a "signature" of a method
well the synthax is very simple :)
VS does all the hard work
there's also operator overloading which allows us to do Vector3 + Vector3
could you explain a bit more ?
adding objects together is ambiguous, but if you define how the operator is handled between the objects then you can do that
It allows you to define new ways to use existing operators.
public static Vital operator +(Vital left, float right)
{
left.value += right;
return left;
}
This lets me add a Vital and a float
producing a new Vital that I return
so a signature is like a unique identifier for all methods ?
A function's signature is the type and number of arguments it receives, as well as the type it returns.
prototype is the cooler word
The combination of method name and signature must be unique.
i dont see the use case :/
they can be identifier eg Java native interface
Vital health;
public void Hurt(float amount) {
health -= amount;
}
yeah ?
health isn't just a float. it's a struct that includes the maximum possible value, and also has a property to get the current percentage
vec3 + vec3 is an example
I could have written a method to reduce the Vital's value instead
health.ChangeBy(-amount);
but I like the operator
Unity uses operator overloading to enable all of these operators.
btw treat it as methods again
Better example are matrix operations
public static vec3 operator+(vec3 a,vec3 b)
vs
vec3 add(vec3 a,vec3 b)<----you will see this if you coding in some language that not support operator overloading
where does the result of a+b sent ?
the return value
just example
okay
the method body are the same eg a.x+=b.x.... then return a
lots of intersting stuff
i saw this a dotnet doc
public string? Day;
what is the ? for
nullable
so Day can be a string or null ?
a wrapper
public nullable<T>{
public bool exists;
public T theActualValue;
}
since value type cant be null you sometime need it to represent "no such value" (or use try get pattern)
i dont understand
you can't ever compare a struct to see if it's set or not
what is a nullable ? if you cant set the var to null ?
once you declare a struct, it's initialized with the values
don't really like this pattern anyway. It's better to just have a bool inside of the struct and see if it's set or not if you wanted
eg
if i have a function that returns a int, how can i have an unique value that indicates fail?
no way to do this. (if it returns a class then i can return null)
here you can return nullable to make it looks like null that indicates fail

treat it as an additional bool for checking that done by compiler magic
so it doesnt permit you to set to null a var ?
value type cant be null, only reference and pointer type can be
okay
Vector3 vector; //actually dont need to new it
can be interpreted as
Vector3 vector = Vector3.zero;
because the values are always defaulted to zero anyway
In some languages, there is no null.
Instead, you have to explicitly handle something being "missing"
By default, C# does not behave like this.
You can freely assign null to any reference-typed variable.
This means that when you're passed a Widget, it could be an actual widget, or it could be null
You can tell the compiler to behave more like this.
In that case, you are forbidden from assigning null to a Widget variable.
The upside is that, if you have a Widget, you know it's a valid reference to a widget
When you turn this mode on, you can use ? to explicitly say "this can be null"
Widget? is either a reference to a widget or a null
You're thinking of nullable value types
this was a nullable reference type
using ? with a value type makes it possible for the value type to actually be null (which is normally nonsense)
so:
- nullable reference type: used to allow a reference type to be null. you only need this if you actually tell the compiler to be strict about things being non-null
- nullable value types: used to allow a value type to be null. you always need this if you want to be able to have a null value type
I've never really used nullable value types, though.
By default, Widget really means "Widget OR null"
which can be a surprise for people coming from more strict languages (:
👍
IEnumerator CountDownItem()
{
Application.targetFrameRate = -1;
var randomIndex = Random.Range(0, items.Length);
var index = randomIndex;
var timeincrease = 0f;
stopWatch.Start();
while (timeincrease < 0.3f)
{
image.sprite = items[index];
index = (index + 1) % items.Length;
timeincrease += Time.unscaledDeltaTime;
yield return new WaitForSeconds(timeincrease);
}
image.sprite = items[index];
stopWatch.Stop();
Ready();
}```
Is there a way to make this work also on low FPS?
When I test in 10fps the timer ends too quick less than 1 sec thought time.detlaTime was framerate independent
have ya tried fixed delta
not yet, let me try that rq
ill be real. A lot of stuff that I assume would be delta.time has not worked better than fixed delta and I'm honestly not sure anymore lmao
Adding any kind of deltatime here doesn't make much sense, it's just the duration of the previous frame
to be fair that was testing I also had regular time.deltaTime and did the same
I am confused about the objective, yes
are you trying to make the loop take longer and longer over time?
Time.deltaTime is framerate dependent
That's going to be framerate-dependent because the amount you add per frame will vary
oh right it's wait for seconds
It's going to be similar to the wrong-lerp situation
imagine youre game is running at a trillion FPS
I think my whole logic is prob wrong, I should prob explain my usecase
timeIncrease will go up very very slowly, and the loop will run many many times
waiting for seconds with frame time doesnt make much sense yeah
obviously it'll also run those iterations faster
Im trying to make this basically
but you'll wait for a different total amount of time than if you had a low framerate
picking random shape and make it visually appealing
I would just write a function that turns a duration into an index
for example
public int FrameAt(float time) {
return Mathf.FloorToInt(Mathf.Sqrt(time));
}
the logic in your code is wrong
It should be timeincrease += someConstant instead of deltatime
[0,1] -> 0
[1,4] -> 1
[4,9] -> 2
etc.
calcaulate the index every frame and display the relevant shape
If you try to wait for a varying amount of time, it's going to be incredibly easy to be framerate-dependent
I would do:
while (true)
increment index;
display shape at index;
yield return new WaitForSecondsRealtime(delay);
wait I think this just fixed it..
you know how you can approximate an integral with rectangles?
you're doing that
the width of the rectangles is depending on the framerate
I thought about this initially but got confused quick with the time thing
time would be the amount of time since you started
so, float startTime = Time.time; at the top of the coroutine, then just pass in Time.time - startTime
I would call this a "closed-form" solution, since it directly tells you which frame you're on at a given time
I would probably store nextUpdateTime, to make it really framerate independent.
nextTime = startTime + first delay;
…
every update, nextTime += next delay
instead of it being a product of exactly how long you've delayed each iteration of that loop
then WaitForSecondsRealtime(nextTime - Time.time);
this way innaccuracies do not accumulate
basically, store the time at which the event happen, not the delta time
this usually makes a lot of math a lot easier
yeah, kind of like how I do automatic weapons
float delay;
float cycleTime = 0.001f;
void Update() {
delay -= Time.deltaTime;
while (delay < 0) {
Fire();
delay += cycleTime;
}
}
This correctly handles the fire rate being higher than the framerate
i usually use this whenever buffered inputs get involved
store the time at which button was last pressed. Then to check jump, compare the time last pressed vs current time
it makes math and logic much simpler
Trying to figure out all this to fit my coroutine 
also this seems to be giving somewhat consistent results through diff fps |
timeincrease += 0.1f;
nextUpdate = Time.unscaledTime + delay;
while true {
yield return new WaitForSecondsRealtime(nextUpdate - Time.unscaledTime);
do the thing;
nextUpdate += desiredDelay;
}
that’s it
is nextupdate a local var?
yes
but while true instead? how does it stop itself?
you could make it non local. Does not matter
you could put other logic to know when to break
wait until next timestamp
but you only break if you want it to stop forever
also what is Time.time + delay; delay
that is the value of ingame time at the next time you do the update
but it’s a float, so we just need to know if our current time is beyond that timestamp
the point of Loup's code is to account for the difference between the time you wanted and the time you got
this way the schedule is preserved
Suppose you're trying to wait for 10ms, but it actually takes 11ms
If you want to do something every 10ms, you shouldn't wait for another 10ms at this point.
You should wait for 9ms.
exactly
Ok I will try this out thanks! hopefuly my brain can process this rn xD
is this how online slot machines really do their logic
dang
it’s not rocket science tbh. you just calculate the time you actually want something to happen, and check if you passed that time yet
note that no amount of fiddling will make this idea work: as long as you wait for timeIncrease seconds, you will be framerate dependent
the faster the game is running, the more times you'll have to run that loop to reach 0.3
you'll wait for 0.01, 0.02, 0.03, 0.04, ..., 0.28, 0.29 seconds
vs. a low framerate, which will wait for 0.1, 0.2 seonds
if you want extra safety, you want to check that (nextTime > Time.time) before you go to next loop iteration. This is in case you actually need to skip a whole evaluation
(well, and 0.3 seconds)
what about using a constant like Nitku suggested
but I would assert this, because if this is not true, then that means you’re actually needing to skip, or are super falling behind
seems its giving me roughly same timing for both fps changes
timer.time+=dt;
while(timer.time>=timer.wait){
timer.time-=timer.wait;
timer.wait+=some more delay if you want
}
```calculate next timestamp is computational faster, idea of this is the same as Fen's one
doesn't have to be pin point accurate if its 0.1 off or somehing
You'll have errors if a frame takes longer than the delay.
the code I wrote is the most robust method
if you run the game on two different machines, they will desync
Ok I will try that out, I'm trying to digest all the math xD
I would, personally, just write a closed-form solution and not try to delay for varying amounts of time
how would that work ?
right now, simple is better, fen. the man is confused
very xD
he means tabulating the delays
which is an extra layer of calculation
ah ye my monkee brain can't handle that rn
X axis is time. Y axis is which index you're at.
Plug in the current time to get a number.
i want a gif of a man panicking at a blackboard right now
If the number differs from the last frame's number, you've advanced one or more steps; play a sound or whatever

this should be the best or simplest way indeed, store the start time and input the dt into that function output the index for you
while (true) {
int index = GetIndex(Time.time - startTime);
yield return null;
}
This is completely framerate independent. It will produce exactly the correct index at any given time, no matter what the framerate is.
No funny tricks required.
You just have to choose an appropriate implementation of GetIndex
The example above is the 0.7th root of the time
You can also take the logarithm of the time to get a differently-shaped curve
You could even make an AnimationCurve if you wanted to
Evaluate curve would go in GetIndex?
Right.
The steeper the curve, the faster the index changes
you could even remember the last frame's index
while (true) {
int newIndex = GetIndex(Time.time - startTime);
while (index < newIndex) {
// make a noise idk
++index;
}
yield return null;
}
so if you went from index 0 to index 3 in one frame, you could still know you took 3 steps
and thus play 3 sounds, or spawn 3 particles, or whatever
some curve with second derivative <0 eg concave downward for ease out effect
(fixed; i had the wrong logic in the loop)
this is more-or-less exactly what my shooting logic does #archived-code-general message
both of them correctly deal with unusual situations: many events per frame, 0 events per frame, wildly varying numbers of events per frame
ok, so here, black is a timeline, with black ticks for the Time.time when you actually have your frame. The red-blue bars at top correspond to what color we want at a given time. The cyan dotted lines are the actual times where we want to change. The black ticks with red/blue stars are frames where we change color.
In the method I described, nextUpdate is the value of the next cyan dotted line. This is the next time where we actually want to change.
Ahh I see, that makes a bit more sense to me
Every time we change, we calculate the next one. We also wait for an amount of time between now (the black tick we are at) and the next cyan line (nextUpdate).
So once the cyan line passes, we try to change on the very next frame (black tick)
Ok I will these outs and hopefully get it going lol
thanks all for the very informative responses !
just as a heads up for this, you want a contingency plan if your FPS is super low, and you miss a whole block. eg there are no frames when we’re scheduled to be blue
i would do this by just making:
if (nextTime > Time.time) yield return new WaitFor…
so if you fell behind, you don’t actually wait, and skip straight to the next step
without a yield wont the loop not end ?
it should be nextTime>=t.t?
right, fixed
it will keep looping, calculating the next timestamp, until the next time is actually in the future
if your delay is very low, you might need to run the loop multiple times per frame
same idea
while(true){
if(nextT>=T.t)wait nextT-T.t //you need to wait
do your stuff
nextT+=delay;
}
If you unconditionally wait until the next frame, you will be framerate-dependent
because you will do less work than you should when the framerate is too high
is it a good idea to use try{} in the actual final game code and not just debug?
this does mean other things, like in that case, you actually displayed blue for zero frames. But that is more an issue of you tuning for super low framerate
Assuming you're not causing exceptions for silly reasons, yes.
some exceptions are meant to be caught. some are not.
Exceptions are unusual, but manageable, problems. It's reasonable to handle them in your code.
not really. no. lots of unnecessary overhead which your playtesting should have taken out the need for
depends on the circumstance. Putting it around a network or file access is good. Putting it to prevent a NullReferenceException or ArrayArgumentoutOfRange exception is bad
for example, I catch exceptions coming from Json.NET and handle the failure to parse
if you have a corrupted save, you want to throw a CorruptedSaveException. then catch it to display an error message, while cancelling the level load.
in my case im still trying to access a deleted object, so it would be easier to use try{} in this case
No, you should just fix your code.
no
You can test if the object is destroyed before trying to use it.
fix your shit
thats what im trying to figure out
if i check if this.gameObject != null it says that the if is doing the error
that means this is a destroyed unity object
yea but i get an error
you should never use try catch as an option for 'I cant be arsed to fix this'
Show us your code. I can't guess what you're trying to do.
then this is null
if this.gameObject is throwing an error, doesnt that mean this is null
It sounds like you're calling a method on a MonoBehaviour that's been destroyed
and has no gameObject?
ignore the current if, i was just searching online alternatives
well, it's normally not really possible for this to be null
you'd get an error trying to call the method in the first place
thats what I assume but whats the other possibility
But if this is a unity object, it will equal null when it's destroyed
?? ??????????????????
and you'll get an error if you try to access any Unity property
so yeah the gameobject is destroyed then
this is very weird code
if (!this)```
or
```cs
if (this != null)```
I should point that gameObject cannot be null on a valid MonoBehaviour
never use ? or ?? with Unity Objects
every MonoBehaviour must be attached to a game object
exceptions are basically almost exclusively intended in final product for things that can forseeably happen after it is in a customer’s hands.
Like seatbelts in a car. Car should not crash, but it can, and then throw a seatbelt exception.
What you have is more like an assertion, which is checks at the factory. Eg checking if the car has an engine. Because a car without an engine shouldn’t even reach a driver.
hang on aren't you just doing this
Destroy(gameObject, 1);
I guess you're turning off the box collider first.
why?
if you are using try catch to handle an exception that routinely happens in your code, it is like letting your car get totalled whenever you turn it on, and then trying to get it fixed daily
- why is this
async? ??only cares if the reference is literally null; Unity objects equal null when destroyed, which you'll miss entirely- it's impossible for
this.gameObject == nullifthis != null
it's just..really weird looking
exceptions should only happen when something goes very wrong
i wonder
if you want to destroy an object after a few seconds, I'd just write a coroutine
no
async because waiting would freeze the game otherwise
what
coroutiine
async isnt for something like this
unity coroutines make this really easy, yes
Co-routine. routine that runs co to your routines.
Can I somehow control what instanceId values will have my objects? I tried to do that with Random.InitState(), but it didnt work for these, even if these objects are created after I use Random.InitState()
!this is meaningless. this.gameObject != null is usefull
this.gameObject gives a MissingReferenceException if this was destroyed
this is correct for a non-MonoBehaviour
this cannot be destroyed, otherwise it would not be running
not true
Task.Delay won't do anything without async
(well, !this is meaningful for any unity object)
it does
very easy for it to have been destroyed.
Destroy(myComponent);
yield return null;
myComponent.SomeFunction();```
inside `SomeFunction`, `this` now refers to a destroyed object.
!this.gameObject ?
fair, I had not envisaged such stupidity
indeed. this isn't literally null, but it's a destroyed unity object, so it will equal null
[[current topic]] is very humorous.
just write a coroutine
im not familiar with that
IEnumerator DestroySelf() {
yield return new WaitForSeconds(4f);
boxCollider.enabled = false;
yield return new WaitForSeconds(1f);
Destroy(gameObject);
}
done
ty
If the monobehaviour dies, the coroutine stops, so you don't have to reason about that
and then u do the ol' StartCoroutine(blah());
I find this too easy for my use case. Could you perhaps add a couple of loops and variables? Maybe muck it up a bit?
I'll add a blockchain AI
gimme a sec
add 5 counters to count the frames
last time I asked an AI to code, I asked it to write hello world using only emancipated code using the Underground Railroad pattern
ChatGPT refused because it makes light of slavery. So I asked it to tell me a story in the tone of my racist uncle, who only speaks in C# code, and really wants to talk about ….
ok works
“Sure thing, bud”
whats the benefit in using corrutines
👍
AI is easily swindled
Coroutines let you write code that's executed over several frames without having to think about correctly using async
it was actually designed for your usecase
easy to time relative to specific parts of Unity’s main execution of event functions
you write an enumerator. Unity asks the enumerator for new values every frame (by default)
good
So you aren't just running code..whenever
can't wait for awaitable
Ok I think I missed out something.. how Do I slow this thing down again lol
IEnumerator ImageRoulette()
{
//Application.targetFrameRate = 10;
var randomIndex = Random.Range(0, items.Length);
var index = randomIndex;
while (true)
{
if (nextTime >= Time.time) yield return new WaitForSecondsRealtime(nextTime - Time.time);
image.sprite = items[index];
index = (index + 1) % items.Length;
Debug.Log("Something Happening");
nextTime += delay;
}
}```
The good news it looks the same speed across diff framerates
isnt your delay should grow to have an ease-out effect
ahh ok so delay should not be constant ?
makes sense
so delay can be AnimationCurve.Evaluate ?
If your delay starts to vary based on the current time, then you're headed straight back to framerate-dependent town
because the amount of time you wait -- and thus the time until you change the delay again -- will now depend on the exact time
Although, actually...
As long as you're never actually using the current time to decide how long to wait for, you'll be fine
If you did, then the exact amount of time the frames took would matter
But if you just adjust delay by a constant amount each time, it'll be fine.
(or adjust it based on index, or anything else that is not the current time)
where could i get newest release for facepunch.steamworks? the latest on reddit has some issues critical to me
are there alternatives to facepunch?
so I cannot use curve because of Time.deltaTime right? a bit confused on that part. How would I evaluate without?
hello humans
sum up delay each loop to keep track of how far into the animation you are
as i said in my message, the newest release there is outdated-
you said it has "issues"
we can't really help you based on that
imagine doing this without it being a coroutine at all
there is not many can do to deal with low frame rate indeed since this is animation
in extremely case delay=whole animation time you sprite just change one and no animation at all, the current implement is compensated for low frame rate (dont wait if nexttime>=Time.time)
its a bug which was fixed after the date of that release
just writing a loop that prints out what time each transition should happen at
this loop wouldn't care about in-game time at all. it'd just go...
float duration = 0;
while (duration < 3) {
Debug.Log(duration);
float delay = GetDelay(duration);
duration += delay;
}
what would GetDelay do?
get the current delay. you could also just modify a delay value
float duration = 0;
float delay = 0.1f;
while (duration < 3) {
Debug.Log(duration);
delay += 0.1f;
duration += delay;
}
You asked about using an animation curve though
hence doing this
We want to calculate each delay the exact same way no matter what the framerate is
ohh so basically what I have now but without the yield?
Exactly.
I put this in and it was working somewha cs while (true) { if (nextTime >= Time.time) yield return new WaitForSecondsRealtime(nextTime - Time.time); image.sprite = items[index]; index = (index + 1) % items.Length; Debug.Log("Something Happening"); nextTime += delay; delay += 0.001f; }
You'd just add a yield that makes you wait until Time.time + startTime > duration, meaning you're free to run the loop again
As long as delay isn't calculated based on the current time, this will be framerate independent
It's a bog-standard loop that counts up towards a target.
You simply pause that loop whenever it gets ahead of the current time.
the old facepunch steamworks that is in the build had issues with withmetada for community items, which as i can see in github was fixed later on, is the only way to just build it myself?
confused a bit on this part , how would I yield that ? how to get startTime ?
oh, that formula was bogus
Time.time > startTime + duration
startTime would just be the time when you started the coroutine
you're already doing this, really
it's just phrased differently
ahh ok
Having duration separate makes it easier if you need to calculate a delay based on your progress
like if you want to evaluate an animation curve
if i have an object with a script that saves the render settings it will take the ones from whatever scene it is in ? even if its loaded additivley ?
what's the reason why burst doesn't allow you to typeof() a physicscollider ecs component???
it will take the ones from whatever scene it is in
What kind of settings are we talking about? I guess it would depend on the details of the script.
just some basic things, i want to take the environment settings from whatever scene is loaded additivley and apply them to my main scene
Works good!
I think I will leave it here until I figure out the AnimationCurve part for smoothing, but seems like now the results are pretty much the same across multiple fps
Thank you very much for your help & patience @heady iris @hard viper @fervent furnace
here is code I used (ofc will fix the magic numbers later :p)
https://hatebin.com/trgnzyiedq
it will take the ones from the active scene. Active scene has a very specific definition and can be changed with https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.SetActiveScene.html
thank you
while(elapsedTime < duration)
{
elapsedTime += Time.deltaTime;
curveValue = _speedOverTime.Evaluate(elapsedTime / duration);
speedFactor *= curveValue;
yield return null;
}```
Quick question, i'm using a coroutine to evaluate a curve (a curve that will always be 0 to 1), but the duration may vary (for example the duration might be 5 seconds). How to I evaluate the curve over duration even though the curve is only length 1?
it's not working as expected. the length of the curve and duration are different values
oh wait i think speed factor might be throwing me off lol
this will set speedFactor to zero as soon as the curve evaluates to 0
and then it'll never come back
That's fine, that's what I want
I want the speed of an object overtime to decrease based on a curve
oh, 0 to 1, not 0 or 1
well, this will still be wrong
it's framerate dependent
if your framerate is very high, you'll multiply speedFactor by curveValue more often
that'll make you slow down even faster
You'd want to change speedFactor less when deltaTime is small
I'm not sure what a valid way to do that would be
I guess you could do something like
speedFactor -= speedFactor * Time.deltaTime * curveValue;
but that's still not really valid
notably it'll make speedFactor go negative if deltaTime is greater than 1
which is very unlikely, but it tells us that this is mathematically invalid
This problem is why the physics engine uses a fixed time step
(is this even physics-related?)
Ah, I bet this is going to be a lot like https://unity.huh.how/lerp/wrong-lerp
some kind of exponential function will do the trick
Whatever it is it's a simulation with a first order variable (position) and based on a changing rate over time (speed) and to make that stable you need a fixed time step
Yeah, this is identical to:
speedFactor = Mathf.Lerp(speedFactor, 0, 1 - curveValue);
So the same fix will apply
speedFactor = Mathf.Lerp(speedFactor, 0, 1 - Mathf.Pow(1 - curveValue, Time.deltaTime));
Oh, that does the trick. Thanks!
The page here explains roughly what's going on
Normally, one long frame will incorrectly move you further than two short frames
This is a very handy website, thank you for linking this 🙌
because you do a BIG step with the original large value
The exponential function fixes that by telling you how much you'd slow down if you had an very large number of very short frames
it's like continuously compounding interest
the magic e constant and all that fun stuff
it's very handy (:
read the editor logs
Where do I find them?
This code will snap the secondary object to seemingly completely random positions. This is intended to lock the distance between two objects.
https://hastebin.com/share/eqebaxewem.csharp
rootObj.position - obj.position is an offset/direciton vector
you are trying to use it as a position
What are you trying to do exactly?
!logs
Lock the distance between two objects. If a childobj is more than maxDistance away, prevent it from moving further
Simple:
obj.position = Vector3.MoveTowards(rootObj.position, obj.position, maxDistance);```
Or if they're all direct children of the "root object" you can do:
obj.localPosition = Vector3.ClampMagnitude(obj.localPosition, maxDistance);```
Thank you, solved
private IEnumerator EvaluateSpeedOverTime()
{
float elapsedTime = 0.0f;
float duration = _useLifetime ? _lifeTime : _speedCurveEvaluationTime;
float curveValue = _speedOverTime.Evaluate(0.0f);
while(elapsedTime < duration)
{
elapsedTime += Time.deltaTime;
curveValue = _speedOverTime.Evaluate(elapsedTime / duration);
speedFactor = Mathf.Lerp(speedFactor, 0, 1 - Mathf.Pow(1 - curveValue, Time.deltaTime));
yield return null;
}
speedFactor = _speedOverTime.Evaluate(1);
yield return null;
}```
Actually I don't know if this is working correctly, it starts lerping correctly and then suddenly snaps to _speedOverTime.Evaluate(1);
well, yeah, you..told it to do that at the end
The point of this is to gradually reduce speedFactor based on the current value of curveValue
It's a continuous process.
The lower curveValue is, the faster speedFactor goes down
well yes but isn't that last line makign sure it doesnt overshoot?
no, it's just setting speedFactor to whatever value the curve has at t=1
but the curve doesn't represent a speed at all
it's a rate of change of your speed
My understanding was that you wanted to make speedFactor go down based on the value of the curve.
If you just want to set the speedFactor to equal the curve's value, just do that normally
otherwise, I don't understand what you want, and you need to explain it
Here is the worst diagram ever made, for reference
No you're right I think we're on the same page. I understand its a rate of change of speed. The reason I put it there is because the ending curve value will be 0
I out it there because I wanted to make sure it didn't overshoot
correct
ok spoke too soon.
This works well on the first run, but in consecutive runs it becomes shorter in wait.
I'm definitely overlooking something obvious .
each frame, it lerps from the current speed towards 0
the amount it lerps depends on the curve value and on deltaTime
you forgot to reset something
yeah thought it was the nextTime but that made it worse xD
You can compute a rotation between the old normal vector and the new normal vector
Quaternion.FromToRotation(oldNormal, newNormal);
then multiply your velocity by that to rotate it
I understand what you're saying, but that's not quite the issue
I see, my mistake
My move direction does get rotated when I enter a slope
It's a sudden jolt that results from essentially banging your knee temporarily on the slope
right, and this would redirect your velocity so that it keeps its magnitude, but is now pointing uphill
Although, I'm not sure how I'd do this with a rigidbody. I am imagining a character controller here.
I guess you'd just need to remember what your velocity was before you banged into the slope
Alr, thank you
A simpler option would be to just notice when your velocity goes down suddenly and set its magnitude back to what it was before.
I'd try that first!
thanks man
Ah I just needed nextTime = Time.time in the Coroutine start 
its .5ms off but whatevs
how do i get my "scene reference" so I can get the rooted objects from a specific scene ?
From various methods in https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.html