#archived-code-general

1 messages · Page 257 of 1

clever lagoon
#

oh.. not at me.. nvm

left violet
#

no I think he was refering to calling methods

hard viper
#

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

clever lagoon
#

@left violet agree with Loup 100%.. my rule of thumb: compiler errors are better than runtime errors.

left violet
#

I was not saying anything against his suggestion 😄

#

Clearly it is better practice to not use Strings

clever lagoon
#

sorry, didn't mean to imply otherwise.. was just giving a reason WHY

untold siren
#

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?
latent latch
#

why is your agent walking on walls

untold siren
#

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

latent latch
#

probably can do it with the navmesh raycast but I'd expect there's another method

molten radish
#

what do u like more rider or vs code?

#

for c#

#

i kinda prefer rider

untold siren
#

rider 100%

molten radish
#

ye its a lot faster with compiling maybe bc its live... and also auto complete seems to be faster too

#

rider auto saves right?

untold siren
#

mhm

molten radish
#

ah thats why

#

ive seen there has been a unity script editor... what happened to it?

#

or is this just vc?

simple egret
#

This one got discontinued. Your mainstream options are now Visual Studio, Visual Studio Code, Rider

molten radish
#

alr... yeah i think u dont even call them mainstream seen a graph where other was at 0%

#

for used programs for unity

simple egret
#

Some still want to suffer, we've seen a few use Notepad

heady iris
#

I saw a student using Word once

molten radish
#

xD

heady iris
#

(in a class I was TAing)

untold siren
#

my lecturer used notepad once

#

bro actually has a phd in "metaverse technology" too

molten radish
#

best ide has typing function

simple egret
#

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

molten radish
#

._.

untold siren
#

I mean powerpoint is turing complete

#

;)

molten radish
#

btw. when using shaders would u rather do it in unity or in blender

untold siren
#

it always prints "On Floor"

heady iris
molten radish
#

materials are often imported tho

quaint rock
#

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

heady iris
quaint rock
#

then you edit those in unity to have the correct shader and textures

heady iris
#

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

latent latch
#

Yeah, I've given up importing anything but general mesh datas

molten radish
#

alr. well ill learn how to do shaders in unity then

heady iris
#

I just create materials in Unity and then assign them in the model importer

latent latch
#

Shaderlab is dumb easy if you like visual scripting

molten radish
#

i kinda dispice visual scripting

heady iris
latent latch
#

shader graph right

heady iris
#

Shaderlab is the text based format

heady iris
#

I use both styles depending on what I’m doing

lean sail
latent latch
#

majority of special shaders you'd make is just copy pasted code anyway

heady iris
#

Writing HLSL works better if you need to do really elaborate stuff

latent latch
#

no reason to reinvent the wheel

static matrix
#

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

quaint rock
#

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

static matrix
latent latch
#

hlsl is also just a bunch of unity methods and macros

molten radish
static matrix
#

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

#

unsure what the issue is here

zinc parrot
#

I ended up doing this in a kind of hacky way, by somewhat abusing serialized static nested structs inside an editor window

deft dagger
#

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 ?

static matrix
#

A:
include ```
before and after you enter your code
and B:
what tf does "JUMP" mean
like what is your actual code

deft dagger
#

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

static matrix
#

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

deft dagger
#

i see, thanks man i will try this

static matrix
#

anyways, anyone have any idea whats up with my code?
is there some glaring issue I am not seeing

vagrant cargo
static matrix
#

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

vagrant cargo
#

It also happens slightly with the wall so I don't think pushing is the problem (though it does exaggerate it)

molten radish
#

well this is prob whats happening. fixed update isnt fast enough for the player speed

vagrant cargo
#

My code is in Update() not fixedupdate

molten radish
#

that doesnt matter update isnt simply fast enough for its speed

vagrant cargo
#

I see, does that video have a way to fix it?

static matrix
#

this is why physics code is usually in fixed update
but the collision is set to continuous doesn't that usually fix that issue?

molten radish
vagrant cargo
#

Ok I'll try it

molten radish
#

did it work?

heady iris
#

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

#

(well, two of the modes sweep out a volume in space)

vagrant cargo
heady iris
heady iris
#

instead of only in physics updates

#

it shouldn't be affecting the actual behavior

molten radish
#

hmm tried Continuous collision still clips through

vagrant cargo
vagrant cargo
static matrix
#

anyways, still unsure what is causing my issue
genuinely stumped

static matrix
molten radish
molten radish
#

yes that works

terse quarry
#

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

static matrix
#

eh as long as there is no lerping it should work I think????
Idk

heady iris
#

deltaTime will simply be zero.

molten radish
vagrant cargo
#
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);
        }
    }
} ```
static matrix
#

