#archived-code-general

1 messages · Page 101 of 1

simple egret
#

Oh and if you don't find anything wrong, then move your question to #💻┃unity-talk as it's not a code issue

mental rover
#

filesystem access issues suggest the problem lies with the OS, or at least outside of Unity - it could be any number of things, but generally the issue boils down to the same thing: something is accessing that file, and you're not allowed to change it while it is

#

could be as simple a fix as restarting if some process didn't end properly - it might be drive specific, sometimes external drives don't have the same permissions by default, might be some local backup software you have running like OneDrive/Google Drive

vague slate
#

Is there a way to have game object in a scene which only exists with some #define?

#

or if MonoBehaviour attached is fully wrapped in define, will it be fine to leave game object as it is? (it's probably will be just empty transform)

oblique spoke
#

Assuming it allows you to build

vague slate
#

Any alternatives to that then? I am trying to publish app to multiple stores which require different sdks

oblique spoke
#

You can separately define out methods and includes

vague slate
#

Sounds awful ngl

oblique spoke
#

Seems common to clean this up by creating separate provider objects with a shared API.

vague slate
#

well yeah, high level API is fine to use defines, but it comes to relying on different game object implementations

#

since some SDKs require interface on MonoB

#

I'll have to play around I guess and see how it works

oblique spoke
#

Whole MB/GO exclusion probably works better when paired with Resources/Addressables.

gray mural
#

What's the difference between slider and scrollbar?

rain minnow
gray mural
#

we're just getting the value from them and doing whatever we want

rain minnow
rain minnow
gray mural
#

oh, I see

rain minnow
#

always search first . . .

gray mural
#

so slider is better for me to use in my current context

heady iris
#

no, they are unrelated concepts

#

slider is used to provide input

#

you drag the handle between the minimum and maximum value

rain minnow
gray mural
#

so that user cannot make it 0,4323 or 57,432432

heady iris
#

you can set the snap value

gray mural
#

just ints

gray mural
heady iris
#

oh wait, you don't set a snap value

#

you just tell it to use whole numbers

#

i was thinking of sliders in the browser :p

#

You can make sliders snap to increments in Unity, too, but you have to hand-roll the code a bit..

woeful bramble
#

I'm trying to add assembly definitions to an asset which doesn't have them so that their scripts can be referenced in our code. I've mostly found the right assemblies, but am having trouble finding the assembly to reference for LitGUI:

#

What assembly is it in?

#

It is not in any of these:

swift aspen
#

Are you using Rider? If so it says if you open it

sour zealot
#

hatebin isnt working for me rn idk why... Will this health script work, like the regeneration part

swift aspen
#

Might be slightly different though since I am on HDRP instead of universal

sour zealot
vagrant blade
true bramble
#

why am I getting an error?

#

how is 0 outside of the array?

woeful bramble
#

the array could be empty

#

Debug.Log(points.Length);

true bramble
#

but im trying to fill it with game objects

heady iris
#

points is serialized

#

it probably got serialized with a length of 0

#

the default value is overwritten when Unity restores the serialized values

#

initialize the array in Awake

true bramble
#

o ok

heady iris
#

default values get assigned as the object gets constructed

#

deserialization happens after that

true bramble
#

its still erroring why doesn't this work

leaden ice
#

(if the length is 0 ANY index will be out of range)

#

why are you doing i < 4 in your loop instead of i < points.Length?

true bramble
#

I would do that anywhere else

leaden ice
true bramble
leaden ice
#

so something is wrong with your logic

#

100% of the time you should use the array length

#

not a hardcoded value

true bramble
#

well I would be even more confused if it didnt go through the loop at all

leaden ice
#

clearly your array is not the right length here - start investigating why

true bramble
#

if it wasn't 4 I wouldn't know that the index thing was an issue

leaden ice
#

sure you would - you would find out in about 30 seconds with log statements

#

or by attaching a debugger

true bramble
#

hm

heady iris
#

all of it

#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

woven matrix
#

hey guys In my canvas, an 2 image is showin up as a red cross in my scene view, and it does show up any idea what this might be?

heady iris
#

that means the element has a negative width or height

heady iris
#

did you remove the initialization in Awake?

#

your screenshot showed that.

woven matrix
heady iris
#

your RectTransform has a negative width or height

true bramble
woven matrix
#

humm ok, it does not

true bramble
#

I made a for loop to try and do it in the same function

heady iris
heady iris
#

an array has a fixed size, which is set when it's created

true bramble
#

didnt seem to work either

heady iris
#

yes, that doesn't initialize the array

#

that sets elements of the array

#

points = new GameObject[4]; will create an array of 4 gameobjects and store it into points

true bramble
#

hm

heady iris
#

(i am referring to the second image)

true bramble
#

okay

#

what if I need to re add the script to the object?

heady iris
#

i do not understand your question

heady iris
#

why would you need to "re-add" the component?

true bramble
#

like when does awake happen

#

when you add the component?

heady iris
#

it runs when the component is created and the game is running

#

so, for objects in the scene, it will run on startup

true bramble
#

well this script can run while the game is running

heady iris
#

for newly created components, it runs immediately after creating the component

#

so, setting points in Awake is a reasonable idea

#

i don't believe it will run if the game object is inactive, though

true bramble
#

yeah

heady iris
#

so, if you called InstantiateConnectors on a component on a disabled gameobject, Awake wouldn't have run yet, iirc

true bramble
#

idk why but it was working b4, just when I added it to a new object it stopped working

heady iris
#

you should make sure the error is coming from the object you think it is

#

click on the exception in the console; it should highlight the offending object

true bramble
#

it is because InstantiateConnectors runs when you click generate connectors button in its editor

heady iris
#

oh.

#

yes, that would, indeed, do it.

#

i would initialize the array in that method, then.

true bramble
#

which is what I did before but I dont understand why I cant initialize it like this

heady iris
#

because arrays have a fixed size

#

that code is storing four new objects in the array

#

it does not make room for four objects in the array

#

this code will throw an exception if the array's size is less than 4

#

and this code does nothing to change the size of the array

true bramble
#

hmmm

heady iris
#

since points is serialized, Unity will create an array that holds 0 elements by default

#

you'd then add and remove elements in the inspector

true bramble
#

so this would

heady iris
#

yes

true bramble
#

alr

heady iris
#

it sounds like the job of InstantiateConnectors is to set up the contents of this points array

#

therefore, it should also initialize the array

true bramble
#

lol that worked

#

thanks

#

Im prolly gonna get rid of those magic numbers now

jaunty sleet
#

Which do you guys think would be more performant? Using an array for a group of items that are updated every update, but the items continue to get updated after they are no longer needed because removing them from the array is a pain. Or switching to a list and having the items removed once they no longer need to be updated

true bramble
#

Use a list

thin aurora
# true bramble why am I getting an error?

In C#, accessing an index that does not exist results in an error, even if you try to null-check it. Unlike languages such as Javascript, which would return undefined. In the case of the array, you should check the length beforehand and then do a null check to have it short circuit in case it does not have the index. Alternatively, use GetElementOrDefault which will do the heavy lifting for you, and return default (which would be null) if it does not exist.

thin aurora
heady iris
#

yeah, it's negligible

#

do whatever's easier to understand

#

not easier to write: easier to understand

thin aurora
#

You can always switch to arrays later

#

Or better, use a span<> sadok

heady iris
#

programming is mostly reading other people's code

#

including the code you wrote two weeks ago (it is basically someone else's code now)

heady iris
#

💥

#

actually i'm not sure you can have a pointer to a managed type

jaunty sleet
#

I have never heard of a span

#

but I did switch to lists and it is easier to understand, thanks

#

because now I don't need a seperate value on every item to tell if it has been deactivated or not

#

I can just remove it

heady iris
#

yes

#

ease of writing and reading is vital

jaunty sleet
#

I've been working on my game on and off for like 8 months and I understand that now

#

the next one I do is going to be so much better organized from the start lol

delicate whale
#

hi, is there a way to access the burst cycles of a particle system in unity?
I have some particles that burst with a probability of 0.25 and i want to play an audio each time it does a burst

#

I can probably count the particles and check when the number increases but for my use it doesn't work as good

#

any alternatives/solutions?

jaunty sleet
#

I've never used particles but you should check the Unity documentation and see if there are any methods / properties that will allow you to do this

delicate whale
#

I have searched the documentation and this didn't come up once

prime sinew
#

check out those documents

delicate whale
#

thanks

#

i will look at those right now

prime sinew
#

I googled "unity particle system burst"

delicate whale
#

Unfortunately, this is another dead end for me, there isn't anything here that will help me in my situation

#

I was looking for sort of a Unity Event that is invoked each time the bursts happen

hexed pecan
#

Play your sounds from there too

fluid tapir
#

Hey guys, is there a way to keep one of the arm fixed to a position while the rest of the body plays an animation? For example, I want to attach one of the arm to a weapon such that they are holding the weapon (left hand on the barrel). I have used Two Bone IK for that but it seems like the arm moves away from the weapon when I walk / run.

potent sleet
golden vessel
#

Hey, the object I'm instantiating isn't a child of the transform I give, I don't really know why. Any ideas?

potent sleet
golden vessel
#

Yeah

fluid tapir
potent sleet
golden vessel
#

2 sec

golden vessel
golden vessel
#

Thanks

solid ledge
#

What could be wrong with loading this FBX model?

        GameObject tubeModel = Resources.Load<GameObject>("Models/Connector");
        componentTypes.Add(new ComponentType("Tube", new List<Vector3>() {
            new Vector3(0, 1, 0), // Top
            new Vector3(0, -1, 0) // Bottom
        }, tubeModel));
fluid tapir
#

What I currently have in my head is the following:

  1. Every weapon will have different locations where the character will hold that weapon hence, I'll create a game object for describing the position of the left hand (and another one if I am using 2 two bone ik constraints for the right hand position).
  2. I'll update the Rig's target transform (from script) to those game objects and build the rig again once the weapon drawing animation is finished.

Is this the proper way to utilize the animation rigging package?

potent sleet
#

then assign the target when weapon is equip

fluid tapir
#

Yeah that's what I am doing, I am keeping the targets on the weapon since that'll make it more dynamic and easier to configure

potent sleet
#

if you want weapon to move with rig/animation then you need a rigtransform

#

so it will act like another bone

fluid tapir
#

But that's what I want to know, should I use 2BoneIK on both hands or only on one?

potent sleet
#

that's up to you or you original weapon posing animation

#

my right hand typically just has multi-aim constraint

thick socket
#

Scriptable object...I have a field for string. Is there any way to make the field expand to be the size of the string? I have naughtyattributes but didnt see anything for jt
(In inspector)

potent sleet
#

multiline?

thick socket
potent sleet
#
  [Multiline(10)]
    public string hello10Lines;
  [Multiline]
    public string hello;
thick socket
#

Oh sweet thx

potent sleet
#

or specify lines

gray mural
#

Is there any build-in method to parse number into format minutes:seconds
188 => 3:08
45 => 0:45
636 => 10:36

thick socket
#

Timespan?

gray mural
#

it should be parsed from audioSource.clip.length that is float

sour zealot
thick socket
sour zealot
#

I’m at school rn

vagrant blade
#

@sour zealot You should wait until you're actually able to test it then. This discord isn't your personal compiler.

#

And if it doesn't work, you can ask follow up questions.

sour zealot
#

Alr

#

Sorry for bothering you

hoary basin
#

Can someone explain where the transform is coming from in this instance?

My assumption is it's getting the transform of "this" i.e the object where the code is written. But I need confirmation.

thick socket
#

The object the code is on

hoary basin
#

ah thanks

thick socket
#

Aka A isnt able to call scripts in B that it inherits from?

rotund burrow
#

it is able to call it I just dont want to have "inherited functions" section in every Update() of any derived class

#

the ideal would be to have Update() in B with all of them, and B considering that A is overriding them, but it doesnt work

hoary basin
#

🐵

potent sleet
hoary basin
#

was the "unless its a child class" a mistake?

thick socket
potent sleet
hoary basin
#

oh its always world position. Thanks

thick socket
#

@rotund burrow
A : B
B : monobehavior
A example

protected override void Start()
    {
        hpText = GetComponentInChildren<TextMeshProUGUI>();
        base.Start();
        Shoot();
    }
#

B example

protected virtual void Awake()
    {
        stats = new();
        myJumps = new();
        pauseShooting = true;
    }
thick socket
#
[CreateAssetMenu(menuName = "Heroes")]
public class Heroes : ScriptableObject
{
    public List<HeroInfo> heroesInfo;
    public VisualTreeAsset heroesPrefab;
}

[Serializable]
public class HeroInfo
{
    public string name;
    public AllHeroes hero;
    public Sprite head;
    [Multiline]
    public string bio;
}
#

ex) if you look at the bottom Void Dragon...the text goes off the screen and doesn't wrap around

potent sleet
#

I don't think wrapping text does work in inspector

#

not vanilla at least

thick socket
#

I found something like this...not sure where to put it 😄

#

EditorStyles.label.wordWrap = true;

#

oh nvm that was from 8 years ago

thick socket
#

nvm

#

found a fix!

#

[TextArea(15,20)]

potent sleet
#

Oh nice! TIL

#

these attributes are lit

thick socket
#

yessir

#

it requires scrolling at some point, but infinite box size 🙂

swift falcon
thick socket
swift falcon
thick socket
#

unlock but yeah

#

I use scriptable objects pretty often to store data that wont change that I need in places

swift falcon
#

Do I have to install scriptable objects or does it exist within unity components

thick socket
swift falcon
swift falcon
# thick socket

Also, to get that "Name, Hero, Head, Bio" etc. Is it all done in code and it appears in the editor?

thick socket
#

except TextArea instead of multiline

swift falcon
west elk
#

Hi, I'm trying to generate multiple arrays of int containing random numbers that doesn't repeat between each other. For exmpl:

Given umbers: 0-9
I want to get 5 arrays like this: [ 5 , 2 ] [ 4 , 7 ] [ 6 , 3 ] [ 8 , 0 ] [ 9 , 1 ]

Any idea on how I could approach this?

swift falcon
leaden ice
leaden ice
open shard
#

Hi, I'm trying to set some random offset on my animations. I have the following code:

        _animator = GetComponent<Animator>();
        _animator.SetFloat("Offset", UnityEngine.Random.Range(0f, 1f));
  }

