#archived-code-advanced

1 messages · Page 4 of 1

upbeat path
#
void Update()
    {
        DoThingAfterStart();
        enabled=false;
    }
regal olive
#

I need all Start() methods to be completed

sly grove
#

Although honestly I'd recommend changing how this works entirely. Have one central script that spawns all the tiles and then does the thing...

for (int i = 0; i < numberOfTiles; i++) {
  SpawnTile();
}
DoThingAfterTilesAreSpwaned();```
regal olive
#

Yeah, my current project is killing GC in the profiler

#

I think that is a much better idea tbh.

upbeat path
#

I would just use script execution order

sly grove
#

That's an option too

regal olive
#

Thanks a ton!

rugged radish
#

hey guys
have anyone seen a library that, simply put, can draw types on a "canvas" of 2d arrays ? with brushes and other functionality typical to canvas drawing

#

I implemented a very simple module for that, but now I need more functionality out of it. maybe I'm wasting my time and there's a mature library that can do just that

sand nacelle
#

can anyone recommend some sources for someone trying to fill in the gaps in their intuition around what is and isn't worth worrying about re: performance?

#

came to unity from a background in web dev (self taught at that) so my CS fundamentals are pretty weak

rugged radish
sand nacelle
#

thanks!

undone coral
#

unitask, yes. really hard to say without seeing hwat you have going on

#

yes, take a look at the xmage project. most "spells and effects" games have architectures similar to the one there

undone coral
#

what is the best way to work with audio with advanced-code skills? i'm scoring the sounds for a passenger vehicle. its engine, the wind, etc., should vary with the velocity, while there are one-shot things like turning it on. can the animation controller "mix" audio sources without weird gaps or clicks, like i see so many people talk about? audio mixer, animated via code? also, i would want to set trims in unity, like specific sections of the sound. google has only shown me dumb stuff that doesn't deal with any of the routine issues in sound

undone coral
compact ingot
undone coral
#

usually i say "Timeline" for audio

#

but is timeline appropriate for like, an animation rig except for sound effects?

sand nacelle
#

thanks @undone coral and @compact ingot

hallow cove
#

can someone please help me with this, I don't have that much time rn, but I have a Search Window, and I can't figure out how to optimize it

#

I literally made special groups that open a whole new Search Window when clicked

#

this helped a bit, but it's still laggy as hell

#

meanwhile stuff like the VRChat UDON Search Window is instantaneous, and the Bolt Visual Scripting one is also faster

rugged radish
#

add some indexing for your data if you haven't done so already

tough knoll
#

I don't actually use it but people keep recommending it to me over and over

undone coral
#

to use with plain old unity audio sources

#

seems kind of nuts though

#

why did unity abruptly stop development on timeline... its model for audio mixing was useful

#

i could have easily done this in timeline if it supported a state machine

tough knoll
#

I meant the FMOD unity integration

#

It has animation features and other junk as well

undone coral
#

yes it does sound like

#

total overkill

tough knoll
#

Yea

undone coral
#

but you're saying this is just how it goes?

tough knoll
#

I'm just saying, if you want to do advanced audio, instead of ramshackling it, you might want to just go and use FMOD since it's extremely feature complete and has a good UI

undone coral
#

yeah i hear you

#

do you know if it emits audio via a plugin or via unity's audio listener?

#

i.e. does it mix in a plugin, but ultimately send data to be heard via unity?

#

or does it interact wth the sound device directly?

tough knoll
#

It has it's own audio engine

undone coral
gray pulsar
plain canopy
#

oops

#

I have a metronome that updates using OnAudioFilterRead() and i want to do stuff every tick, but since it's not in the main thread i'm very limited. are there any ways of going about this?

undone coral
plain canopy
#

woah this intrigues me. thankls

undone coral
#

is there a robust script for starting and stopping sounds in animation clips?

#

sometimes i am baffled at

#

how it's 2022 and the simplest things are so hard

tough knoll
#

If you dont want clicks and pops and shit you're gonna need to do crossfades

#

yeah

#

Unity AudioSource is like, bizzarely primitive

#

Even really straightforward stuff like syncing audio tracks is jank

undone coral
#

and prepped the files for looping

tough knoll
#

Oh, I thought you meant at arbitrary points during the file

#

my b

undone coral
#

i figure i can do the crossfade between two one-shot clips by animating the volume

undone coral
#

it will just work

#

in terms of transitioning between two clips

#

but maybe i'm wrong

tough knoll
#

Feels high-maintenance tho

undone coral
#

i only have 3 audio files lol

tough knoll
#

true

undone coral
#

it looks like i have to author a statemachinebehaviour

#

but i feel like this already exists

#

and is also error prone

#

i am struggling to find it

#

unbelievable

#

this leads me to believe this is the wrong approach

gray pulsar
#

Yeah, all the stuff you're describing is what I expect from audio middleware. You're really talking about FMOD's bread and butter

tough knoll
#

Wwise also

#

I know even less about that one

cyan nacelle
#

Anyone know anything about ScriptedImporter? Specifically fileIDToRecycleName vs internalIDToNameTable? Or maybe the new TextureImporter?

noble tendon
#

DOTSNET or NetCode for DOTS? Which one is better for MMO game?

plain canopy
undone coral
plain canopy
#

what is unitask and how do i use it?

zenith ginkgo
#

oh no

tall briar
formal lichen
#

Does Unity offer or is there a 3rd party that offers grid computing software for like a list of Unity projects?

#

I feel like it'd be nice to have something that you can give a bunch of random projects with different build types and just let it go to town using a bunch of "botnetted" computers to build the projects quickly

undone coral
#

is there a pre-existing property drawer to select animation parameters / does odin have one?

formal lichen
humble onyx
novel plinth
#

making your own thread dispatcher still the way to go, and it's not hard to make one anyway

cerulean loom
#

usually, in videogames, do developers use a gizmo function to make an attack hitbox? To limit the range of the attack

cerulean loom
#

Yeah like on order to draw the hitbox

#

Or not hitbox perse but the attackrange

sly grove
cerulean loom
#

Ohhhhh

#

That makes much more sense

#

And that's standard, I mean the physics overlapBox

#

?

sly grove
#

not sure what you mean by "standard" here

cerulean loom
#

As in there are no other ways of doing this,or like it's the most commonly used thing for this type of thing

sly grove
#

There's no other way to immediately check which colliders are inside a box-shaped area using Unity's physics engine than to use OverlapBox

solar hawk
#

what is the using statement to access the Rig Builder in code

zenith ginkgo
#

ParticleSystem.Update is taking a pretty large chunk of the time doing whatever its doing. has anyone come in contact with this before, and know how to solve it?

undone coral
#

is there a git plugin for unity that lets me right click on a field and click "revert" to go back to staged changes?

crystal parrot
#

is there any way to extract root motion from animation clips and use it to move character without animator?

crystal parrot
#

i don`t need animator on server but i do need to play some skills root motion "motion"

#

@steady stirrup i have extracted them from clips, 3 AnimationCurves from MotionT but idk how to apply them

#

doing this does not work

#

advancing time by Time.deltaTime

undone coral
zenith ginkgo
#

i mean, i have alot of torches that are visable at once

#

that use a particle system

crystal parrot
steady stirrup
#

No idea, sorry

devout orbit
#

So I've got a pretty basic question.
I've got a object that only needs to lookAt a target on the x-axis I've been googling but I can't find the answer.
Non of those solutions worked.

Is there any who know's how to do that?

devout orbit
#

In 3D,

sly grove
#

so how do you only look at something on one axis?

devout orbit
#

I only want this axis to be used to look at something

sly grove
#

oh easy

#
Vector3 pointToLookAt = target.position;
pointToLookAt.x = transform.position.x;
transform.LookAt(pointToLookAt);```
devout orbit
#

Is it also possible to use Quaternion.RotateTowards or just a smoothing on it?

sly grove
#

yes

#
Vector3 pointToLookAt = target.position;
pointToLookAt.x = transform.position.x;
Quaternion targetRot = Quaternion.LookRotation(pointTolookAt - transform.position);
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRot, TIme.deltaTime * degreesPerSecond);```
devout orbit
#

Thanks!

#

The problem is that this would still rotate y /z

sly grove
#

how so

devout orbit
sly grove
#

anyrotation you see on y / z would only be due to the fact that:

  • we're not using localRotation so the parent rotation may be a factor
  • gimbal lock
sly grove
#

then do this

#

and do local Rotation

devout orbit
#
pointToLookAt.x = transform.position.x;
Quaternion targetRot = Quaternion.LookRotation(pointTolookAt - transform.position); <-- this one?
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRot, TIme.deltaTime * degreesPerSecond);```
sly grove
#

I think like this:

Vector3 localTarget = transform.parent.InverseTransformPoint(target.position);
localTarget.x = 0;
Quaternion targetRot = Quaternion.LookRotation(localTarget);
transform.localRotation = Quaternion.RotateTowards(transform.localRotation, targetRot, TIme.deltaTime * degreesPerSecond);```
#

the .parent is important

devout orbit
#

Yea this worked.

#

Quite a lot of work for such a small change

#

😅

