#archived-code-general
1 messages · Page 135 of 1
I'm in the middle of a "Reimport All" so my own editor is indisposed at the moment so I'm going strictly by memory
oh damn
okay, so this is good news. The inventory slot IS being affected, just... not in the way you wanted
so how do i fix it?
I mean honestly right now I would be poking at the settings for the grid layout component
just to see if I can get the inventoryslot to change its spacing
and to do this when there are multiple inventoryslots attached
I'm just duplicating your setup
try stretching the width of your toolbar
UI - Image
it's only set to 8px, I think
yeah, something like that
no I mean, stretch it to like, 800px
just to see if it moves those slots apart
cause it should look sorta like this
the child allignment is supposed to be set as middle center on the grid layout group
like there's some settings here
I'm gonna try putting my grid layout object on the root like you did
oh yeah, it works...
and I set the Child Alignment to Middle Center like you did
then what did i do wrong???
the slots have nothing on them, just rect transforms
I'm gonna play Spot The Differences
how's the root of this UI set up?
root?
got a screenshot of the canvas? also.... this is probably outside of the realm of code and more of a thing for #📲┃ui-ux
will playerprefs be reset when i build into webGL? like rn in the editor i have some player prefs saved but when i build the game will they reset
what's wrong with centipedePrefab = Resources.Load<GameObject>("Assets/Prefabs/Centipede/Centipede.prefab");?
yeah I'm pretty sure your toolbar node is too narrow
I don't think so.
what do you mean narrow?
I playerprefs saves to the registry and those values will stay until something comes along and overrides them
it's only 8.4px wide so it's mashing all your slots on top of each other
well when i widen it it doenst fix anything
how far are you widening it? it must be the width of a slot x the number of slots you want it to hold
so if a slot is 100px wide and the capacity is 8 slots then it must be at least 800px wide
I don't understand your query
are you receiving an error?
Resources.Load will only work from a folder named Resources or sub folder therof
thank you, I practically never use that Resources folder and that never occurred to me
yeah it was null when i tried to instantiate
where is the editor layout information stored?
is there a way to manually type the width of panels in pixels or something somewhere? even editing a file if necessary?
i cant fix it
So, as Steve astutely pointed out, since Resources.Load rummages through all folders marked Resources, it couldn't find your file in there
Hedgger, I really hope you can get your problem solved but I think you'll find more experts in #📲┃ui-ux -- this is the place for code!
sorry moat
this stuff is beyond my pay grade!
I wish you luck and I hope you can get it solved - I know how infuriiating it can be
would that help at all?
I am, like many others in this channel, not an expert in UI We've definitely reached the meagre limits of what I know.
If you solve this thing you'll know more than I do
Does anyone know of a way to move objects by script without playing the game? I want to do this to make a tool to help me make my game, and to save me from having to manually move objects
is there a way to search for a file via scripting
yes ofcourse
for example: searching for a scriptabe object and putting it in a class
scriptable object only lives within the project files
I haven't really dabbled with editor tools, but are you maybe looking for something like this?
https://docs.unity3d.com/ScriptReference/EditorGUI.PropertyField.html
Also if you just need to align a bunch of objects or randomize positions there are a few numeric field expressions for it.
https://docs.unity3d.com/Manual/EditingValueProperties.html
I've used them before to line up a bunch of objects without having to move them all manually.
hey, I have some red circles and i wan t to preserve aspect and be in the anchors points like the preserve aspect in Image but for parent gameObject someone knows?
I have made scriptable objects that act as dictionary indexes for other scriptable objects
so that way they only have to be pointed to this one scriptable object and then they can get other scriptable objects via an enum
and in other situations where I needed even more modularity I used Addressables and stored addressable references and I have these scriptable objects loaded in advance during an init stage
so there are many ways to go about this
But I think if you're looking to say, throw scriptable objects into a folder and be able to search that folder and load them up, it probably won't work at runtime
you're better off serializing that sort of data in JSON and just export it separately because those operations will work at runtime
look at the AssetDatabase class
as long as they’re in a folder called “Resources” then AssetDatabase can find them at runtime
...isn't AssetDatabase in the UnityEditor namespace?
nope it’s intended for runtime use
the restriction is that it’s limited to only folders labeled Resources, and subfolders
TIL
You sure? I dont think youd be able to make a build of your game if its using AssetDatabase code (outside a Editor folder)
i’ve definitely done it before
you're mistaken, if you actually make a build it would fail
ohhhh hang on
the class i’m thinking of is called Resources
but yeah that’s the class you want if you want to find assets at runtime
Hey, so I'm deforming a terrain at runtime. Since there are multiple terrains, it happens that the deformations are along the edges and go a bit too deep, creating a bit of a gap where you can see through. How could I, through code, blend the edges together or clamp them or something? Thanks!
How are you doing the deformations?
thanks
the resources class not the assetdatabase class
Modifying the heightmap of a Unity Terrain (Data)
right, but what method are you using?
It looks like you're only deforming one terrain tile at once, causing the seams if your deformation tries to hit two tiles at once
A bit like a brush basically, but cause it would be too costly to just have one big terrain I think. I need to keep the terrain small and just use a bunch
So I'm trying to find a workaround to make the edges come together after deformation
I think you'll be interested in https://docs.unity3d.com/2022.3/Documentation/ScriptReference/TerrainTools.TerrainPaintUtility.html
It collects heightmap data from one or more terrain tiles and gives you a texture
you then draw on that texture and send it back to be applied
when my game suddenly needs to load 5 mins for something, should i be concerend, or just restart unity? 😆
(This is part of the Terrain Tools package)
Seems quite hard to find code examples of this so far
I think maybe BeginPaintHeightmap
well, here's an example of how I used it
i use this to stamp a texture into the terrain
"Terrain Add" is a custom shader I made to do that.
Hi, I have the problem that some time ago I probably coded a bug in the world generation that occurs in a specific case when unloading and reloading chunks. The bug causes a complete freeze of the Unity Editor. I don't have an error message and since the changes in this scripts were more than a month ago I have no idea where to look. How would you proceed in this case? Is there a way to at least find the "problem script" or something similar?
that would be if you asked for an area that has no terrain on it
this is just an issue of needing to deform two piecces of terrain simultaneously
(which Terrain Tools handles for you)
get into frozen state, attach debugger, hit pause
Yeah I don't mind making a thread, just annoying that everything above wont be in it haha
Hello y'all, I want the trail renderer to NOT go through the lighter blue note, but rather be hidden/not visible/stop emmiting past it's position... and I don't know how to do this... Does anyone know?
Depends on whats being loaded, you could try restarting the engine, if it doesnt solve the problem, you could try checking the profiler and "background tasks" window to see what might be taking the time, if its editor-specific it could just be a slow in your workflow, if it happens at runtime too, that could indicate a performance problem, likely if this didnt happen before it could be related to a memory leak (for example, unmanaged events) or a editor window doing work on the main thread or something else
do you know what kind of tool could kind of smoothen or blend?
still not sure where to start, cause in your case you were applying a really specific shape
you would run a blur shader on the texture
on the heightmap you mean?
start by just getting it to set the height to a specific value
then you can worry about implementing something more complex
(so, a shader that just sets the color)
yeah.. might end up doing that
still hoping to find something similar to what i'm trying to do
uhm, i guess that won't work because the entire unity editor frezes, I can't even pause the game or do anything
so at least i have some building blocks
? that makes no difference to the debugger
that's fine.
hit pause in the debugger, they mean
I'm pretty new to unity, how can I attach a debugger?
you'll do it through visual studio.
ohh, alright
thank you <3
I get the exception "Frame is not in module" when trying to pause the visual studio debugger, what does that mean?
you might be pausing on the wrong thread, or something like that
i haven't used visual studio much recently..
or it's just pausing outside of your code
hm okay
okay, if I watch the taskmanager unity uses more and more ram, so I think there somewhere a infinite loop. I guess I will search for that manually
https://paste.ofcode.org/38GyTT2DBGq4fh7mgyKvY8r the player is not flipping positions to match tthe direction theyre moving in... anyone know why and/or how to fix?
You are setting inputHorizontal in start. Then checking for it in update. But I don't think it ever changed aster Start because it's not in update loop?
found it, thanks for your help <3
ill try it moving it, thank you for the idea
omg its working
Haihai! Looking for a little help within the animator for Unity. Basically I have a paramater set to the angle of a bone. When the angle changes, the bone changes. I want to convert this paramater into ∆ so I can then say "if [∆ paramater] is greater than 0.3 (since it's a float) then xyz" but I'm unsure exactly how to convert this float point to ∆
I don't understand what "a parameter set to the angle of a bone" means
Is this an animator parameter that is controlling a blend tree?
So I'm using the VRChat SDK for this so there may be some missing context. Within the SDK they have their own Bone system. In this, there is an aplility to set a float based on the angle of a bone. In this screenshot, I have used "Jiggle Test_Angle"
ah, okay.
sounds like you just need to add a transition based on that parameter, then
so that the transition is possible if the parameter is greater than 0.3
The problem with that is the ground 0 needs to be fixed whereas the ground 0 in this case can change. To explain it more simply, I need something that says "is it moving"
Like the basis, like a base number where if its moving its higher or lower but if its not moving it's equal
i don't know if you can accomplish that with just the animator
Yeah, I'm sorry I'm dumb at explaining things
I actually detect something like that on my VRC avatar by just using a very loose physbone
if it deflects far enough, then I figure it's moving fast enough to count
Okay! Can you share how you did that? That's basically what I'm looking for lol
So what I'm concerned about is this. I'm using the bone as a 3d bell on a choker. I basically want to make an animator that says if the bell is moving, turn on/play an audio source for a jingle but if the velocity is high enough to play a longer version of that jingle. I'm concerned that if I get turned upside down or made to where it's not movingbut at a high angle it will still play the sound
I think I'm overcomplicating things as usual 😂
oh yeah, that's exactly the kind of thing I detect
just turn off gravity on the invisible physbone
it will deflect based on how fast it's getting moved
(also, i dunno if you're already there, but !vrc would be the appropriate server to ask this stuff in)
er
!vrchat
Join the growing VRChat community as you explore, play, and create the future of social VR! https://discord.com/invite/vrchat
i keep forgetting that one
Ah, thank you!
Why we don't have an includeLayers property in CharacterControllers?
Is there a way to specify layers a given controller can collide with?
https://docs.unity3d.com/2023.1/Documentation/ScriptReference/Collider-includeLayers.html
is setting the layer of the object the controller is on not enough?
includeLayers is just for extra control
I need this extra control
why?
Some runtime flags can arbitrary change whether the CharacterController can or cannot collide with other colliders
And creating a new layer for every flag combination is simply impossible in this case
actually
Makes no sense for includeLayers not being exposed for CharacterControllers
the docs say that it does have includeLayers
only in 2022.2 onwards
but that's also the case for colliders
wait
🤦♂️
You sent the Collider page, not CharacterController
whoops, sorry
But yes, it is a newer Unity feature then
i must've tabbed over or something
no, no, it's not on CharacterController
I had wound up on the Collider page and got confused
It is on the CharacterController, but it is listed as something inherited from the Collider class
I hope my project doesn't break with the update
for a hero shooter would i use multiple imput action frames for each hero
well, that's what version control is for!
i bumped to 2023.1 on macOS and i'm having some issues with the editor hanging. maybe I shouldn't have done that...
the longer I wait the more annoying it'll be to re-apply my changes on top of the old 2022.2.x commit
ooof...my project is 100% code-based, no assets, so I think I should be safe
which one is more performant?
!myList.Any() or myList.Count == 0
I'd run a performance test but one uses LINQ and the other compares integers . . .
count it is then
dude it's like 15 seconds every time i save script and go back to unity
also another good 15-20 seconds to enter play mode
is there a way to reduce those times?
You can basically remove the enter play mode time by disabling Reload Domain in the settings https://docs.unity3d.com/Manual/DomainReloading.html just have to make sure to abide by a few new requirements (mainly around things like statics), but I disable it in every project. I keep the Reload Scene option enabled just so that my objects are reloaded.
awesome. just turned it off
what about some "incremental build" stuff.
does it apply to the visual script saves i do? or is it just for actual game builds?
That's for actual builds
Rebuilds the parts that changed since the last build, instead of the whole game again
so can't avoid the 15s after saving scripts?
You can use assembly definitions . . .
- Faster CPU, helps to a certain degree
- Smaller codebase
- Proper use of assembly definitions (misuse can make it worse)
Hello, I'm trying to make my inventory work with an XBOX controller. Specifically, I want to show description of hovered items. I use IPointerEnter/IPointerExit to show desc. when hovered over with mouse. These however don't fire up when I use controller's UI navigation. Best I can think of is check for changes in an update loop but that seems stoopid. Any pointers would be highly appreciated.
If the item inherits Selectable, you can utilize the existing navigation system with overriding OnSelect and OnDeselect (item selection is when the navigation sets a new obj as active)
https://docs.unity3d.com/530/Documentation/ScriptReference/UI.Selectable.OnSelect.html
https://docs.unity3d.com/530/Documentation/ScriptReference/UI.Selectable.OnDeselect.html
Or I think you can use the interfaces to piggy back off of a selectable already on the same object (like a button), although I haven't used these on their own myself.
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/api/UnityEngine.EventSystems.ISelectHandler.html
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/api/UnityEngine.EventSystems.IDeselectHandler.html
That works absolutely splendidly!
Now I have to wonder. Are both necessary? IPointerX for mouse and ISelect for navigation? Or would ISelect suffice by itself?
Select for mouse (without a prior element selected) requires a click, so most likely the former
Isn't "select" the same as "hover" though? It works as such in my case. PointerEnter fires when mouse is hovered over button. OnSelect fires when I navigate to the button via Dpad, none of which actually 'press' the button actually. Or am I missing something?
The only difference being the UI navigation requires some initially selected element to "kick off" from.
link me a good read?
Select is when the object is active with the event system, hover is its own thing. So when you click a button, it sets that object as "selected" and now you can arrow around to other elements through the nav system. Or if you use gamepad, and manually set some object as active with the event system, it functions the same way when you dpad around.
So yeah basically your second message
So, to further try to draw connections with stuff I'm more familiar with, would selected be similar to focused? E.g. in the HTML environment?
Yeah basically
Alright, that gives me a better picture. Anyways, I really appreciate the help. It works wonderfully now.
is there a most popular way of storing settings in a file?
seems unity doesn't have an ini parser?
Don't have one on me now (on mobile at the park) but Google: assembly definitions unity to link to theirs . . .
Unity does have a json parser (and a free one that extends on it in the asset store for more functionality), which is why I just used json
You'll find there isn't the most best way but many with different use cases. You can use json or an SO . . .
i'm not sure there's even such a thing as an ini format
json would be ideal for storing settings
An INI file is a configuration file for computer software that consists of a text-based content with a structure and syntax comprising key–value pairs for properties, and sections that organize the properties. The name of these configuration files comes from the filename extension INI, for initialization, used in the MS-DOS operating system whic...
as in, a single, coherent specification
as the wikipedia page notes, there are many dialects
there are definitely ini formats
True, most games I see with it (a ton of games, even in recent years) tended to use the basic structure of a few headers and basic keypairs. Or they just shoved all of em in a single header 
Ark does the single header approach
hi, Ive come to a massive roadblock with my procedurally generated game, and I need help. I'm trying to procedurally add a stylized grass shader to a mesh, but nothing ive tried has worked. ive tried many different shaders and placing methods. I need ideas on how to begin rendering and placing this much grass automatically
thanks
is the problem in putting the grass shader on the mesh, or about placing the mesh?
putting the grass on the mesh
Hey, what would be the least expensive conversion of NativeArray<float3> to Vector3[]? Linq Select and then ToArray() is awfully slow and I'm new to the NativeArray stuff
is there a way to freeze my game and then check the runtime value of the local variables of a function i'm trying to debug?
Yeah, the debugger
Check the pins in #💻┃code-beginner
There's one on debugging
thank you!
if i want something to change color should i make the base asset white/monochromatic
you dont have to specifically make the materials white in the asset. if you use the mesh alone, it wont have the materials attached, and itll just be white. You can edit the materials color however you want
Oh. Goodbye then
Im working on FSM AI and so far have implemented 2 working approaches but im not sure if my second approach has any drawbacks over the first - the first approach has states as just classes and specific "types" of AI create instances:
public class FSMState { ... } //virtual funcs
public class IdleState : FSMState { ... } //override funcs
public class SomeAgent : Mono
{
IdleState idle;
AttackState att;
void Start()
{
idle = new IdleState(this);
att = new AttackState(this);
}
}
The second approach turns FSMState into a scriptable object instead, that way SomeAgent can hold a List<FSMState> which can be assigned from the inspector, then I dont need a super specific type of AI to test states, the SO base also has the same virtual functions for transitions and updates/coroutines, are there any drawbacks to using SO's in this way as opposed to new instances in super specific scripts? Does it make sense to use both approaches, having SO's for generic enemies and regular classes for super specific AI like bosses?
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
I have looked through this code so many times and still cannot figure out why it isn't procedurally spawning grass objects https://gdl.space/kiwenijefe.cs
Have you taken any debugging steps, such as adding log statements?
all i wouild be able to log is the position x
You would be able to log "Spawning an object"
that's all you care about right now
since you said "it's not spawning objects"
yeah
so.. do it
see what happens
does it print? How many times does it print?
that will tell you a lot
I have it log the spawned tiles when it creates them already
you're doing this: Debug.Log($"Tiles: {spawnedTiles}");
which tells you nothing
doesn't that just print List[]GameObject or something
I should log it with the position too, right?
No you should put a log where the Instantiate is
to make sure it's getting called and how many times it's getting called
get rid of the log in Update
to remove spam from console
Should i also have it say where it spawned the object?
if you want sure
but that's not that important yet
we just want to know if it spawned at all first
good
that tells us a lot
now time to put another log here:
GenerateInitialTiles```
print out tileDistance
so we can see if for (int i = 0; i < tileDistance; i++) is even going to do anything
perhaps tileDistance is 0 for example
where exactly should i put it
before the loop
which one, there are two
it prints out a single zero
exactly
so tileDistance is 0
hence the loop never even runs one time
that's why it's not working
set tileDistance to something higher than 0 😉
wait, line 14 was already
public int tileDistance = 50;
irrelevant
that number is meaningless, you set it in the inspector
that number is only the default for when you create a new instance of the script
it works now
i set it to 50
now i just need to find out why they spawn together
they are supposed to be multiple tiles apart
keep debugging 😉
I found out why, I promise i'm not stupid, I just went to working on Unreal and I wanted to make a 2d game, unreal doesn't have 2d, so I tried to remember what I could for Unity
I was not thinking/accusing you of stupidity 🙏
I kmow, my thoughts just start going places sometimes
this game is cursed
My computer is possessed
The more ide's I have open the more demons start swirling around my pc.
Anyone know how to increase both acceleration and deceleration at the same time with addforce? I tried adding drag, but that just makes the acceleration far, far slower than it should.
Use a vector with a larger magnitude..?
Drag is like if you had a giant parachute attached to you
Not really sure what else this question is supposed to mean. If you add more force, you get more velocity. If you add more counterforce, you get less velocity
I see I see. I managed to fix that issue, but now I have another issue: I am using addforce for jumping, but after doing a completely normal upward arc, it chooses to float down instead of fall down
did you remove the drag you set?
theres a few reasons it could appear to float (but i assume you just mean slowly falls),
like your object scale is too large,
you adjusted gravity,
you have an upwards force being applied which counteracts gravity,
you have a super fast brain and it just appears slow but it is you who is fast
I wound up having to re-add drag and mess around with the rigidbody a bit
That's how I fixed the weird movement lol
you likely dont want drag
Yeah. I tried methods that didn't involve addforce, but every single one of them resulted in my character teleporting through walls
Even changing velocity lol
adding to velocity and addForce are both viable options for changing the velocity of a rigidbody
both are almost the same anyways. You can achieve the exact same results, the only difference is addForce happens during the physics part
Another issue I had was that I really have no idea how to use velocity in terms of jumping
most just add an impulse, addForce allows u to input what ForceMode you want
https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html
the docs go well into detail
Yeah, I currently use the Impulse forcemode for jumping
Huh. Just for a test, I tried adding a constant downward force to the player to see what would happen to the gravity. It's moving at literally the exact same speed as before.
A constant, steady slow fall instead of a gradually increasing one
i assume you still have drag set then
Yeah. I wanted to see if adding an extra force would offset it.
why add drag then in the first place if you are just gonna need to offset it
^
imagine if you were running around with a parachute at all times, and instead of taking it off, you asked a friend to help push you around
that is essentially what you are doing with drag
I really don't, but then the directional movement gets screwed up with how floaty it is
Like it's like walking on ice without drag
so you do need to offset it..
Is there a way to get the SpriteRenderer.color in HSV values instead of in RGB?
you can add drag temporarily to slow it down, but theres a ton of ways to slow down rigidbodies. Depends on what your game is
Thanks
I'll look into it
Hello. Is there a way to copy values from one ScriptableObject instance to another (of the same type). I mean it should be just copying it's serialized data but I see no methods for that.
What I'm trying to achieve is:
I clone my original SO on start by Instantinate() method and I want to be able to apply changes I made during runtime back to original instance. So by default changes can be made in runtime and they won't override original values but if I want I can do it.
- I struggle to find any information of yield return allocations. What factors affect allocation size when using yield?
- Afaik SO values are reset in builds every time you close your game, so i doubt that you can
I'm not about working in build but in editor
- Ah. In editor you can modify the asset only after you load it. In game objects it's resources/adressables. In editor it's asset database. As for saving an instantiated SO, i haven't heard of any way
I'm asking how can I copy values from one instance of SO to another, not about how to modify assets which isn't loaded
is it possible to use properties package with builtin components? for example if I try to set anything on Transform it doesn't work. property bag is there, just doesn't contain any properties.
package works fine with everything in my assembly, just not with engine ones. is there any additional steps to setup it for engine classes?
- Well, value by value, manually ¯_(ツ)_/¯
- In c# there's a clonable interface, but SO don't implement them. You can however derive from SO, implement the interface and use it. Here's another article on this topic https://stackoverflow.com/questions/78536/deep-cloning-objects
Yeah, I mean of course without doing it manually 🙂 I'm in case where SO have 100+ fields (production realities)
- Well, the article i linked should solve this in the dirtiest, but the easiest as well way. In a nutshell, it serializes the instance and loads it back immediately. Of cource the class has to be serializible, which i believe it already is
is 0.2 seconds good for coyote time?
Is inheritance generally a better approach than interfaces when making a FSM?
Trying to use OverlapCircle (https://docs.unity3d.com/ScriptReference/Physics2D.OverlapCircle.html) with this overload:
public static int OverlapCircle(Vector2 point, float radius, ContactFilter2D contactFilter, List<Collider2D> results);
like this:
var colliders = new List<Collider2D>();
Physics2D.OverlapCircle(
transform.position,
3f,
ContactFilter2D.NoFilter,
colliders
);
Getting:
Cannot resolve method 'OverlapCircle(UnityEngine.Vector3, float, method group, System.Collections.Generic.List<UnityEngine.Collider2D>)', candidates are: int OverlapCircle(UnityEngine.Vector2, float, UnityEngine.ContactFilter2D, System.Collections.Generic.List<UnityEngine.Collider2D>) (in class Physics2D) int OverlapCircle(UnityEngine.Vector2, float, UnityEngine.ContactFilter2D, UnityEngine.Collider2D[]) (in class Physics2D) UnityEngine.Collider2D OverlapCircle(UnityEngine.Vector2, float, int, float) (in class Physics2D)
ContactFilter2D.NoFilter is a method
If you don't want to filter the results then just use OverlapCircleAll
It says "Use non-allocating method 'OverlapCircleNonAlloc'" to not allocate memory, which "will be deprecated in a future build and it is recommended to use OverlapCircle instead."
ContactFilter2D.NoFilter() gives an error: Cannot access non-static method 'NoFilter' in static context
What says? AFAIK OverlapCircleAll is the recommended method
you can not call non-static methods like that, you have to create an instance of the ContactFilter2D object first
I belive this is rider hint. Not official unity recommendation, but there is a reason for this hint, right? It can't be just random fake hint.
So is it intended to create empty objects to call noFilter to use this function whithout filtering? Seems like there should be more straightforward approach.
dont know, but i wouldnt dig too deep, if it works it works, something like new ContactFilter2D().NoFilter()
Ok, thanks
I created a custom log handler to forward logs from Debug.Log and friends to Unity.Logging, like so:
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void LogFormat(LogType logType, UnityEngine.Object context, string format, params object[] args)
{
switch(logType)
{
case LogType.Log:
Log.Info(format, args);
break;
// .. other log types here
}
}
// .. somewhere in start
Debug.unityLogger.logHandler = new RedirectLogger();
However I get strange results. The first time after compiling it works for some of them (as in first image). When I then stop play and play again, none of them work anymore (?!) (second image).
I'm sure it has something to do with the object[], but I'm a little confused here... Unity.Logging.Log.Info and friends don't take params, just a regular object[], so I don't really understand its behavior here.
Perhaps a code-gen issue... it looks like it creates a function expecting only one argument when the params are forwarded 🤔
I suppose that could explain why it only breaks the second time
although it's very strange to have only part of the code working, no?
breakpoint in assignment, ensure it does it
I can break in the code, it just works properly the first time I play after compiling for the Info message (but not for the warning message)
it's for a dedicated server build
let me check how i did my logger maybe ill get ideas
ha, actually, the first time when it works, I can't break on the Info one, so there's definitely something related to that (I have no idea how it succeeds to replace only half a function though!!)
i dont think agressive inline is the cause, method probably wont be considered for inline
agreed
all symptoms tell me there is something there dangling from previous playsession
still trying to access dead objects
yes, this seems to be the case; if I put the breakpoint on the switch statement it doesn't work even the first time after compiling
the interesting part is also that the "previous" playsession has the same code.. I guess it's very likely this bug won't reproduce itself once I quit the editor
if it doesn't I'll write a bug report
just modifying the file
you refresh asset db?
anyway the real issue for me is that I can't forward the logs because it just writes me System.Object[] instead of using the array contents.. I'll have to come up with something else I guess
I'm just letting unity do its recompilation, nothing more
is there something in log that should look into an array?
Log.Info(format, args);
is format?
it uses code gen to create the proper overloads, so it just takes the object[] as an argument for the first format item
why not interpolated strings?
i suppose I could work around it with a switch statement for the number of items in the array, which makes me cringe, but if it works ^^"
doesn't matter in this case, it seems the Debug.unityLogger.logHandler interface gets its items handed to it as "{0}", params
I created this monstrosity, which does the job 😅 😅
switch(logType)
{
case LogType.Log:
switch (args.Length)
{
case 1: Log.Info(format, args[0].ToString()); break;
case 2: Log.Info(format, args[0].ToString(), args[1].ToString()); break;
// ... etc
}
it doesn't accept objects either so a manual ToString() was necessary
thanks for your insights btw ! 🙏
barely any
maybe you feel like that, but it's nice to have someone on your side 🙂
Looking to blend/stitch/adjust the height maps of theses two terrains at runtime.
Currently the two terrains start flat, and then get deformed, and I'm stitching AFTER the deformation. (image of the result below)
I did try a bunch of things but nothing worked out so far, last attempt didn't seem to do much but maybe I'm missing something?
public void StitchToBottom(Terrain terrain, Terrain bottomNeighbor)
{
TerrainData data = terrain.terrainData;
int resolution = data.heightmapResolution;
// Take the top y-column of neighbors heightmap array
// resolution pixels wide (all x values), 1 pixel tall (single y value)
float[,] edgeValues = bottomNeighbor.terrainData.GetHeights(0, resolution - 1, resolution, 1);
// Stitch with other terrain by setting same heightmap values on the edge
data.SetHeights(0, 0, edgeValues);
}
Also tried with SetHeightsDelayLOD but I think that's just a performance thing, shouldn't matter when it comes to it working or not. Maybe the fact the terrainData is duplicated prior affects it?
Hey, how to get the width and the height of a rectTransform like this with code? i tried .rect.width but it seems like it s not right
.rect.width should be correct
googling unity rectransform height width in code will get you the answer
it also kinda depends which coordinate space you want the answer in
.rect will give you canvas space size (which further depends on the canvas render type)
Hey,
I'm trying to add a Listener to a button that changes the vehicle in the game.
The SpawnVehicleByIndex method is not registering in Unity as shown in the picture.
The user can't click on the button.
Ideas 🤔
// the button is being generated here
Button button = Instantiate(prefab, transform).GetComponent<Button>();
// setting up the button with the listener
button.onClick.RemoveAllListeners();
button.onClick.AddListener(() => { SpawnVehicleByIndex(vehicle.index); });
public void SpawnVehicleByIndex(int index)
{
GameState.Singleton.selectedVehicleIndex = index;
MissionAssembler.Singleton.DisableVehicle();
MissionAssembler.Singleton.UseVehicle(GameState.Singleton.selectedVehicleIndex);
}
AddListener does not add a persistent listener in the inspector
it's a runtime only listener.
When you add a listener using code it does not appear in the inspector . . .
persistent listeners are the ones that show in the inspector
Persistent listeners are methods attached to an event (the button) using the inspector . . .
Okay I see now.
but the method is not invoked by clicking the button
is there a way to log all listeners?
Add Debug.Log to it to make sure
The method has a Debug.Log in it but I removed for display
Debug.Log($"SpawnVehicleByIndex '{index}'");
is your button graphically responding to your mouse input?
When the user clicks the button it does not go in to the clicked state.
The user has to hold TAB to see a menu where the button is could this be causing this?
// simplified
bool isActive = Input.GetKey(KeyCode.Tab);
menu.SetActive(isActive);
if (isActive) Cursor.lockState = CursorLockMode.Confined;
else Cursor.lockState = CursorLockMode.Locked;
When setting a CharacterController transform position directly, then moving it with "Move" at the same frame, the transform position is restored to the one before setting the transform position. Is there a way to fix it?
If you want to teleport a CharacterController, disable it before you set its position
then reenable it
That is what I'm doing. I just wasn't sure this was the "right" way to do that
Sounds like you might not have an event system in the scene
or perhaps there's another UI element blocking things
But looks like it is preventing the character from activating some physics triggers. I'm still not sure if that is the reason, tho
i forget how character controllers interact with colliders in general
i.e. if they trigger physics messages, as a rigidbody would
they don't
Strangely, after updating to Unity 2022.3.3, I don't have to disable the character collider to teleport it anymore
is this in FixedUpdate or Update
Update
hm, dunno, would have to look closer
And yes, if you keep enabling/disabling the CharacterController, it will fail colliding with some physics triggers
I've just tested it
wait, do you mean it won't collide, or that it won't receive physics messages?
Wont receive OnTriggerEnter/OnTriggerExit
In my case, OnTriggerExit
Sounds a bit random, but when I don't disable the CharacterController, it doesn't happen at all
Hey thanks I was missing the EventSystem component and Standalone Input Module.
Now the button works.
{
// Get the current stage and mission from GameDefinition
int currentStage = GameDefinition.currentStage;
int currentMission = GameDefinition.currentMission;
// Get the currentValues based on the current stage and mission
currentValues = GameDefinition.stageMissions[currentStage, currentMission];
// Return the currentValues
return currentValues;
}```
I get an error code: CS0120 in the line currentValues = GameDefinition.stageMissions[currentStage, currentMission];
I have been diggin abit and I cant find any solution can anyone help me out here?
ok i hope it s correct, i did all of my code with that, i did that
logoParentRectTransform.anchorMin = new Vector2((1-(sizeX / logoParentRectTransform.rect.width)) / 2, 0);
logoParentRectTransform.anchorMax = new Vector2(1 - ((1-(sizeX / logoParentRectTransform.rect.width)) / 2), 1); ```
but idk why the value on the picture (anchor X) Xmin not = 1 - Xax
What?? i did just a variable to simplify my code and it works ?? that s strange but cool
those formulas are very hard to read
one minus one minus uhhh
i don't know
break them up
yes i broke the formulas and it works idk why i don t know what was wrong with my code
ok i have this code, but it don t work for the second part
private void Awake()
{
RectTransform logoParentRectTransform = logoParent.GetComponent<RectTransform>();
if (logoParentRectTransform.rect.width / ratio > logoParentRectTransform.rect.height)
{
float sizeX = logoParentRectTransform.rect.height * ratio;
float anchorMinX = (1 - (sizeX / logoParentRectTransform.rect.width)) / 2;
logoParentRectTransform.anchorMin = new Vector2(anchorMinX, 0);
logoParentRectTransform.anchorMax = new Vector2(1 - anchorMinX, 1);
}
else
{
float sizeY = logoParentRectTransform.rect.width / ratio;
float anchorMinY = (1 - (sizeY / logoParentRectTransform.rect.height)) / 2;
logoParentRectTransform.anchorMin = new Vector2(0, anchorMinY);
logoParentRectTransform.anchorMax = new Vector2(1, 1 - anchorMinY);
}
logoParentRectTransform.offsetMin = Vector2.zero;
logoParentRectTransform.offsetMax = Vector2.zero;
} ```
this code should do like preserve aspect on an image but for a RectTransform here
oh there is a feature for that... thks
ok thks in 2 clicks it works
yo! How am I supposed to ignore a layer in a Physics.Linecast. I used the layermask on it but it ignored every single layer for some reason
Use a layermask
but do it properly 😉
(show what you tried and explain what you want)
If you get the layer mask for the layer you want to ignore, you can use ~ to inverse it.
var mask = ~LayerMask.GetMask("MyLayerToIgnore");
I don't use java
That's not Java
If you know the ID of the layer you can make that more performant too.
var mask = ~(1 << layerId);
what lol
They've seen var and didn't know it was valid C#
nah sorry bro I thought that was java for a sec
~ <- this is bitwise not operator....
kinda tired rn didn't even look
var is not valid Java. or at least it wasn't 10 years ago when I did Java
Also it would be JavaScript not Java I believe
a more advanced way to ignore some target layers is (-1)^(some layers) and everybody will ask why dont you just use ~
does anyone have an easy wat to check collision with circle circumference?
i don't care about what's inside the cricle, i want to test if there's any object in it's circumference, like a raycast, but circular
I'm trying to prevent the linecast hitting some layers
Any reason that you cannot just use https://docs.unity3d.com/ScriptReference/Physics2D.OverlapCircle.html ?
show how ignoredLayers is defined
circularcast
instead of preventing the linecast from hitting the assigned layer it ignores everything
you said that already
Give more information if you want help with it
ok gimme a sec
can i filter by distance from center?
btw a layermask tells you which layers to HIT, not which to IGNORE
yes the radius of the circle
Yes
so you're suggesting getting all the colliders and then filtering by distance, that can work
you are misinterpreting the docs
a layermask tells you which layers to HIT, not which to IGNORE
it can be used to ignore things by excluding them from the mask
It depends what you're trying to achieve.
If you need to check if anything is in the circle, you'd only technically need one.
i want to check if anything is in the edges of the circle
i don't care about the middle
that doesn't work either
YOu still haven't shown your mask
so it's hard to help without any details
I don't have a 'best' solution for that.
You could perhaps do two overlaps and compare which ones aren't in a smaller exclusion zone (in the centre).
note that you also have that if statement inside which is checking a tag
right now the mask has no layers assigned to it
if that's what you need
then the linecast will never ever hit any object
I looked at ContactFilter2D, sadly there isn't anything about distance.
How i'm currently thinking of implementing it is to get all the colliders, and with for-each loop filter the ones that have distance < minimum
so you want obejcts inside a ring
yeah
you could do:
- OverlapCircle then filter by distance
OR - two overlapCircles and take only the objects that are in the larger circle and NOT in the smaller circle
e.g. with HashSet.ExcludeWith
Oh that's wonderful, didn't know that existed. Thanks!
the second solution sounds buggy af, if there's a collider which exists in the ring but also in the smaller radius it gets excluded, not good
both solutions have that problem
because they don't really account for the size of the thing
i can potentially get the furthest point/ closest point from center of the circle (don't have an easy solution as to how) then filter from there. (if furthest - closest in ring -> return)
one option is to predfine a few extremity locations on the objects (perhaps with empty child objects) and check each of them for distance to center
if any are within the ring, you're good
Ok, I've been struggling with this for a while now...
Loading Scriptable Objects with Resources.LoadAll sometimes just works and sometimes not.
It worked for a while and then it stopped, now I'm getting the second Exception more often than it actually works properly. The instance get's called by my AssetPostProcessor to check for any new Scriptable Objects.
Any ideas what might be causing that (and more importantly - how to fix this)?
How do I get a random rotation on this axis?
{
while(true)
{
Vector2 randomPos = new Vector2(Random.Range(minWidth, maxWidth), Random.Range(minHeight, maxHeight));
Instantiate(beanPrefab, randomPos, Quaternion.identity);
yield return new WaitForSeconds(spawnDelay);
}
}
Instead of Quaternion.identity
I've kind of found LoadAll not to be that reliable for this use case (scriptable singleton) I just hardcode the resources path
should be faster that way hopefully anyway?
Anyone?
So just writing
Resources.Load<MissileLibrary_SS>("Scriptable Singletons/MissileLibrary")
should work then?
Or are you talking about something else entirely
yes that
https://docs.unity3d.com/ScriptReference/Transform.Rotate.html This uses Eulers instead of quaternion.
I'm not entirely surei t's what you wanted tho
after looking slightly deeper into it, found that unity has a method that calculates closest point to bounds, but not furthest.
What i'll end up doing it calculating the closest point to center, closest point to ring edge by extending the closest point to reach the edge, draw a line from said to points and check if it happens to be inside the ring (image for visualization)
I see, I'll do it this way then, thanks
Oh. I mean you could just randomize a number and set transform.rotation if they don't need to move.
You can get a reference through newBeanOrWhateverName = Instantiate(...)
note that Bounds is not the actual edge of a collider, just the AABB
it's closest point to certain bounds https://docs.unity3d.com/ScriptReference/Collider.ClosestPointOnBounds.html
ahh alright, random between 0 and 360?
Yeah
Quaternion.AngleAxis
you give it an angle and an axis
it gives you a rotation around that axis
trying to write a limit framerate script to cut down on performance load but so fari its not working help?
where do i type that in?
ERROR: program using top level statements must be an executable
well, you need to put it in a method...
put it in something that runs at the start of the game
basics of code still apply...
thanks i'm super rusty i just had to add code into the script i already had
it worked btw lol
this script is for passing in my of map data(a Element[,]) getting the groups of elements as lists of dictionaries, and then identifying it's edges but I'm having trouble with the last step, if a shape has a vertical pillar of elements with a thickness of 1 it seems to hang but I cant figure out where as the only while loop has a limit
I think I may fix it on my own after more trouble shooting but another pair of eyes could help(I've already been troubleshooting for like a day)
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.
while (currentPoint != startPoint && iter < pointsOnEdge.Count + maxIter);```
infinite loop right here
nothing can possibly change because there is no content to the loop
(line 131)
oh i'm an idiot didn't notice it's a do/while
There's another while loop on line 41 though @rugged storm
i dont think this loop would be causing issues as i thoght that part of the script was done but ill check it and place a limiter on it
checked it but it still seems to hang when there is a 1 element thick column of elements
when you say "hang" what do you mean?
are you getting the log on line 134?
guys please help fast how do I make two 2D colliders not collide with each other but collide with other stuff
layer based collisions
pls I only have 58 minutes
like unity just freezes up what it does when a while loop goes on infinity, and i have to force close it,
i'm not getting any debug logs
even with your escape hatch?
the maxIter thing?
um you're wrong
there is a matrix in 2d
and it works the same exact way
seemingly, maybe i need to wait longer before force closing but max iter is only 100 and the count of pointsOnEdge isnt that big
if that's not stopping it then the infinite loop is elsewhere
I recommend attaching the debugger and pausing while it's frzoen to see where the thread is
You can do that???
yes
alright will try
ik about the debugger and use it sometimes but did not know you could just pause it at anytime to find the current thread
hi i was trying to make a different background ambience depending on your current location but at some point the "background sound" stops and I'm struggling on making a loop. Can anybody help me pls?
okay how do i figure out which thread is doing the thing i need to figure out?
the main thread
how do i know which one is the main one? this is the screen i have rn
It will be called Main thread or something along those lines
go into the dropdown and look at all the threads
just look through all the ones that aren't clearly the wrong thread 😉
.e. ignore the iothread, reaper, burst threads etc
i think i found it,
its on like 167 if (nextPoint == startPoint || (pointsOnEdge.Contains(nextPoint) && !resultGroup.Contains(nextPoint)))
everytime I unpause and pause its stuck there? waaaait is me modifying I during causing this?
right so that just tells us the infinite loop is that for loop there
i.e. the startPoint is never being reached
nor are edge points
guys how do I decrease a countdown fast pls
i'm sorry
like this
It shoudl just drop out and fail if its not reached
ahhh i think I never reaches Neighbors.Count + currentIndex; Because i %= Neighbors.Count;
i %= Neighbors.Count;
yeah
anyone pls
subtract things with the - operator?
¯_(ツ)_/¯
I have like 34 minutes left this is so scuffed
No but I want to do it each second
Time.deltaTime
you want it to always display a whole number?
time for a format string
timer.text = $"{timeLeft:N0}";
$ enables string interpolation. Anything in {curly braces} gets evaluated and turned into a string
would it be fixed if i just set something = to i and alter that?
so it uses a variable named timeLeft
after the : comes the format specifier
N0 means it's a number with 0 decimal places
IEnumerator DecreaseTime()
{
while(true)
{
timeToPlay--;
yield return new WaitForSeconds(1f);
}
}
Nevermind I am doing it this abhorrent way
I forget if rounds up or down
This also works.
i set a int pointer = i and change and use that now so it no longer hangs, the do while loop fails all the time tho but gets caught so i still def have some code to fix, but now i dont have to force close unity when things break
this whole things was just to make the 2d array of my map data into polygon collision but honestly at this point it might of just been faster to make my only phsyics engine that direcly checked map data..
@heady iris the other day you said that polygoncollider2ds cant be convex but i dont get why not? it appreats to work fine
without the graphics so you can better see the colider
now i just need to properly draw the edges instead of just the positions of each block along the edge
I didn't say they can't be concave.
I said that the algorithm you showed -- sorting the points in a clockwise fashion -- would not work for non-convex shapes
OOh
(most random shapes are non-convex)
convexity basically means that there aren't any insets
i'm not sure if you'd actually call non-convex shapes "concave", actually..
well yeah ofc that's why I was trying to write new code
and now it does, well it support shoapes without strctures like these, i just noticed thoes two white squares, im not sure whats causing them to appear, maybe related
Oh i figured it out thoes should be rendered red it was a glitch with my draw world script, but they actualy should not as only the elements which are on the edge of thier current body should be red and there are no elements in thoes locations
(It rendered white becuase i was adding the color read isntead of settings it, on the black elements it was black+red which si red becuase black is 0 but the sky color, cyan+red=white)
https://pastebin.com/fLcbFmCi ive updated this to reflect the fixed to keep it from hanged, would anyone mind helping my figure out why the script falsely thinks there are edges of blocks located there?
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.
it seems pointsOnEdge is not being properly set
actually nm i was wrong i think part of the issue is that im adding current point twice to currentEdgePoints
How can i make Image with fill type Radial360 to start filling at custom angle, e.g. 35°
deepnding on what your image is - just start it at top or right and rotate the image
I didn't think about rotating image 👀 Thanks 👍
So i've got a problem where explosions hit a single enemy multiple times because of the limb hitboxes
you'll need to filter out duplicates from the same enemy
this can be as simple as ignoring a collider if you've already seen one with the same Enemy component on/above it
I was thinking of having it work like tf2 where the capsule around the character takes explosion damage
oh yeah, that's a reasonable plan.
you would want to make a separate layer for the big collider
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.
but im not sure how i can do this with IDamageable
do what?
wait i think i have an idea
Hello, I am overriding the GameObject's transform position(because have a script simulating custom physics for it), but I want to be able to drag the gameobject in the editor, but since the position is overridden by my physics, trying to drag the gameobject with the move tool in the editor doesn't work, the object's position is locked.
Is there a way to get the event or value of the editor's move tool if the user drags and moves it by one of the axes? (so then I can add that to my physics object's position)
Thanks
Have the enemy bones on a different layer so hitscans can hit them
Hello, My name is Daan and i am working on a game that has gardening aspects. I am trying to get the tiles to dynamically update like in Stardew valley, where if you have two tiles with a one tile seperation (that are ready for planting) and you place another between them. They all connect to make a larger bed. However my code isnt working exactly how id like and i dont know why. You can see in the image that they dont always update properly. If youd like more info please just let me know, here is my code in paste of code -https://paste.ofcode.org/RkZmYKBPzkghHY8y5XdNkd
I think that should work. I hope i did this right, im new here so if not please let me know as well.
I have been trying all day to fix this and i got it working with just the initial dry tiles. But then i wanted to update it so that the dry, tilled, and wet tiles all update and you can have dry tiles attached to wet tiles etc. But now if i place a dry tile next to another dry tile they both update without either being clicked and turn into tilled tiles. I am very confused
Delete all of your code and use Rule Tiles
https://learn.unity.com/tutorial/using-rule-tiles
😂 No way, I cant believe ive spent two days on this and there is already a system in place. Well thats helpful, thank you. I will give it a shot :)
I came from working in C and making games from bare scratch so thats probably why that carried over. Thank you again!
ha :p
If you know what you're doing in general, but don't know much about unity, I'd suggest skimming the !learn material
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
just to learn what's out there
If you are a complete beginner is this the best way to learn?
So I should use unity learn? Got it
Unity only inlcudes the assemblies included in the chosen .NET profile
sure, just find a dll and drop it in
Anyone here using Rider ?
ask your question.
Is there any point in starting Unity via Rider Debug Mode ?
(i'm used to doing this with Unreal Engine 😄 )
no
So assuming Rider is connected per say to the Unity editor, when Unity crashes i should have a proper report on what's what and what caused the crash without starting the Editor via Rider ?
Rider will not get Unity crash reports in any circumstance
oh
cheers, i thought it would be similar to UE
Would you recommend using the backtrace for proper crash reports ? Or any other options out there?
I generally have very little interest in editor crashes in the rare occasion they happen
In Unity if your C# code "crashes" it's usually going to cause little more than an exception to printed to the console
it will not generally crash the editor
if the editor crashes that's usually due to a bug in the editor itself, and you can certainly submit those crash reports to Unity
true, thanks for your insight
What is { get; private set; } used for?
that is the syntax for an auto-implemented property in C#
how would you name t in such functions like Lerp where t is inside [0, 1] but when I can't name it like that because it is more like a progress
so progress it is 🙂
Thanks, that made it clear but what's wrong with setting a variable "normally" without a function inbetween?
The answer is somewhere between "nothing" and "it violates the principle of encapsulation" depending on who you ask, and what the context is.
also this way allows you to have a public getter but private setter, for example
public fields mean that you can't trust that a field won't just...change
using an auto property instead of a field will also allow you to refactor later to add validation code or something without having to change other objects
well the whole point of making a variable public is because you do want it to be exposed and change externally
directly changing value externally 👎
Point is separating interface and internal data layout 😄
i like directly changing values. I have always hated defining a whole extra method just to change something. It might as well be public at that point lol
the benefit being being able to search for changes, ig
What if you want to change it's functionality, it is easier when you already have it as property
Otherwise you gotta update all the usages
you mean change what the property means?
or change what happens when you update that property?
public has 2 components read and write
in case of a field you cant separate those
also much rather have OnPropertyChanged () thx
More of this. For example you want to update/notify when the value change
hating properties is a weird thing in c#, i would understand hours long arguments over this in other languages but in c# its deeply ingrained
so much that people expect that if something is a property it is intended for public access, and rarely you see public fields, in statics for example
heres what i do: i have a public field -- when it comes time for me to add validation, i just turn that field into a property. just faster to code that way
Ah that's fascinating - INotifyPropertyChanged? I haven't seen that before - looks super nifty 👌
Yeah C# property is much convenient compare to Java etc
sure you can have a public field and then later encapsulate it with a property, but at that point that field was already read/write and a whole codebase grew around it with assumption that it will always be read/write
You can do that when you are not writing shared code or library.
so to avoid all of that confusion it is simpler to make it a property from the start, and read only if its intended to be readonly
yeah it's really cool, I've encountered often with regular .net apps , they use properties a lot and this is good way to autoupdate UIs
in my code if anything is accessible from outside in the main codebase and not utility tooling, its a property
I think the answer is to have good foresight over what you will need.
clairvoyance you mean
writing a method just to read and to write for every single public field you put into a class is lunacy
in 99% of games its pretty easy to just right click and find all references. you know how much code youre breaking when you do that
elaborate why?
i agree with snoop
also i feel like this discussion is getting out of hand at this point. no?
it’s just unnecessary. If you know that updating a field might lead to some additional baggage in future, then you should probably dress it up for future.
But not every field needs that
properties in c#
why it is unnecessary and why not?
Uhh no, when your code is used by many other people? That's not ideal.
I think only learned about properties after I took codecademy courses on my freetime, I rarely see them mentioned in context of Unity.
But I'd imagine that they make any kind of big project (especially with multiple programmers) far less nightmarish, since you know nobody can write to that thing that should only ever be read etc.
Reduce the risk for errors and don't usually take that much time to set up either.
I should probably use them more often.
whats the best way to make a state machine where the states can be easily changed?
Animator
not best, just easiest
public Dictionary<string,ICommand> moveCommands => new(){ {"run" , new RunCommand()}, {"walk" , new WalkCommand()}, {"jump" , new JumpCommand()}, {"teleport" , new TPCommand()}, };
this is what i have so far, its going to be compositional and the states call these commands via the dictionary. There must be another way to do this other than using strings though, right?
strings are fine, enum is fine
in case of strings wrap them in static class
static class MoveCommand
{
public const string Run = "run";
public const string Walk = "walk";
}
fsm.SetState(MoveCommand.Run)
functionally identical to enum, almost
with strings you can add insert runtime generated states if needed
If you want to give a named value to something for ease of use use enum, if you want to display the value to the user use string, don't use strings for internal values which aren't displayed
or editor created states
since you dont rely on hardcoded values
but for it to work you would also need to have transitions
Thats very smart
Yeah enums are good although you cant make child enums so they are quite limited in that regard
Child.. enums? 🤔
as in you cant ovveride enums or add to them in a child class
and you also i dont think can use polymorphism for enums
is there an easy way to make movement not fps dependent?
FixedUpdate()
Multiply Time.deltaTime?
alright
im not a programmer myself, but a friend i know is and hes struggling with it a lot but refuses to ask for help anywhere
private static void DiscoverAndAddElements()
{
// Get all types in the assembly that inherit from Element
Type elementType = typeof(Element);
Assembly assembly = Assembly.GetAssembly(elementType);
Type[] elementTypes = assembly.GetTypes()
.Where(t => t != elementType && elementType.IsAssignableFrom(t))
.ToArray();
// Create instances of each element type and add them to the dictionary
foreach (Type type in elementTypes)
{
if (Activator.CreateInstance(type) is Element element)
{
elementTypeDictionary.Add(element.ElementID, type);
//elementDictionary.Add(element.ElementID, element);
}
}
}```
i have this script, in the final if statement how could I sort out specific things that inherit from a seperate class that also inherits from element?
like say i dont want to add any thing that inherits from the "Seeds" Class and the but the seeds class it's self inherits from Element
also ingeneral is this a good way to go about getting everything that inherits from a specific class and putting it into a list without hardcodeing them into a list?
Make the seeds class abstract and check whether the type is abstract or not
IsSubclassOf
in general having
Assembly.GetAssembly(elementType);
Type[] elementTypes = assembly.GetTypes()
.Where(t => t != elementType && elementType.IsAssignableFrom(t))
.ToArray();
in every place you need to get reflected data is bad, create a static store for reflected types, then access it anywhere you need, construct once, query later
Is there a way to use Random.Range(float, float) with exclusive max/min? Or is there some analogue?
He has elementTypeDictionary right?
yes for element type
what will it exclude?
float.epsilon? some other value?
max or min value. Like the int overload.
so if max is 0.88213991 it should not include it, but 0.88213990 is ok
if max is 1f, I don't want to get 1f.
but 0.9999999 is ok
i really dont know, i dont even know how to clamp it
since what do you clamp it between
1f - float.Epsilon equals 1, so you would need to if it with direct comparison, and then clamp it at some arbitrary lower value
i may not understand something but this seems like undefined territory riddled with float precision issues and weird arbitrary constants
Specifically, Time.deltaTime turns a value into "per second", so moving something 5 * Time.deltaTime units on X will move it 5 units per second
I am planning a livestreaming screen sharing environment. Is it possible to integrate zoom for the screen sharing on the screens that will be in the building? If not...what are the options to get screensharing into the environment. Any help is appreciated.
float min = -2, max = 2;
float random = Random.Range(float.BitIncrement(min), float.BitDecrement(max));``` I suppose
I guess System.Random NextDouble works for me.
"A double-precision floating point number that is greater than or equal to 0.0, and less than 1.0."
https://learn.microsoft.com/en-us/dotnet/api/system.random.nextdouble?view=net-7.0
lets look at how they did it
that's inclusive on the min side
Would clamping between 0f and 1f - Mathf.Epsilon not work
no
1 - Epsilon will not work
pretty sure this is the best way
ok so what they do is they store internally the values as ints
Yes, I need exactly that, inclusive on one side and exclusive on the other.
Maybe I should have specified it, because "max/min" don't look like min xor max.
and the internal max int is ensured lower than the max bound
when you say 1 - epsilon what you actually want is float.BitDecrement(1f)
Thanks for the alternatove solition
so yeah having it as int bypasses all clamping problems just by the nature of it
BitIncrement is not in 4.8
not in standard either
This is just called once when the project is ran and saved to that Element type dictionary and I have a separate static method Wich retrieves a type from the dictionary based on the inputed id
i understand, but you most likely will eventually have hundreds of such callsites
all calling reflection api and retreiving same data
anyway doesnt matter not an issue at this point
i think ive seen unity providing a central reflection data class somewhere in changelogs
The constant is 0.99999994f and seems to compare without issue manually assigning it, but I would comment appropriately since it's very magic-numbery
How can i make it so that, in a swipe-detector code the swipe isn't only registered when the touch ends? Like to detect the swipe without taking your finger off the screen?
you can track position delta, have some thresholds for velocity difference between current and previous, test for magnitude and direction
also a timer
Is it posiible to create generic type based on the class type?
I want method in parent class that return object of the parent class and overridden method in child class that returns object of the child class.
you can construct generic types and use them in activator
Type t = typeof(List<>).MakeGenericType(typeof(int));
I want something like this:
public record Base
{
public float FloatField;
public virtual T Foo<T>() where T : Base
{
return this with { FloatField = 0 };
}
}
public record Child:Base
{
public string StringField;
public override T Foo<T>() where T : Child:Base
{
return base.Foo() with {StringField = ""}
}
}
return base.Foo<T>()
where T : Child
should work
i just dont understand whats the point
it already inherits Base and has access to its members, why does it have to be generic?
and it wont work
I want it to return Child in Child class
you cant override and change signature
are you trying to make the return type more specific?
i'm not sure if that'll work here
covariant return types let you make a derived type's overriding method return a more specific type than the parent type's virtual method
Looks like what I need. Thanks, I'll check it
and I believe unity is on C#9.0 right now
Getting "Target runtime doesn't support covariant return types in overrides." 😢
what's your api compatibility level in the player settings?
might change if you target .NET Framework instead of .NET Standard
Where should I change it?
project settings -> player
I set .NET Framework, still not working.
It worked after I added additional files to project (https://github.com/dotnet/docs/issues/22949#issuecomment-784082929)
It's not ideal, but you could do something like this instead, assuming you don't want to bypass the safeguards.
public record BaseRecord {
public float floatField;
public BaseRecord Foo() {
return this with { floatField = 0f };
}
}
public record ChildRecord : BaseRecord {
public string stringField;
public new ChildRecord Foo() {
return (ChildRecord)base.Foo() with { stringField = "" };
}
}
Thanks!
why is not allowing me to override (to save) this reference to this debug TMP field?
Is there a built in method somewhere which would allow me to find the SkinnedMeshRenderer component on an avatar from one of its children, even if the root of the avatar is itself a child of another object?
I know transform.root exists, but that won't work if the root of the avatar is a child of another object.
And I know I I could traverse up the hierarchy to find the first parent that contains an animator and then search for the component in the children of that, though that would probably traverse the armature first which would be a lot of work for nothing. I guess I could look at only those children that are direct descendants of the avatar root to figure out which one has the component.
But I'm kinda hoping and thinking that Unity has a method already built into it for this specific case.
Specifically what I am trying to do here is I am trying to allow a component on a child to access one of the avatar's blendshapes. Hence the need to find the skinnedmeshrenderer component.
And I don't want to just have a field that I have to fill in in the inspector because that would require me to fill that in for every avatar I create, which is just extra work for nothing and another potential bug in the long run.
there can be many skinned mesh renderers
EditorApplication.delayCall += () => { SceneView.FrameLastActiveSceneView(); SceneView.FrameLastActiveSceneView(); };
.NET Framework is older and no longer receiving updates
.net standard is just as old
its the same thing but standard is more limited due to cross platform
.net this, .net that
To minimize the garbage collector overhead, avoid methods such as Assembly.GetTypes and Type.GetMethods() in your application, which create a lot of C# reflection objects at runtime. Instead, you should scan assemblies in the Editor for the required data and serialize and/or codegen it for use at runtime.
😬
c++ style reflection when
does c++ actually have it now
always did with libraries
ah, right
you just scan code construct reflection data as code at compile, access it at runtime
just wondering, is it possible to have markers and clips on the same timeline trackasset?
figured it out nvm 🙂
Honestly was kind of a mess until they started unifying things later
What's the modern/correct way to rotate an empty along 1 local axis, i.e. the equivelant of edit only X, Y or Z euler value directly?
transform.Rotate is an option
I cant get it to do a local rotation
it has an override
public void Rotate(Vector3 eulers, Space relativeTo = Space.Self);
Nice this override version works perfectly thanks
GetComponentInParent<SkinnedMeshRenderer>() searches ALL parents all the way up to the root. not just the parent immediately above
transform.Rotate uses local space by default
doing Space.Self is the default
I want to make custom navigation movement depended on navmeshagent. Like I want to keep doing best use of navmeshagent's pathfinding and local avoidance. What to do in that case?
custom?
dont wanna use autoupdate position
also determinism is another thing to worry about
make your own a* pathing?
I've recently done this for vehicles as NavMeshAgents are worthless due to the turning behaviour, and it's nothing less than a pain.
If you use this as a resource:
https://github.com/Unity-Technologies/UniteAustinTechnicalPresentation/blob/master/StressTesting/Assets/Scripts/Utils/PathUtils.cs
What you have to do isn't pretty either. Due to the current unreliability I have required to temporarily result to try/finally statements which I will eventually weed out.
using var result = new NativeArray<PolygonId>(maxPathLength, Allocator.Persistent);
using var query = new NavMeshQuery(NavMeshWorld.GetDefaultWorld(), Allocator.Persistent, maxPathLength);
var from = query.MapLocation(start, Vector3.one * 10, agentId);
var to = query.MapLocation(end, Vector3.one * 10, agentId);
var status = query.BeginFindPath(from, to, areas);
int maxIterations = 1024;
...
var pathResult = query.GetPathResult(result);
var straightPath = new NativeArray<NavMeshLocation>(pathLength, Allocator.Temp);
var straightPathFlags = new NativeArray<StraightPathFlags>(pathLength, Allocator.Temp);
var vertexSide = new NativeArray<float>(pathLength, Allocator.Temp);
try
{
int straightPathCount = 0;
var pathStatus = PathUtils.FindStraightPath(query, start, end, result, pathLength, ref straightPath, ref straightPathFlags, ref vertexSide, ref straightPathCount, maxPathLength);
if (pathStatus == PathQueryStatus.Success)
{
path = new Vector3[straightPathCount];
for (int i = 0; i < straightPathCount; i++)
{
path[i] = straightPath[i].position;
}
return true;
}
path = default;
Debug.Log($"Nav query failed with the status: {status}");
return false;
}
finally
{
straightPath.Dispose();
straightPathFlags.Dispose();
vertexSide.Dispose();
}
Looks like DOTS
if only there was more guides and proper Hybrid approach
I have a game where around 5000 units will be common
but dont know how to keep it at 60 FPS at as much as low-end devices possible
Do not forget the editor has additional overheads.
yeah that too. I can hardly reach 2000 with all crazy optimizations possible
like turned off animator
at far distance
for 5000 units you need DOTS
especially on mobile
can mobile RAM handle that much?
Usually if the GPU and CPU are bad, the RAM will follow.
Assuming every phone has 8GB of RAM.
Which they do not
no but many do
isnt 2-4 GB common for mobile? Even less on older mobiles?
hopefully you do have a main script that controls all unit movements instead of each unit having their own pathfinding/navmesh agent logic ye?
rare to see 4GB
currently keeping it temporary to navmesh autoposition. For climbing and few other stuffs, turning it off and back again
8GB is pretty standard these days, even for midrange phones
anyway it doesn't matter
DOTs is not going to use significantly more memory
it is going to make significantly more efficient use of both your CPU and your memory though
The first midrange phone I just checked out had 6GB, being a Samsung.
Samsung's £250 phone has 4GB however.
just saying, if each unit has their own script for pathfinding you are looking a lot of wasted cpu power
3 GB my phone
ok I really don't see why we're discussing phone memory, it's not really relevant
Profiler tools will be your best friend
Mostly because you said:
8GB is pretty standard these days, even for midrange phones
Anyway I couldn't get working with DOTS too much. Really feels soooooo complex
It's just a learning curve
if you want 5000 units, it's really the only way to go
yes it has a learning curve
want to do Hybrid approach but all tutorials and guides outdated
even few new ones got deprecated stuffs which were months ago
If you learn in a side project, you can learn how to implement a hybrid approach
Anyhow, I provided a hint in the direction you want for a custom navigation on a navmesh; linking someone's work who works for Unity.
public void InitializeUnit()
{
id = idCounter++;
string gameObjectName = gameObject.name; // Register stuffs
string[] gameObjectNameParts = gameObjectName.Split();
if (gameObjectNameParts.Length != 0)
{
gameObject.name = gameObjectNameParts[0];
}
gameObject.name += " " + id;
units.Add(id, this);
// from here I want to reference to a entity somehow be it be through Entities.Add() or Get an Entity from pooling
// after that call OnSpawnEvent
OnSpawnedEvent?.Invoke(this);
}
Are you trying to remove any numbers at the end of a GO's name?
private void OnDestroy()
{
units.Remove(id);
// later remove reference from
Destroy(gameObject);
}
You'd probably have better luck using Regex
that's a way of identifying stuffs better way and keeping away extra nonsense like (Clone)/Variant/etc. But that's not the point here
I want easy access between Entities and MonoBehavior. Like I want to call old MonoBehavior stuffs from Entities and vice versa
PraetorBlue would probably be better here to help you if they're around, in this regard.
@leaden ice clue?
is there a question here?
TLDR; that's the code I got and I want my MonoBehavior to keep track of Entity for easy access to datas related to it. Vice versa as well from Entities to MonoBehavior