however the default state is always played without offset. Once the default state is played once it works fine and in the animator window I can see that the Offset parameter is set correctly. It is only for the first cycle of the default state that it does not work

gray mural
#

your idle state plays at the beginning

#

when the game starts

#

you should consider doing another animation with Coroutine like offset if I do understand what you need to do

neon plank
#

How can I prevent the agents from pushing each other?
They are trapped in a disconnected room, and I command them to reach a point outside it.
So they moved to the point inside the room that is closest to their destination point outside it.
However, they are pushing each other in order to reach that point...
¿How can I make that agent stop push each other?

gray mural
neon plank
#

Yes

gray mural
leaden ice
neon plank
#

But what if they collide in a different situation, like running to two different points?

gray mural
neon plank
leaden ice
#

can't you?

neon plank
gray mural
#

@neon plank or do it so that the Vector3.Distance between them cannot be less than minDistance, otherwise change their moving direction

neon plank
gray mural
#

sorry for my drawing and white square

white arrow
#

guys how do i make it so when I instantiate a prefab with a script, the script finds a specific object in the scene

neon plank
white arrow
#

ill try that for now

#

thanks

gray mural
#

last place on international drawing Olympiad💪

neon plank
#

¿And if they are trapped in a room which doesn't have a connection to reach its destination?
Agents will try to move to the point inside the room closest to the destination point. But if they start to rotate when near with other agents, they will get stuck in a loop, getting away and near the point constantly.