#

            Vector3 pointToLookAt = target.position;
            Vector3 localTarget = transform.InverseTransformPoint(pointToLookAt);
            localTarget.x = 0;
            Quaternion targetRot = Quaternion.LookRotation(localTarget);
            barrel.localRotation = Quaternion.RotateTowards(barrel.localRotation, targetRot, Time.deltaTime  * gunRotationSpeed);```
undone coral
devout orbit
#

Correct

undone coral
#

you only want the canon to pitch up and down, such that it points, essentially, at the height of any point

devout orbit
#

Yes,

undone coral
#

and you want to move this point around, and you want it to gracefully animate between these rotations

devout orbit
#

Correct.

undone coral
#

okay, you will need separate hierarchy for pitch, yaw and roll, just like a real cannon

devout orbit
undone coral
#

the local rotation in euler will "make sense" to you, in the sense that it will be x = pitch

devout orbit
#

I want that base to rotate on Y axis

undone coral
#

you have to name them the real thing

devout orbit
#

barrel only on x pitch

undone coral
#

otherwise this gets too confusing

#

don't say axis

#

it's pitch yaw and roll. "x axis" is too ambiguous

#

nobody knows what you're talking about

#

you have a few ways you can do this - using the hierarchy, which wasn't clear to someone else who was helping you that you already have some weird hierarchy

#

you can also do this with the single object itself

#

usually, in systems like these, there is only one rotation computed

devout orbit
#

But I would the rotating base separate from the barrel.
So the base only looks at the direction and the barrel looks at the height

#

So, I've got the base working


            var targetBaseDir = target.position - rotationBase.position;
            targetBaseDir.y = rotationBase.transform.position.y;
            

            var targetBaseRotation = Quaternion.LookRotation(targetBaseDir);
            rotationBase.rotation = Quaternion.RotateTowards(rotationBase.rotation, targetBaseRotation, Time.deltaTime * gunRotationSpeed);```
#

How would you approach it?

undone coral
#

should it feel like it has momentum or that it instantly starts and stops?

#

when it's rotating towards the right position?

#

if you need it to feel physical, you have to use a PID controller. there's no alternative. you can search my messages and see where i've said almost those exact words, and the user was really happy he listened

devout orbit
#

and this is already looking at the correct position

undone coral
#

if you don't need it to feel physical, you rotate the base and barrel separately, and it should just work

devout orbit
#

but the barrel should look at the height

undone coral
#

you can compute the euler angle using atan2, so that it makes more sense to you.

#

you can also turn the aim direction into euler angles, since they make sense in this context, and animate the y and x separately

#

"y" and "x"

#

but you haven't answered my question - does it need to feel like the gun has weight? @devout orbit

#

or can it start and stop rotating instantaneously?

devout orbit
#

it can start and stop instant

sly grove
devout orbit
#

Base first,

sly grove
#

ok part of the problem may be my code above assumes that the base is rotated instantly I think

devout orbit
#

Hmm, even when I put the code infront it acts the same

deep peak
#

you still need help with this? (edit: seems like it solved, im off then)

empty plaza
#

Hi yall, I have an issue where the terrain.setAlphamaps function sometimes updates a 256x256 section in 3ms and sometimes takes a whole 18ms. Does anyone know what could be the cause of this? I already made sure that it is actually only updating 256x256. The total terrain size is 1024x1024, updating that all at once is too slow for me which is why I'm splitting it up.

undone coral
#

does unity not do timezones...

quartz stratus
undone coral
quartz stratus
undone coral
#

ty my dude

#

right now i'm authoring both the unix and windows timezones..

quartz stratus
#

There may have been other dependency packages? But I think it was just that one. It's always sort of a game of whackamole using .dlls in unity lol

fickle inlet
#

I have a gameobject with children and I want to add a box collider. The box collider has to match bounds of the gameObject, but there can be multiple mesh renderers and they are all in childrens, so I do not know how to match Box Collider with GameObject at a runtime.

#

Box Collider is on parent and parent is an empty transform.

deep peak
#

from the meshes inside the object, and calculate new bounds that can wrap all meshes inside one collider

gray pulsar
regal olive
#

What's the best way to set up a database in Unity? MySQL? I just need a direction to go in, I've never worked with databases.

deep peak
#

database for the game itself for game stuff like enemies and weapons, or for game server?

regal olive
#

well in this case a high score. but yes at some point a game server too.

sly grove
#

Like global high score?

regal olive
#

Yes: to compete with other users. I have a local high score set up by storing data using BinaryFormatter and FileStream

sly grove
#

At that point you wouldn't really be making a database "for Unity" you'd be making a web API and have a database backing that

regal olive
#

web API to read local high scores? and display them globally?

sly grove
#

Honestly you're probably better off using an existing service for stuff like high score

vestal lily
#

Im currently having a problem with my player controller being jittery when its moved by a platform moving up
I currently have tried:
-Making it a Child of the platform
-Adding Force for it to go up at the same rate the platform is
Im not sure how id make this look good since gravity is constantly being applied downward

sly grove
vestal lily
sly grove
#

well... that kinda janky setup is the issue

vestal lily
#

understandable

#

this isnt necessary for what im doing but do want a decent character controller for the future

sly grove
#

The main way I know how to get smooth platform movement is:
Platform and player have rigidbodies. Platform's body is kinematic and uses MovePosition in FixedUpdate to move.

#

wait also is the platform moving in update

#

or fixedupdate

#

or what

vestal lily
#

just normal update for both

sly grove
#

one issue is also that you probably want to make sure the platform's update runs first

#

maybe with script execution order or something

#

if the player moves first, the platform could them move into the player

#

which is no good

#

the other way around might be smooth

vestal lily
#

i could see that being it ill do alil digging into that thanks

quartz stratus
#

Hopefully someone else can help out with the math, but I wanted to jump in to make sure you're aware that Update is very likely to execute varying times per second, based on your FPS. So I would recommend moving to FixedUpdate, if you want to move this to an event function.

crystal parrot
#

Is it possible to play a single animation without animator controller?

#

AnimationClip

sly grove
crystal parrot
quartz stratus
#

Oh xD my bad, just noticed that

quartz stratus
#

I can try to find the specific Unite talk, but I remember that pretty clearly

quartz stratus
crystal parrot
#

@quartz stratus is this wrong?

#

i`m having this code

#

but i`m adding the clip to the list

quartz stratus
silver schooner
#

Why can't I find these variables in the script, and how come when I set variables in the script to public they don't show up here?

#

I search for "headtransform" and nothing comes up. I search for "NeckVerticalWeight" and nothing comes up.

#

I search "[Range" to try to find instances of sliders being created and nothing shows up.

sly grove
#

But it looks like there's probably some custom editor stuff happening here

silver schooner
sly grove
#

ok well I'd guess they've got a custom editor for this script, which explains all of the above

#

see if you can find that

silver schooner
#

I'm trying to adjust how far up and down a character can look, but I don't know which variables to change. But there were some promising constants in the component that controls the looking and I was gonna set them to be public to play with them in VR and see what effect they have, except when I do nothing shows up in the inspector.

sly grove
#

look in the Editor folder for the asset

#

there'll be scripts in there for custom inspector

silver schooner
sly grove
#

it wouldn't be in the main script

#

there'd be a separate editor folder in the asset files

#

somewhere there'll be a script with [CustomEditor(typeof(TheScriptYouCareAbout))]

silver schooner
#

I think I found it. Thanks!

tidal roost
#

How can I deal with slopes jiterring while using moveposition?

royal timber
#

you need to move relative to the slope

#

when you move forward you are moving into the slope

#

using normal, camera, and input rotations you need to make a movement axis that is relative to the slope

#

pressing the rigidbody down will not solve it (and will probably be unreliable)

#

use a character controller instead if you can, it solves the problem perfectly

#

and is less prone to physics or collision issues

#

unity themselves even states that rigidbodies are too realistic for usual character physics

tidal roost
royal timber
#

i have made a solution before

#

it required me to get the normal of a slope, get up and right vectors of the slope and use input to rotate that, then use the camera to make the rotation relative to the camera

#

its tough to explain on paper

tidal roost
#

I managed to get the normal already

#

I was following a tutorial, however it was made in 2D

#

so I'm having issues with the following part of the code:

#

unfortunately there is no "Vector3.Perpendicular"

#

I tried looking for an alternative but couldn't find anything

crystal parrot
#

I need to queue AssetReference.LoadAssetAssync on adressable?

#