what is protected and virtual for I have never really used those keywords

molten radish
vagrant cargo
#

how would force be a vector3? isn't it just a float?

molten radish
#

well it needs vector3 variables um... and intellij says so

vagrant cargo
#

Why should I use addforceatposition instead of just addforce

molten radish
#

uh u can use the other too

static matrix
#

huh????

molten radish
#

ye prob better if u use just addforce

#

if u dont want rotations

#

rotation would be kinda funnie tho

vagrant cargo
#

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

static matrix
#

you could lerp it if you want that smooth feel

#

Lerp my beloved

vagrant cargo
#

It's not that the movement isn't smooth it's that it keeps glitching in/out of other colliders

static matrix
#

just change the layers so it doesn't look like it
we love rugsweeping

molten radish
vagrant cargo
molten radish
#

and doesnt accelaration happen anyways if u multiple by deltatime

vagrant cargo
#

No because before I was just changing the position manually, not changing the velocity

molten radish
#

i mean like

static matrix
#

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

molten radish
#

it would still clip through if it goes bullet speed

static matrix
#

not if continuous detection is on

#

or it shouldn't if cont is on

dapper schooner
#

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.

molten radish
molten radish
#

goes through

static matrix
#

well this is 3d

molten radish
#

oh

#

maybe 2d it aint

#

well i dont think my method actually changes really the speed tho?

molten radish
latent latch
#

here's the secret

#

raycast yourself

molten radish
#

i still dont understand

latent latch
#

use as many raycast methods you need if you're clipping

vagrant cargo
vagrant cargo
molten radish
#

so the speed would be too

static matrix
#

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?

latent latch
#

well, performance hit vs clipping

#

choose 1

molten radish
#

can someone explain raycast i looked it up but it doesnt fit in this context

#

really

latent latch
#

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

molten radish
#

ah

#

seems like a lot of calculating

#

before actually doing stuff

latent latch
#

one raycast is fine, but when you've more complex meshes then that's a lot of extra calculating

molten radish
#

yeah so it wont really work with super fast stuff

latent latch
#

fps games will interpolate bullets via raycast (assuming they are not hit-scan / instantaneous registering bullets)

#

but those are relatively cheap

molten radish
#

they do?

#

but doesnt ur laptop just die

latent latch
#

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

vagrant cargo
#

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?

latent latch
#

yeah, unity does ok, but if it's not enough then add your own custom logic for checking

vagrant cargo
#

Ok how would a general outline of that work

molten radish
#

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

latent latch
molten radish
#

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

molten radish
#

ill have a look at the blog thanks

severe sable
#

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

jagged snow
#

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

leaden ice
#

Did you know that RaycastHit has multiple properties on it