gray mural
neon plank
#

That is the point closest to the destination. So the 3 agents try to stay in that point.
If they start rotating they will get stuck in a loop.

gray mural
#

yeah, so you need to stop them?

neon plank
gray mural
#

and you shouldn't stop them, when they hit each other while running?

#

yes

gray mural
#

why don't you count the time with OnCollisionStay?

neon plank
#

If the 3 agents decide to stop in order to avoid pushing all the time, and then at runtime the navmesh changes (e.g: a door is opened) so now there is a path to move. ¿How will they realize they should start moving again?

gray mural
#

just make them move again when the navmesh is changed ??

neon plank
gray mural
#

in this case they just gonna stop moving again

#

otherwise I do not see any reason why they cannot move

neon plank
#

Ok, I will try

gray mural
heady iris
#

and then snap the destination to the navmesh with SamplePosition

#

although, that could wind up snapping to the wrong side

neon plank
heady iris
#

exactly that: use NavMesh.SamplePosition to get a position that is on the navmesh

#

although, iirc, agents will already just try to get as close as possible and then stop

neon plank
neon plank
#

Ok

swift falcon
#

maybe im thinking too easy right, because idk how important it is for them to keep remembering to go to that point. like if you can change something and want them to instaly act on it this might not work. but cant you tell them to forget about trying to move there once theyve reached it once? that way they might push eachother for like a very brief moment by which time they all been at the spot and stand still pretty close by?

neon plank
#

I guess, I can try to adapt my code to do something like that

wide pecan
#

Hey everyone. A small question. What is the best system to save a lot of data in a game(like whole classes of characters, instantiated objects etc)? As I see using Binaryformatting isn't the best way to do it.

steady moat
wide pecan
wide pecan
knotty sun
heady iris
#

I am working on a survival horror game. The player has a flashlight. I want to make enemies notice when the flashlight is being shined...

  • in their eyes (easy)
  • on a surface they can see (uh oh)
#

i'm not sure how to handle that second one

wide pecan
heady iris
#

I guess I could do some rudimentary path tracing

#

shotgun rays out of the enemy's eyes, then see if any can make it back to the player

#

oh, yes, that's exactly what I should do

knotty sun
heady iris
heady iris
#

i think it gets a slightly unfair bad rap

knotty sun
#

it does

heady iris
#

it's not as catastrophically bad as, say, Python's pickle

#

which you can trivially tell to run arbitrary commands

wide pecan
heady iris
#

"binary" just means that the data is not in a text format -- i.e., something that a human being could read

knotty sun
#

there are other binary serializers, BinaryWriter springs to mind

heady iris
#

it's a lot harder to understand binary data by just looking at it

#

it's significantly more efficient, though

#

consider how there are what...62 alphanumeric characters?

#

you can encode 256 different values with a byte, so a format that only uses those 62 characters is going to be four times less efficient than a format that can just write anything it wants

#

a binary format can also directly represent data, rather than requiring a conversion step

#

consider storing the string "1000" vs. just storing the actual value

#

...although, in that case, a 4-byte int would be just as efficient as a 4-char string :p

#

a large number would skew that.

wide pecan
#

ok, thanks, I'll try using BinaryWriter

wide pecan
deep fable
#

In the SceneView.duringSceneGui callback of a custom editor is it possible to know which element of an array the use has currently selected?
For example in this case it should return 2 since I am selecting the Element 2 of the array

simple egret
heady iris
#

JSON.NET (a lot of people call it Newtonsoft.Json, since that's the namespace you'll use) works pretty well.

wide pecan
#

oh, ok

#

I hope I won't have too much data to save so I'll stick to json

hard sparrow
#

How to render an object on canvas A above anything on canvas B, when canvas B has a higher sorting order?

#

(specifically for draggable objects which you want above everything else while dragging)

latent latch
#

add a new canvas component or make a dummy draggable object that is higher in the ordering

#

or a dummy draggable object with a canvas component

hard sparrow
#

Is it smart just to make every draggable object have it's own canvas?

latent latch
#

it's smart to break up your UI into multiple canvas

leaden ice
latent latch
#

but for slots it creates problems

#

batching issues or something, honestly didnt read too much up on it

sour zealot
#

is there any way to toggle a bool

#

on and off

#

at the same time

#

not like bool = !bool

#

but like when I press it, it sets true, and one millisecond later it goes false again

summer helm
#

How can I change the API using a dropdown? I can’t find any tutorials or anything

heady iris
sour zealot
#

im triyng to do a health regen script

#

this is the script

#

if im doing something the hard way, please lmk

heady iris
#

well, you have like five copies of the same thing in that RegainHealth coroutine

#

i'd just store the last time you got hurt

#

if lastHurtTime + regenDelay <= Time.time, regenerate health

#

that's how I do stamina regen in one game

sour zealot
#

...

#

confusion

#

can you like elaborate

heady iris
#

what part of it confuses you?

#

oh

#

i wrote deltaTime

#

whoops

#

force of habit

#

if you got hurt at t=8 and you have a 3-second regen delay, then you're allowed to regen health once you get to t=11

#

if you get hurt again at t=10, you don't regen until t=13

wide pecan
heady iris
#

i'm not sure if there's a particularly "correct" way to do that.

#

My current strategy is to give each scriptable object a GUID (i actually just yoink the GUID from the asset)

#

I use a custom json converter for the SO

#

the writer just grabs the GUID and writes it as a string

#

the reader decodes the GUID, then looks the SO up in a dictionary

#

the dictionary is populated by using Resources.LoadAll

wide pecan
#

damn

#

thanks

sour zealot
heady iris
#

no, I'm not going to spoonfeed the answer to you.

sour zealot
#

lol

heady iris
sour zealot
#

can u explain more

heady iris
#

i don't know what to tell you if you just say "please explain more"

#

suppose the regen delay is 5 seconds

#

if you get hurt, you can't regen for 5 seconds after that moment

sour zealot
#

hmm

#

do i literally use the code u sent

#

and does it go in a coroutine

heady iris
#

i want you to implement this idea. it's very little code.

#

and no, it does not involve a coroutine.

sour zealot
#

hmmmmmmm

#

im still having a lot of trouble

#

like i dont know where to start

heady iris
#

do you know how to get the current time?

sour zealot
#

nope

wide pecan
heady iris
sour zealot
#

then what

heady iris
#

write that to a field every time you get hurt

sour zealot
#

a field?

winged mortar
sour zealot
#

float lastHurt = Time.time;

sour zealot
heady iris
#

if you do not know what a field is, then you really need to do some more reading...

sour zealot
#

i do

#

i was suprised why we would need a field

#

float lastHurt = Time.time;

#

is this right?

heady iris
#

because you want to remember the value

winged mortar
#

That's not a field

heady iris
#

putting it in a local variable and then immediately throwing the variable away does nothing.

wide pecan
#

what is he doing, btw?

heady iris
#

health regen

wide pecan
#

and what's the problem?

heady iris
#

get hurt, wait 3 seconds, start healing

heady iris
sour zealot
#

i am the problem

heady iris
#