i can`t load many in parallel using this?

viscid anchor
#

I was basically switching one texture to another when the player looked at the ground and held left click. basically painting

violet locust
#

I have an issue with scriptable objects, I am making a thibg that has several scriptable objects that need to be assigned after the main asset is created and add these as sub assets

#

I am making the instances of the child assets in the awake function but aster saving the main asset i get error that the other asset is not persistent, and adding asset to object failed

#

In the inspector where the child asset should be it changes to a type mismatch

#

This is the code i have

upbeat path
violet locust
#

It manages to create the asset but fails to add it to the main asset

#

At least there is no type mismatch anymore

#

Also i dont have access to this path variable

#

AssetDatabase.GetPath doesn't return the path of the main asset because it probably doesn't exist yet

upbeat path
violet locust
#

Is there a way to intercept where the asset is going to be saved to?

upbeat path
#

intercept?

violet locust
#

I am using tge asset create menu and I'd want the asset to be saved in same location

upbeat path
#

so you need to find the path of the parent asset

violet locust
#

Yes

#

Problem is in awake and onenable are called before the asset is actually saved

upbeat path
violet locust
#

This should do

#

Same error

#

I will need a custom editor window anyways so i guess i will do this initialization of subassets when the window is opened

obsidian glade
violet locust
#

Rider just did that when i selected invert if

#

Didn't even look at it

fresh salmon
#

If WaveController is a MonoBehaviour definitely prefer != null as is { } may perform a pure null check, which does not take in consideration the "destroyed but not null yet" state of Unity objects

rugged radish
#

is there a way to schedule a job without allocating all of its output NativeContainers (it is known in advance that they won't be used in specific circumstances)

rn I have to allocate 0 length native arrays, then resize them and reassign them back into the job instance. works fine but looks ugly

turbid stirrup
#

my unity linux build is segfaulting, any ideas what might be causing it?

Mono path[0] = '/app/dist/moba-server_Data/Managed'
Mono config path = '/app/dist/moba-server_Data/MonoBleedingEdge/etc'
Caught fatal signal - signo:11 code:1 errno:0 addr:0x8
Obtained 14 stack frames.
#0  0x007f589506b140 in funlockfile
#1  0x007f58970d53dd in _dl_rtld_di_serinfo
#2  0x007f58970dcf05 in _dl_find_dso_for_object
#3  0x007f5894fca300 in _dl_catch_exception
#4  0x007f58970dc8fa in _dl_find_dso_for_object
#5  0x007f5894e8d258 in (Unknown)
#6  0x007f5894fca300 in _dl_catch_exception
#7  0x007f5894fca3bf in _dl_catch_error
#8  0x007f5894e8da65 in dlerror
#9  0x007f5894e8d2e4 in dlopen
#10 0x007f58960f5937 in PreloadPlugins()
#11 0x007f58960f3ffb in PlayerMain(int, char**)
#12 0x007f5894eb8d0a in __libc_start_main
#13 0x0055f0c9597029 in _start
sly grove
rugged radish
flint sage
olive thunder
#

Oh no

#

Stackoverflow is down for maintainance

#

How will I get any work done

#

I am done for

novel plinth
#

you need twitter, not discord for sure... smh

#

best you can get #💻┃unity-talk that is if anyone there care what your personal problem is 👀

olive thunder
#

Lul it's back online

novel plinth
#

who tf cares!🔥

undone coral
undone coral
#

(2) once you see that that works, try copying the _Data folder from your working windows standalone player build to your linux-built one, and observe that the player works

mortal orchid
#

Trying to make a sword swing mechanic in unity. I am using slerpUnclamped for movement currently the sword is moving from left to write it is the endpoint is specified manually so when the player is moving the endpoint cannot be changed where the sword should finish also the sword is just moving how can I add swing element to it?

hazy epoch
#

Is there a way to by-pass inheritance? Example... in the attached screen shot. Is there a way to achieve this?

humble onyx
hazy epoch
humble onyx
#

if the classes are public its working

#

but that does not solve your problem

#

officialy its not inteded that you can do it

hazy epoch
#

My work around for the time is to just C&P (cringe) the code from ClassA's method into ClassC's method and just not call base.Foo().

undone coral
#

@hazy epoch do you see that it (1) doesn't matter that ther eis a class B?

#

(2) if you want to make code not overridable, don't mark it virtual/abstract, and call it where you need to

#

what is your objective @hazy epoch ?

#

you can also do something like

#
class B : A {
 protected void BaseFoo() {
  base.Foo();
 }
 override void Foo() { ... }
}

class C: B {
 override void Foo() {
  BaseFoo();
 }
}

@hazy epoch but this stuff is a code smell

hazy epoch
undone coral
#

okay

tough knoll
#

Can't you just base.base.Something

#

huh I guess not

#

wtf, I always believed you could

undone coral
#

but i think this user has in the past asked for things that do not make sense

#

when you have access to the source code (as the user says, to copy and paste) access control is meaningless

#

this is a level 2 or maybe even level 3 expanding brain meme stage of access modification in programming

tough knoll
#

Yeah there's definitely some funky inheritance chains going on, but, really, base.base should be a thing

undone coral
#

because if you have access to the source and can edit it... you just, modify it to make more sense

hazy epoch
#

Most things don’t make sense when asked for out of context. However, copying and pasting is bad practice in coding. If you’re copying and pasting regularly then you’re missing some vital understanding of coding.

#

In my question inheritance is involved. So the root code is irrelevant.

tough knoll
#

this is a bad take

undone coral
#

it's okay

#

the example i showed is sort of how you assign a name to a particular overridden method

#

that you can reference in subclasses

tough knoll
#

In this context copy and pasting is maybe bad because it means you're duplicating your code and making it harder to maintain if it changes in the future though

#

or something

undone coral
#

in c# it's true you can only get the current method and the immediate predecessor via symbols

#

they have a good reason for that, it has to do with optimizing method dispatch

#

it's also sometimes unknowable - consider if you are extending an interface

#

what would base.base.InterfaceMethod refer to?

#

kind of tricky

#

c# also lets you declare new names using the new keyword

#

also very tricky

tough knoll
#

I figured it probably was a technical thing

#

I mean for the other thing it could obviously be restricted in those cases

#

The new thing though

#

yeah

#

I don't like new in general, it's awkward

#

Unity declaring every imaginable component name and then deprecating it in MonoBehaviour tho

cerulean minnow
#

Maybe someone here can help me. I created a new project last night , connected it to firebase and Facebook , and I got Facebook login working with firebase but every time I've tried to build to my android phone it crashes and says (game name) has stopped and gives me app info option and close app option.

#

It works fine in the editor. when I build it doesn't give error or warning of any kind. And its the same whether I build to device or build to pc and copy apk over

turbid tinsel
#

I think you need to have debugging on in developer option on your phone for that to work

#

and while you're at it, you can turn on wifi debugging so that you dont need to connect to the pc at all via cable, you just need to be in the same network

turbid tinsel
#

yea, but you need to enable debugging in developer options on your phone, or else it wont work

cerulean minnow
#

this is a new project , i moved an assets folder inside and did my facebook login tut with firebase and everything is good in editor but everytime ibuiild it crashes

viscid anchor
viscid anchor
cerulean minnow
#

not my first rodeo . im 3 years into unity , just never had this happen on a new project

turbid tinsel
#

also, for apk transfer between devices, you might wanna consider justbeamit.com, just make sure to cancel the first download and then retry when downloading from phone, there's a silly bug

turbid tinsel
#

u should have console output in your editor as you run the game

long ivy
#

if you can get to the point where it's waiting for a debugger to attach, attach a debugger and see where the crash is happening

turbid tinsel
#

from the moment it runs

long ivy
#

there might not be any output from Unity if it's crashing when loading modules

cerulean minnow
turbid tinsel
cerulean minnow
#

ok one sec

turbid tinsel
#

you can click build to phone or sth, but anything will work

#
> gradle build
> one sec

choose one lmao

turbid tinsel
ebon obsidian
#

Can anyone give advice on how to organize the source code control for a medium sized game project that involves the following?
1 - Unity project/scripts/etc
2 - Game code base and assemblies
From what little I can find it looks like Unity projects in general don't get along with git so I am curious how people with larger projects solve this problem.

cerulean minnow
turbid tinsel
#

like the one that github provides as a template when making a repo

turbid tinsel
turbid tinsel
#

to save space when saving big assets

upbeat path
turbid tinsel
#

and not grow your repo ad infinitum

turbid tinsel
#

maybe with a single object with a debug.log in Awake()

cerulean minnow
upbeat path
#

Sorry, not to do with Firebase or Facebook

#

you should filter with the tag Unity iirc

ebon obsidian
ebon obsidian
# turbid tinsel they do, just use a good gitignore

the reason I say they don't is when tracking change to assets they are treated as binary files so I was hoping there was some better solution for those kind of things. Also having all that in the same repo can slow things down so I was curious if people organized the Unity stuff in a separate repo from the main code and then built the separate pieces that would be used by Unity

turbid tinsel
ebon obsidian
#

I am trying to find out what the best practices are before I go do the wrong thing

turbid tinsel
#

I am not 100% sure how that works tho, didn't use it, but you might be able to do what you want this way

#

this seems helpful

ebon obsidian
#

I went through some tutorial trying to use git ignore with unity projects and it got kind of gross kind of fast

turbid tinsel
#

have you tried this one?

ebon obsidian
ebon obsidian
turbid tinsel
#

LFS is designed to use little storage

#

compared to normal git

ebon obsidian
#

so in general Unity projects are big monolithic things?

turbid tinsel
#

?

ebon obsidian
#

I know that was a weird question, let me try to rephrase it

long ivy
viscid anchor
#

how can you adjust brush size in c# for terrain?

ebon obsidian
#

In things like Xcode and Visual Studio it is possible to have sub projects to help organize and factor my build system. In Unity it looks like it is oriented around having a big project that represents the game/app you are creating and then you can import various packages that you build separtely

cerulean minnow
turbid tinsel
#

I don't think that's the case for Unity, as far as I know
I mean, you can have multiple projects, but that's not helpful

#

although packages which you import, are imported not into the project folder but to a shared folder somewhere in the unity installation folder

ebon obsidian
#

But when I have tried to create packages out of things it doesn't bring in everything in an immediately usable way. I had to do a certain amount of manual work to reuse something from one project to another

turbid tinsel
#

like asset store or stuff

#

you can add a package as a git link

ebon obsidian
#

like I took the player controller from 3D Game Kit and enhanced it and then exported it as a package and put it into another project

#

but I still had to assemble the player controller, camera, etc in each new project I used it in

turbid tinsel
#

you can export entire prefabs, you can set everything up in them

#

or even entire scenes

#

and load them without unloading other scenes

ebon obsidian
#

if you add a package as a git link then does it just pull a binary off the git?

#

can you bring in a package during run time?

turbid tinsel
#

yea I believe
but it's cached so you can use it in many projects

turbid tinsel
#

you can have a scene in a package, and load that
or a prefab

ebon obsidian
# turbid tinsel why would you need it?

I am building a game that supports building inside of it so I want to let a user choose a package and bring it in that has a set of prefabs and some special data structures I am designing

turbid tinsel
#

ah
I see what you mean

#

wait, do you need them to be able to download stuff made by other players, or just new content by you

ebon obsidian
#

I want to let someone download something like this https://assetstore.unity.com/packages/3d/environments/dungeons/destroyed-opera-environment-120675#publisher and then in my editor map parts of it to my data structure and then be able to use those pieces to build an area of the game with it

Elevate your workflow with the Destroyed Opera Environment asset from Michał Wawruch. Find this & other Dungeons options on the Unity Asset Store.

#

I realize there are a pile of interesting licensing issues with this but I am just using it as an example of the technical requirements

turbid tinsel
#

ok, you have two options
either take some packages like this one, and distribute them to your players from your server (probably a legal nightmare), for that you need the Addressables system (an extension of the Asset Bundles system)
Using this option, you can also deliver anything you make yourself, you can just make it into a package, put on a server, and go

you cannot pass code this way tho

#

Second option
I think there might be a way in unity to process .asset files on runtime, but I never used it, so you'll have to do some research

ebon obsidian
#

and by server I am assuming this can be my local file system at first?

turbid tinsel
#

yea
addressables have a neat option where you can make your own editor a server for a bit

#

for your local network

ebon obsidian
#

like basically here is a file, Unity read this using the Addressables system and go

ebon obsidian
#

for my purposes I may need to do the second

#

as I understand it you can build your own unity editor in your app, is that correct?

#

or is the Editor assembly limited to inside of the Editor runtime?

turbid tinsel
#

no
you need to put some code that will download the asset from the web, and save it to a file, then use some function that will transform it into a Unity object

#

and u can instantinate it then

#

in the buld

#

build

ebon obsidian
#

what I mean is suppose I want to use things like the manipulator handles UI from the unity editor, can I access those outside of the Unity editor without having to build my own?

turbid tinsel
#

ah
yea you gotta make that yourself

ebon obsidian
#

oh so the Unity editor is not usable in my app:(

#

I don't want my game builder to have to run inside of unity

turbid tinsel
#

I really do recommend looking into the addressables tho
since downloading from the asset store is a legal nightmare
you can just distribute it as asset bundles, less content but 100x easier

#

you can make a simple map editor yourself

ebon obsidian
#

but I would like to use potentially some unity editor extensions like Gaia. Maybe they provide an API for me to setup that stuff programatically

turbid tinsel
#

that won't work, I bet they're using the UnityEditor namespace

#

this requires the full unity editor to work

#

you might be able to modify it kinda, but that'd be a lot of work

#

or make something from scratch

ebon obsidian
#

so I can't use dotpeek to pull out stuff cuz I bet it has a lot of native code lol

#

I am so used to modding games where I can pull the entire source out with dot peak and do whatever I want

turbid tinsel
#

I mean, you can get the code, as in the C# code with dotpeek, probably
but it's a editor-only code, it won't work in builds

ebon obsidian
#

sounds like learning about Addressables is a good thing to do, thanks for that and the useful feedback

turbid tinsel
#

yea, good luck!

eager sundial
#

I want to find a way to make a kind of "red light / green light" game. The enemies should only move when your back is turned, and will have to stop when you're looking at them. Im not sure whether or not I want them to stop moving when they're either in view of the camera, or just if theres a flashlight being shone on them. But Im running into problems with both.

For the "in view of camera" idea:
I've been experimenting with a few of unitys "isVisible" features and such, but it will still tell me the object is visible even if its being obscured by an object, naturally. Im a little unsure how to go about creating code that can detect if its being obscurred or blocked / not actually being seen. I also dont know if this is the most "efficient" way to achieve this, using the render.isvisible thing.

For the "flashlight" idea:
Im just a little unsure how to go about this idea in general. I've got a few thoughts, but I dont have all that much experience with lights in unity anyways, so I dont know if they'd even work, but perhaps i could use this as an opportunity to learn.

If anyone has any ideas about what I could use to try implementing either of these, or any concepts I can look into that would help me, I'd love to have that discussion!

#

Im trying to use this game project as a learning oppurtunity, so I'd appreciate if people could point me in the right directions, or talk these ideas out with me, rather than giving me a lot of code 👍

solar hawk
#

I have a question

#

i get this error:

#

Disconnecting connId=0 to prevent exploits from an Exception in MessageHandler: NullReferenceException Object reference not set to an instance of an object

#

when i shoot a rigid body

#

this is my code

#

any help is appreciated

inland delta
#

Debug your variables to see which one is null

solar hawk
#

ok

#

i use mirror btw

solar hawk
#

what do i do now

undone coral
# eager sundial I want to find a way to make a kind of "red light / green light" game. The enemi...

the most advanced approach would be to pass the object ID AOV pass to gameplay on the next frame, and count the number of pixels visible in an object. https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@13.0/manual/Custom-Pass-Creating.html#object-id-custom-pass however this would be complicated for objects behind transparent objects - you would have to measure their contribution to the albedo of the image, which is harder

#

the efficiency of this approach depends on how well you understand how gameplay and rendering interact with one another

#

usually it only goes in one direction: gameplay --> rendering

#

most people instead use raycasts

#

you would raycast from the corners of a collider to the camera

#

really depends on the shape and quantity of objects in this approach

eager sundial
undone coral
tough knoll
#

I dont even have LFS

#

Just be careful not to pop that 100mb per-file limit

#

I have a ridiculous 20gb massive project with one gorillion files in it, and it's on git, and I commit multiple times a week. Never had a single problem. I didn't even modify the github provided gitignore that you got up there. You can literally not go wrong.

#

Every now and then I get a sprite sheet that's over 100mb, oops, split it into 2, it gets atlased anyways at runtime

#

i should say, it's on github

quartz stratus
tough knoll
#

i have all my assets in there even including the source .xcf layered files (•_•)

undone coral
#

github's lfs costs are too high. it's like $5/mo/5GB for every 5GB transferred 🙄

#

you will eat like 100GB of data working on stuff with other people in 2 days

undone coral
#

it is easier to use than bazel

regal olive
#

hi,
I have a question, I want to make a build THEN add in the directory an fbx file and read it and import the model to the current scene... what libraries would I need to use

novel plinth
#

not sure with fbx tho

grave fossil
#

So I was stupid enought to create event on a class which is not mono behavior....... And ended up with infinetly increasing events listeners. Is it possible to remove event listener from class that is not monobehavior. As it doesnt have ondestory, or on disable functions.

EventManager.stringUIButton.AddListener(OnStringSettingsButton);
        EventManager.boolUIButton.AddListener(OnBoolSettingsButton);
novel plinth
#

btn.onClick.RemoveListener(OnStringSettingsButton);

#

Optionally you can remove all
btn.onClick.RemoveAllListener();

#

the latter will throw if the event never assigned to it, so try-catch it

grave fossil
novel plinth
#

the fact that you keep adding the same event over and over kinda tell you that you should re-think the design

obsidian sierra
#

Does anyone know how a hinge joint calculates force?

#

i am getting joints that are breaking at velocities that shouldnt be able to break them

#

is there a way to print the force exerted? is it multiplied by something?

lilac viper
#

Hi guys quick question

#

How can I make my AI enter a vehicle and drive just like GTA?

stuck onyx
#

im trying to check if any of the Vector2Int are inside of a BIG HashSet of VectorInt and the operation takes 11.6 ms which in my context is way too much... I'm doing this:

myVector2IntHashset.Intersect(myVector2IntList).Any();

the hashset might have a maximum of 16384 entries
i thought by making it a hashset this kind of operations would be much faster but seems it still not enough... anybody knows how could i improve this?

fresh salmon
#

Have you tried the good ol' foreach for the list, and a bunch of hashSet.Contains calls inside?

#

Might be faster than using Intersect

#
foreach (Vector2Int val in list)
{
    if (hashSet.Contains(val))
        return true;
}
#

Update, HashSet has an IntersectWith method that is optimized, especially when intersecting 2 hashSets

novel plinth
#

your list is what making it slow in this case...

stuck onyx
#

i just read Overlaps might help too

novel plinth
#

how big is the List?

stuck onyx
#

the list might be just... 20 items as much

fresh salmon
#

Intersect is LINQ, which is inherently slow

#

Same with Overlap

novel plinth
stuck onyx
#

should i convert the small list into a hashset?

novel plinth
#

no

stuck onyx
#

or should i simply not use linq

fresh salmon
#

Try the loop, and the dedicated IntersectsWith methods

#

Compare the results and pick the most performant one

stuck onyx
#

okay, ill try

novel plinth
#

Just in case you don't know, Unity support fastspan now

lilac viper
#

Anybody?

stuck onyx
#

whats fastspan?

fresh salmon
stuck onyx
#

unity version 2022 ?

novel plinth
#

yeh

#

since 2021.3.x

stuck onyx
#

hmm, no chances now, ill try SRP2 approach

novel plinth
#

proly earlier than that

stuck onyx
fresh salmon
#

Sure, you could do that to boost perfs even more

stuck onyx
#

hmmm little problem:

fresh salmon
# lilac viper Bruh what is this server

Don't question the server, question yourself. You're asking something that is way too broad and cannot be reliably answered because it's lacking a lot of information.
Like how your AI is implemented, is it a homebrew, or an asset? Etc.

stuck onyx
#

seems i need to turn it into a inumerable

fresh salmon
timber flame
#

I do not know if it is related to this channel or not
Suppose there is a core package and several impl packages depending on the core package.
Also, a factory class exists in the core package. My problem is that this factory class does not know anything about implementation classes.
One way is to bring it out and add the factory class in the project itself and not inside packages (core/implementations). So, I should implement it for every project.
Because the factory has some methods which are common, another way is to define an abstract class with common methods in core package and then implement it in the project.
Another way is to inject that implementation types to the factory class. In this approach, factory class remains in the core package as well but inject dependencies (implementation types) from outside (project)
What is your suggestion?

placid shell
#

is there any easy way to interact with direct x in unity? (11 or 12 is fine)

tender light
# timber flame I do not know if it is related to this channel or not Suppose there is a core pa...

I mean. What is your question really 🤔 ?
All of these solutions have different properties. And depending on your use-case may or may not be the best ones.

One way is to bring it out and add the factory class in the project itself and not inside packages
Does not sound very nice. But in Unity it can be hard to avoid this if you are looking to re-use your internal library on multiple games. So it might be a valid solution,
another way is to define an abstract class with common methods in core package and then implement it in the project.
Sounds reasonable to me. But if you want to publish this as an asset that its a no-go. You don't want to force customers into implementing something they have no idea about.
Another way is to inject that implementation types to the factory class.
Sounds the best. Find your implementations through reflection or maybe some kind of scriptable object/serialize field with a type reference.

flint sage
#

To solve that I've created interfaces in a package with no other dependencies, so that it can be references by everything

#

We had DI to resolve the instance where needed but you can also solve that in different ways

native lintel
#

Im trying to make a bone system in unity where it creates a new bone on top of an already premade bone from an armature but i dont know how i would do this. Anyone got any ideas?

placid shell
native lintel
dire reef
#

Hi. I'm going to deploy my unity project on Azure, but don't know how cloud file system works. Could I create folders and load files with System.IO like on local machine?

devout hare
#

No. You'd have to use their API.

dire reef
#

Unlucky. Thanks for answer.

#

Is there any tutorials about Unity + Azure? I managed to find nothing but deployment guide.

wind gyro
#

Hi, not sure if this is the right channel, but is it possible to build / push docker images in the unity cloud build?

maiden turtle
#

I need help with ui rects. So my problem is that I'm trying to animate scrolling to a particular item in a scroll rect. I've tried tackling this problem before, wasted a couple of days and then gave up. I used to try doing this via normalized scroll amount. Now, I needed the same behavior and tried doing this again, with a different approach. On the internet, I've seen people kind of achieve this by setting localPosition of scrollRect.content. The code from the internet works, but it relies on default, and cannot be animated. Also, it would scroll even if the item is already visible. What I want, is to only scroll if the item is not already in view. So since there are no solutions on the internet, I had to try and tackle this problem myself again.

#

Here's what I've got so far

#
public static Vector3 GetPositionToScrollIntoView(this ScrollRect scrollRect, RectTransform child)
{
    var content = scrollRect.content;
    var viewport = scrollRect.viewport;

    var vrect = viewport.rect;
    var vsize = vrect.size;

    var crect = content.rect;
    var csize = crect.size;
    var clocal = new Vector2(crect.xMin, crect.yMin);

    var irect = child.rect;
    var isize = irect.size;
    var ilocal = new Vector2(irect.xMin, irect.yMin);

    var ileft = ilocal + clocal;
    var iright = ilocal - isize + vsize + clocal;
    
    Vector2 vstart_in_c = -clocal;
    Vector2 iposition_relative_to_start_of_v;

    {
        if (ileft.x > 0 && iright.x < vsize.x)
        {
            iposition_relative_to_start_of_v.x = ilocal.x - vstart_in_c.x;
        }
        // Off to the right
        else if (ileft.x > 0)
        {
            iposition_relative_to_start_of_v.x = vsize.x - isize.x;
        }
        // Off to the left
        else // if (iright.x < vsize.x)
        {
            iposition_relative_to_start_of_v.x = 0;
        }
    }
    {
        if (ileft.y > 0 && iright.y < vsize.y)
        {
            iposition_relative_to_start_of_v.y = ilocal.y - vstart_in_c.y;
        }
        else if (ileft.y > 0)
        {
            iposition_relative_to_start_of_v.y = vsize.y - isize.y;
        }
        else // if (iright.y < vsize.y)
        {
            iposition_relative_to_start_of_v.y = 0;
        }
    }

    var d = -ilocal + iposition_relative_to_start_of_v;

    var result = content.localPosition;
    var localScale = content.localScale;
    result.x += d.x / localScale.x;
    result.y += d.y / localScale.y;

    return result;
}
#

I've tried to use rect, because I cannot reliably use localPosition — it has some weird coordinates. It is not centered relative to the top left corner, I guess it takes the pivot and the anchored position into account

#

I thought rect would just give the top left aligned rectangle as seen from the parent's point of view - which it does not

#

Rect still uses either the pivot or the anchor, I can't figure out what

#

So what i'd like to have here is just a way to view a child's rect from the point of view of the parent, in their coordinates

#

Assume it's never going to be rotated

#

How do I do that?

#

Again: what I need at this point is a way to get a child's rect relative to its parent, that is, how it would be seen by the parent, without taking into account any anchors or pivots - it all should be relative to the top left corner of the thing

#

Right now the code has inexplicable behavior due to my wrong assumptions

deep peak
#

your easiest bet is to properly set anchors and pivots, and so everything will use their top left / top bottom (whichever you like) as their localPosition

maiden turtle
#

No this code should work for any pivots and anchors

#

All it does is it calculates offsets from one thing to another

#

And at the end it just adds the said offsets

#

To the local position

#

So it shouldn't matter what the pivots are

deep peak
#

well, i think unity still handles global positions of the items inside the scrollview too, so you can use RectTransform.GetWorldCorners

#

on the scrollbox, and the item, and compare those

#

you working with absolute world positions then

maiden turtle
#

Yeah that should work

#

I'll try

buoyant leaf
#

anyone here have luck with hooking up a juce plugin to unity?

regal olive
#

Hi there, i am developing a game for android and since upgrading to unity 2021.3 i am experiencing very long startup times. Profiler tells me its Resource.Load that takes so long, but i am not even using this myself, just 2 Plugins use this, Ironsource and TextMeshPro. Is someone of you also experiencing this or has a clue, how to fix this?

#

For just loading one scriptable object it takes 10sec+

buoyant leaf
#

how are you loading these objects?

regal olive
#

What do you mean by this? They are getting loaded with the Resource.Load function

tender light
sly aurora
#

How can you make breakpoints work in unity?

tender light
sly aurora
#

they don't for me
i have it selected it and it's working for any other type of project asp.net/console, but not in unity

regal olive
tender light
deep peak
undone coral
tender light
#

No... thats bs actually... unless they write directly into it the asset database should handle that...... hmm

undone coral
#

if it's happening in editor

undone coral
undone coral
# dire reef

based on this, you are only taking the first steps on a very long grand journey

undone coral
maiden turtle
deep peak
#

haha, rects and ui can be complicated

maiden turtle
#
public static Vector3 GetPositionToScrollIntoView(this ScrollRect scrollRect, RectTransform child)
{
    var content = scrollRect.content;
    var viewport = scrollRect.viewport;

    static (Vector3 origin, Vector3 x, Vector3 y) D(RectTransform t)
    {
        Vector3[] fromWorldCorners = FromWorldCornersCache;
        t.GetWorldCorners(fromWorldCorners);

        return (
            // top left
            fromWorldCorners[1], 
            (fromWorldCorners[3] - fromWorldCorners[0]),
            (fromWorldCorners[1] - fromWorldCorners[0]));
    }

    var (vpos, vwidth, vheight) = D(viewport);
    var (ipos, iwidth, iheight) = D(child);
    var (cpos, cwidth, cheight) = D(content);

    var vsizevec = vwidth + vheight;
    var isizevec = iwidth + iheight;

    // make sure the vectors are colinear
    var x = vwidth.normalized;
    var y = vheight.normalized;

    {
        const float epsilon = 0.01f;
        assert((x - iwidth.normalized).sqrMagnitude < epsilon);
        assert((x - cwidth.normalized).sqrMagnitude < epsilon);
        assert((y - iheight.normalized).sqrMagnitude < epsilon);
        assert((y - cheight.normalized).sqrMagnitude < epsilon);
    }

    var vsize = new Vector2(Vector3.Dot(vwidth, x), Vector3.Dot(vheight, y));
    var isize = new Vector2(Vector3.Dot(iwidth, x), Vector3.Dot(iheight, y));
    var csize = new Vector2(Vector3.Dot(cwidth, x), Vector3.Dot(cheight, y));

    var ileft = (ipos - vpos);
    var iright = (ipos - isizevec - vpos + vsizevec);
    
    Vector3 desiredOffsetRelativeToStartOfV = Vector3.zero;
#
{
        var ileftx = Vector3.Dot(ileft, x);
        var irightx = Vector3.Dot(iright, x);

        if (ileftx > 0 && irightx < vsize.x)
        {
            desiredOffsetRelativeToStartOfV += Vector3.Scale(ipos - vpos, x);
        }
        // Off to the right
        else if (ileftx > 0)
        {
            desiredOffsetRelativeToStartOfV += vwidth - iwidth;
        }
        // Off to the left
        else
        {
        }
    }
    {
        var ilefty = Vector3.Dot(ileft, y);
        var irighty = Vector3.Dot(iright, y);

        if (ilefty > 0 && irighty < vsize.y)
        {
            desiredOffsetRelativeToStartOfV += Vector3.Scale(ipos - vpos, y);
        }
        else if (ilefty > 0)
        {
            desiredOffsetRelativeToStartOfV += vheight - iheight;
        }
        else
        {
        }
    }

    var oldContentPos = cpos;
    var newContentPos = desiredOffsetRelativeToStartOfV + vpos;
    var contentWorldToLocal = content.worldToLocalMatrix;
    var oldContentPosLocal = contentWorldToLocal.MultiplyPoint3x4(oldContentPos);
    var newContentPosLocal = contentWorldToLocal.MultiplyPoint3x4(newContentPos);

    return newContentPosLocal - oldContentPosLocal;
}
#

Idk, I'm sure I'm missing something obvious in this code

#

Hey, did no one really ever implement this? Did everyone just give up?

deep peak
#

lemme check the code

maiden turtle
#

I feel like you've gotta need this functionality for half the games

#

It's a very common thing to need I feel like

deep peak
#

so again, you want to animate-scroll the scrollview to an item in the scrollview?

maiden turtle
regal olive
undone coral
#

a viewer? for what?

#

you can use trilib to load FBX files at runtime, but i am confident there is something else to this you haven't told me yet (for some reason) because you surely found that

regal olive
# undone coral a viewer? for what?

just a viewer, i want someone to be able to be able to make several 3d objects (on any platform), and during game play to use those files (put them in a specific directory and then read them and use them)

regal olive
undone coral
#

like give an example

#

you're beating around the bush here

#

what is this really?

regal olive
#

a mix of robot and 3D printer

#

🤓

undone coral
#

you can use this

#

should suit you well

undone coral
#

it's a good scroll view

undone coral
#

@maiden turtle you can go to the discord listed there and search if it supports scrolling to

#

i think it does

#

but i use so many things across so many platforms i don't remember

maiden turtle
#

I'm not going to be paying for a scroll to item function lol

#

Thanks for the link, but it's not free, so no

undone coral
#

oh there we go

#

excellent.

#

it's a pretty great asset if your game has a massive scroll view

#

i used it in my card game collection view

#

tons of text on cards, huge number of cards

#

it worked well

crude isle
#

Im going a little crazy here. I'm creating a .cs file from code and saving it to my project with a custom editor. That class inherits from another class that inherits from ScriptableObject. I'm trying to create an instance of that ScriptableObject and save it to the AssetDatabase like usual... but its not recognizing my .cs type as deriving from ScriptableObject. Any thoughts?

deep peak
#

are you sure the FileName is the same as the scriptableobject's class name?

crude isle
#

yes I triple checked the names and stuff. I'm using the same variables to create the class and passing them into the ScriptableObject.CreateInstance method. Its giving me the "doesn't inherit from ScriptableObject" error.

flint sage
#

Show code

crude isle
#

how do I format the code properly?

deep peak
#

wrap with ```

