#archived-code-advanced
1 messages · Page 4 of 1
I need all Start() methods to be completed
yes this will do that, since all the other starts will happen in the first frame
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();```
Yeah, my current project is killing GC in the profiler
I think that is a much better idea tbh.
I would just use script execution order
That's an option too
Ok then I'll go with disabling the script after it occurs once so it doesnt constantly check
Thanks a ton!
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
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
https://docs.unity3d.com/Manual/OptimizingGraphicsPerformance.html good starting point
thanks!
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
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
i would search for a ray wenderlich tutorial about it 🙂
i'd just start making stuff and profiling it, second hand knowledge is always wrong or irrelevant to your actual project
usually i say "Timeline" for audio
but is timeline appropriate for like, an animation rig except for sound effects?
thanks @undone coral and @compact ingot
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
add some indexing for your data if you haven't done so already
This might be overkill for your needs but FMOD provides a bunch of ways to mix audio dynamically to do this kind of thing
I don't actually use it but people keep recommending it to me over and over
well right now i'm prepping everything in audacity
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
Yea
but you're saying this is just how it goes?
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
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?
It has it's own audio engine
fudge
Why is that an issue?
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?
there are lots of ways to signal between threads. i like to use unitask for all of my between-thread stuff
woah this intrigues me. thankls
just how it be
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
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
yes, i prepared the audio files now
and prepped the files for looping
i figure i can do the crossfade between two one-shot clips by animating the volume
well i figured if i "animate" the volume property on the audio source
it will just work
in terms of transitioning between two clips
but maybe i'm wrong
Feels high-maintenance tho
i only have 3 audio files lol
true
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
Search across a half million git repos. Search by regular expression.
unbelievable
this leads me to believe this is the wrong approach
Yeah, all the stuff you're describing is what I expect from audio middleware. You're really talking about FMOD's bread and butter
Anyone know anything about ScriptedImporter? Specifically fileIDToRecycleName vs internalIDToNameTable? Or maybe the new TextureImporter?
DOTSNET or NetCode for DOTS? Which one is better for MMO game?
oh god. i have no idea about this stuff. what is the simplest way to execute commands in the main thread?
in unitask it is easy:
// anywhere
UniTask.Void(async () => {
await UniTask.SwitchToMainThread();
// here, you are now on the main thread
});
what is unitask and how do i use it?
oh no
Has anyone implemented a hitbox/hurtbox/pushbox system for a 2d sprite game before? I read this article https://strangewire.blogspot.com/2018/05/hitboxes-and-hurtboxes-in-unity.html but not sure what workflow you would use to edit the bounding boxes for each frame of each animation
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
is there a pre-existing property drawer to select animation parameters / does odin have one?
Is it possible to set it to use local servers instead of Unity's cloud servers?
you can make your own build automation but that by far more difficult the using unitys officical service
no
simple thing to do with factory
await Task.Factory.StartNew(async () => await SomeFunc(someParam), token, TaskCreationOptions.LongRunning, yourUnityContext);
making your own thread dispatcher still the way to go, and it's not hard to make one anyway
usually, in videogames, do developers use a gizmo function to make an attack hitbox? To limit the range of the attack
a gizmo function?
gizmos would be used to visualize things in a debugging context, but the actual hit determination would be via physics queries such as Physics.OverlapBox or colliders
Ohhhhh
That makes much more sense
And that's standard, I mean the physics overlapBox
?
not sure what you mean by "standard" here
As in there are no other ways of doing this,or like it's the most commonly used thing for this type of thing
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
what is the using statement to access the Rig Builder in code
what namespace is rig builder in?
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?
is there a git plugin for unity that lets me right click on a field and click "revert" to go back to staged changes?
is there any way to extract root motion from animation clips and use it to move character without animator?
plastic scm
why would you do that
Networked game with authorative server
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
can you narrow it down to the specific particle system?
i mean, i have alot of torches that are visable at once
that use a particle system
Is it possible?
No idea, sorry
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?
is this 2D?
In 3D,
so how do you only look at something on one axis?
oh easy
Vector3 pointToLookAt = target.position;
pointToLookAt.x = transform.position.x;
transform.LookAt(pointToLookAt);```
Is it also possible to use Quaternion.RotateTowards or just a smoothing on it?
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);```
how so
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
oh you need to translate the position to local space
then do this
and do local Rotation
pointToLookAt.x = transform.position.x;
Quaternion targetRot = Quaternion.LookRotation(pointTolookAt - transform.position); <-- this one?
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRot, TIme.deltaTime * degreesPerSecond);```
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
Yea this worked.
Quite a lot of work for such a small change
😅
Still acting a bit wierd
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);```
okay so instead of "rotate only on x" you mean "only pitch" right?
Correct
you only want the canon to pitch up and down, such that it points, essentially, at the height of any point
Yes,
and you want to move this point around, and you want it to gracefully animate between these rotations
Correct.
okay, you will need separate hierarchy for pitch, yaw and roll, just like a real cannon
the local rotation in euler will "make sense" to you, in the sense that it will be x = pitch
I want that base to rotate on Y axis
you have to name them the real thing
barrel only on x pitch
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
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?
it depends on what kind of behavior it's supposed to have
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
So, this is the base I'm a rotating
and this is already looking at the correct position
if you don't need it to feel physical, you rotate the base and barrel separately, and it should just work
but the barrel should look at the height
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?
No not really, it's and automatic gun.
it can start and stop instant
Are you rotating the base first or the barrel first
Base first,
ok part of the problem may be my code above assumes that the base is rotated instantly I think
Hmm, even when I put the code infront it acts the same
you still need help with this? (edit: seems like it solved, im off then)
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.
does unity not do timezones...
Not as far as I know. I use https://nodatime.org/ in Unity projects for timezones, it works like a charm
do you do the nuget unpacking thing to use this?
hmm let me check real quick, i imported it a while ago
Okay, yeah I downloaded the nuget package https://www.nuget.org/packages/NodaTime and extracted the .dll. I did the same with its one dependency package, System.RuntimeCompilerServices.Unsafe https://www.nuget.org/packages/System.Runtime.CompilerServices.Unsafe/. I think I just used the .NET Standard DLLs for both.
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
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.
seems like you need to read https://docs.unity3d.com/ScriptReference/Mesh-bounds.html
from the meshes inside the object, and calculate new bounds that can wrap all meshes inside one collider
https://docs.unity3d.com/ScriptReference/Bounds.Encapsulate.html
You can encapsulate the bounds of each child mesh
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.
database for the game itself for game stuff like enemies and weapons, or for game server?
well in this case a high score. but yes at some point a game server too.
Like global high score?
Yes: to compete with other users. I have a local high score set up by storing data using BinaryFormatter and FileStream
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
web API to read local high scores? and display them globally?
Honestly you're probably better off using an existing service for stuff like high score
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
What components does your player have?
What components does the platform have?
How are you moving each?
currently the platform is a quick test and it just has a box collider and thats it, it is moving by just setting the transform based of a sin function and mid point
player controller is using a character controller that is kinda modified to simulate forces from a rigidbody, this is being moved by CharacterController.Move()
well... that kinda janky setup is the issue
understandable
this isnt necessary for what im doing but do want a decent character controller for the future
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
just normal update for both
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
i could see that being it ill do alil digging into that thanks
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.
Is it possible to play a single animation without animator controller?
AnimationClip
you could us the legacy Animation component
Is it safe to use the legacy animation component? is the performance ok?
Oh xD my bad, just noticed that
Based on some Unite talks, the legacy Animation component is more performant when dealing with simple animations
I can try to find the specific Unite talk, but I remember that pretty clearly
It's fine I'm sure
Here's the timecode in the Unite Berlin 2018 talk where they break down test results between the Animation and Animator component if you're interested/concerned about performance: https://youtu.be/W45-fsnPhJY?t=1968
@quartz stratus is this wrong?
i`m having this code
but i`m adding the clip to the list
I've only used the Animator component myself, sorry, I won't be much help here.
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.
What script are we talking about?
But it looks like there's probably some custom editor stuff happening here
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
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.
look in the Editor folder for the asset
there'll be scripts in there for custom inspector
I thought that might be the case, but I know nothing about custom editors, and the documentation on them hasn't been much help. There's no instances of "editor" or "xml" in the file.
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))]
I think I found it. Thanks!
How can I deal with slopes jiterring while using moveposition?
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
hmmm i see, would you have any guide, or anything that could help me with that?
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
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
I need to queue AssetReference.LoadAssetAssync on adressable?
i can`t load many in parallel using this?
So out of curiosity, could someone explain to me how this works? I'm finding hit or miss things online and I actually solved what I wanted to do with it and it works for the most part but I'd still like to actually learn how it works instead of just copy and pasting code https://docs.unity3d.com/ScriptReference/TerrainData.SetAlphamaps.html
Here is where I have it, http://pastie.org/p/0SVvgrRbq87becPf4zU2Vq
I was basically switching one texture to another when the player looked at the ground and held left click. basically painting
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
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
This is the code i have
you need something like
AssetDatabase.CreateAsset (Controller, path+"name.asset");
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
you need to define path. its the path where you want the asset saved relative to Assets/
Is there a way to intercept where the asset is going to be saved to?
intercept?
I am using tge asset create menu and I'd want the asset to be saved in same location
so you need to find the path of the parent asset
Yes
Problem is in awake and onenable are called before the asset is actually saved
https://stackoverflow.com/questions/45786451/how-to-get-the-path-to-the-current-directory-scriptableobject-unityeditor-ass
look at the last answer
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
as an aside I haven't seen if (Controller is { }) return; before, is this doing something other than if (Controller != null) return;? is there a reason to prefer it?
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
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
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
Can you keep the zero length ones around permanently for reuse?
right, I can just keep them and use in those scenarios, simpler and prettier, ty 👍
Forums is best bet to ask for help for linux
Oh no
Stackoverflow is down for maintainance
How will I get any work done
I am done for
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 👀
Lul it's back online
who tf cares!🔥
this could be any number of issues
(1) try building a standalone (not dedicated server) build using a windows desktop and with the mono runtime
(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
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?
maybe ask in #💻┃code-beginner or #archived-code-general
Is there a way to by-pass inheritance? Example... in the attached screen shot. Is there a way to achieve this?
maybe this can work
(this as ClassA).Foo();
Nope... It doesn't access Foo() beyond the ").".
if the classes are public its working
but that does not solve your problem
officialy its not inteded that you can do it
Ah.
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().
class A {
protected void SomeBaseBehaviour() {...}
protected virtual void Foo() {...}
}
class B : A {
}
class C : B {
protected override void Foo() {
// it's up to you if you want to call base.Foo();
base.Foo();
SomeBaseBehaviour();
}
}
@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
It’s overrideable because I need it overrideable. And there is a reason for all of it. Doesn’t matter what the reason is. If it’s not possible then I’ll go about it a different way. Thanks for trying to help.
okay
Can't you just base.base.Something
huh I guess not
wtf, I always believed you could
nah
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
Yeah there's definitely some funky inheritance chains going on, but, really, base.base should be a thing
because if you have access to the source and can edit it... you just, modify it to make more sense
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.
this is a bad take
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
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
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
ah
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
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
try connecting the phone to pc via a usb cable that supports data transfer (some dont, for some reason) and while building the game for android, in build settings click development build and autoconnect profiler
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
Thats how i transfer my apk
yea, but you need to enable debugging in developer options on your phone, or else it wont work
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
so I am using this https://docs.unity3d.com/ScriptReference/TerrainData.SetAlphamaps.html to change terrain at runtime but how do I change brush size? it's too small when it paints
i have done that
current code is http://pastie.org/p/1qFdjCFx8q4CDj2QCimows
not my first rodeo . im 3 years into unity , just never had this happen on a new project
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
then all u need is autoconnect profiler in build settings and done
u should have console output in your editor as you run the game
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
you can just see the console output directly in editor with my method
from the moment it runs
there might not be any output from Unity if it's crashing when loading modules
Ok eneable development build , enable autoconnect profiler then what build to phone?
yea, after selecting, just run a new build as normal
ok one sec
you can click build to phone or sth, but anything will work
> gradle build
> one sec
choose one lmao
while connected via cable still obv
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.
It shows mw nothing and still crashes
they do, just use a good gitignore
like the one that github provides as a template when making a repo
nothing at all?
you may also look into git LFS (large file storage)
to save space when saving big assets
install unity android logcat package
and not grow your repo ad infinitum
does a 100% empty project work?
maybe with a single object with a debug.log in Awake()
I actually just did that , are you familiar with logcat error because I'm not, but there's issues
Sorry, not to do with Firebase or Facebook
you should filter with the tag Unity iirc
that is helpful, thank you
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
for that, pretty sure you can mess around in .gitattributes, so that git doesn't recognise them as binary anymore
I am trying to find out what the best practices are before I go do the wrong thing
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
I went through some tutorial trying to use git ignore with unity projects and it got kind of gross kind of fast
I think as long as you have LFS you're gonna be fine
have you tried this one?
will github freak out at me for using all that storage or do I need something else?
no I haven't seen that... cool
nope, you're good, just don't overdo it with terabytes per repo or sth
LFS is designed to use little storage
compared to normal git
so in general Unity projects are big monolithic things?
?
I know that was a weird question, let me try to rephrase it
are you using proguard or have code stripping on? Did you resolve all android dependencies?
how can you adjust brush size in c# for terrain?
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
i have resolved android dependencies , idk what progaurd or code stripping is
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
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
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
you can export entire prefabs, you can set everything up in them
or even entire scenes
and load them without unloading other scenes
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?
yea I believe
but it's cached so you can use it in many projects
why would you need it?
you can have a scene in a package, and load that
or a prefab
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
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
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
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
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
and by server I am assuming this can be my local file system at first?
yea
addressables have a neat option where you can make your own editor a server for a bit
for your local network
like basically here is a file, Unity read this using the Addressables system and go
neat
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?
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
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?
ah
yea you gotta make that yourself
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
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
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
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
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
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
sounds like learning about Addressables is a good thing to do, thanks for that and the useful feedback
yea, good luck!
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 👍
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
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
any help is appreciated
Debug your variables to see which one is null
none of them are null
what do i do now
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
Interesting, ill definitely take a look. Luckily i dont plan on having any transparent objects. Ill only have a few simple objects/enemies. Raycasting is something ive tried but its not worked as well as id like, but maybe im just not utilizing raycasting to its full potential. Thanks for the info!
the trilib guy hangs out here. trilib imports fbx files at runtime and might be what you are looking for. if you need general unity assets, you'd have to do a unity editor backend API, which i have been advocating for him to do
Just get a good gitignore file
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
Yeah, I use a gitignore file and git submodules with a large project. No problems.
i have all my assets in there even including the source .xcf layered files (•_•)
there's a good article on git + unity online
you should run your own LFS server on AWS using this - https://alanedwardes.com/blog/posts/serverless-git-lfs-for-game-dev/
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
you can use gradle to set up building between multiple projects ,including possibly non-csharp languages
it is easier to use than bazel
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
We had success with GLtf using external libraries https://github.com/KhronosGroup/UnityGLTF
not sure with fbx tho
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);
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
Thank you. Did in similar way, just removed all listeners before assigning it again. Not perfect solution but works in this case.
the fact that you keep adding the same event over and over kinda tell you that you should re-think the design
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?
Hi guys quick question
How can I make my AI enter a vehicle and drive just like GTA?
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?
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
your list is what making it slow in this case...
i just read Overlaps might help too
how big is the List?
the list might be just... 20 items as much
then that's not the issue
should i convert the small list into a hashset?
no
or should i simply not use linq
Try the loop, and the dedicated IntersectsWith methods
Compare the results and pick the most performant one
okay, ill try
Just in case you don't know, Unity support fastspan now
Anybody?
whats fastspan?
Refer to Sejadis's answer in #archived-code-general. It also applies to this channel, as well as the whole server.
when you say now? you mean 2022 ?
unity version 2022 ?
hmm, no chances now, ill try SRP2 approach
Bruh what is this server
proly earlier than that
then i should convert the small list into a hashset too
Sure, you could do that to boost perfs even more
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.
seems i need to turn it into a inumerable
Ok maaan
Use .Comtains for checking single elements, refer to my example snippet
👍
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?
is there any easy way to interact with direct x in unity? (11 or 12 is fine)
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.
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
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?
perhaps whatever system unity has for extruding from a vertex can be used for extruding from a bone?
well the one im doing isnt much for extruding bones and such. Im basically trying to make a new bone with copied weights from an existing bones.
oh ok, welp i wish you luck!
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?
No. You'd have to use their API.
Unlucky. Thanks for answer.
Is there any tutorials about Unity + Azure? I managed to find nothing but deployment guide.
Hi, not sure if this is the right channel, but is it possible to build / push docker images in the unity cloud build?
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
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
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
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
anyone here have luck with hooking up a juce plugin to unity?
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+
how are you loading these objects?
What do you mean by this? They are getting loaded with the Resource.Load function
Are you sure no other plugin is using it?
Profile the editor maybe even with deep profiling and see where the time is actually spent.
How can you make breakpoints work in unity?
#💻┃code-beginner
They just do. You have to have your IDE connected to Unity for that you need to select your IDE in settings but other than that it just works.
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
Time is actually spend on File.Read. SO yeah, its loading the file veeeery slow
Thats... suprising for sure... Is maybe some other plugin still writing into that file?
With 10s I would guess its waiting for someone to close the file so that it can read.
My guess is that you have domain reload/scene reload off and the plugin is not 100% compatible 🤔
if you have any antivirus or similar running, it can also cause slow loading
i think don't upgrade if you don't have to
No... thats bs actually... unless they write directly into it the asset database should handle that...... hmm
you should probably make a ticket
if it's happening in editor
deploy my unity project on Azure
do you mean you want to run your unity executable as a game host on azure, and you want multiple copies of this to meet demand for multiple players in a multiplayer game automatically?
based on this, you are only taking the first steps on a very long grand journey
use unirx. you will be better off starting from scratch
what's your objective?
No, I can't do this, I give up on that idea. It's 5 times more complicated to the point I can't think straight
haha, rects and ui can be complicated
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?
lemme check the code
I feel like you've gotta need this functionality for half the games
It's a very common thing to need I feel like
so again, you want to animate-scroll the scrollview to an item in the scrollview?
I animate with dotween, I just need the final local position
for someone to put a 3D model (fbx), initialize it in the scene as a game object and change its transform
okay but what's the app/game?
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
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)
what is the game though?
it's not a game, we're trying to let people modify a 3D model.. by editing parts and uploading them
okay but what KIND of 3d model
like give an example
you're beating around the bush here
what is this really?
you can use this
should suit you well
optimized scroll adapter from the asset store i think has this feature
it's a good scroll view
thank you
@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
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
it won't let me do image replies, but i sent you a salute emoji
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
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?
are you sure the FileName is the same as the scriptableobject's class name?
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.
Show code
how do I format the code properly?
wrap with ```
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
classSuffix is just a string that equals "_ID"
I'm guessing, it hasn't recompiled the changes yet before trying to create an instance
and thus it doesn't exist
(Please use Path.Combine (System.IO) to combine paths proprerly)
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.
@undone coral ah look there actually is a free mini version https://assetstore.unity.com/packages/tools/gui/scrollview-adapter-listview-gridview-106425
"SmoothScrollTo a specific item "
yeah
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
well you're putting the array that is too large on the stack...
you simply cannot do that
ok i have to ask this here bc is kinda next level of bullshit
how should i open Unity without internet and VPN!
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]--;
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
@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);
}
}
i see, no problem then, though with this you cant have 2 separate stacks of wood in the inventory
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
perfectly fine then, this isnt overcomplicated at all
What about the HashTable issue
if i wanna replace my dictionary with the HashTable
how can I do stuff like addition or substraction on the value of the key?
i would still store the item in the list to be consistent
and find the same item inside the list, and stack that
unity will open without internet access i think, provided you've opened it at least once before with internet access to authorize your personal license
its not the first time for this reason i ask 😅
this is a #archived-code-general / #💻┃code-beginner question. you can use a datastructure called a bag to hold items that can* be repeated, or a "default dictionary" of objects to ints where the default value is 0.
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?
use a compute shader
10,000 will be a breeze
depending on what you want a simple vertex animation shader could work too with normal MeshRenderers
Hmm I essentially want to do this animation https://www.youtube.com/watch?v=Tszx6NDQdso&ab_channel=NoOne. Planning on using it as background water in a voxel game. I'll look into compute shaders for this
you can also use visual effect graph
which emits the compute shader for you
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
there are multiple moving rods samples
oops
this is #💻┃code-beginner
or that
Is there any way to stream the output of a Camera to bytes/across the net?
you can render the camera into a RenderTexture, you can read its native data and do your thing
yes, but this is a very very hard problem. i make a platform that does this, but if you need something... artisanal, you can try to use com.unity.webrtc
My apologies, I do not understand
Where can I find docs for this?
this package is from the people who make furioos, who do a unity streaming thing
i also do a unity streaming thing
assembly
What the fuck
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
@deep peak what do you mean about the render texture?
https://docs.unity3d.com/ScriptReference/RenderTexture.html but the above mentioned solution is better if you want to stream the camera, for example to OBS or to online streaming
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
🤦
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)
How can the core package (core asmdef) find impl types in other packages (impl1, impl2, etc. asmdefs)
i forget, are you trying to do something across multiple unity projects
i vaguely remember
or making a plugin thing?
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();
?
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
Thanks, I can find all assemblies
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
It is OK for me to find all implementation types in different packages
this isn't going to work in il2cpp
out of the box
it's going to barely work in mono
what's the objective?
like what are you trying to achieve?
you can use reflection to find a bunch of names of types sure, but why...
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
question is if you need to give it the root or the object that actually changed.
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
That's one of the examples i found also and unfortunately I have tried setting it to the component that did the change and it still didn't work
i have tried multiple things such as tile, tile.transform, tile.gameObject
this works for for me
https://hatebin.com/vsqpdlwrcu
the important part seems to be the SetDirty
else the scene don't thinks anything has changed
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?
Do you know how to not put in the stack?
or how to increase the stack size?
Is there a free solution?
Thank you for that, I have got it all working now. It appears that it actually was working haha...Though I was thinking that it would be saving/updating the prefab too but i was missing PrefabUtility.ApplyPrefabInstance() to do that 😄
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?
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?
hi ,
I need to get the velocity of a projectile with ridgidbody after a certain deltatime , how to do that ?
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.
You might be able to predict it if you know the specific algorithms rigidbodies use to calculate their physics
as far as I know it's just velocity*gravity/deltaTime, or something like that.. I'm not tottaly sure.
then use a for loop to simulate it over a bunch of 'frames'
I think it might be something like that https://schatzeder.medium.com/basic-trajectory-prediction-in-unity-8537b52e1b34
predicting a trajectory, after certain time, it would have a certain velocity
there are a bajillion ways to do this. one robust way is to pass a pointer from C++ to C# of the array to fill, then fill it in C#
you can also use Spans
it really depends what the objectives are. it is better to have a singleton than a bunch of static methods, because initialization of statics occurs right at the beginning - when a scene hasn't even loaded yet
a singleton you can control its initialization whenever you want
In my case, the static variables are public and can be modified anywhere, so the issue of time of initialization doesn't come up
hmm
well what's the goal
same one as before?
i wouldn't touch it
it's small beans
Is there an alternative to unity's test runner that doesnt require asmdefs?
I have explained several times
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.
.
@tender light
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?
Looks like you can access it via a native code plugin
https://github.com/darshanshankar/Unity-DX11-Native-Plugin-Texture-Clear/blob/master/RenderingPlugin/Unity/IUnityGraphicsD3D11.h
ooh thankyou!
(not tested but looks worth a shoot)
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
Wouldn't DX# give you a new context and not the same one Unity is using?
he doesn't even know what dxsharp would do to his game/project
if it had acces to direct x, i am hopeful it will be able to give me some list of contexts and i can somehow get unity's
true lol
I mean, like I said the other day, you've been dabbling with this lowLevel stuffs blindly...
yes, but the more i dabble the more i learn, it is fun, even if it seems pointless, i am learning slowly but surely
aight, carry on!
lol
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
that literally nothing 😃 ...
?
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
ok so I have an variable(array) of my GunItem(s) in my shooting script and after creating every GunItem I have to add my gunitem in the array to check the gun but as Albert Einstein once Said Saurn is lazy. So, I wanna automate the process and btw all my gun Items are in the same folder(currently) if that helps
if it's an assets you can bulk load them https://docs.unity3d.com/ScriptReference/AssetDatabase.LoadAllAssetsAtPath.html
then filter it based on your condition
ok
what does the Asset database mean here?
it is a string for what is displayed in the menu
??
i think it's just the XY problem we're trying ot get ot the bottom of. what is your objective? like what do you need factories in a video game for? you're going to author 100% of your XR plugin framework plugins, so you control them all, so you know all the types ahead of time
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
what is your objective?
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.
Perfect, yes I can add a symbol for each
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
reflection makes sense when you don't have all the source and you don't have all the types ahead of time
but for me, it is completely OK and elegant to define some symbols and let that project add those symbols
in this case you do
@undone coral Appreciated
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());
}
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
which is still, essentially, a serviceloader
i would use the example i showed with the scripting defines
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
Each plugin introduces itself, perfect
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
yes, surely return an interface
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
this is just tricky to make work in il2cpp
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)
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
}
this is fine
just don't call it a factory lol
I think your another suggestion is better
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
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
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
but if they introduce themselves and add them to that static list, it will be perfect
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
Let's gooo! I've figured the scrolling to item out! The code from that library did not help @undone coral , they have multiple internal abstractions which I just didn't understand, so I just tried some ideas until it worked out. https://gist.github.com/AntonC9018/7ff3dbb5f07a1be43a6fb014ee735cd3
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);
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
that's surprising to me
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.
@elder compass I do not know of such shortcuts a year sounds like a very reasonable estimate even without advanced strategies.
Brackeys used to be the go to source for me before learning to read documentation and making small games.
Brackeys retired tho.
Not going to happen, a year is no way long enough
If that's just knowing how classes work and how you make them communicate, 1 year is definitely enough
He's talking about advanced C#, so I guess he knows that already, but learning all of the Unity APIs in 1 year?
"advanced" is pretty relative and subjective though
Nobody knows the whole Unity API lol
There are of course variations between peoples learning speed.
Think about it, going from nothing but C#, how much of Unity did you know after 1 year
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
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
They need to learn both, posted a few hours ago:
So probably more than one year to be proficient
Then God help them. On the other hand, that's why we are here
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?
You need to configure VS 2022 so it works with Unity, for you to get autocomplete and errors in the code directly: see the guide in #854851968446365696
This step is required in order to get help here.
i do have the unity package
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.
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
its talking about a package for visual studio in the package manager but i dont see it there
Make sure you switched the display from "In Project" to "Unity Repository" with the button top-left
How long would you say it’ll take to learn C# from beginner to proficient?
Depends where you start from, normally i would say 2 years
Ok
Ful-time or part-time?
i dont understand what you said
Could do recommend any good resources?
full time
that's if you actually using it for stuff, not just doing tutorial for 2 years
University
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
This channel is for advanced code issues. If you don't know how to use the UPM, ask about it in #💻┃unity-talk.
Say that you need to install the VS Editor package, but you can't find it in the list.
k
@elder compass if you are already proficient in another language then try https://dotnet.microsoft.com/en-us/learn/csharp