this is what you need to do:

  • when you get hurt, update the "last hurt" time
  • every update, check if it's been at least 3 seconds since the "last hurt" time
  • if so, add health
wide pecan
#

the most basic variant for me is using a timer that you set to 3 in OnGetHurt() and in Update it'd just be decreased every frame

#

it doesn't work or what?

heady iris
#

that would also work

sour zealot
heady iris
#

yes

#

so you reset the timer...

sour zealot
#

yeah

wide pecan
vagrant blade
#

@sour zealot You've been told before you should be posting in #💻┃code-beginner. Your next question goes there.

heady iris
#

I like mectorn's idea more. It is more intuitive.

sour zealot
#

okay

heady iris
#

count down to zero

wide pecan
#

OnGetHurt puts back the timer to 3 and resets regen time

sour zealot
vagrant blade
#

Secondly, you don't need coroutines for regen. You can just track time in Update and when it surpasses an amount of time, you get health back. Reset the timer to zero and let it continue.

wide pecan
#

If you wanna be madman, use StartCoroutine, StopCoroutine

sour zealot
#
 private IEnumerator RegainHealth()
    {

        while (health < 100)
        {
            yield return new WaitForSeconds(1);
            if (damageTaken == true)
            {
                StopAllCoroutines();
                StartCoroutine(RegainHealth());
            }
            yield return new WaitForSeconds(1);
            if (damageTaken == true)
            {
                StopAllCoroutines();
                StartCoroutine(RegainHealth());
            }
            yield return new WaitForSeconds(1);
            if (damageTaken == true)
            {
                StopAllCoroutines();
                StartCoroutine(RegainHealth());
            }
            yield return new WaitForSeconds(1);
            if (damageTaken == true)
            {
                StopAllCoroutines();
                StartCoroutine(RegainHealth());
            }
            yield return new WaitForSeconds(1);
            if (damageTaken == true)
            {
                StopAllCoroutines();
                StartCoroutine(RegainHealth());
            }
            health += Time.deltaTime * regenSpeed;
            yield return null;
            if(health >= 100)
            {
                StopAllCoroutines();
            }
        }

        yield return null;
    }
``` hgeheheheheheheheeehe
#

that is my current one lol

sour zealot
#

lmao

#

im not good at health

vagrant blade
sour zealot
#

yes I know

wide pecan
#

I like that you stop everything, even not related to regen angerjoy

turbid surge
#

I can see this being beneficial in that its more secure as you could only access certain properties/logic by what the interfaces methods expose. Also I guess its more organized and easy to tell off the cuff that a script utilized a singleton? (Even though your editor can help with that idk). Maybe good for team projects too? Or would it just be annoying/unnecessary? Thoughts?

cold parrot
cerulean oak
#

I created a test script, but the test script doesnt seem to have access to any of my other scripts. so how am i suposed to test them xd
How can I make it find them?

cold parrot
#

even just as a way of making explicit what part of a class is used by another that holds a reference to an interface it implements can be beneficial

thin turret
#

Hi all, look for some help. Trying to do the following:

  1. I need to be able to send the model created by the user to the backend
  2. The be able to view and modify the model upon retrieval

However, I am not able to retrieve it. Any help would be appreciated

void basalt
#

nor do I think you're going to have an easy time hot loading 3d models in at runtime using binary data

thin turret
void basalt
#

and then rebuilding it based on that

#

How are you serializing it right now?

#

I hope you aren't trying to send raw object binary data over the internet and constructing objects with that

thin turret
#

I was.

void basalt
#

Let me guess. Binary formatter?

#

That's how you get hacked. Microsoft warns against it for good reason.

#

Back to the point: Just pack up each avatar's individual features. Hair color, hair type, skin color, etc

#

then you can probably rebuild it from that.

thin turret
#

Yea I’m not optimizing for security. But the idea of serializing attributes makes a lot of sense. I just have to figure out how to do it.

#

Any advice of documentation you'd suggest?

void basalt
#

yep let me find it

#

You can safely write and read binary data with this. It lets you serialize all primitive types

#

If this is too advanced, just use json

thin turret
#

Super helpful

#

Thank you so much

cold parrot
#

binary writer only does primitive types (thats why its safe), for advanced types you need to supply your own serialization/marshalling and security checks

weary depot
#

peeps

#

anyone here familiar with the render streaming package?

potent sleet
weary depot
#

welp I fixed my issue, but it's a package for streaming unity content on the web via webRTC

weary depot
#

yes it's pretty cool but a bit janky, I had issues with trying to read my mouse via browser but alles gut

winged sphinx
#

so I'm having an ienumerator problem. when I do this:

yield return StartCoroutine(cardAnimation());
print("it reaches here just fine");
removeCard();
updateHand();
placeCardOnTable();

but I want to remove the card and update hand before the coroutine. but when I do this:

removeCard();
updateHand();
yield return StartCoroutine(cardAnimation());
print("for some reason nothing after the coroutine runs now");
placeCardOnTable();
tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

potent sleet
woeful slate
#

What's the best way to sync up Animators? I have one for hair, body, etc

potent sleet
winged sphinx
#

no.

potent sleet
#

removeCard();
what does this do?

winged sphinx
#

removeCard(); removes the card reference from the Hand
updateHand(); does destroy and remake the card objects, but this is happening in the game controller.

winged sphinx
#

no exceptions thrown.

potent sleet
winged sphinx
#

no this script is in the game controller.

potent sleet
#

do you change timescale at all ?

winged sphinx
#

no

potent sleet
#

no print either after yield return ?

winged sphinx
#

only in the second case, yeah.

cosmic rain
# winged sphinx only in the second case, yeah.

That would mean that either the current coroutine is being stopped (for example if the object that runs it is disabled or destroyed), or that the second coroutine does not return control to this one(either stuck in a loop, stopped or waiting for another coroutine).

winged sphinx
#

cardAnimation(); creates an animation object (from an animation controller) then yield return new waitForSeconds(that object's lifetime)

cosmic rain
winged sphinx
#

in this order, it reaches all three break points.

#

in this order, it reaches only the first two break points.

cosmic rain
#

What's coroutine here?

#

It looks like you didn't read my message properly. I was referring to the inner coroutine.

winged sphinx
#

the only yield in the second enumerator is a waitforseconds, which according to break points it gets past, but doesn't return to the first. and only in the second order.

cosmic rain
winged sphinx
#

I will eat something comically inedible if either of these objects are being disabled.

#

it made me nervous for a second but no, it only gets there when I stop the game.

winged sphinx
#

Ok so I was doing a workaround where I would just disable the sprite on the card display. and decided just to try disabling the gameobject, and apparently that also caused the issue. RemoveCard destroys that gameobject, but that's a void and otherwise it isn't where either enumerator is running...

#

...but yeah disabling the sprite before the card animation is at least close enough to what I need to do that I'll just give up and go with that.

lyric panther
#

trying to do a thing where i have two rigidbodies, i want it so that if i move rb1, it moves rb2, and vice versa. and then when i block one from moving the other one stops moving

prime sinew
ashen yoke
#

cyclical dependency

#

there are spring joints and other joints

lyric panther
worldly hull
#

i have a coroutine where it needs to return a list of data classes, the coroutine is done and without errors, however, i cant do it like this right?

    private async void updateHistorical(List<UserActivity> activities)
    {
        completedQuests = StartCoroutine(RetrieveCompletedQuestFromActivity(activities));

        HandleCompletedQuest(completedQuests);
        ....irrelavant codes...```
lyric panther
#

basically it's a set of two sliding doors, if you open one the other one opens too in the other direction.

prime sinew
worldly hull
#

does coroutine has .Result or something like that?

worldly hull
#