jagged snow
#
            {
                Debug.Log(hit.transform);```
leaden ice
#

did you read the documentation on that?

#

Maybe you actually want .collider

jagged snow
#

oh so raycast.hit.transform always calls the parent?

#

ah

severe sable
leaden ice
#

Everything follows from there

severe sable
#

Thats what I've tried my best to do 😭

leaden ice
#

Well are you well versed in graph/tree data structures and algorithms?

severe sable
#

I feel like I'm just overcomplicating things

leaden ice
#

What issues are you having

severe sable
#

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

leaden ice
#

Sounds like you're having trouble separating your GameObjects and Components from your actual data structure of your game

severe sable
#

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

leaden ice
#

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

severe sable
#

Presentation layer? Let me show what I have

#

That sounds like what I have done

#

Like this is what I need right?

leaden ice
#

Have you ever heard of MVC?

severe sable
#

model view controller

#

I am a bit familiar

leaden ice
#

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

severe sable
#

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?

leaden ice
#

Small classes are a good thing

sick timber
#

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.

devout radish
sick timber
#

yeah. It's a two player game and player 1 uses wasd

devout radish
#

So create two bindings, one for player one and two

#
Movement P1
Movement P2
sick timber
#

yeah I have them. My problem is how to turn player 1 in the direction its goin

devout radish
#

Or if you want to be able to control the rotation specifically

#

You can use other keys

#

like Q and E

sick timber
#

k imma try atan2 thanks

hard viper
#

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:

  1. In editor, serialize a 256 long array of all possible neighbor combinations, and the answers.
  2. 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?

chilly surge
#

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.

lunar python
#

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

cosmic rain
errant raven
#

Does i5 4th gen, 4 gb ram, GT 610 support Unity 3D?

cinder juniper
#

does anyone have a good first person movement script???

somber nacelle
errant raven
somber nacelle
#

that's not a code question. you can also just look at the system requirements on the docs

cinder juniper
#

which teaches the best movements

#

i need to iclude rigidbody

somber nacelle
cinder juniper
#

bro, i searched yt but i cant find good ones with rigidbody

cinder juniper
cinder juniper
somber nacelle
dawn nebula
#

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

▶ Play video
#

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.

west lotus
#

Why SO? This can easily just be a flags enum

lean sail
# dawn nebula Tl;dw in cases where you want a GameObject to have more than one tag, you create...

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

latent latch
#

bitwise enum is best enum

#

Unity tags into bitwise enums when

cosmic rain
#

There's already layers for that😛

latent latch
# cosmic rain 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

frigid bone
#

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 😛

lean sail
frigid bone
#

It works , i was just asking if anyone had any other way of doing it more optimaly , especially since getcomponent can be taxing

lean sail
#

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.

main shuttle
# frigid bone Anyone have any good tips for optimizing a grenade sending damage to alot of obj...

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.

frigid bone
#

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

main shuttle
#

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.

latent latch
lean sail
#

You can even add a for loop that does nothing except iterate 1 million times per frame and still have >100 fps

frigid bone
#

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

errant raven
latent latch
#

at most, if you're going to use overlap you do want non-alloc because gc is the bigger problem

errant raven
#

Just asking if it'll be fine on a i5 4th gen

lean sail
main shuttle
frigid bone
#

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

main shuttle
#

Exactly, but grabbing the main camera component each frame is not a good idea, just cache that one.

lean sail
#

Well yea those you cant cache because itll be unique everytime

latent latch
#

you can also minimize the type lookup by reducing the components on the object that you're checking

deft timber
#

if you are grabbing components from the same object, it is better practice to do it in Awake

frigid bone
#

But yeah , i should experiment more. Cheers guys 🙂

fervent furnace
#

just assign it in inspector?

main shuttle
#

Not always possible with prefabs

lean sail
# errant raven Just asking if it'll be fine on a i5 4th gen

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

frigid bone
#

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

latent latch
#

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

frigid bone
#

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

vapid condor
sly crag
#

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?

deft timber
sly crag
deft timber
#

sure, this is still a code related channel

sly crag
#

ok thx

static matrix
hard viper
#

@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

static matrix
#

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

chilly surge
hard viper
#

256 shorts x 100 SOs is probably insignificant, right?

round violet
#

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);
hard viper
#

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

tender patio
#

Here is my WeaponSway code but I want to increase the Y rotation by 180

#

How can I do that?

chilly surge
#

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.

hard viper
round violet
#

funny, I would say A

hexed pecan
hard viper
#

i would not do B tbh, because it is messier.

hard viper
tender patio
#

it's not working

hexed pecan
#

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 🤔

round violet
#

also another question, why can't you change a transform position x,y,z coords independently like you would do with a normal vector3

hexed pecan
tender patio
#

I tried this but didn't worked.

#

Then GPT told me to do this

#

and now it's working

hexed pecan
#

I knew it's GPT..

round violet
tender patio
#

I just asked the question

heady iris
#

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.

round violet
heady iris
#

you wouldn't be modifying a copy

hexed pecan
hexed pecan
fervent furnace
#

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

buoyant crane
heady iris
#

Note that this doesn't depend on whether position is a property or a field. This is entirely a characteristic of Vector3

fervent furnace
#
int a=10;
public get_a(){
  return a;
}
get_a()=100;
heady iris
#

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.

buoyant crane
heady iris
#

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

#

😵‍💫

round violet
#

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 ?

heady iris
#

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
}
round violet
#

what is =>

late lion
#

Shorthand for { get { return 3 }}

#

Expression body

heady iris
#

=> is the lambda expression operator

fervent furnace
#

lambda expression

late lion
#

Works for methods too:

public int Buz() => return 5;
heady iris
#

It appears in a few places.

round violet
#

so this is why Baz is a property, because it isnt returning self as a ref ?

heady iris
#
public int Foo {
  get {
    return 3;
  }
}
#

this is also a property

round violet
#

im trying to memorize the "difference" between a property and a field

heady iris
#

A field is basically just a variable, with nothing else going on.

fervent furnace
#

property is method

heady iris
#

A property is made up of accessors (get and set) that call methods

round violet
#

so as soon as you add some get and set to a var it becomes a property ?

heady iris
#

I wouldn't say you "add" them

#

fields and properties are two completely different things

round violet
#
public int Foo {
  get {
    return Foo;
  }
}

what would this be ?

heady iris
#

a stack overflow error :p

#

It is a property.

#

Its get accessor returns Foo

round violet
fervent furnace
#

they are method so

int Foo(){
  return Foo();
}
heady iris
#

it reads Foo

#

and how does Foo decide what to return?

#

it reads Foo

#

[...]

round violet
#

but when not setting any get, isnt this the "default" behaviour ?

heady iris
#

what do you mean "not setting any get"?

#

you explicitly gave the Foo property a get accessor

round violet
#

when you just write sometype somename

round violet
heady iris
#
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

leaden ice
#

hence infinite recursion

heady iris
#

you can read about properties in the C# docs

round violet
late lion
#

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.

heady iris
round violet
heady iris
#

No. There is no set accessor at all here.

round violet
#

since you only "overrided" the get ?

#

oh

round violet
heady iris
#
[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);
    }
}
round violet
#

ty

heady iris
#

an example of a property

late lion
#

readonly get is going to be confusing without explanation

heady iris
#

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.

fervent furnace
#

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
late lion
#

Java has no properties, so most Java codebases are filled with get_x set_x methods.

heady iris
round violet
#

what is get and set called ?

heady iris
#

When I set Percentage, I use Lerp to calculate a value between 0 and maxValue

late lion
#

getter and setter methods

heady iris
#

a property has one or more accessors in it; they're how you interact with the property

#
public int What {
    set => maxValue = 123;
}
round violet
#

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 ?

late lion
#

There are no default getters and setters

heady iris
heady iris
#
        public int Automatic { get; set; }
#

If you don't provide an implementation, C# can automatically generate something for you

heady iris
#
public int Automatic { get; private set; }
#

a slightly more interesting application

#

this means that the setter is private, even though the getter is public

round violet
#

i feel my brain starting to learn to much, but this is very intersting

heady iris
#

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)

round violet
#

ty everyone for answering my questions :)

heady iris
#

completely ignoring the value you tried to assign

#

i've never done this one :p

round violet
#

that would avoid me creating a private and public var just to get it from outside

round violet
fervent furnace
#
public void set_a(int value){
  a=123;
}
round violet
#

i missread sorry

heady iris
#

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.

hard viper
#

at that rate, just use a const

heady iris
#

yes, this is just for illustrative purposes

round violet
#

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

hard viper
#

value

heady iris
#

yeah, value

hard viper
#

is the name of the keyword

fervent furnace
#
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);
    }
}
round violet
#

okay ty

heady iris
#

it's a special keyword that's only a keyword sometimes

heady iris
#

because value is the value that's being passed to the setter

hard viper
#

is there a reason when I make a ruletile that it won’t serialize a [SerializeField] private field from a generic base class?

heady iris
#

Can't think of one.

round violet
#

also, in csharp can you do something like the ... in lua ?

#

let me write an example

heady iris
round violet
#

yes

#

like a Print

heady iris
#
public int LotsOfArgs(params int[] argsHere) { } 
round violet
#

so "params" is the keyword ?

heady iris
#

correct

late lion
#

With an array of some type

late lion
#

And it must always be the last argument

round violet
#

only array, can't make it a list ?

late lion
#

Only array

round violet
#

okay

heady iris
#

It must be a single-dimendsional array.

fervent furnace
#

it is called variadic arguments

latent latch
#

usually if I find myself in a situation using params I eventually go back and pass by a struct

round violet
#

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 ?

latent latch
#

overloading?

round violet
#

overloading isnt for the non-obligatory args ?

heady iris
#

That's called overloading, yes.

round violet
#

okay

#

can you make one yourself ?

heady iris
#

The correct method is chosen based on the types of the arguments you provide.

#

Sure.

fervent furnace
#

same method name but different signature

latent latch
#

overloading isn't the word I've would of used naming this concept

heady iris
#

Unity isn't "special"; it isn't breaking any C# rules here

round violet
#

where can I find the synthax to make one ?

round violet
round violet
#

VS does all the hard work

fervent furnace
latent latch
#

there's also operator overloading which allows us to do Vector3 + Vector3

round violet
fervent furnace
latent latch
#

adding objects together is ambiguous, but if you define how the operator is handled between the objects then you can do that

heady iris
#

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

round violet
heady iris
#

A function's signature is the type and number of arguments it receives, as well as the type it returns.

latent latch
#

prototype is the cooler word

heady iris
#

The combination of method name and signature must be unique.

round violet
fervent furnace
#

they can be identifier eg Java native interface

heady iris
round violet
#

yeah ?

heady iris
#

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

fervent furnace
#

vec3 + vec3 is an example

heady iris
#

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.

round violet
#

its only for vectors ?

#

or is this a illustration image

fervent furnace
#

btw treat it as methods again

latent latch
#

Better example are matrix operations

fervent furnace
#
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
round violet
fervent furnace
#

the return value

round violet
#

okay

#

so you dont write {} or anything inside ?

fervent furnace
#

just example

round violet
#

okay

fervent furnace
#

the method body are the same eg a.x+=b.x.... then return a

round violet
#

lots of intersting stuff

#

i saw this a dotnet doc

public string? Day;

what is the ? for

fervent furnace
#

nullable

round violet
#

so Day can be a string or null ?

fervent furnace
#

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)

round violet
#

i dont understand

latent latch
#

you can't ever compare a struct to see if it's set or not

round violet
#

what is a nullable ? if you cant set the var to null ?

latent latch
#

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

fervent furnace
#

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

round violet
fervent furnace
#

treat it as an additional bool for checking that done by compiler magic

round violet
#

so it doesnt permit you to set to null a var ?

fervent furnace
#

value type cant be null, only reference and pointer type can be

round violet
#

okay

latent latch
#

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

heady iris
#

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

heady iris
#

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

heady iris
heady iris
#

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.

heady iris
#

which can be a surprise for people coming from more strict languages (:

round violet
#

👍

rigid island
#
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
latent latch
#

have ya tried fixed delta

rigid island
#

not yet, let me try that rq

latent latch
#

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

heady iris
#

if you're using unscaledDeltaTime, then you'll want WaitForSecondsRealtime

mellow sigil
#

Adding any kind of deltatime here doesn't make much sense, it's just the duration of the previous frame

rigid island
#

to be fair that was testing I also had regular time.deltaTime and did the same

heady iris
#

I am confused about the objective, yes

#

are you trying to make the loop take longer and longer over time?

hard viper
heady iris
#

That's going to be framerate-dependent because the amount you add per frame will vary

latent latch
#

oh right it's wait for seconds

heady iris
#

It's going to be similar to the wrong-lerp situation

#

imagine youre game is running at a trillion FPS

rigid island
#

I think my whole logic is prob wrong, I should prob explain my usecase

heady iris
#

timeIncrease will go up very very slowly, and the loop will run many many times

latent latch
#

waiting for seconds with frame time doesnt make much sense yeah

heady iris
rigid island
#

Im trying to make this basically

heady iris
#

but you'll wait for a different total amount of time than if you had a low framerate

rigid island
#

picking random shape and make it visually appealing

heady iris
#

for example

#
public int FrameAt(float time) {
  return Mathf.FloorToInt(Mathf.Sqrt(time));
}
hard viper
#

the logic in your code is wrong

mellow sigil
#

It should be timeincrease += someConstant instead of deltatime

heady iris
#

[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

hard viper
#

I would do:
while (true)
increment index;
display shape at index;
yield return new WaitForSecondsRealtime(delay);

rigid island
heady iris
#

you know how you can approximate an integral with rectangles?

#

you're doing that

#

the width of the rectangles is depending on the framerate

rigid island
heady iris
#

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

hard viper
#

I would probably store nextUpdateTime, to make it really framerate independent.
nextTime = startTime + first delay;

every update, nextTime += next delay

heady iris
#

instead of it being a product of exactly how long you've delayed each iteration of that loop

hard viper
#

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

heady iris
#

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

hard viper
#

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

rigid island
#

Trying to figure out all this to fit my coroutine UnityChanThink

#

also this seems to be giving somewhat consistent results through diff fps |
timeincrease += 0.1f;

hard viper
#

nextUpdate = Time.unscaledTime + delay;
while true {
yield return new WaitForSecondsRealtime(nextUpdate - Time.unscaledTime);
do the thing;
nextUpdate += desiredDelay;
}

#

that’s it

rigid island
#

is nextupdate a local var?

hard viper
#

yes

rigid island
#

but while true instead? how does it stop itself?

hard viper
#

you could make it non local. Does not matter

hard viper
fervent furnace
#

wait until next timestamp

hard viper
#

but you only break if you want it to stop forever

rigid island
#

also what is Time.time + delay; delay

hard viper
#

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

heady iris
#

the point of Loup's code is to account for the difference between the time you wanted and the time you got

hard viper
#

this way the schedule is preserved

heady iris
#

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.

hard viper
#

exactly

rigid island
#

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

hard viper
#

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

heady iris
#

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

hard viper
#

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

heady iris
#

(well, and 0.3 seconds)

rigid island
#

what about using a constant like Nitku suggested

hard viper
rigid island
#

seems its giving me roughly same timing for both fps changes

fervent furnace
#
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
rigid island
#

doesn't have to be pin point accurate if its 0.1 off or somehing

heady iris
hard viper
#

if you run the game on two different machines, they will desync

rigid island
#

Ok I will try that out, I'm trying to digest all the math xD

heady iris
#

I would, personally, just write a closed-form solution and not try to delay for varying amounts of time

hard viper
#

right now, simple is better, fen. the man is confused

rigid island
#

very xD

hard viper
#

which is an extra layer of calculation

rigid island
#

ah ye my monkee brain can't handle that rn

heady iris
#

X axis is time. Y axis is which index you're at.

#

Plug in the current time to get a number.

hard viper
#

i want a gif of a man panicking at a blackboard right now

heady iris
#

If the number differs from the last frame's number, you've advanced one or more steps; play a sound or whatever

rigid island
fervent furnace
#

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

heady iris
#
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

rigid island
#

Evaluate curve would go in GetIndex?

heady iris
#

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

hard viper
fervent furnace
#

some curve with second derivative <0 eg concave downward for ease out effect

heady iris
#

(fixed; i had the wrong logic in the loop)

heady iris
#

both of them correctly deal with unusual situations: many events per frame, 0 events per frame, wildly varying numbers of events per frame

hard viper
#

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.

rigid island
#

Ahh I see, that makes a bit more sense to me

hard viper
#

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)

rigid island
#

Ok I will these outs and hopefully get it going lol
thanks all for the very informative responses !

hard viper
#

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

rigid island
fervent furnace
#

it should be nextTime>=t.t?

hard viper
hard viper
heady iris
fervent furnace
#
while(true){
  if(nextT>=T.t)wait nextT-T.t //you need to wait
  do your stuff
  nextT+=delay;
}
heady iris
#

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

swift falcon
#

is it a good idea to use try{} in the actual final game code and not just debug?

hard viper
#

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

heady iris
hard viper
heady iris
#

Exceptions are unusual, but manageable, problems. It's reasonable to handle them in your code.

knotty sun
leaden ice
heady iris
#

for example, I catch exceptions coming from Json.NET and handle the failure to parse

hard viper
#

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.

swift falcon
heady iris
#

No, you should just fix your code.

knotty sun
#

no

heady iris
#

You can test if the object is destroyed before trying to use it.

hard viper
#

fix your shit

swift falcon
heady iris
#

any Unity object can be compared to null

#

if you get "true", it's an invalid object

swift falcon
#

if i check if this.gameObject != null it says that the if is doing the error

heady iris
#

that means this is a destroyed unity object

swift falcon
#

yea but i get an error

knotty sun
#

you should never use try catch as an option for 'I cant be arsed to fix this'

heady iris
analog axle
#

if this.gameObject is throwing an error, doesnt that mean this is null

heady iris
#

It sounds like you're calling a method on a MonoBehaviour that's been destroyed

analog axle
#

and has no gameObject?

swift falcon
#

ignore the current if, i was just searching online alternatives

heady iris
#

you'd get an error trying to call the method in the first place

analog axle
#

thats what I assume but whats the other possibility

heady iris
#

But if this is a unity object, it will equal null when it's destroyed

knotty sun
#

?? ??????????????????

heady iris
#

and you'll get an error if you try to access any Unity property

analog axle
#

so yeah the gameobject is destroyed then

heady iris
leaden ice
heady iris
#

I should point that gameObject cannot be null on a valid MonoBehaviour

knotty sun
#

never use ? or ?? with Unity Objects

heady iris
#

every MonoBehaviour must be attached to a game object

hard viper
#

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.

heady iris
#

hang on aren't you just doing this

#
Destroy(gameObject, 1);
#

I guess you're turning off the box collider first.

swift falcon
hard viper
#

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

heady iris
# swift falcon why?
  • 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 == null if this != null
#

it's just..really weird looking

hard viper
#

exceptions should only happen when something goes very wrong

swift falcon
heady iris
#

if you want to destroy an object after a few seconds, I'd just write a coroutine

knotty sun
swift falcon
hard viper
#

what

analog axle
#

coroutiine

analog axle
heady iris
#

unity coroutines make this really easy, yes

hard viper
#

Co-routine. routine that runs co to your routines.

south violet
#

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

knotty sun
#

!this is meaningless. this.gameObject != null is usefull

leaden ice
swift falcon
#

alright, removed async and no errors

#

final ver

heady iris
knotty sun
#

this cannot be destroyed, otherwise it would not be running

primal wind
heady iris
#

(well, !this is meaningful for any unity object)

swift falcon
leaden ice
swift falcon
knotty sun
heady iris
analog axle
#

[[current topic]] is very humorous.

heady iris
swift falcon
#

im not familiar with that

analog axle
heady iris
#
IEnumerator DestroySelf() {
  yield return new WaitForSeconds(4f);
  boxCollider.enabled = false;
  yield return new WaitForSeconds(1f);
  Destroy(gameObject);
}
#

done

heady iris
#

If the monobehaviour dies, the coroutine stops, so you don't have to reason about that

analog axle
hard viper
heady iris
#

gimme a sec

analog axle
hard viper
#

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

swift falcon
hard viper
#

“Sure thing, bud”

swift falcon
#

whats the benefit in using corrutines

analog axle
#

👍

hard viper
#

AI is easily swindled

heady iris
#

Coroutines let you write code that's executed over several frames without having to think about correctly using async

analog axle
hard viper
heady iris
#

you write an enumerator. Unity asks the enumerator for new values every frame (by default)

heady iris
#

So you aren't just running code..whenever

primal wind
#

can't wait for awaitable

heady iris
#

I can wait

#

[audience laughing]

rigid island
#

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
fervent furnace
#

isnt your delay should grow to have an ease-out effect

rigid island
#

ahh ok so delay should not be constant ?

#

makes sense

#

so delay can be AnimationCurve.Evaluate ?

heady iris
#

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)

onyx marten
#

where could i get newest release for facepunch.steamworks? the latest on reddit has some issues critical to me
are there alternatives to facepunch?

rigid island
crimson spoke
#

hello humans

leaden ice
heady iris
onyx marten
heady iris
#

we can't really help you based on that

heady iris
fervent furnace
#

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)

onyx marten
heady iris
#

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;
}
rigid island
#

what would GetDelay do?

heady iris
#

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

heady iris
#

We want to calculate each delay the exact same way no matter what the framerate is

rigid island
#

ohh so basically what I have now but without the yield?

heady iris
#

Exactly.

rigid island
#

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; }

heady iris
#

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.

onyx marten
rigid island
heady iris
#

oh, that formula was bogus

#
Time.time > startTime + duration
#

startTime would just be the time when you started the coroutine

heady iris
#

it's just phrased differently

rigid island
#

ahh ok

heady iris
#

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

rocky jackal
#

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 ?

analog axle
#

what's the reason why burst doesn't allow you to typeof() a physicscollider ecs component???

leaden ice
rocky jackal
#

just some basic things, i want to take the environment settings from whatever scene is loaded additivley and apply them to my main scene

rigid island
#

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

leaden ice
cerulean mist
#
        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?
heady iris
#

that code looks fine to me

#

if the animation curve ranges from t=0 to t=1, at least

cerulean mist
#

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

heady iris
#

this will set speedFactor to zero as soon as the curve evaluates to 0

#

and then it'll never come back

cerulean mist
#

That's fine, that's what I want

#

I want the speed of an object overtime to decrease based on a curve

heady iris
#

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

cerulean mist
#

ahh i see

#

so curve value needs to be multiplied by Time.deltaTime

heady iris
#

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

leaden ice
heady iris
#

(is this even physics-related?)

#

some kind of exponential function will do the trick

leaden ice
#

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

heady iris
#

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));
cerulean mist
#

Oh, that does the trick. Thanks!

heady iris
#

Normally, one long frame will incorrectly move you further than two short frames

cerulean mist
#

This is a very handy website, thank you for linking this 🙌

heady iris
#

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

heady iris
leaden ice
#

read the editor logs

swift falcon
hidden flicker
leaden ice
#

you are trying to use it as a position
What are you trying to do exactly?

heady iris
tawny elkBOT
#
📝 Logs

Documentation

Editor logs

Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log

Unity Hub

Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs

hidden flicker
leaden ice
#

Or if they're all direct children of the "root object" you can do:

obj.localPosition = Vector3.ClampMagnitude(obj.localPosition, maxDistance);```
hidden flicker
#

Thank you, solved

cerulean mist
# heady iris ```cs speedFactor = Mathf.Lerp(speedFactor, 0, 1 - Mathf.Pow(1 - curveValue, Tim...
    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);