crude isle
#
        public void Create()
        {
            string classFilePath = Application.dataPath + BaseStatsPath + StatClassPath + statName + classSuffix + fileExtension;
            string fullAssetFilePath = Application.dataPath + BaseStatsPath + StatAssetPath + statName + classSuffix + assetExtension;
            string localAssetFilePath = BaseStatsPath + StatAssetPath + statName;

            if (!File.Exists(classFilePath))
            {
                File.WriteAllText(classFilePath, GetClassFileString());
                AssetDatabase.Refresh();

                if (!File.Exists(fullAssetFilePath))
                {
                    var statAssetInstance = ScriptableObject.CreateInstance(statName + classSuffix);
                    if (statAssetInstance == null)
                    {
                        Debug.Log("Instance is Null");
                    }
                }
            }
        }
        private string GetClassFileString()
        {
            StringBuilder builder = new StringBuilder();

            builder.AppendLine();
            builder.AppendLine("using UnityEngine;");
            builder.AppendLine();
            builder.AppendLine($"[CreateAssetMenu(menuName = \"Statistics/{statName}\", fileName = \"{statName}_ID\")]");
            builder.AppendLine($"public class {statName}_ID : StatID");
            builder.AppendLine("{");
            builder.AppendLine($"    public override string StatName => \"{statDescription}\";");
            builder.AppendLine("}");

            return builder.ToString();
        }```
#

damn thats still ugly

flint sage
#

What's classSuffix

#

And what's StatId

crude isle
#

classSuffix is just a string that equals "_ID"

flint sage
#

I'm guessing, it hasn't recompiled the changes yet before trying to create an instance

#

and thus it doesn't exist

fresh salmon
#

(Please use Path.Combine (System.IO) to combine paths proprerly)

crude isle
#

its added to the end of each stat name. The StatID is the inherited class that inherets from ScriptableObject

#

Hmm yeah maybe it's not compiling the type by the time I try to create the asset.

#

@fresh salmon Ahh didn't know that existed, thanks.

#

I was hoping AssetDatabase.Refresh would force it to compile but I really have no idea. Haven't messed around with I/O or the AssetDatabase api much.

maiden turtle
undone coral
maiden turtle
#

yeah

odd veldt
#

calling c++DLL causes stackoverflow, when I pass in a big array

#

unsafe public static extern void Func([In, Out] MyStruct[] destination);

#
[StructLayout(LayoutKind.Sequential)]
  unsafe public struct MyStruct
  {
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
    public int[] a;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 126 * 3)]
    public byte[] b;
  };
#

I tried the function to be a empty function, still crash

undone coral
#

you simply cannot do that

hasty hinge
#

ok i have to ask this here bc is kinda next level of bullshit

how should i open Unity without internet and VPN!

sly aurora
#

I am implementing an inventory system that uses a List to hold the objects
and a Dictionary<Object, int>
to hold non unique items that can be repeated
Like wood
am I overcomplicating things?
also, i tried using a Hashtable, but I can't do any process on the value, because it's identified as an object

#

like if a player is trying to drop 1 wood
it wont let me go do Table[wood]--;

deep peak
#

this might be a different thinking that you do about inventory item/storage

#

but if the item is stackable, and have no unique properties, then Wood1 and Wood2 is technically the same, even if they have different id

#

so you can just use 1 wood, with an "amount" int field

#

and when you split then, you make 2 items out of 1, so if you have 2000 wood, you dont need 2000 separate object

sly aurora
#

@deep peak
that's what im doing in the dictionary

#
public void AddItem(Item item)
    {
        if (item.isUnique)
        {
            //add to list, dont pay attention to repetition
            //it won't repeat
            items.Add(item);
        }
        else
        {
            //if it's in table, just increase its count in table, it already exists in my list
            //if it's not in table, add it to list & add it to table
            if (table.ContainsKey(item))
            {
                table[item]++;
            }
            else
            {
                items.Add(item);
                table.Add(item, 1);
            }
        }

    }

    public void DropItem(Item item)
    {
        Item dropped = items.Find((x) => x.id == item.id);


        if (!item.isUnique && table[item] == 1)
        {
            table.Remove(item);
            items.Remove(item);
            Instantiate(dropped, droppingTransform);
        }
        else if (item.isUnique)
        {
            items.Remove(item);
            Instantiate(dropped, droppingTransform);
        }
        else
        {
            table[item]--;
            Instantiate(dropped, droppingTransform);
        }

    }
deep peak
#

i see, no problem then, though with this you cant have 2 separate stacks of wood in the inventory

sly aurora
#

I can
I actually did this way
so when I call the ShowInventory function
it seperates them into stacks based on how much in a stack
and the name of the item

deep peak
#

perfectly fine then, this isnt overcomplicated at all

sly aurora
deep peak
#

i would still store the item in the list to be consistent

#

and find the same item inside the list, and stack that

undone coral
hasty hinge
undone coral
wet ice
#

Hey All, I am trying to figure out the best way to render say 10,000 cubes and have them animated up and down with perlin noise. At the moment I am leaning towards using DrawMeshInstanced because I know how to do this. I was also considering using Dots/ECS or maybe going more a shader route, basically the same perlin code but acting directly on a large mesh's vertices (as if it was a bunch of cubes). Do you have any recommendations?

sly grove
#

10,000 will be a breeze

#

depending on what you want a simple vertex animation shader could work too with normal MeshRenderers

wet ice
undone coral
#

which emits the compute shader for you

wet ice
#

Oo yeah I was thinking about that as an option as well, thats the one tool I havn't dived into yet its probably about time

undone coral
#

there are multiple moving rods samples

#

oops

deep peak
sly grove
deep peak
#

or that

placid violet
#

Is there any way to stream the output of a Camera to bytes/across the net?

deep peak
#

you can render the camera into a RenderTexture, you can read its native data and do your thing

undone coral
placid violet
placid violet
undone coral
#

i also do a unity streaming thing

placid violet
#

assembly
What the fuck

undone coral
#

you can look at this package and try to understand it and how to use it

#

there's also UnityRenderStreaming, which is more complete examples

#

good luck

placid violet
#

Well

#

You can’t make an omelette without breaking some eggs

#

Thanks man!

placid violet
#

@deep peak what do you mean about the render texture?

deep peak
frozen prawn
#

Hey all, I'm getting a really weird error with the Action delegate:
I'm trying to make an interaction system to handle the priority of different raycasts for different actions.

Here is the code for the interactionservice raycast:

    public void PhysicsRaycast(int priority, Ray ray, float range, int layerMask, Action<RaycastHit> callback)
    {
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, range, layerMask)) {
            raycastRequests.Add(new RaycastRequest(priority, callback, hit));
        }
    }

Here is the code which uses the interactionservice:

handleCallback.interactionService.PhysicsRaycast(2, ray, Mathf.Infinity, onlyHit, (RaycastHit h) => Debug.Log(h));

However, instead of printing the raycasthit, it gives me this error

#

I checked through all of the values and all of them are defined.

#

FFS i forgot to initialize raycastRequests, rubber duck moment

#

🤦

timber flame
# tender light I mean. What is your question really 🤔 ? All of these solutions have different ...

Core package

public interface SomeInterface{}
public class Factory{
  public SomeInterface Create(TypeA type){
    // create the specific implementation based on type but there is no implementation in the core package
  }
  private void SomeMethod(){}
}

Impl package1

public class ImplPackage1 : SomeInterface{}

Impl package2

public class ImplPackage2 : SomeInterface{}

My suggestions
1- put factory class in the project not core package.
2-

// Core Package
// Implement an abstract factory class
public abstract class AbstractFactory{
  public abstract SomeInterface Create(TypeA type);
  private void SomeMethod(){}
  //...
}

3- Inject dependencies from outside to the Factory

// Core Package
public class Factory{
  public Factory(Dictionary<TypeA,SomeInterface> _instances){}
  public SomeInterface Create(TypeA type){
     //...
     return ;
  }
  private void SomeMethod(){}
  //...
}
#

Reflection is the best to find all related types and instantiate automatically. Thanks
but does the core package have access to other impl packages? No. It is independent and has different asmdef
How can the core package (core asmdef) find impl types in other packages (impl1, impl2, etc. asmdefs)

undone coral
#

i vaguely remember

#

or making a plugin thing?

timber flame
#

You suggested to use reflection to find all implementation types implementing an interface

#

The interface is in a core package

#

but impl types are in different packages

#

Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
?

undone coral
#

it's actually really easy to make a plugin thing:

the plugins:

internal abstract class PluginBase : MonoBehaviour
    {
        internal const string pluginResourcePath = "(Plugin Resources)";

        internal static void EnsurePlugins()
        {
            var existingPlugins = FindObjectsOfType<PluginBase>();
            if (existingPlugins.Length != 0)
            {
                return;
            }

            var pluginPrefabs = Resources.LoadAll<PluginBase>(PluginBase.pluginResourcePath);
            foreach (var pluginPrefab in pluginPrefabs)
            {
                var gameObject = Instantiate(pluginPrefab);
                gameObject.name = gameObject.name.Replace("(Clone)", "");
            }
        }
    }
}

public class MyPlugin : PluginBase {}
#

in the application:

EnsurePlugins();
#

then, when you want to make something that plugs into unity, add a prefab with the MyPlugin component on it to a well-known "Resources/(Plugin Resources)" folder

#

that's it

#

does that make sense? @timber flame

#

you can also use RuntimeInitializeOnLoad, but that is harder to get working with il2cpp

#

the approach you have right now is extremely painful to make work with il2cpp

#

the reason this works is... unity already has dependency injection, factories, etc.

#

it's the component model

timber flame
#

Thanks, I can find all assemblies

Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
#

It is OK for me to find all implementation types in different packages

undone coral
#

out of the box

#

it's going to barely work in mono

#

what's the objective?

#

like what are you trying to achieve?

undone coral
willow lantern
#

Can anyone lend a hand in how to save the update to my prefab instance? Everything i've read says this should be working but it doesn't. Though all the examples i've seen aren't updating child objects on the prefab so there may be an issue there

humble onyx
#

In the example i found

 gameObject.transform.localScale *= 2;

was changed
and
to save it they call

  PrefabUtility.RecordPrefabInstancePropertyModifications(gameObject.transform);

so not the gameobject but the component that actually did change

willow lantern
#

i have tried multiple things such as tile, tile.transform, tile.gameObject

humble onyx
calm ocean
#

I could use some design decision advice. I am working on a game with a team, and they have made public static variables in a class so that those variables can be accessed and re-assigned on a global scope without needing an instance. Is this bad design?

I feel like it is because it is hiding dependencies and going against the interpretation of what "static" means. It's like we are using static to convert the class to a semi-singleton. But at the same time, the code works and we have the benefit of not matching up dependencies via the inspector. Thoughts?

odd veldt
#

or how to increase the stack size?

willow lantern
orchid sedge
#

hey just wanted to ask about the unity's integrated networking, can you make it so that I can make players make their own accounts?
or can't I do it?

wet burrow
#

I'm learning about Unity's IAP package but the documentation is pretty crap. From what I've gathered you want to use the IAPButton component to have something that the player clicks to make a purchase, but I can't reference it in code.
I added the namespace 'UnityEngine.Purchasing' to my script, and I made sure to get the exact name 'IAPButton', but it's not recognised and gives me a 'does not exist in the current context' error.
What am I doing wrong?

woven kettle
#

hi ,

I need to get the velocity of a projectile with ridgidbody after a certain deltatime , how to do that ?

wet burrow
woven kettle
# wet burrow as in predicting the velocity of the rigidbody after a period of time?

yeah, I'm dealing with a complex scenario were a projectile hits something that is not supposed to hit, so to fix that I've add a function to reapply the correct velocity bk after the incedent.
i tried to store the velocity before the issue but I got no luck, I always hit the object and get the rebounce velocity instead.

so I thought of running a delta time as the projectile travels and save how long it has been traveling and when I want to reset the velocity, I could just predict what would be the object velocity after that period of time and let it fly.

wet burrow
woven kettle
#

as far as I know it's just velocity*gravity/deltaTime, or something like that.. I'm not tottaly sure.

wet burrow
#

then use a for loop to simulate it over a bunch of 'frames'

woven kettle
#

predicting a trajectory, after certain time, it would have a certain velocity

undone coral
#

you can also use Spans

undone coral
#

a singleton you can control its initialization whenever you want

calm ocean
undone coral
#

well what's the goal

#

same one as before?

#

i wouldn't touch it

#

it's small beans

plucky laurel
#

Is there an alternative to unity's test runner that doesnt require asmdefs?

timber flame
#

Each concrete (implementation) type is in a different package.
A factory and interface is in a core package. I want to find all impl types in that factory and after instantiation return it based on type argument.

placid shell
#

not very familliar with how direct x 11 works with unity, so perhaps someone could correct me if i'm wrong, but as far as i know unity uses a ID3D11Device to interact with direct x 11 right? Is there anyway to get access to this via code?

humble onyx
# placid shell not very familliar with how direct x 11 works with unity, so perhaps someone cou...
GitHub

Implementation problem for render view in directx as a native plugin for unity - Unity-DX11-Native-Plugin-Texture-Clear/IUnityGraphicsD3D11.h at master · darshanshankar/Unity-DX11-Native-Plugin-Tex...

humble onyx
#

(not tested but looks worth a shoot)

placid shell
#

ill definitely try it, thanks a ton!

#

lacks documentation which is a tad annoying, and ive never used a native plugin without a dll, but i'm sure ill eventually work out how to get it working!

#

ooh from further research i could try using dx sharp, although cause nuget doesn't work with unity i would have to manually import it and get it working

flint sage
#

Wouldn't DX# give you a new context and not the same one Unity is using?

novel plinth
#

he doesn't even know what dxsharp would do to his game/project

placid shell
novel plinth
#

I mean, like I said the other day, you've been dabbling with this lowLevel stuffs blindly...

placid shell
#

yes, but the more i dabble the more i learn, it is fun, even if it seems pointless, i am learning slowly but surely

novel plinth
#

aight, carry on!

placid shell
#

lol

rapid flume
#

I had this variable for a long time, I was just going through my variables (idk why) and thought of automating the process of getting all the gunitems in my project, because adding manually is not a big deal but I am lazy so pls help

novel plinth
#

that literally nothing 😃 ...

rapid flume
novel plinth
#

you're asking for help, but didn't give any details of what you're trying to do other than just posting an array, thus literally nothing

rapid flume
novel plinth
#

then filter it based on your condition

rapid flume
rapid flume
obsidian glade
undone coral
#

it is negative ROI

#

it's a ton of work for

#
// the literally four classes
void BaseXrPlugin[] GetPlugins() {
 var availablePlugins = new [] {
  new NullPlugin()
#if XR_PLUGIN_OCULUS_QUEST
  , new OculusPlugin()
#endif
#if XR_PLUGIN_HTC_VIVE
  , new HtcVivePlugin()
#endif
 };
 return availablePlugins;
}
#

and you use the asmdefs and that's it

#

the asmdefs can export the symbols correctly and your code can be aware of what the project is using

#

you know ALL THE TYPES AHEAD OF TIME

#

so you never need to look through the assemblies

#

you would NEVER load this stuff at runtime. it will NEVER work

#

and there is NO reason for it. anyone who asks for that is wrong

undone coral
#

it is kind of complicated to access the graphics devices on unity

#

if you only want to support directx11, it doesn't make things that much simpler - you'll still want to make a cmake project, import the right stuff, etc. etc.

timber flame
#

One person suggests reflection and says it is not perfect to force a project to know or add/change some stuff to use that package

undone coral
#

reflection makes sense when you don't have all the source and you don't have all the types ahead of time

timber flame
#

but for me, it is completely OK and elegant to define some symbols and let that project add those symbols

undone coral
#

in this case you do

timber flame
#

@undone coral Appreciated

undone coral
#

yes a unity package can automatically add those symbols based on what assemblies are loaded

#

in the editor

#

those are the scripting defines in the asmdef inspector

#

the reason only unity does this is because typically, in a video game, you control all the source

#

you're trying ot make a something something xr plugin framework right gladiator?

#

an even simpler thing to do is

in the core package:

internal static ISet<BaseXrPlugin> plugins = new HashSet<BaseXrPlugin>();

in a plugin package:

[RuntimeInitializeOnLoad(...)]
static void Init() {
 plugins.Add(new OculusPlugin());
}
timber flame
#

My exact scenario is defining different video ad platforms and let a project decide which one it wants to use
the core package contains all interfaces, factory and some utility classes.
Each video ad platform has its own package

undone coral
#

which is still, essentially, a serviceloader

undone coral
#

because it will correctly and gracefully handle video ads platforms going out of business 🙂

#

if this is meant as a library for other people to use

#

i would hide the concrete types from them

#

and think extremely judiciously about how to expose more functionality down the line

#

generally hte end user should receive an interface

#

like

#

they should receive an IAdsServices

#

and access it via a static and that's it

#

and if you want to add more functionality later down the line

timber flame
undone coral
#

define another field inside ads service that is itself an interface of a collection of methods

#

don't keep making 1 thing bigger and bigger

#

so

timber flame
undone coral
#
interface IAdsService {
 IHeaderBiddingConfiguratorService headerBidding { get; }
 IUguiRectDisplayService uguiRectDisplay { get; } 
}
#

if you want to later support awards

#
interface IAdsService {
 IHeaderBiddingConfiguratorService headerBidding { get; }
 IUguiRectDisplayService uguiRectDisplay { get; } 
 IAwardsService awards { get; }
}
#

the reason to do this this way is you don't want to ever change the types of something the end user sees, especially an interface

#

because you have no fucking idea how they're going to use and abuse it

#

and then the gateway to your thing should be

#
IAdsService adsService = AdsServices.defaultAdsService;
// later
IAdsService adsService = AdsServices.testAdsService;
#

do you see why? people don't want complexity

#

they're too dumb

#

so make it simple

#
AdsService
 .defaultAdsService
 .uguiRectDisplay
 .AddVideoDisplayComponentsTo(rectTransform);
#

if they use a plugin they should have tyuped configuration int he plugin

#
VungleConfiguration.instance.vungleKey = "abcdefgh...";
#

and that's it

#

you need to support configuration at any time

#

you can make a "Vungle Configuration" prefab to drag and drop with a field that sets the code field for the user on Awake

undone coral
#

the original method i showed where the core is fully aware of the packages is best

#

it also lets you deal with idiosyncracies

#

for example two separate packages might add different versions of the same ios framework

#

or both might add System.CompilerServices.Unsafe

#

and you have to deal with that specially

#

does that make sense @timber flame ?

#

so it's unavoidable. they're not really separate packages (in the long term)

timber flame
#
 public class AndroidVideoAdFactory : IVideoAdFactory
    {
        private readonly Dictionary<int, Func<AdUnitIds, VideoAdvertisement>> _dictionary;

        public AndroidVideoAdFactory()
        {
#if VIDEO_AD_TAPSELL
            _dictionary.Add(VideoAdPlatform.Tapsell.Value,(adUnitIds)=>new TapsellAdvertisement(adUnitIds));
#elseif VIDEO_AD_ADMOB
            _dictionary.Add(VideoAdPlatform.Admob.Value,(adUnitIds)=>new AdmobAdvertisement(adUnitIds));
#elseif VIDEO_AD_DEEMA
            //...
#else
            //...
#endif
        }
undone coral
#

just don't call it a factory lol

timber flame
#

I think your another suggestion is better

undone coral
#

okay

#

yes this all works

#

like you shouldn't have a public class with the name factory in it

#

if this is meant to be used by other people

#

adUnitIds i wouldn't do that either

#

you don't want constructors with arguments

#

you have to support configuration at any time

timber flame
#

because in the above approach, the core package should know about implementation types and if impl packages change them, it should be updated as well

undone coral
#

yes

#

it has to

#

because it will need to in order to fix bugs when two packages otherwise cannot really interact wiht each other

#

i wouldn't use elseif though

#

because surely you mean to support multiple vendors

timber flame
#

but if they introduce themselves and add them to that static list, it will be perfect

undone coral
#

all i'm saying is that on il2cpp

#

runtimeinitializeonload

#

is very problematic

#

so problematic i stopped using it

#

i used to do that approach for my plugins

maiden turtle
timber flame
#

I think I do not need to have Init method and RuntimeInitializationOnLoad in every package to add.
Every project should add them to that list. It is OK.

   VideoAds.Configure(_requiredVideoAds);
maiden turtle
#

Unity's coordinates are flipped, which threw me off before. Y usually increases downward, but in Unity it's the other way

#

That messed up my math yesterday

undone coral
#

that's surprising to me

elder compass
#

Has anyone got any suggestions for quickly and effectively learning Advanced C# for Unity game development? I need to learn how to program in Unity in a year.

regal olive
#

@elder compass I do not know of such shortcuts a year sounds like a very reasonable estimate even without advanced strategies.

elder compass
#

Really?

#

Do you know any resources for learning advanced C# from beginner?

regal olive
#

Brackeys used to be the go to source for me before learning to read documentation and making small games.

#

Brackeys retired tho.

upbeat path
fresh salmon
#

If that's just knowing how classes work and how you make them communicate, 1 year is definitely enough

upbeat path
#

He's talking about advanced C#, so I guess he knows that already, but learning all of the Unity APIs in 1 year?

sly grove
#

"advanced" is pretty relative and subjective though

fresh salmon
#

Nobody knows the whole Unity API lol

regal olive
#

There are of course variations between peoples learning speed.

upbeat path
#

Think about it, going from nothing but C#, how much of Unity did you know after 1 year

fresh salmon
#

I made the mistake of starting C# with Unity

#

Stopped and went back to regular C#, I don't remember how long it took to re-learn Unity afterwards, but definitely less than a year, on and off

#

They're starting from scratch though

I need to learn how to program in Unity in a year

#

So in this case a year would be a reasonable delay to be decent at both

upbeat path
#

you miss the
'learning Advanced C# for Unity game development'
so I guess they already know c#

#

even so if you have no game dev experience and no knowledge of Unity then 1 year is not going to be enough to be proficient

fresh salmon
#

They need to learn both, posted a few hours ago:

#

So probably more than one year to be proficient

upbeat path
trim raven
#

so im making a reloadable gun in vr and im following the tutorial from valmen on the gun but this script he made isnt working for me anyone know why?

fresh salmon
#

This step is required in order to get help here.

trim raven
#

i do have the unity package

fresh salmon
#

Read the guide, that's not all there is to it

#

There are a few steps to do in both VS and Unity's settings.

trim raven
#

oh

#

ok

azure sonnet
#

Hey, is there any solution to avoid freezing the game while watching ADS? (UnityAds). When user is watching ad the game is "suspended" and nothing is doing in the background and when user will close the ad or finish its starting from the place where user started watching the ad

trim raven
fresh salmon
#

Make sure you switched the display from "In Project" to "Unity Repository" with the button top-left

elder compass
upbeat path
elder compass
#

Ok

regal olive
#

Ful-time or part-time?

elder compass
upbeat path
#

full time

deep peak
#

that's if you actually using it for stuff, not just doing tutorial for 2 years

upbeat path
thin mesa
# elder compass Could do recommend any good resources?

if you like books, i recommend the C# Players Guide by rb whitaker. it will get you to understand the basics. then from there learning is basically a choose your own adventure where you need to decide what you want to learn and find relevant resources for that

fresh salmon
trim raven
#

k

upbeat path