whats that new stuff

ashen yoke
prime sinew
#

and is the direction fixed

ashen yoke
#
 // You can await IEnumerator coroutines
    await FooCoroutineEnumerator();
prime sinew
#

so you can select either door, and both doors just open?

lyric panther
#

it's done via rigidbodies

prime sinew
#

so you open the door with physics

lyric panther
#

yeah

prime sinew
#

you could use inverselerp?

ashen yoke
#

@worldly hull with unitask using coroutines becomes pointless

prime sinew
#

some sort of lerp, you check the progress of one door, then you move the other door

ashen yoke
#

in any case since that is not what you asked

worldly hull
#

lol i cant just add random packages into my team project 💩

lyric panther
worldly hull
#

but i will check it out

ashen yoke
#

im not aware of any mechanism apart from class member field that could inform the coroutine state

#
    public sealed class Coroutine : YieldInstruction
    {
        ~Coroutine();
    }
#

yay

#

minimalism

ashen yoke
#

both resolve most coroutine issues

#

havent used unity coroutines in years outside of editor coroutines package

lyric panther
#

this seems to work

ashen yoke
#

@worldly hull well actually if you pass a callback to the coroutine

#

you would while it

worldly hull
#

dw , even if i cant install this, i can still use it in my own project 👍

ashen yoke
#

or some general token object

worldly hull
#

i thought of a stupid way but still be able to do it

ashen yoke
#
class CoroutineCompletionHandle
{
    public bool Done {get;set}
}

IEnumerator DoStuff(CoroutineCompletionHandle handle)
{
    // does stuff
    handle.Done = true;
}
worldly hull
#
Task.Delay(500);```
give me my kekw emoji
ashen yoke
#

ill give you a raise

#

also .net tasks generate 0.5kb each afaik

worldly hull
#

idk how u feel about this, but our ways to spawn all in game objects are using addressables asyncs

#

team project ofc, not in my own project

ashen yoke
#

dont feel because practically zero experience with adressables

worldly hull
#

all the interactables and NPCs and parts of the UI will be spawned using this function

#

and in the function of calling this coroutine, the function is actually an async function, cuz it needs to spawn something out

#

so i can still use Task.Delay there

worldly hull
lyric panther
ashen yoke
#

can use similar method to call coroutines globally

worldly hull
#

welp i can just change the coroutines to void

sudden hinge
#

https://forum.unity.com/threads/cannot-start-coroutine-within-method-called-by-unityevent-if-singleton-is-used-ui-button.1435414/
If someone knows a fix for this let me know.
It seems to be impossible to start a coroutine from a singleton script using Unity Events

worldly hull
#

or just void function

#

wait

ashen yoke
worldly hull
#

this is the call

    private async void updateHistorical(List<UserActivity> activities)
    {
        ProcessCompletedQuestFromActivity(activities);```

this is the function
```cs
    private void ProcessCompletedQuestFromActivity(List<UserActivity> activities)
    {
        List<string> completedQuestid = new List<string>();
        List<UserActivity> completedQuestActivity = activities.Where(x => x.type == "QuestComplete").ToList();
        foreach (UserActivity activity in completedQuestActivity)
        {
            completedQuestid.Add(activity.refId);
        }

        completedQuests = QuestManager.instance.questLog.questsData.Where(x => completedQuestid.Contains(x._id)).ToList();
        HandleCompletedQuest(completedQuests);
    }```
#

welp it has no errors anyway lol

quartz folio
sudden hinge
#

Oh wait a second

#

The tools I use use invoke

#

Thanks!

ashen yoke
#

Im reading all assemblies, getting all types, finding exact match by string UnityEngine.Light, using the found type in GetComponent(Type type) and it doesnt find the component

#

my guess is that im getting something from legacy assemblies instead, meaning i have to skip it when gathering types

#

is there any read on which are actual final dlls?

#

hm but the weird thing is im getting them all already and only finding one UnityEngine.Light type, id get several if there were duplicates right? how would that even work

#

ah no nevermind i xy'ed myself

quartz folio
#

Why on earth would you search assemblies for strings to do this

ashen yoke
#

user input

pallid cradle
#

Is it possible to call ParticleSystemRenderer.BakeMesh on the job system?

winged mortar
worldly hull
#

oh this is way too long ago lol

#

i already get everything done, thx 👍

winged mortar
#

for coroutines we just wrote a simple callback function

#

gotcha

opal cargo
#

Hey guys, trying to implement some Collide and Slide stuff into a character controller, has someone a nice ressource for this?

slim condor
#

Saving the texture of the MeshRenderer

wide pecan
#

Hey everyone. I don't quite get how do I use Bson in new versions of unity(editor says it's obsolete and has a separate package but I can't find any new solutions or this package).


            SaveData data = new SaveData();
            SavePlayers(data);

            using (var stream = new FileStream(CommonPath, FileMode.Create))
            using (var writer = new BsonWriter(stream))
            {
                JsonSerializer.CreateDefault(null).Serialize(writer, data);
            }

I found this code that should save data as binary but it saves it as regular json with some weird characters and the file even weights more than a regular json save file.

static lantern
#

While we're troubleshooting Json stuff, does anyone know why it's returning "Null" for name? Am I using the deserializer incorrectly?

{
  "name": "Sebastian",
  "Characters": {}
}
StreamReader sr = new StreamReader(path);
string json = sr.ReadToEnd();
sr.Close();

wd = JsonConvert.DeserializeObject<WorldData>(json);

Debug.Log(wd.name);
static matrix
#

is there a way for a NavMeshAgent to automatically change the mesh/surface it is baked on without having to place hundreds of bridges at the ends of all my chunks?

ashen yoke
static lantern
#
public struct WorldData
{
    public string name { get; private set; }
    public Dictionary<string, CharacterData> Characters { get; private set; }
}
onyx marlin
#

hello everyone im new to c# and i need some help with my project , i want to make an app in unity that pulls notifications(like whatsapp ,messages etc. ) from an android phone and send it to my arduino through a bluetooth module , i have done the bluetooth part but i dont have any idea how to recive notifications using code.Please mention or dm me if you can help ,thank you in advance.

ashen yoke
#

is it opt in/out?

static lantern
#

Uh... let me try to fill it with some default data and see

static matrix
#

any help with my nav issue or do I just have to place the bridges everywhere

ashen yoke
#

navmesh already has tiling built in which optimizes large worlds

static matrix
#

procedural world

ashen yoke
#

you dont need to keep separate navmehses

static matrix
#

its procedural, so i do

ashen yoke
#

you plan to simulate the whole world at all times?

static matrix
#

no

ashen yoke
#

then usual approach to this is to update the mesh at runtime around the player

#

well, one of the approaches

static matrix
#

that will work?

ashen yoke
#

yes with NavMeshComponents

static matrix
#

each chunk has its own surface

#

the problem is monsters stop at the edge of chunks because they dont switch navmeshes

ashen yoke
#

i understand the problem, and i dont have an immidiate solution, apart from maybe hacking around with the agent by disabling and pushing to another mesh then enabling

#

problem is path itself

static matrix
#

rn my solution is placing hundreds of offmesh links at the edge of every chunk, which causes the creatures to be jittery near the edges and takes a ton of time to set up

#

ill see if I can try and bake at runtime maybe

static lantern
ashen yoke
#

you added attributes?

static lantern
ashen yoke
#

youre using newtonsoft json?

static lantern
#

Yes

static lantern
#

Oh, I don't have opt-in

#

That constructor should help, though

ashen yoke
#
By default a type's properties are serialized in opt-out mode. What that means is that all public fields and properties with getters are automatically serialized to JSON, and fields and properties that shouldn't be serialized are opted-out by placing JsonIgnoreAttribute on them. To serialize private members, the JsonPropertyAttribute can be placed on private fields and properties.
static lantern
#