heady iris
#

well, yeah, you..told it to do that at the end

heady iris
#

It's a continuous process.

#

The lower curveValue is, the faster speedFactor goes down

cerulean mist
#

well yes but isn't that last line makign sure it doesnt overshoot?

heady iris
#

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

hidden flicker
#

How would I prevent my player from losing speed when they enter a slope?

heady iris
#

otherwise, I don't understand what you want, and you need to explain it

hidden flicker
cerulean mist
#

I out it there because I wanted to make sure it didn't overshoot

heady iris
#

I'm not sure what you mean by "overshoot"

#

as in, the speed goes negative?

cerulean mist
#

correct

heady iris
#

that's impossible

#

the code moves towards a speed of 0

rigid island
heady iris
#

each frame, it lerps from the current speed towards 0

#

the amount it lerps depends on the curve value and on deltaTime

rigid island
#

yeah thought it was the nextTime but that made it worse xD

heady iris
# hidden flicker

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

hidden flicker
#

I understand what you're saying, but that's not quite the issue

cerulean mist
hidden flicker
#

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

heady iris
#

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

hidden flicker
#

Alr, thank you

round violet
#

Can you add an offset to a additive scene ?

#

or get all objects from this scene

heady iris
# hidden flicker 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!

rigid island
#

its .5ms off but whatevs

round violet
leaden ice