ok

#

Thank you for your help

static matrix
#

theres probably a setting somewhere that lets agents cross meshes

ashen yoke
#

cross it maybe, but how will you compute a direct path

#

how large is the world again?

static matrix
#

idk as long as it doesn't stop at the edge of the chunk and stand there awkwardly

ashen yoke
#

infinite?

static matrix
ashen yoke
#

navmesh tiling allows you to rebake an arbitrary area at runtime

static matrix
#

ok let me look at that

ashen yoke
#

so if you opt for player centered mesh, you can bake only those areas that are in the bounds of the loaded chunks

#

this means you will have to periodically recenter and rebake the whole thing starting from player chunk outwards

#

but even given the large size of it you are still only computing loaded chunks

#

i assume you already do world shift

static matrix
#

wdym world shift

#

I might im just not familiar with the term

ashen yoke
#

origin shift

static matrix
#

yes

#

the world generates from the player

#

or the generation gets the players position and generates the world around it

ashen yoke
#

so each time you shift the world you can do the big rebake

#

and when new chunks encountered you do only them

static matrix
#

so what would I attach the navmeshsurface to?

ashen yoke
#

i have a feeling you dont do origin shift

static matrix
#

No i think i do

ashen yoke
#

you have to shift the whole world towards zero once the player reaches around 2-3k units

static matrix
#
 void GenerateFromCenter()
    {
        for (int x = -2; x < 3; x++)
        {
            for (int z = -2; z < 3; z++)
            {
                bool Occupied = false;
                foreach (Chunk c in Chunks)
                {
                    if(c.coords.X == x+Center.X && c.coords.Z == z + Center.Z)
                    {
                        Occupied = true;
                    }
                }
                if (!Occupied)
                {
                    GenerateChunk(new Coords(x + Center.X, 0, z + Center.Z));
                }
               


            }
        }
       
    }
    //Check if the player is far enough away to spawn new chunks
    void CheckDespawn()
    {
        foreach (Chunk c in Chunks)
        {
            if (DifferenceInCoords(PlayerIn.coords, c.coords) > 3)
            {
                if (c.gameObject != null)
                {
                    Destroy(c.gameObject);
                }
              
            }
        }
    }

ohhhhhh
no i dont do that

#

heres the generative part of the generation script

ashen yoke
#

when you get to the shift, just incorporate the rebake into it, and youre good

static matrix
#

ok so
which object is doing the baking

ashen yoke
#

some static class in the api

static matrix
#

so do I stop attatching a navmeshsurface to each chunk?

ashen yoke
#

yes it just has to be attached to the world transform

#

rather the shift transform

static matrix
#

woah

ashen yoke
#

no

#

it just has to be at 0

#

all the time

#

lol

static matrix
#

uh
should all the chunks be children?

ashen yoke
#

your player will essentially only ever move around the zeroes, while the rest of the world shifts under him

#

how you implement it i dont know, the parenting will probably be worse than just iterating over chunk roots

#

because any parenting incurs transform hierarchy update cost

static matrix
#

alright ill figure things out

young hamlet
#

Hi

I got a problem of this and I don’t know the reason😳 anyone can help?

ashen yoke
#

i advice to just keep track of chunks and agents and move them by iteration

#

that will be much faster

young hamlet
#

I can just cut the object in the original counter, the duplicated one doesn’t work😳

#

If I just put an object in the duplicated counter, nothing works

ashen yoke
#

you provide the bounds with NavMeshData struct

#

yikes its not struct

#

yikes its not even the correct one

#

UnityEngine.AI.NavMeshBuilder.UpdateNavMeshData() there we go

static matrix
#

ok ill look there

ashen yoke
#

theres an async version as well

swift falcon
#

Apparently block keeps turning out to be null and giving me an error. Why?
and I have checked prefab, it's not null.

https://gdl.space/lohubejami.cs

Exact error:

NullReferenceException: Object reference not set to an instance of an object
TerrainGeneration+<LoadWorldCoroutine>d__80.MoveNext () (at Assets/TerrainGeneration.cs:1375)

Line 1375: block.transform.parent = this.transform;
static matrix
#

hmmm what do I use for the data param for updatenavmesh

ashen yoke
#

probably just grab it from existing navmesh

#

re-feed it

static matrix
#

yeh

#

whats the async one called

ashen yoke
#

click on NavMeshBuilder

#

press F12

static matrix
#

nope

ashen yoke
#

then right click -> go to definition or something

static matrix
#

he just sits there at the chunk endge

#

ok wait

#

what if

#

big brain time

#

I attatch an offmesh link to the front of the monster

ashen yoke
#

all that i was suggesting was based on the idea of a single large navmesh

static matrix
#

ohhhhhh

ashen yoke
#

so that method would update an area of it

static matrix
#

lots of small meshes

#

yeah

#

ok

#

ill try that

#

yoooooooooooooooooooooooooo
I got it fixed
I just need a bridge in front of the monster

wide pecan
heady iris
#

No idea.

slate quest
#

sup guys, does someone know how I can make the missile (only move forward) to start with same rotation and direction the player is?

I've tried:

void Start()
{
  transform.rotation = player.transform.rotation
}

void Update()
{
  transform.Translate(transform.forward * speed * Time.deltaTime);

}
leaden ice
#

transform.Translate(transform.forward * speed * Time.deltaTime); is wrong, since Translate works in local space.
transform.Translate(Vector3.forward * speed * Time.deltaTime); would work

slate quest
#

hmm let me check

leaden ice
#

that is assuming you don't already have a problem in your Start function

slate quest
#

but Vector3.forward isnt a fixed global coordinate?

leaden ice
#

Translate works in local space

#

so itd be "forward in local space"

#

which is what you want

#

the object's forward direction

#

Vector3.forward itself is not implicitly belonging to any coordinate space.

slate quest
#

yep that's why I dont understand, because Vector3(0,0,1) should move in the global Z

#

it worked

#

thanks

wide pecan
# heady iris No idea.

hmm, so I guess Json isn't that good for storing large quantities of data(like positions and variables of all items dropped in the game), is it?

slate quest
#

but still doesnt understand why it should be a fixed value xD

heady iris
#

but then again

#

i wouldn't really worry about it until i wound up with multiple megabytes of data

fallow palm
#

I’m currently trying to make my player’s position persist between scene transitions. I want it so that if I enter a different scene and then go back into the previous scene my player is in the same place. I have this script that I use to transition between scenes: https://gdl.space/oyunilazef.cs. The purpose of this script is to allow the last visited scene to be loaded. I also implemented two methods in my player script to save the player position into PlayerPrefs: https://gdl.space/ifebihiwuf.cs. The issue with my code in the SceneChanger script is that the part after the scene is loaded in the LoadScene method does not run after the scene is loaded, which is what I want it to do. I was doing some research and found out that Unity has an event called SceneManager.sceneLoaded that is called when a scene is loaded: https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager-sceneLoaded.html. However, I have never used events in Unity before and I am not sure how to go about implementing logic to load the player’s position when a scene is loaded. Is anyone able to help me out?

mossy minnow
#

hey, silly issue. im trying to initialise a material as green, and the material itself is green, but when i put it onto a line it just displays as white

#

when i change the colour manually, it works fine, the only issue when initializing the lines with code

#
        gridMat.color = new Color(128, 255, 128);```
        ```line.material = gridMat;```
leaden ice
#

Color uses 0-1 values

mossy minnow
#

ohhhh ok

leaden ice
#

You can also use Color32 which uses 0-255

mossy minnow
#

perfect, thanks!

hollow hound
#

Is it possible to make a prefab based on other prefab?
I have prefab Child without any links to other prefabs. I want to create empty Parent prefab add make it base prefab for Child, then apply some of the components of Child to Parent.

hollow hound
leaden ice
#

Well I know in newer versions of Unity there's a way to re-establish a prefab link from an object in a scene

#

not sure if there's a similar mechanism for prefab -> variant

fleet furnace
thick socket
#

thus the position stays the same

fallow palm
thick socket
#

I probably have to much stuff on "Don'tDestroyOnLoad" 😄

wide pecan
#

How can I stop Json from adding junk to my floats?

wide terrace
wide pecan
#

-8.67 turns into -8.670000076293946 in json

hollow hound
leaden ice
#

It has nothing to do with JSON

wide pecan
wide pecan
#

ok then

leaden ice
#

floats take up 32 bits of space no matter what

wide pecan
#

that's neat

leaden ice
#

The number 1 takes the same amount of space as this

wide pecan
#

thanks

fleet furnace
hexed pecan
#

Isn't JSon stored in strings though

leaden ice
#

yes

#

when the json string gets parsed into a float you get this

leaden ice
#

didn't realize you were saying that

wide pecan
leaden ice
#

Yes as json - if you care you can format the number to a limited number of digits

fleet furnace
#

But this might get you started.

wide pecan
fleet furnace
hexed pecan
#

Do you think storing a decimal would result in shorter numeric strings?

#

I don't see how it would

#

Or would it? Less imprecision?

fleet furnace
#

Well. Its gonna take up more bytes in memory but it will be shorter in the json. (or at least it will get rid of the imprecision)

slim condor
#

Problem reading .obj file

wide terrace
#

@wide pecan are you using Newtonsoft.JSON?

wide pecan
hexed pecan
#

I have some json files that could probably reduce their file size by 30% by doing something like this

wide terrace
#

It looks like Newtonsoft might have an attribute which can be used to specify serializers, and one such serializer for this purpose:

[JsonConverter(typeof(RoundingJsonConverter), 4)]
public float myFloat;

But I've not tested it

Edit: possibly only on properties - unclear https://www.newtonsoft.com/json/help/html/JsonConverterAttributeProperty.htm
Edit Edit: looks like you may need to implement the actual converter yourself still :/

fleet furnace
#

Now if you were sending vertex data as json or something crazy like that.
With milions of vertexes. Then sure I guess.

hexed pecan
#

Damn I keep forgetting that optimization is a curse word here

fleet furnace
#

But serialization/deserialization should happen outside of gameplay. Hidden by a black screen.

hexed pecan
#

The answer is always something like "its not worth it" without any context

fleet furnace
#

I mean. Damn. I just remembered the story about GTA5 loading being cut by like 60% by a guy optimizing their JSON 😅

hexed pecan
#

I think ive heard of that, wasnt it a random guy?

fleet furnace
hexed pecan
#

That dude went vigiliant lol

fallow palm
wide pecan
hexed pecan
#

Can you tell it to not serialize properties

#

Because thats what it is doing

swift aspen
#

Only if you make a custom serializer

hexed pecan
#

Lol, Newtonsoft isnt that superior after all is it?

sage latch
#

What's the best way to make a system where enemies not in view are disabled? Stick a trigger on the camera and run something like GetComponent<IProximityHandler> on every colliding object? Maybe OnBecameVisible?

hexed pecan
#

OnBecameVisible is my first thought

thick socket
#

what I do instead is this...

sage latch
thick socket
#
using UnityEngine;

public static class BootStrapper
{
    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
    public static void Execute() => Object.DontDestroyOnLoad(Object.Instantiate(Resources.Load("Systems")));
}

named BootStrapper.cs

hexed pecan
sage latch
#

I'll try it

thick socket
#

inside my resources folder is an object with the things I want to always be "Don'tDestroyOnLoad"

#

idk how the script works exactly...but it isn't on anything but it initializes that only once when the game starts

fallow palm
#

So I don't have to attach this to anything? Do I need to call anything in my DontDestroyOnLoad objects?

thick socket
#

nupe

#

that script just runs once by itself when game starts and puts the "Systems" object that is in Resources folder into Don'tDestroyOnLoad

#

I named it systems....doesn't have to be called that

#

code name and object name need to be the same tho

fallow palm
#

How do you create that object?

thick socket
#

make object in scene

#

drag into resources folder

#

aka make a "prefab"

fallow palm
#

And that folder should have prefabs of all the other DontDestroyOnLoad objects as well as this script?

wide pecan
#

Ok, I've tested and having 500 saved items only takes up 35 kb, so rounding their position isn't that necessary here

sage latch
thick socket
#

if you didn't just want 1 main object with others as children you would need to drag all prefabs into the resources folder

public static class BootStrapper
{
    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
    public static void Execute() => Object.DontDestroyOnLoad(Object.Instantiate(Resources.Load("Systems")));
public static void Execute() => Object.DontDestroyOnLoad(Object.Instantiate(Resources.Load("Player")));
public static void Execute() => Object.DontDestroyOnLoad(Object.Instantiate(Resources.Load("gamemangera")));
public static void Execute() => Object.DontDestroyOnLoad(Object.Instantiate(Resources.Load("etc")));
}```
hexed pecan
thick socket
#

easier to just put all DDOL on one prefab and call it once imo

fallow palm
#

Yeah the other way looked simpler

#

I'll try it out

hexed pecan
sage latch
#

Yeah I saw that, but it does require a renderer which one of the objects I want this for does not have, makes me wonder if the OnBecame messages also need a renderer to work.

hexed pecan
#

Ah, well yes you do need a renderer

#

I'm thinking maybe you can use a "dummy" renderer that isn't really visible but gets detected by camera?

#

Basically just use the bounds of it

sage latch
#

Yeah

#

That way I can add padding as well

hexed pecan
#

Yep, without messing with the bounds of the visual

#

Sounds reasonable

#

@sage latch Lemme know if it works

sage latch
#

Guess I'll have to disable the components one by one

hexed pecan
sage latch
#

yes

hexed pecan
#

And that script would have a List<Behaviour> or something
And then enable/disable those behaviours accordingly

sage latch
#

Well, having it on a separate script was the plan all along Composition > inheritance 💪

craggy quartz
#

Osmal

wide pecan
# hexed pecan Isn't JSon stored in strings though

in the end I decided to just store position as vector3 with all 3 values being floats multiplied by 1000 and rounded, this way json doesn't add any junk because now they are just like integers. When instantiating, I just divide the position by 1000

fallow palm
hollow hound
hexed pecan
wide pecan
#

and from 190kb 2000 items now take up 127kb

thick socket
fallow palm
#
using UnityEngine;

public static class BootStrapper
{
    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
    public static void Execute() => Object.DontDestroyOnLoad(Object.Instantiate(Resources.Load("Systems")));```
#

Screenshot is coming

hexed pecan
fallow palm
thick socket
fallow palm
#

Ok, I'll try that

#

Ok it worked but it created two players. I deleted the Systems from my scene and that created one player but it broke my Cinemachine follow camera since it references the player object

thick socket
#

or code on camera to find player

fallow palm
#

Well another problem I have is that there are some scenes where my player isn't present, i.e. menu and UI scenes. What should I do about that?

thick socket
#

other solution...don't have player in don'tdestroyonload, and just store its previous position in a gamemanager before moving to next scene so you can give it the old position in new scene

thick socket
#

if you change player looks/armor/weapons etc...its better to be dontdestroyonload imo

fallow palm
#

Ok. I'm going to try a few things then

thick socket
#

(code wise its not that hard to find player in scenes 👌 )

rotund burrow
#

if i have 1 method that is supposed to be abstract, should i make entire class abstract or just make method virtual?

simple egret
#

You can't have abstract members in a class that's not abstract, so that option is out

rotund burrow
#

i know

#

so leave method abstract and just add abstract before class name, or make method virtual

simple egret
#

Okay, so ask yourself the following question:

Does it make sense to have instances of [your class]? Or is it intended to only instantiate child classes of [your class]?

rotund burrow
#

it's the second

simple egret
#

Then, mark the base abstract

cobalt wave
#
private void OnCollisionEnter(Collision collision)
    {
        ContactPoint[] contactPoints = new ContactPoint[collision.contactCount];
        int contactCount = collision.GetContacts(contactPoints);

        Vector3 avgNormal = Vector3.zero;
        foreach (ContactPoint cp in contactPoints)
            avgNormal += cp.normal;
        avgNormal /= contactCount;
        
        if (avgNormal.y > 0.95f) //ground
        {
            Debug.Log("Added " + collision.transform.name + " to groundCollisions.");
            groundCollisions.Add(collision);
            return;
        }
    }

    private void OnCollisionExit(Collision collision)
    {
        ContactPoint[] contactPoints = new ContactPoint[collision.contactCount];
        int contactCount = collision.GetContacts(contactPoints);

        foreach (Collision gc in groundCollisions)
            if (collision.Equals(gc))
            {
                groundCollisions.Remove(collision);
                Debug.Log("Removed " + collision.transform.name + " from groundCollisions.");
                return;
            }
    }

I spawn on the ground,
console prints Added floor to groundCollisions. as expected
I move up to a wall
console prints nothing as expected
I move away from the wall
console prints Removed wall from groundCollisions. which is not possible in my opinion

if (collision.Equals(gc)) #<- because of this part here
            {
                groundCollisions.Remove(collision);
                Debug.Log("Removed " + collision.transform.name + " from groundCollisions.");
                return;
            }

how can the collision equal the one in the ground collection if they are colliding with two completely different objects as shown by the console?
is it just that the Collisions are a non comparable type?
comparing their transforms yields the same results

#

also, note that the groundCollisions is a HashSet<>

topaz ocean
#

How do I rotate a pre-existing quaternion an amount of degrees about a variable axis?

topaz ocean
#

this only seems to return a post-operation value, how would I add this to another quaternion?

cobalt wave
#

transform.rotation = Quaternion.AngleAxis(30, Vector3.up); damn it even has an example

topaz ocean
#

:|

#

this doesnt answer my question

cobalt wave
#

i think they literally mean add though

topaz ocean
#

yes, and I understand that part, the problem is that you cant add quaternions

hexed pecan
cobalt wave
#

yea i missunderstood

hexed pecan
#

AngleAxis can still be used here, you can combine rotations with * operator

topaz ocean
#

nice

#

thanks

hexed pecan
#

The order matters in some cases

#

Like a * b can be different than b * a

topaz ocean
#

Im trying to calculate object orientations before they become transforms, so quaternion math is something ill have to famliarize myself with

hexed pecan
#

And all the helper methods: LookRotation, FromToRotation, AngleAxis, etc

topaz ocean
#

epic

wintry crescent
#

Hi - is converting between quaternions and euler angles fast or not really? Compared for example to calling transform.rotation

topaz ocean
#

previously I was generating transforms by having a parent and creating children in it's local space, but im planning to ditch that hierarchy for more stable rigidbody simulations :)

wintry crescent
#

I'll be doing it a lot and idk if I need to optimise it

#

a lot - I mean thousands per frame

hexed pecan
#

I have seen Internal_ToEulerRad or whatever pop up in my profiler every now and then
Especially when doing procedural animations/active ragdolls

topaz ocean
#

Im trying to generate a car, so I only need to do these operations once so that I can force objects to remember their original relative orientation.

cobalt wave
#

they weren't replying to you oops
quaternion multiplication isn't expensive generally

#

so don't worry

hexed pecan
cobalt wave
#

does anyone know why my code behaves the way it does?
the post above these convos, I can reply to it

hexed pecan
#

I mean it's reliable in doing what it does

#

Im looking a bit more into it hold on

cobalt wave
wintry crescent
# hexed pecan They aren't exactly cheap operations

yeaaa, thought so
I have a bit of a problem then
because I will need to do a ton of calculations on rotations (either eulers or quaternions) for my machine learning project
adding noise to it, to be specific
Basically what I'm doing is reading a list of rotations/positions from a file, then every frame setting a ton of copies of gameobjects to that data, but each copy gets some (different) noise added to it
and I'd like to squeeze out preformance, as much as I can, I'm hoping to train my agent overnight :/

hexed pecan
flint sierra
#

Anyone know how to deal with Cannot build player while editor is importing asset or compiling scripts

cobalt wave
#

I'll check that out brb

lean sail
#

I dont think comparing collision works, i was just trying it and i never got it to even remove my terrain from collision exit

cobalt wave
#

I even tried comparing their transforms (which are different as tested by the Debug and proven in the console)

hexed pecan
#

Which could lead to a reused collision to be the same object as in a different collision

cobalt wave
#

I set it to true and it still behaves the same
I don't think it's a physics issue tbh

#

I have no idea what is it though

wintry crescent
cobalt wave
#

it'd be nice if I could debug the HashSets themselves

hexed pecan
cobalt wave
#

damn

#

you're right

hexed pecan
cobalt wave
#

it works now
I'm just afraid what does this mean in the long run

hexed pecan
cobalt wave
cobalt wave
hexed pecan
#

Or it was true?

cobalt wave
#

it was true to begin with because that's the more optimized way

#

less work for the garbage collector

hexed pecan
#

Makes sense that it fixed it then

cobalt wave
#

it'd be awesome if I could set this value to be false only for my player and everything it touches
because the enemies and everything else won't need that luxury

hexed pecan
#

The doc says it reuses one Collision if its true

cobalt wave
#

and well, if I have alot of entities walking around and colliding that just sounds like a lot of collisions to sort through

hexed pecan
#

Keeping a Collision object alive for longer than the collision message method seems sketchy to me anyways

cobalt wave
#

I'll try to think of another way

#

but if I don't think of sum else, this still works, so thanks

hexed pecan
heady iris
#

Collision has a bunch of cruft you probably don't care about

cobalt wave
#

well the actual reason is really dumb

hexed pecan
#

What data are you currently using from the stored Collisions? I see only transform

cobalt wave
#

it's cheaper to compare collisions
than to create a new vector
run a loop to get an average of all the contact point normals
and then compare that average vector to a stored one

#

because I really only need the average vector of the collision

#
foreach (ContactPoint cp in contactPoints)
            avgNormal += cp.normal;
        avgNormal /= contactCount;
        Debug.Log(avgNormal);
        if (avgNormal.y > 0.95f) //ground
        {
            Debug.Log("Added " + collision.transform.name + " to groundCollisions.");
            groundCollisions.Add(collision);
            return;
        }
#

this is what decides if the collision gets added

#

which is fine because it's necessary

hexed pecan
#

You just reminded me of this extension method I wrote years agocs public static Vector3 GetAverageNormal(this Collision col) { var count = col.contactCount; var result = Vector3.zero; for (int i = 0; i < count; i++) { result += col.contacts[i].normal; } result /= count; return result; }

#

Now that I look at it, its kinda garbage
I should at least normalize the result

cobalt wave
#
foreach (ContactPoint cp in contactPoints)
  avgNormal += cp.normal;
avgNormal /= contactCount;

I would have to also have this in the exit too
which isn't terrible but still

cobalt wave
#

we both wrote the same one catcrymic