#archived-code-general
1 messages · Page 228 of 1
and start your game, play in unity, run it until this line is hit
debugger will break and you can look into whatever you want in your code
read what buttons do on the top debugger panel
all those step over, step into
I see... Thaaanks, this might take a while
Might want to have a look at the Microsoft manual on VS debugger.
It's not very easy to understand just from discord messages
there were no nulls
uhm.. wdym by throws?
throws a null ref exception
its called throw, theres an operator throw in c#
throw new ArgumentNullException();
The line that causes(throws) the error.
most exceptions you encounter that arent NullReference are added by programmers, NullReference is thrown automatically, in any case, if its still not null, then you can add a conditional to the breakpoint
right click the red circle > Conditions and type into the field data == null and press enter
when you are exiting playmode?
yes
that is expected, you should add case to handle that
uhm... how? I'm quite a beginner in handling this stuff
You probably subscribe to some event that is called when the game closes and the object is already destroyed. You need to unsubscribe from it properly.
Or avoid invoking it at that point.
uhm can I put an if statement where it checks if its null? transfer the data if it's null?
ill write up a gist that can be just dropped into the project
Might want to share the code for us to provide proper advice.
The code of where you call that SaveData method.
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Is there a good way of determining why a TextAsset won't load through Resources for a specific end user - when it works for the majority of users? I have this method: https://hastebin.com/share/saqorudoki.csharp
It works for my machine and the other developers, but deployed to a playtester on Windows 10 failed to load any of the files.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I found out that, it's still trying to access the object even tho it's destroyed
Where you call save data.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
There are probably several issues. One is that interfaces don't reflect if the object has been destroyed or not.
void SomeMethod()
{
if(PlayModeUtil.NotPlayingOrExitingPlaymode)
return;
}
Another one is that you're calling it in OnDestroy() which is not entirely safe imho.
Hi all, I'm having a problem with bullets not detecting when they run into a wall. The wall has a box collider (not set to trigger), and a static rigidbody2d, on the default layer. The bullet has a circle collider (again, trigger unchecked), and a kinematic rigidbody2d, also on the default layer. Here is the code I'm using to check for collisions:
private void OnCollisionEnter2D(Collision2D other) {
Debug.Log("Bullet collided with " + other.gameObject.name);
DestroyBullet();
}
private void DestroyBullet() {
Destroy(gameObject);
// sfx, particle effects, etc.
}```
All enabled
did you read the page
oop I thought you were asking me to check mine
how are you moving the bullet?
rigidbody.velocity
don't matter kinematic and static dont trigger messages, you either remove static from wall or change ur bullet to nono-kinematic
do you have Full Kinematic Contacts enabled?
works now, thank you!
according to docs that is incorrect
Full Kinematic Contacts enables kinematic to receive events from statics
Oh I havent checked there
where can i find it?
i don't see it here https://docs.unity3d.com/Manual/CollidersOverview.html
Enabling Full Kinematic Contacts enables a Kinematic Rigidbody 2D to collide with all Rigidbody 2D Body Types.
oh..interesting, they should probably put something in their collision matrix graph
hi friends can anyone help me to create script of my fidget spinner game?
Drag clockwise and anticlockwise and when swipe and release spinner spins fast
I'm working with a navmesh agent that could potentially have navmesh obstacles put in front of its path that carve the navmesh bake. This causes the path to sometimes become PathPartial, great. The thing is, I want to make sure that the agent actually continues moving until it reaches the bloackade, but right now it just freezes and stands still. Is this a possible mechanic i can do natively (as in, is there a method or field in the agent that contains the last valid location on the path) or will i need to code that myself?
I answered here if you didnt notice #💻┃unity-talk message
Yes, Thanks Osmal I am working on this
No DMs please, keep the questions in these channels
This happens every time I try to write a concise mini tutorial.. lol
Long !code should go in a paste site 👇
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Its wobble like this Im dragging my mouse in one directoin but rotation is wobble
You are printing the abs value of the angle, remove the abs for better info
No, put it in a paste site like i said, and delete these long messages
Its just debug but i use normal value to transform.Rotate
Okay but why print the abs value? It tells you less about the direction
Does the cube have a rigidbody?
Ah you are updating the touch start pos only when you press the mouse down
You should use the value from the previous frame instead
So that you can calculate the difference each frame
alright understood
let me try
@hexed pecan https://paste.ofcode.org/LuPij67C2933Lr7gMnTCGX
still same wobble things!
Ok almost there, the problem is that centerPos is in world space, you need to convert it into screen space
Because Input.mousePosition is in screenspace, you can't mix those
Use centerPos = camera.WorldToScreenPoint(trandform.position)
Wonderful! Thank you so much brother!
@hexed pecan Now for dragging rotation i use transform.Rotate, but i also want to swipe on perticuler direction like clock wise or counter clock wise to rotate object freely by applying tourqe so how can i determine the amout of swipe from this code?
Nice 🤌
Hmm how is that different from what you currently have?
The SignedAngle gives you the angular direction of the swipe here
You can use that with rigidbody.AddTorque, if thats what you want
Yes Thanks let me try
@hexed pecan Its Working fine after applying torque with signed value, but one issue here when I touch the spinner it just snap and rotate like shown in video, i think is because of i make isdragging = true any idea when I should makes it true so that snap rotation issue solved?
Set startPos to the current mouse pos when you click, GetMouseButtonDown
Otherwise it will use an outdated startPos for one frame
@hexed pecan https://paste.ofcode.org/35jFb3y6qZQE3zx3YK4z8SK
I do this but still snap the rotation
You want previousTouchPos = Input.MousePosition on line 35
The idea is that the previous and current position will be the same when the dragging starts.
Line 53 will also conflict with this, you need to change it up a bit
Maybe add a if(isDragging) check just for line 53 in that code
Done! Working Perfect! Thanks you save my day man!
for some reason this does not work
Physics.CheckBox(triggerZone1.bounds.center, triggerZone1.bounds.extents,Quaternion.identity, LayerMask.GetMask("Player"), QueryTriggerInteraction.Ignore)
What is triggerZone1
Collider2D triggerZone1;
I don't think Physics.CheckBox works with 2d colliders.
Assuming you're actually using 2d colliders
No, it's impossible
You can remove 2d from build though.
hmmm ok
I have an interesting problem and I'm stuck. Why is this returning 0 and not 42?
it might help if you debuged type as well and then screenshot your console
type is damage
we can see in debug window
currently I have a theory it's showing the wrong dictionary
but I don't know where it's getting it from. if you have any other ideas, I would like to hear them
lol nevermind. player is extending entity (current class) and player had a seperate modifiers field . Thank you for your time 🙂
Hey! Currently I have all my Main menu's Characters and Core Managers in one Level. I am at a point now where I would like to start working on different levels that I can start loading into etc. The issue I have is, as it's my first time, I am not sure how to split up my Managers to always be loaded and because I have a few inspector assigned variables, I can't wraip my head around how I would assign these varaibles if they are in a different level?
Some advice would be fantastic
Hello, in the animation window, for the slash animation I put at the begening stopMovement and at the end startMovement, but it's like they're never called, even if the enemy ai attack, the enemy will move. Someone can help me to solve it please ?
show scripts
I pm you?
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
https://gdl.space/efuzaxajoh.cs BossController.cs
https://gdl.space/ayihujepin.cs BossAttack.cs
you put a debug.log in stopmovement ?
directly in the function ?
yes check if its called
It's not called
so then your enemy isnt stopping
Nop, only for optimisation and trying to solve some bug
in french too!
in Boss start ?
that is what I said isn't it?
Little sleepy here but for the constraint:
public class Stats<T> where T : Enum```
This applies such that the constraint is the type but now if I made a method of T such that
```cs
public void Method(T enumValue)```
Does this imply that the method accepts values of that enum?
yes
Yeah but why it's wrong ?
you do not assign the return value to a variable
Oh ! in bossAttack, yeah, I never saw it before, thanks
I did it, but it shouldn't solve my problem no?
well if you were relying on it to fill the bossController variable then it might help
I put bossController = GetComponent<bossController>(); but yeah, the boss still move when he attack
no shit, your method of stop is not being called you said.
Yeah but I don't understand why , could there be a conflict with something?
are u sure that animation runs? are you sure the transition isn't skipping animation event?
Oh idk
try putting it in the middle, test out a few diff config
I tried yesterday but the debugging was a fail, or I don't under how do, I'll check a tuto later
debugging isn't hard, you just test out different things
even with the stop event in the middle, the enemy move
Yeah
Okay so its not printing then its not running, if even in the middle it skips it then you have to be sure thats the animation your Animator is playing at runtime
so it's maybe in the animator ?
you have to look at the animator / animation at runtime to see whats happening exactly
with the enemy selected
ur transition looks wrong
looks too long
that arrow takes forever to reach slash
idle from slash ? I have to put the same time as slash to idle ?
let me see it
the transition
cause Idle and Slash seem to be playing at the same time
Only transitions do that
yeah dude
you're skipping half the clip
your transition is too long
you see your whole IDLE goes into Slash
your animation event is skipped
Ohhh
Idle to Slash should not having any Exit Time
so I have to put 0% ?
they are no exit time
Has Exit time is already Uncheck
I get it but transition is still too long
click settings and make duration l ike 0
or move the blue arrow small
make sure its almost 0 so its instant
and not skips animation keyframe
@rigid island Isn't that what they asked here lol
yeah 9am brain fart xD
🍵
Now he don't finish the animation
you changed the Slash to Idle ?
also at least now the method is running no ? stoopping
Show transition from idle to walkInPlace because that's the transition that is getting triggered
looks like the problem is mainly slash to idle
Yeah, I'll try something
if I put slash to idle at 0 it's like it
i never said put that one to zero though did i?
Nop, I just tried something
i said the problem was idle to slash
ahh
not sure why u touched slash to idle lol
Yeah I can't find how to solve it
wdym put the Slash to Idle longer
also show the new setup for your animation event keyframes
make a thread but rn this isn't a code issue so move it to #💻┃unity-talk or #🏃┃animation
How janky does it sound if I make all instant effect sources (damage, mana drain, stamina drain) independent from the ability/attack instance (the controller for which these effects are applied)? Previously I had them tied to the instance of the attack, but when working with upgrades and modifiers it makes more sense to have them separate from the controller. Unfortunately it makes a lot of extra assets on the editor as I need to make a new asset instance for each little damage effect when creating them via SO.
I'll make a thread
I'm so dumb, I forgot to remove the call of the startMovement in the script 
Thanks so much for you're help bro
It really depends on what you want. Having to much ScriptableObject is most of the time a pain, however you can alleviate the issue by making a good editor. What I am afraid of when I see that you want that, is that you might not use ScriptableObject correctly (in my opinion). They should not be mutable. This way, the concept of ability A is the same accross all your game. If you want to have a modified ability, than you would have ability A+ or ability A (Effect 1, Effect 2). In other words, you should not modified what ability A is at anytime.
They are immutable, it's just that I have Ability A (immutable) with Effect1, Effect2, Effect3, which are all unique assets to that ability
why when i have collider and nav mech agent on same object, it makes collisions with other objects register twice. When i disable nav mech agent, collisions register how expected. i tried to make the nav mech agent radius smaller but still it does what i said.
I think the problem that it seems smelly is that I can't jam all these SO assets into their own single file as well
because of editor reasons
Imagine I have a List<Collider2D>, and I want to make a method in List<T> that lets me do some operation specifically to whatever is at index 0 at the time it is called. And say this method is unique to the type that is held (Collider2D). Is there a way to do that?
I have my own class I am writing, I'm just asking like this for simplicity
if (T is Collider2D) maybe?
You can use subasset if it is an issue. You can also use [SerializeReference] if all effect are unique and shouldnt be referenced dirrectly.
idk, I want to make like a method in List<T> that takes in a generic action, which can be specified once class has a concrete instance.
List<T> has no idea that T would have a .bounds property
if (T is Collider2D collider) {
collider.bounds
}
and the goal of the action is to mutate the entry that is there
Yeah, SerializeReference is probably a good idea but then I lose some of that reusability if I want it. Hard choices.
that won't really work right. List<T> shouldn't be having any information in it that is unique to Collider2D. It should just know to pass on the information.
Is it a good reusability if they are all unique ? If they are conceptually unique, you would be making an error to reuse them because there is a good chance that they evolve differently.
I guess I should probably just make a concrete derrived class, and be done with it...
Can you just inherit from List<T> and make a ListCollider2D ? You could also make a wrapper around List<T> which would probably be more safe for Unity Serialization system.
yeah... that is probably the smarter way. ty
ok, this turned kind of awkard
i think I’m going to make a static method in the held class to make an action and tie it how it needs to be tied.
Rewriting some of my classes for the sake of it:
public class Stats<T> where T : ValueModifier
{
Dictionary</*T EnumType*/, List<T>> enumDictionary = new();
}
public abstract class ValueModifier
{
//No base enum implementation
}
public class AbilityValueModifier : ValueModifier
{
AbilityStatEnum enumEntry;
}
Trying to figure how to couple my Stats class with a type of ValueModifier with ValueModifier being composed of a float and an enum type and value. I'm assuming ValueModifier needs a constraint too for the enum type? I don't know why this seems so difficult to resolve.
You want to store different enums in your dictionary?
An example is if the constraint is AbilityStatEnum, which has values Damage, Speed, Duration, then the dictionary in Stats would be as:
Dictionary<AbilityStatEnum, List<AbilityValueModifier >>
In the constructor I'd have something like
foreach (T enumValue in Enum.GetValues(typeof(T)))
{
enumDictionary.Add(enumValue, new());
}```
to grab all enum values as keys
every enum has its unique type
you cannot store different types in a single dictionary
you'll have to store them as Types
so
Dictionary<Type, List<T>> enumDictionary = new();
I mean the values would be the key
of the specific enum
which I'm grabbing in the constructor foreach there
Maybe the idea is to give ValueModifier<Enum> constraint or something
you either have to set a default enum type for this dictionary or use Type as a key
Not too sure what you mean. It should always be a single type depending on the constraint, unless you mean generic types don't work with dictionaries here.
Your dictionary should look either like this:
Dictionary<YourSpecificEnum, List<T>> enumDictionary = new();
or like this:
Dictionary<Type, List<T>> enumDictionary = new();
Yeah, but what I'm getting confused with is how I'd grab the Enum type from T, which I'm assuming I can't and that I need another constraint that's specifically that enum
because if I set the constraint as AbilityValueModifier, I should know the dictionary key type would be AbilityStatEnum
I don't think it's possible
you already have a reference to the AbilityStatEnum in your AbilityValueModifier class
and you cannot access it as a key for your dictionary
the only thing you can do it change your class
no, actually you cannot
Ultimately the goal is that I have a Stats class that can take in a type of StatModifier and that the Stats class maps each enum value specific to what that StatModifier has declared
you still have to use Types
Anyone know if there is a way to read SO data while in the editor, for use in editor scripts ? I only know of Ressource.Load but that's for runtime use. Does a similar method exist for editor use?
I don't see why it should be a dictionary
it can just be a list of lists then
or just a List<T>
I just need some lookup
So when I do a search for all Speed modifiers I can just plug in Enum.Speed
and it'll return List<string> ?
public class Stats<T> where T : ValueModifier
{
Dictionary</*T EnumType*/, List<T>> enumDictionary = new();
}```
Would be a list of ValueModifiers
Stats is just a manager type for a bunch of different types
Yeah, and I'd get a list of all modifiers that are also of enum speed
I see, so Speed is an enum
I have a lotttt of stats which is why I'm using a dict
your logic seems quite strange to me
I do like making things difficult for myself. I'm already thinking I need some covariance because why not.
assuming I want to give value modifier a constraint
first of all, you cannot reference your enum like this
The possible solution is to make a method that find enums by its name GetEnum(string name)
And your dictionary'll be Dictionary<string, List<T>> enumDictionary then
enums are just int basically under the hood
strings can work too but enums are the way to go
c# a little janky though so I do see a lot of string lookups lately
ok, if you want another variant, you can use Dictionary<Type, List<T>> enumDictionary as I've mentioned earlier
but it's more complicated and I don't think it's better than with strings
Yeah, type would work too. Honestly I've already had the class written, but the data wasn't as coupled as I wanted.
enums are specific and you cannot just make Dictionary<enum, List<T>>
I would consider using strings, it's safe if you make sure the key is enum's fullName
this way no enum'll appear in the list more than once
I'm pretty sure just extending each class out would suffice too, but I can't see why this is so difficult rofl
Such that I have AbilityStats w/ AbilityModifiers
I don't see why fullName isn't enough
It looks like this btw:
"Microsoft.Win32.RegistryHive",
"System.Security.Cryptography.X509Certificates.X509KeyStorageFlags",
"UnityEngine.Rendering.VirtualTexturing.FilterMode",
"YourEnum"
Anyone know how to get the scriptable object using AssetDatabase loading? I would like to read some data from a SO at a specific filepath
var is confusing you here
Don't use it
what's the return type
And use the generic version of LoadAssetAtPath
So you can assign it directly to a variable of your specific SO type
GetComponent is clearly not correct here since a ScriptableObject has nothing to do with GameObjects or Components
Oh I see. Thank you tons, but I'm doing this now and it is definitely not reading the correct values 🤔 (no errors though)
What would the "correct values" be and what's happening instead
How are you even checking?
Actual values are 5 and 4, correct would be 4 and 2. I am checking using ShowNonSerializedField via naughtyattributes and then debug drawing the box with the values
Well if they're not serialized they won't be saved in the asset
if I use delegate -= function, how does program know “I’m looking for X until I find a match to remove.”
because I imagine you would never be able to do delegate += with a lambda expression, with any hope of -= to remove it. or am I incorrect?
correct, you cannot remove a delegate added via lambda
ok, so if I make
void MyFunction() { }; and += it to a delegate, how does my program now know how to -= it?
Yes you cannot remove a lambda if you do not store it. I dont know what kind of answer you are expecting to your first question, it has the invocation list stored (which takes a method and an object to invoke the method on) so it can also find the same function to remove it as well
magic
Not sure if that implementation is public
the kind of answer I’m looking for is: how do delegates identify matches for -=
basically Class->Instance->Method
Because you're passing an actual named thing in
By reference
so it’s like a reference to the object, but since it is named, it’s like the class has a static reference for that method?
MyFunction is a reference to that particular method on that particular object instance
gotcha
Unless it's static of course but then it's just the global static method
so if I want to use -=, i need to make sure I match the reference later to match
ty guys
this (in case you come from #archived-code-advanced
you are proably better in #archived-lighting
Should I copy paste?
yes, and remove from here and advanced
oka
I do have a question based on the specifics of what I'm trying to do.
I have:
Class1Base
Class1 : Class1Base
Class2<T> where T : Class1Base { T class1Instance; }
Class3 (has delegate)
I want to (un)subscribe a function to Class3 that: looks at a specific instance of Class2<Class1>, and calls a specific method in the class1Instance (of type Class1). The specific instance referenced by class1Instance changes
I could do this by making a specific concrete derived class of Class2<Class1>, but I feel like that isn't very clean (because I plan to do something like this again)
It's very difficult to wrap my head around this when everything has abstract names like this.
ContactState is a base type that holds information for grounding, slope normals, isTouchingLeftWall etc.
ContactStateManager<T> where T : ContactState, this is a class that holds a currentContactState and lastContactState.
Some ContactStates are derrived classes (eg PlayerContactState has bools for onJumpableGround, onSlipperyFloor etc)
PlayerContactState has a function to add new information into the contact state on a collision callback, which is something that the base ContactState class cannot have
I want to make sure ContactStateManager<PlayerContactState> can subscribe a function, so when we have a collision callback, the currentPlayerState gets updated
does this help?
I'm not quite sure I see your problem. When you subscribe you do so using a specific instance+method when you want to unsubscribe you use the same instance+method. So where exactly is the problem?
I want to (un)subscribe a method in whichever thing is composed, because the instance referenced by currentState gets moved around
does not matter
and I want to avoid subscribing the instance of the currentState,
I want to make sure we look into whatever the ContactStateManager property currently points to for its current state, if that makes sense
and the generic ContactStateManager<T> has no knowledge of exactly what type of ContactState T is
ok, sounds like you need to keep your own reference to what is subscribed and then check that
well, I'm trying to figure out how to do that most cleanly, without messing with the generic
what I'm thinking of right now, is to make an extension method specifically for the concrete ContactStateManager<PlayerContactState>, so I can specifically subscribe the right instance
Hey folks. In an attempt at spreading out AI processing over multiple frames, I'm moving away from each NPC processing their own Update() call, and leveraging a master object to selectively call each NPC's Update() in a distributed manner. However, I just noticed the list of NPCs consists of the GameObjects, not the NPC AI component attached to the GameObjects. I'm worried the performance hit from calling GetComponent every critter every update will make this a futile effort. Is my only recourse to create and manage a second list of the underlying components I wish to call update on?
why not just use a list of the components in the first place?
Just make 1 list of the components, the way you worded this sounds like you did not even create the list yourself
It is all my own code, apologies for text having limitations for conveying ideas :/ When an NPC is instantiated I add its gameobject to a list, and that list is what gets used everywhere for higher level display and management. It is also used for saving and loading.
why, just add the correct component to the list
component->gameObject == trivial
gameObject->component == not trivial
I didn't realize the hit from grabbing the gameObject from the component was much less than vice-versa.
Thank you for that
of course all components have a .gameObject variable
Saving the gameObjects made sense when I was trying to export the lists to JSON for saving in a single call. But that all fell apart at some point and I did it manually anyways haha... I never went back and thought about revisiting the list model. This shouldn't be too hard to refactor then.
1000 entities doing circlecasts for engagement is just brutal. I'm turning engagement checks on/off by zones now, and have optimized the physics layers being used for it, so now the next step is to split up the AI calls and distribute them more across frames.
Hello. What would be the most efficient way to call an animator bool to be true on a lot of objects and have them synced up? Doing it through a for loop always makes them a little out of sync.
use the same animator instance
Thanks, sorted it c:
Every NPC in my game has a boxcollider on the same layer. Not for localized physics so much as for AI processing. When doing raycasts or circle casts for selecting NPCs or analyzing engagement, each function loops through, evaluates the faction and type and handles it appropriately. For dense engagements this can mean iterating through dozens of friendly NPCs and ignoring them. I've considered making each NPC's box collider belong to its own layer and adding intelligence everywhere so the casts are only done on the layers of interest. This would seem like a good performance boost yes? Or might adding extra layers to the Physics engine outweigh the extra looping? Just curious what folks might think of this.
I started a 2D project and imported a template. I decided to delete that project and start over, but I cant import my template now. I open it and select my project, but it just launches the project without importing any files. Anybody know how I can fix this?
Well the problem can be that there is a possiblity of running out of layers. Is that relevant to you? Could there be idk 16-20-50 different teams? If not and its just 3-4 max then sure. You can use the layers.
Right now I have 5 layers for functional purposes of the tilemaps, shadows and water. And 6 for the teams.
The layers have all interactions disabled with everything. I just wasn't sure if there would be a performance hit from the base adding of layers to the platform.
But to be honest for spatial quarries using(/abusing) the physics engine like this is not recommended.
It will definitely work for smaller games no problem. But if you are going for something truly big I think you need to invest a day/two into implementing a quad tree (/oct tree)
Not really. Adding a layer should have 0 (or 0.00001%) impact
Ok, great to know.
total layers makes no difference. Layers are stored as the individual bits of a 32 bit integer
you need to store 1 integer for the whole layer mask, and your CPU will perform operations on the whole integer
:nod:
whether you use 5 of the 32 bits, or 32 of 32 bits, the processor still needs to do the operation with the whole integer
Does the optimization I described seem like a fair approach?
Rather than having all NPCs be on the same layer, and having to post-filter the circle-casts...just assign them all to individual layers and filter on the cast itself?
layers help you filter out irrelevant collisions
lets say Goombas are on an Enemy layer, and Enemy layer interacts with Terrain layer, but not Enemy layer.
if I make a giant death ball of 500 goombas on one spot, on a ground tile, then your game will create 500 collisions for goomba-floor.
Well, these collisions aren't used dynamically.
They are a way for the AI to determine who is close.
All interactions are handled from script via casta.
if you do NOT use this layer filtering, then the game will generate 500^2 = 250,000 collision callbacks for all the goomba-goomba collisions
Yes I understand the fundamentals from a physics engine standpoint. Its more about how to best optimize using physics for AI. I've also experimented with distance calculations between every NPC to every other NPC, but that seems very wasteful compared to casting.
if unity's physics engine is running, then it WILL try to calculate it
unless you actually take it out of simulation, or don't simulate
Yes but I have all layer interactions disabled in the matrix.
oh, then layer is just an integer between 1-32 that you can use for whatever purpose then
especially filtering on casts
:nod: yeah I was more worried about some kind of overhead that wasn't obvious I might incur.
but using gameobject layer isn't the smartest way to do this, because it has limitations
Circle casting 200 NPCs every 100ms was bringing me down to 30fps.
I would make a component or something to keep tabs on everything
I've added a sub-object to the gameobject that holds the box collider with the layer.
when you circle cast, do you want to filter by layer?
That was the whole point of this conversation haha...
I would use layers to help sort things by general type of what should interact with what
Originally every NPC had a sub-gameobject with a box collider component on it on the "NPC" layer. Then when doing circle/ray casts I'd get every NPC and filter in a loop by Faction or Type.
this way you can call Cast/CircleCast etc and filter effectively using the layer
My optimization was to assign each boxcollider to its own layer ie, Player1, Player2, Player3... and filter on the cast itself
I do not think that is helpful
unity's casting methods already filter by what things are in the vicinity
it first checks bounds to roughly determine what colliders are even relevant for a cast query
In example 1 I might get 20 friendly NPCs and 4 enemies. I then need to loop in code to sort them after the cast.
In example 2, I only get the 4 enemies.
layers are primarily a means of prefiltering and optimizing physics queries, like casting/collision/etc
Yes, hence why in example 2 I only get the 4 enemies I am interested in...
but you usually want to filter by gamelogic. not by proximity
We are saying the same thing.
Engagement is typically done by proximity though?
I wish for my NPCs to only engage if they are sufficiently close to an enemy and have LOS.
you mean when you have a big death ball of lots of things colliding?
if you do not want those to be queried like that, you want to filter them out with layers
Exactly what I proposed as my optimization.
My reason for asking, was concern from the overhead adding more layers to the system might incur that were not obvious. For example every NPC is a rigidbody interacting with the floor (this is a top-down 2D RTS game), and I have observed adding more layers will incur a penalty to the Physics2D friction calculations.
what you proposed is giving every NPC its own layer
No, every group of NPCs...
Player1, Player2, Player3...
There's only 5 players max.
So all of Player1's units would be on the Player1 layer.
I apologize if that wasn't clear.
Hey everybody, I have an array of Vector3 that forms an outline. Each Vector3 has two neighbours that they are connected to. But my array is not ordered. So my question is: What is the name of the algorithm/approach to order the array and pass it to my lineRenderer? All Vector3 are on a grid position if that helps. 😄
Sort
Just pick any node and do a depth first search until it finds itself again
The traversal order will be a valid outline list
So I have this code that is currently only used to enable and set Dynamic Resolution on game start (or through console).
https://hastebin.com/share/vafotaweyu.java
Issue is, the LoadSettings method always results in a black screen.
When I use the console command in order to manually apply it, it works properly, and both should use the same methods, am I missing anything?
Console Command Behavior:
- pp set gfx_drs_enabled 1 (default: 0) -> BLACK SCREEN (for some reason is all black but next command fixes it)
- pp set gfx_drs_value 0.4 (default: 1) -> you can now see again and the dynamic resolution is applied
I know for a fact LoadSettings() loads them in the same order because of the console output (see image below)
Also, tried to add a delay to LoadSettings(), just to make sure something external wasn't the cause of the issue.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
oh thx
When debugging, occasionally I'll trigger a halt on NullReferenceException: Object reference not set to an instance of an object. Despite having a live VStudio debug session, the IDE isn't breakpointing on this error so I can identify the line number and observe the Call stack. How does one effectively debug these kinds of errors?
Look in the unity console, it will give you all the information you need
and the stack trace?
I must not be aware of what that is?
Call Stack, which you mentioned above
The Call Stack is only visible in VStudio. Since VStudio isn't breakpointing during this error, its not refreshed.
No also in the console
I didn't know a stack trace view existed in the console. Interesting. How does one enable it?
Do you have collapse enabled in the console?
I'm clicking COLLAPSE on and off without any visible effect, at least in this stopped state.
Collapse off, additional info or stack trace at bottom of console when an error is selected
AFAIK collapse just hides duplicate entries. But no, I am not seeing additional info for this type of error when I click it. Note that some errors do show additional info and break in the debugger. But this type of error seems different.
Yeah, hence why this is so frustrating haha. At least I am used to debugging blind in my day job so can usually sort it out. Hrmph.
screenshot your complete console window
Let me get another error going. Had to reset and try again since we've been talking.
Oh..there it is. On the top right is 3 dots, and under that is settings to enable/disable stack tracing. I'd completely missed it being so small.
Let me see if that helps.
Most things were apparently OFF.
Is there a way I can "Straiten Out" my navmesh line? I want it to stay away from the corners as it gets to a turn
make your agent radius wider or your obstacle size greater
Ok , I will try this. Thank you
hello my friends. i am once again asking for your financial support: https://paste.ofcode.org/vsACHHwrMjz4jhwREwwRrX
line 30 of this is what i'm getting an error for. when i playtest, if the ray isn't connecting with anything, it constantly returns a null reference exception:
can't figure out what the issue is
Yes, look at what object u are trying to get a component on. If there is no hit object, you are still trying to find a component
In this method if there is no extra logic needed, you can return early if there is no hit
ah so i need to return out if nothing is getting hit. i didn't think that would effect the whole method. i thought that just worked for if statements. thank you
You can either put all the logic in the if(isHitting) statement or return if not hitting. Both result in the same thing, you dont have to return
i have simulated Celeste's room switching behaviour for the camera. ive done this by making a room prefab which has a cinemachine virtual camera and an Empty called "Bounds" which has a polygon collider. The virtual camera cannot leave the bounds area, and this collider is set as a trigger. Next to the bounds is another Room prefab. So, when the player leaves the first bounds, the camera pans to the camera within the bounds that the player is in now.
The issue is that the players movement doesnt account for this. For example, when leaving room 1 and entering room 2 to the right side, i can stop moving. the player will then be barely visible. or, when i transition to a room up, instead of pausing the player movement and giving me a little "oomph" after the transition, gravity just pulls me straight down again.
How do you guys suggest to fix this? i honestly have no idea where to strt
gotcha. okay, i get it now. putting the return there just makes it so i can do the other stuff outside of the if statement
also sorry if i respond slowly il be showering rq
i didin't understand anything from this
im not sure how else to explain it 
I'm trying to teach a stick figure to stand using machine learning and my question is what would be the best joint type to use in a 2D space? I believe the only way to set a rotation angle with 2D hinge is by setting the min and max limits (would like to wrong there). The limit approach results in overly stiff movement and sometimes causes the joint to rotate a full 360 to reach the specified limit. Configurable Joint seems to be the best option if it were available in 2D.
The limits wouldnt be for moving the limb, it would just be for the range of motion that can exist. You might have to apply your own torque to reach a desired rotation (which your AI can provide). I havent used 2d so I dont know the approach commonly used, but the term is 2d active ragdoll if you want to try to find a tutorial online.
2d joints do look a lot more limited, configurable joint allows you to set a target rotation
Thanks for your response. I believe torque is really only a max speed setting on the hingejoint 2d. I think I might just give the ML agent access to the limits and see what it comes up with (though I'm sure it'll start by helicopter'ing itself out of existence)
Sorry I didnt mean the torque on the hinge joint at all, I meant adding your own torque towards a desired rotation. The limits would be defined by you most likely, since it wouldnt really make sense to let the agent do it. If the agent did it then yea it wouldnt be making a stickman walk, itd probably figure out a way to compress and launch itself like a spring instead of walking lol
i return with request for aid. https://paste.ofcode.org/p8EkWWhEdvJcQEUxkxLPjn
i'm trying to make it so the referenced script is forced to call it's StopMethod when the player is no longer looking at the object they are interacting with, however that isn't working. i'm able to save a reference to the previous script, but the code i have now doesn't work and i ain't sure why
Show the full script and StopMethod
i am stuck in "fullscreen" mode in the unity editor, does anyone know how i can get out of it, i can provide a ss if needed
https://paste.ofcode.org/8ajJ9P7XzADsgDgu8Ma4iG player script
https://paste.ofcode.org/35XzXHyJN8gvEhx8R27dt5x script with stopmethod
Which part exactly isn't working? Put some Debug.Logs in the related methods and find out if they run as expected
i have. the methods function properly. the problem is somewhere in the player script, i'm assuming at line 142, as it doesn't call the stopmethod when the previous if statement returns false
i know its populating lastScript as i used debug.log to run an if statement by itself to send if it isn't null
trying to use an else if() statement doesn't work though, so i'm not sure what the issue is there
but i'm pretty sure that would be the correct way to try to do this
i'm just not executing something correctly
Lines 137+:cs else { interactScript.StopMethod(); }
I feel like this shouldn't be inside the if statement with TryGetComponent
It will currently only detect that you stop pressing the mouse button when the ray is also hitting the object
correct. that is intended. but i'm trying to make it call stopMethod if the ray stops hitting the object, even if the mousebutton is still pressed
Ok I see
aint tryna have no exploits you feel me
Is there any other way to accomplish this?
Could you draw a line on this screenshot to demonstrate the kind of line you want?
It's a bit unclear to me
one sec
Well that message wasn't really worth the ping
Something like the black line
where it uses the corners better
Ok yeah that's what I was thinking, just wanted to be sure
Does UnityEvent require to be on MonoBehavior class?
@tawny mountain The NavMesh API is a bit limited for this kinda stuff
You could maybe use a bunch of NavMesh.Raycasts but it would be really hacky and inaccurate
What about using a grid on the plane surface and use small grid cells with A*
Sounds like a grid-based A* implementation would work better for this, yes
I'm working on getting a grid on the plane surface.. I'm making it with game object and trying to get it on the plane
no it is not required in the sense that you can write it in a poco and it wont complain. unity event is so you can easily plug in events through inspector, so if you want to use it for its purpose then yea its gonna have to exist on a monobehaviour in some form. If its on a poco, the class will have to be serializeable then exist on a mono
I dont know what a poco is
Plain Old C Object.
It is a class that doesn't inherit from MonoBehaviour or anything like that
Just a class
Got it
so I might have broken something.
Not sure if related:
https://i.gyazo.com/80b1a049884f5e837917abd3187ae981.png
But how can I find the error in code with this type of error message?
that one is an editor error, can likely be ignored by clearing it or restarting unity
I will try
That actually worked..
Idk if I should be happy or sad that I get those errors randomly :}
neutral, just ignore it and keep working if its not an actual common issue. Sometimes ill get them while just leaving VFX graph open. If u havent added any editor stuff, no need to care
Alright thanks 😄
What is best way to mimic const (from C++, const SomeClass*) in C#?
private readonly SomeClass obj; looks broken IMHO (when working with referencial types, object's state can still bechanged despite the variable being declared as readonly - so what's the point?)
because I am still able to change obj.var = ... or obj.ChangeSomeVarInObject()
Note that I don't want to make entire class completely immutable. In some context class should have non-const object state but I also want to be able to make its object state const in other cases
it sounds like you just want specific fields itself to be const, readonly only stops you from changing it to a new instance
hei, i got a quick question, does anyone knows why i have this error in the code?
this is the piece of code
It says your index for an element access in the loop was out of range
Either vertices or uvs
You can make obj.var itself into a readonly field too. Or use access modifiers to prevent it from being changed from outside
readonly fields, or properties that have a getter only, can be set in the constructor
Or in the initializer
i dont really see the problem.. i start from 0 go to < than the height and the width
What if vertex index is greater than vertices array or uvs array?
Maybe consider breaking the loop is index greater than length of each array
What is the type of meshData?
Is it a Mesh? I thought it was a MeshData object but that doesn't have vertices
maybe the vertexIndex + width?
Are you absolutely sure that width and height are the same values that you use as meshWidth and meshHeight?
Oh also you are accessing heightMap[x, y], so it could be that as well
i have a noise map and thats what i use for the width and the height, and they have worked fine so far
Do you pass those same values into the MeshData constructor as well?
i pass this
readonly means the variable you declare cannot be re-instantiated as a new instance but that doesn't mean it's immutable. If you want to make the data of that instance inaccessible, then you need to restrict access from within that class itself with accessor property or methods.
But where do you set the meshData's vertices array (or where do you call its constructor)?
Honestly showing the whole script(s) whould be easier
You use [y, x] as the indices (in heightMap[y, x]), but your width corrsponds to the first dimension and height corresponds to the second dimension
Isn't that wrong?
If your map is non square then it's not correct
It seems I wasn't clear enough: variables of my custom class should be generally non-const, but I want to be able to pass that object to some functions and not let those functions change data of object. TLDR: Only in some contexts object should be passed as constant (similar to const SomeClass* from C++), but they don't have to be const always. Is such goal achievable in C#?
You can pass stuff as interfaces which limits the scope of the data you pass (can pass method getter implementations and such)
you're right
it seems the error is still there
Start by moving heightMap[y, x] into a different line so you know which [] is producing the error
Oh wait, the error tells that it is about the heightMap, not the vertices
Notice the (System.Single[,] heightMap)
i dont really understand why but once i made the height equal to the square it works
and now i can modify it
maybe it needed to be a square in the initialization? but i dont really get it
@restive turtle What did you change to address this issue?
Really just sounds like your X and Y dimensions are flipped at some point
i made the width and the height equal and then i clicked start
maybe because im relying on the noise map that i have and it can not be bigger that that one?
but it makes no sense cause i can modify it
You should try swapping the GetLength(0) and GetLength(1) instead
And keep the map non-square for testing purposes
sure
With this I meant that it's not correct with your current setup. But after a fix it should be
doesnt work.
it shows that error again
Show current !code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
No screenshots, use a paste site
how do i give you the link to the first one?#
like this?
it seems that now it works properly, and i dont really know why. i change again getLength(0) with getLength(1 ) and it works with no problem.
jesus....
Oh, you swapped two things, so it's like you changed nothing
yes
You changed [y, x] to [x, y]
Change either one.
It makes sense to have [x, y] and width = GetLength(0), height = GetLength(1)
Unless you have a reason to have y first
so still having the issue, but i think i've better narrowed down what isn't working. i can save a reference to the previous script into lastScript, but lastScript only has the value if the ray is detecting an object with the InteractScript component. so i think i need to go about saving the reference differently, but i don't know what other methods there are to do this. would appreciate a point in the right direction
To put it simply, try this exact code ^ but just change [y, x] to [x, y]
Let me know if it works
public class Stats<T, E>
where T : ValueModifier<E>
where E : Enum
{
Dictionary<E, List<T>> enumDictionary = new();
}
Solved it with a double constraint. Few things that's confusing is that even though T implies E, I still need to add that constraint onto Stats. I think the problem arrives from the fact that enums can't be extended upon or be overridden so I have to use a base implementation of type Enum.
and so the usage would be as:
public Stats<AbilityModifier, AbilityStatType> AbilityStats { get; }
public Stats<EffectModifier, EffectStatType> EffectStats { get; }
//IDE will catch this error
//public Stats<EffectModifier, AbilityStatType> WrongStats { get; }
enums can't be extended upon
Not sure if this is what you mean at all, but enums do support extension methods
Oh do they? As different types too?
Yes, if I get what you meancs public static class Ext { public static bool IsThing(this MyEnum e) { return e == MyEnum.Thing; } } public enum MyEnum { Nothing, Thing, }
I've been just remaking my enums if I needed to extend upon them. It's a little sloppy but it somewhat works assuming I know the type.
Ah, yeah that makes sense, but I'd probably have to design that for runtime, yeah?
Yeah it probably doesn't solve your issue, just thought I'd point it out
i've copied everything into a new project and it still aint working. at least now i know it's not just a corrupted project and i am doing something wrong.
so i know what the issue is for sure now. trying to reference the script only works if the ray is detecting something. but i can't get it to work otherwise and i just can't figure anything else out, not even with chatgpt, so for now i'm just gonna make it so the player can't move or look around. only compromise i can think of for it to not get screwed up
Had to scroll a bit, but yeah, that's what your code does.
You have some messed logic with the nested of statements there.
Something you have been pointed out by Osmal, but it seems like you misunderstood.
this is gonna be super specific but does anyone know of a way to completely ignore colour in a texture? not just turning it into greyscale but treating it as if the base colour is white
or rather a material
Not sure what you mean by "treating it as a white or a material", but you can do all sorts of stuff in the shader.
for example taking image 1 but having a seperate camera see it as image 2
i essentially want one camera to see a different material than another camera does
but i don't think that's possible
If you want to specifically condition on a color, you'd need a custom shader for that.
It's possible with replacement shaders(a feature that allows a camera to render objects with a different shader/material)
What render pipeline are you using?
urp and a custom shader that renders shadows as crosshatching
Yeah was about to say, replacement shaders are possible with BiRP
it's just wildly inconsistent depending on the uv for some reason
In URP and HDRP you need to use a custom render pass, as far as I know
I implemented thermal camera on Builtin RP some years ago but didnt make it for HDRP yet, but it should be possible
so i could apply a render pass to one camera that throws out the base colour?
i've not delved into shader passes yet
You could also just swap the material for the object just before the other camera renders 🤔 that could be simpler in your case
ideally i could just swap the base colour between its set value and 255,255,255
then i wouldn't have to add any additional materials for each new object
Yeah true
i've never delved into render passes though, will be a learning curve i reckon lol
Hi there I was wondering how could I add a double jump and a dash to the 2d platformer microgame
actually yeah i could use replacement shaders to just swap between the original shader and a copy of the shader that doesn't accept base colours or textures
If its just one/some objects then you don't need a custom pass, is what Im saying. Just modify/swap a material just before a camera renders
Then I'd say look into custom passes 👍
just from skimming over the documentation shader replacements do look like a good bet but are they only functional for built in?
Yeah they are only for builtin rp
Yeah, they were pretty convenient
guess i'm diving into render passes then
i found this, might try it
seems too straight forward
although i'd have to get an array of every material or make it get the material of whatever is in the camera's view which doesn't seem performant
although i could do a sphere cast
yeah that might work
Could also stencil it and render the scene twice with different layers rendering
Is this chatgpt?
OnPre/PostRender does not work on SRP.
You want to use these https://docs.unity3d.com/ScriptReference/Rendering.RenderPipelineManager.html
looks like stackoverflow
nah stack exchange
yer close enough
bugger
Not much different, you just use events in SRP
can i still use it as a script attached to the camera? the render pass is a bit over my head atm
Sure, it doesnt matter where the script is as long as it runs
IIRC you want to subscribe to one of the beginXRendering events
yeah onbegincamerarendering seems right
okay so it works but i can't figure out how to isolate it to a single camera
i assumed i could pass a camera into the function since it has room for one but it doesn't appear to work like that
i just need to insert it before and after the highlighted camera
but i can't figure out how
Oh, so does it work?
actually, creating a new class for every enum...
2 classes, actually
going to be 3 :)
don't you think you should reconsider your functionality...
The class to enum is just a hard constraint I've set. I could technically just pair everything by dictionaries like I was doing before, but this way actually makes it a specific type instead of a data struct of data coupling
With a dictionary that combination of enum and class type would not be caught so I just feel like it's wonky. Honestly not the biggest problem but I'd just wanted to pair stuff up more tightly.
I think you're overthinking it 😅
Here I have 2 enemies. One of them is using A* and the Other Dijkstra. the enemy using Dijkstra shows the path and colors the node but the A* doesnt. I am using the same grid and node for both Pathfinders
Can you debug the actual A* path that's calculated? It might just be not calculated.
Or, the code with coloring grid for A* has problem with it.
Or, it's been using same "visited" array etc...
Yup the A* works if i remove Dijkstra
The enemies are at different locations, right? The problem is definitely with integration with Grid(or other script, since I can only assume how you structured your code)
sounds like you have a static variable in there or you are using the same instance of a class for both results
Im sharing the grid and the node with both pathfinders
but that is the source data, no? Not the path result data
Its the path result data
if i use both of them at once of them doesnt show the path
then don't share
Do you have "visited" variable in your node GameObject?
I have to use 2 different path finders on 2 different enemies
same input graph doesnt matter
modifying the shared input is a bad practice, unless you will clear the intermediate results
Hello all, hope this is the correct place to ask. Is there a startup argument i could use with a unity game that does what -Duser.language=en does in java? many thanks.
I think not but check https://docs.unity3d.com/Manual/PlayerCommandLineArguments.html
I'm afraid I've already checked those... Any other way I could force the game into english locale?
not a command line argument but you could try
https://learn.microsoft.com/en-us/dotnet/api/system.globalization.cultureinfo.defaultthreadcurrentculture?view=net-8.0&redirectedfrom=MSDN#System_Globalization_CultureInfo_DefaultThreadCurrentCulture
using invariant culture will give you en-us
Halo
I installed a Nuget package, then I get a .nuspec file
I can't refer anything from the package from my scripts. Is there some asmdef setup for this to work? Bcoz the .nuspec can't be assigned to anything and I'm not getting a .dll?
did you use NuGet in VS ?
sorry, I don't know that. If I want a nuget package in a Unity project I...
- Create a new VS project.
- Install the Nuget package
- Locate the package dll
- Copy that dll to a Assets/Plugins folder in the Unity project
Yeah this package doesn't give a dll
https://www.nuget.org/packages/SixLabors.ImageSharp
In case it's relevant
pure c# source?
Yes i think
think? you mean you dont know?
I see the link you sent is for .Net 6 which is not compatible with Unity anyway
no, normally nuget packages are in dll format
They're archive files, change the extension to zip and you'll be able to open it. The DLLs are somewhere inside them
They = .nuspec?
Tried that and didn't work
Yeah supposedly this package solves that and dumps it in Unity
But in this case it doesn't give a .dll
any advice on how I can solve this?
essentially what's going on is
- hand gets disable when I pickup an object
- object attaches to hand's attach point.
- when I let go, the hand is enabled again and object is let go
- the object and hand's colliders interact. Hand is immovable so object shoots out.
Hello does somebody know is it possible to detect point of collision in this case?
i have vehicle that has not Kinetic Rigidbody , and child Gameobject "Collision" with Mesh Collider.
i need detect hit position when Mesh Collider collide with Wall collider.
Tried to add rb with IsKinetick check marked to that child but it gives no effect. but works when isKinetick check mark turned OFF but in this case it loses all sense
OnCollisionEnter function never executes
Vr hand collision
Collision detect without rigidbody
I think this question belongs here. I bought a cool FPS pack that I felt would work well with the game I am trying to make but there is an error and I can't find the solution for it. the error reads "Quality Settings does not contain a definition for globalTextureMipmapLimit.
thats not helpful lol
yea and that's the problem I have with it 0_o. it's not a script I wrote but one I DLed and the links to their website are no help and their discord link is down. I will try e-mail next but I figured I'd post here first to see if anyone knows what it is somehow and it's an easy fix or something lol
if its a paid Asset def get support or get your refund lol.
sounds like it could be an assembly definition issue
thanks. that gives me a new place to look 🙂
Hello everyone. I'm trying to setup the testrunner in Unity. I'm using 2022.1.13f and the default version of the Test Framework is 1.1.3 but the latest stable version seems to be 1.4. Checking the Package Manager only 1.1.3 is available and I can't find any way to update to 1.4. Can anyone point me to a resource on this?
when working with a struct, you effectively call the constructor every time you assign or return it, right?
or is the copying part of passing by value smarter than that?
It doesn't call the constructor, it just copies the whole chunk of memory from one place to the other
Anyone know of any good resource for prefab tweens? I'm using DOTween and don't have an animation background, and despite my best efforts at googling up nice juicy animations, my tweens all look kind of stupid and stunted.
I want to make a .. pretty simple? UI animation for when something like a dialog or icon appears. I want a little bit of a juicy "sproing", and am kinda discouraged with my best efforts to do this.
(or is this just .. what I gotta do, and maybe ask in #🏃┃animation for tips on improving a specific animation)
DOTween has a bunch of built in Easing functions you can use
Largely corresponding to these: https://easings.net/
Yeah, I'm trying DOPunchScale for this but.. it's .. not quite right.. but I don't have the eye to see what
easings.net and DG documentation have been up nearly 100% of this exercise on my other monitor 😛
To use in DotWeen you do something like .SetEase(Ease.OutBack) on your tween
Sorry, my question might not be clear. I know exactly how to tell dotween what to do.. but I'm bad at figuring out what eases/timing/coefficients for these tweens would look good. 😛
oh
That's more of an art than a science I guess. I usually just try a bunch until I like one
15 minutes of effort and it still is just all wrong
that's using a DOPunchScale.. but it's like.. not "settling" fast enough and it's seeming to settle on the wrong scale? I dunno. It's.. just coefficients on the tween but I cannot for the life of me get it to look right
DOPunchScale punches the scale to the destination and back again so .. i dunno if i should use it at all, actually.. Maybe I want to do two overlapping tweens on scale - one that's punching "around 1" and another that's growing it from 0-1 at the same time. Although I'm presuming that DOTween is gonna be able to figure that out
Hello, i was wondering is there a reason that stuff like DrawWireDisc is part of the Handles and not Gizmos?
If i am correct Gizmos can be used in a build too but Handles only in editor?
I think it would be nice to have OnDrawWireDisc also work in a build
ChatGPT to the rescue.
Turns out I was making it more complicated than it needed to be. Ease.InBack and OutBack pretty much gave me just what I needed, with a little tweaking to an intermediate step
Not sure why, but I'd expect it has to do with the fact that handles can manipulate scene/editor values. One way to draw the same stuff as handles, is to use a wireframe shader Material on a regular mesh. Of course, this option means you'd need a mesh/ or to dynamically create one, of a "ring/disk". That said, I agree, it would be nice to have those functions available for build.
yeah, there probably are a few assets for this, but the options out of the box would be nice. this can probably be suggested on the forums somewhere i assume. I mostly like it so i don't have to use a model
BoundsInt not working even tho the point is clearly within...any thoughts?
Neither Gizmos nor Handles will be visible in builds
ah yeah, i probably misread somewhere or read some wrong info
I believe Gizmos can be visible in the Game view as well as the Scene view, maybe that is the info you misread as a build
yeah, it's probably something like that
If you guys use ChatGPT I setup the "How would you like ChatGPT to respond?" part of the Custom Instructions with the following:
Chat GPT should always respond with code examples when asked a coding question. I don't ask just to know what you think, I want actual examples. I don't care how complex it may be. I pay for this service, I'd prefer not to have prompts wasted with barebone answers.
It has been providing much more concrete answers and examples since I've done this.
Last thing you want to do is make chatgpt angry
It's worked really well! I was refactoring code and it kept saying it was a lot of work. Once I put that instruction it's just been flying through everything without hesitation
Not for beginners I'd agree. But it certainly is for people that can guide it.
it does a good job reading back the vulkan documentation that I love to neglect
Yea, I have nothing lol A blanket statement like that is just so bizarre.
Thing has no problem setting up builders, factories, strategies with little push. Just a basic here's my code, I know a builder would be better, show me. It's bizarre not to think of it as a useful tool to increase speed of workflow.
ah yes, the spam generator can take the most basic and common patterns which already exist online and show it to me
It's a spam generator that causes a lot of issues.
But mostly just keep in mind that it's against the rules to use it here in questions or answers
#📖┃code-of-conduct message
The thing has no problem providing you a weighted reponse based on a uncomprehensible amount of scraped data. At the end of the day it's a storytelling engine. It's giving you what it thinks is the best answer, And the "best answer" does not have to be true in any capacity.
When it gives you code it isn't because it understands how C# fundamentally works and implemented the request, It just gives you as close to similar code as possible that it has an explicit connection to the words you asked it about
Um yes. That is fine 90% of the time. If you're not a beginner you'll recognize the other 10%. I get it though, purests only. No problem.
It's not about being pure, It's about wanting support from someone who knows what they are talking about
I'm going to be using the 2D lighting in my project. However, I am wondering if I should apply this first before anything when starting the project. What I'm asking is if there are issues installing lighting later, and if starting at the beginning is the best action to do.
if you knew what you were doing, you wouldn’t be using chatGPT to make code in the first place
and if you don’t know what you are doing, then you have no ability to correct the mistakes that chatGPT will inevitably produce
neither target demographic is well served by this
I have 20 years of programming experience. I use it mainly to minimize the amount of typing I have to do. I didn't come here to convince people, didn't realize there was so much salt regarding this when I've had a good experience with the tool.
chatGPT doesn’t really know anything. it just puts things together with what looks like proper syntax because it specializes in language
The salt here is due to the huge cohort of people who come here every day with chatGPT code that needs "fixing". If you are getting value from the tool don't let anyone deter you from using it, but it just has a bad smell around here.
it doesn’t actually know what any given line of code does, it doesn’t know how it fits into any part of the program, and it will actively bullshit you and tell you it’s correct
Are you basing this off gpt4? and actually training it a bit and breaking down the issue?
I remember you can ask it for a 60 card yugioh deck, and it will give you a 45 card deck with half of them being made up. and if you ask it about the made up cards, it will return card text that sounds like a real yugioh card. But that isn’t a real card
same thing happens with code
We already know it's bad at math.
i have also tried to make it work with pokemon strategies before. it just copy paste parts of other strategies that have been out, and mashes them together.
It will recommend combos of pokemon that make no sense together, or tell you to run a pokemon with moves/abilities that it doesn’t learn
but if you knew nothing about pokemon, it sure sounds right
it will also tell you how to play the strat, while making up parts that contradict what was there before
it cannot do logic
it’s specialty is language syntax
yes, which programming is
is not, you mean
and again, a tool is only as good as the person who uses it
you could have provided it all the pokemon data and the ruleset instead of hoping it knew
a good programmer won’t use chatGPT
I mean if you can't find a use for it, then it's not a big deal
this is complete nonsense
how so?
because you argue that you can only get a logical outcome if you provide all the background knowledge of a particular gigantic topic
You're not using it to it's actual capability and you just want it to work perfectly out of the box. It's funny really.
which means you can only expect it to create good code if your prompt contains years of explanation of basic logic
then explain what the actual capability is that causes chatGPT to output good code, that saves more time than it costs to fix
That's false man, you don't need perfect code lol you're talking like you want to be able to say design me the final fantasy 8 battle system. Provide me all code and tell me how to hook it up. It's just unrealistic.
that’s literally how people use chatGPT
Yea but that's not a good way to use it
either code from one language goes in, expecting output in a different language. Or requesting brand new code to do X
So the way I use it is mainly for refactoring and I don't take it at face value. I might upload one of my scripts and ask it if it thinks there's a better or more efficient way to do something, and then I'll research that to see if it's true.
A lot of these complaints really are giving me gpt 3.5 vibes tbh and not 4+
Heyo, anyone has an idea why unity tells me my meshcollider mesh must have at least 3 distinct verts even tho the mesh is working fine? Using linq also tells me the verts are not distinct and returns a distinct count of 1 (Debug.Log($"Verts: {verts.Length}, Distinct: {verts.Distinct().Count()}");) ... The mesh is generated using a compute shader
Have you tried logging the values of those vertices?
It kinda sounds like the mesh is fine on the GPU side (used for rendering), but not on the CPU side (used for physics)
I haven't done that myself, but maybe you need to sync the mesh data to the CPU somehow
This should be set to true at least
https://docs.unity3d.com/ScriptReference/Mesh-isReadable.html
Same results when logging the first 1000 verts, they are all at 0,0,0
How are you reading back the vertices etc. from the compute shader back to CPU?
https://forum.unity.com/threads/render-object-in-different-material-per-camera-need-onprecull-onpostrender-alternative.825303/
man this is basically exactly what i need but there is no more information than the functions i'm already using
Show your current code
private void OnEnable()
{
RenderPipelineManager.beginCameraRendering += OnBeginCameraRendering;
RenderPipelineManager.endCameraRendering += OnEndCameraRendering;
thisCamera = GetComponent<Camera>();
}
void OnBeginCameraRendering(ScriptableRenderContext context, Camera camera)
{
camera = camera.GetComponent<Camera>();
for (int i = 0; i < gameObjects.Length; i++)
{
Renderer renderer = gameObjects[i].GetComponent<Renderer>();
if (renderer != null)
{
Material material = renderer.material;
Debug.Log("i can see everything");
_default = material.GetColor(colorPropertyName);
material.SetColor(colorPropertyName, myColor);
}
}
}
void OnEndCameraRendering(ScriptableRenderContext context, Camera camera)
{
camera = camera.GetComponent<Camera>();
for (int i = 0; i < gameObjects.Length; i++)
{
Renderer renderer = gameObjects[i].GetComponent<Renderer>();
if (renderer != null)
{
Material material = renderer.material;
Debug.Log("i can't see everything");
material.SetColor(colorPropertyName, _default);
}
}
}
ik the getcomponent's terrible but i'm just testing atm
and it does switch out the colour but for both cameras
You need to check which camera is triggering that callback
For example if(camera != thisCamera) return;
And yeah remove the camera = camera.GetComponent<Camera>(); ofc
In my enemy detection script to see if the player is in sight, i seem to be getting a lot of gc, but I can't seem to find out why? Maybe I'm being dumb, but it's really lagging my game all of a sudden lol. If anyone has any ideas, I'd be glad to hear them!
This is the part in question:
private IEnumerable<RaycastHit> orderedShapecastHits;
private void DoShapecast() {
Physics.BoxCastNonAlloc(
center: transform.position,
halfExtents: transform.lossyScale / 2f,
direction: (Player.players[0].transform.position - transform.position).normalized,
results: shapecastHits,
orientation: Quaternion.identity,
maxDistance: currentReach,
layerMask: LayerMask.GetMask("Player", "Walls")
);
orderedShapecastHits = shapecastHits.OrderBy(hit => hit.distance);
foreach (RaycastHit hit in orderedShapecastHits) {
if (hit.collider == null) {
continue;
}
if (hit.collider.gameObject != Player.players[0].gameObject) {
break;
}
inSight = true;
Alert(hit.point);
break;
}
}```
GC is probably from Linq OrderBy
So it returns readable is true, the mesh allocation looks like this: ```C#
_mesh = new Mesh();
// We want GraphicsBuffer access as Raw (ByteAddress) buffers.
_mesh.indexBufferTarget |= GraphicsBuffer.Target.Raw;
_mesh.vertexBufferTarget |= GraphicsBuffer.Target.Raw;
// Vertex position: float32 x 3
var vp = new VertexAttributeDescriptor
(VertexAttribute.Position, VertexAttributeFormat.Float32, 3);
// Vertex normal: float32 x 3
var vn = new VertexAttributeDescriptor
(VertexAttribute.Normal, VertexAttributeFormat.Float32, 3);
// Vertex/index buffer formats
_mesh.SetVertexBufferParams(vertexCount, vp, vn);
_mesh.SetIndexBufferParams(vertexCount, IndexFormat.UInt32);
// Submesh initialization
_mesh.SetSubMesh(0, new SubMeshDescriptor(0, vertexCount),
MeshUpdateFlags.DontRecalculateBounds);
// GraphicsBuffer references
_vertexBuffer = _mesh.GetVertexBuffer(0);
_indexBuffer = _mesh.GetIndexBuffer();```
are there any better alternatives or do i just need to change how im doing it?
LayerMask.GetMask will also be allocating due to params array
i guess that would make sense too
I haven't used the new Mesh API yet so I don't really know, sorry
Seems like you only care about the closest hit, so you could manually for/foreach loop shapecastHits and store the closest hit in a variable
true. I think i originally planned on that but got lazy and did this lol. now its come back to bite me
You can make that a class level variable too, IIRC GetMask works in a field initializer
no sadly. i tried
and after i assigned it on init, gc shot up to 2mb
seems to be from this
Ah true, seems like I was doing thiscs static LayerMask sceneryMask; public static LayerMask GetSceneryMask() { if (sceneryMask == 0) sceneryMask = LayerMask.GetMask("Scenery", "SceneryTransparent"); return sceneryMask; }
Np i think i have found a solution, reading the buffer back and converting it to an array (var buffer = meshBuilder.Mesh.GetVertexBuffer(0);) .. thx anyways
idk what its doing there, but for some reason, its using stringbuilder to append a LOT of strings
Something is throwing an exception. That's expensive
this is some exception printing a stack trace
okay, so this does seem to be it! it works a lot better now, thanks!
it is detecting the right camera but the wrong cameras still swap it for some reason
they shouldn't render at the same time, they're completely seperate parts of the stack
oh wait the default colour isn't being set properly it needs to set to an array duh
now it just sets them all to the original colour even for the camera that's meant to replace damn
actually it might be working
but not rendering to the camera preview
yeah nice it's just that the preview camera is rendererd seperately to the render texture
it's working properly now, thanks @hexed pecan
Hi, I'd need help with a model I'm trying to use!
Basically my problem is I've got an FBX model that's already in use in the scene and I don't want to reimport a new one or even use an external modeling software again (I'm terrible at using Blender).
aaand my objective here
is I want to modify every MESH that the project explorer sees inside of the FBX so that they all have their Bounds Center set to 0
crucially, it has to modify the actual FBX ON DISK as well
Is it possible?
FBX exporter could help
https://docs.unity3d.com/Packages/com.unity.formats.fbx@2.0/manual/index.html
You can load the sub-meshes from the FBX file with AssetDatabase.LoadAssetsAtPath, I believe.
I know that modifying a copy of a mesh is possible, but I have never exported it back to FBX
Just saved as an asset
Hmm I'll have to look into that
This is pretty complex for something you could easily do in blender though.
I mean I did manage to achieve this programmatically but yeah it doesn't change the actual FBX in my assets
I personally save my generated meshes as a sub-asset of a ScriptableObject
It's also possible to save it as a prefab
I mean, if I did this, would anything I've made using the FBX be lost? Or can I reimport it after I'm done and have every (unpacked) little piece update to the new meshes that have been recentered?
Unity treats 3D models as prefabs with MeshRenderer+MeshFilter anyways
You can overwrite the FBX and the import settings and references will stay
As long as you don't change object names/hierarchies in the FBX
Hmm okay now that sounds good
I suppose fixing it through Blender really is the smarter choice, would you happen to know if some place explains the use case of literally just changing the Bounds Center in a simple way?
I'm kinda lost with Blender but I'd rather not ask for someone to walk me through every step on a Unity server lol
In blender, Shift + S -> Cursor To World Origin
Go to object mode, select the object, open the commands (F3?) and search for Set Origin -> Origin To 3D Cursor
If you want to set the object's origin to 0,0,0.
Also !blender
A supportive community for Blender artists of all levels. Share your work, ask for help, and learn from others! https://discord.com/invite/blender
See that's also what I'm confused about
might as well ask here as it's not completely Blender-related just yet
so erm… I think setting every piece's origin to (0, 0, 0) is what was done already
I mean, I believe so; all I can see is Unity's inspector shows Bounds Center with some gibberish values, different for every piece… so I guess I don't want them to have 0 as their origin?
That's why I'm confused. All I know is the end goal is to have Unity show (0, 0, 0) as the Bounds Center for all the pieces, but this might be a case of “oh it's the opposite actually” and in Blender that's not what we want~
Why do you need the bounds center at 0?
The way the FBX was originally exported from Blender (by someone else), all origins were reset (I believe that's the term they used)
as such, every child GameObject once imported in Unity had precisely (0, 0, 0) as its transform position
Is the FBX like a 3D scene with multiple objects? And their origins are at zero, not at where the objects are?
In any case I don't think you want to edit bounds. Those are used for culling, for example
that's pretty much it yeah~
idk I'll wanna have moving parts in there and it made sense to me that GameObjects actually appeared to be at their true locations, with the origin gizmo and all
Then do this, except you want Origin To Geometry instead
And don't need to do the Cursor To World Origin part
So yeah I since changed each piece's coordinates to be that of its associated mesh's Bounds Center. But in return, you guessed it, I figured I needed to recenter every mesh.
ooo yeah makes sense, I'll try that—I'm guessing it'll then translate to (0, 0, 0) Bounds Center in Unity
Yeah Origin To Geometry does exactly the same as adjusting the origin to bounds.center in unity
Nice! But if I understood correctly, that's not a recommended thing to do?
Of course and thank you for that!
But you said changing that kind of model setup is usually not something we want. Was there some misunderstanding between us or am I really trying to do something unusual?
Actually you might want to try one of the two bottom options too, see what works best for you
Changing the origin is fine, the hierarchy order and naming is what would cause it to unlink
Though do make a backup of the FBX and/or blend file before you change stuff
Oh yes of course, I'm not going to change the FBX's hierarchy as that's now where my stuff is pulling resources from!
I mean hopefully I won't change it, if I don't mess this up~
I work with Git (yeah shame) so I do have a backup of the FBX indeed 👍
So… (I mean I really should go annoy Blender people at this point) but that can be done with all the pieces selected, right? Would A literally do the trick? (cuz I'm guessing some of the elements are containers of sorts and don't have meshes attached or whatever)
It does work for multi selection. Try it and see
sure thing, Imma do it right now, I'll see if it exports the same
Send possible further questions into #🔀┃art-asset-workflow or blender discord
got it about Blender questions, thank you very much for your help so far!
It's possible that you want to exclude the 'containers' from the selection, but you have to try to see.
No prob!
yeahhh nested hell
OH THIS WORKED SO WELL!
massive thanks @hexed pecan ❤️
hit F3, type funny stuff, click, export and win :3
For future reference, for anyone reading this whenever: the first suggestion of going with Origin to Geometry was it. Centers of mass are interesting but I don't suppose they really correspond to the Bounds, which was my use case ^^
Hey everyone
Does anyone know how to achieve wall jumping?
The issue is, I'm able to make the 2D box jump from one wall to another back and forth
But I want my character to be able to jump along the same wall if the left arrow is held
I tried with trial and error
But it doesn't seem to be doing much
Show what you have now
Should I DM it?
Or should I just paste it here?
No, never
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Oh ok
Thanks
@spring creek
Ignore the comments, those were there so that the rest of my dev team didn't have to be confused by everything
What I do is I have a class for ComtactState which stores and accumulates information about what we are touching
Mhm
Can you show the WallCheck object
ContactState has things like grounded, onLeftWall, onRightWall, etc
ContactState gets populated from EITHER: 1) Collision callbacks, or 2) reading GetContacts
Yeah I figured. I wanted to see where it was though.
So it's only on one side it looks like.
Yes
Yup
either way, before you actually issue any jumps, you need to go through and get information for your current ContactState, to know if you are touching a left wall, right wall, floor, etc
True
I should change it to accomodate it that way
you will want it for enemies too, so you might as well
Yeah I can make it a common class
for wall jumping, there’s a bit that goes into it. are you struggling more with logic of when to do it, or how to make the wall jump happen?
eg the physics of the jump
No no
I think you misread my question
I can make it wall jump between two walls
But I can't make it so that the character wall jumps across the same wall if the left key is held
Well, right now it looks like what you have should work if you're facing the wall. Might be an issue that you change the local scale any time you jump from the wall though
if you want to capture both sides, you probably need a check on both sides.
you mean chaining wall jumps against one wall?
True
Yeah
It's a direction issue i think
separately, the first thing I would do, is rip out all the bools for “isWallSliding”, isWallJumping, isJumping… etc. This should all be one enum because they are mutually exclusive states
player movement scripts get super complex, and this will simplify everything dramatically
Sure
But how do I fix the actual problem where it's not going in one line?
Or how do I figure it out?
your code confuses me in how you split wall jump and regular jump
It's not really a 'but'. Making your code cleaner will help everyone else debug it too
Don't use the wallDirection to set _frameVelocity
wall jump should get called AFTER an attempt to call a normal jump fails. Not just calling WallJump in the main update loop
Sure
Wdym?
Ah
i would start refactoring with a MoveState enum. it will help tremendously
sure
What would I use in place of this do you think?
enum MoveState { Neutral, Swimming, Jumping, WallJumping, Sliding }
alright
thank you :D
when I'm done I'll tell you
if it still doesn't work as well as i want it to
but it helps a lot thank you so much, I'll get to it right now
You can still use properties like bool isWallJumping => moveState == MoveState.WallJumping if you want
hm yeah
_frameVelocity.x = wallJumpingDirection * _stats.wallJumpingPower.x;
i inheritted some code from dawnosaur, and I never fully recovered from spaghetti poisonning. Your code looks like that, but less intense. And you should nip it in the bud before the spaghetti monster comes for you
But a state machine would be best, where you don't have to do those checks
what do i use instead?
lol
i tried at least 3 times to refactor, and I still could not get it all out
It depends on what you want. Do you want the local scale to define the x component of your velocity? Seems like NOT what you want. So just don't do that. Use input instead.
If you press left, go left, etc
the main challenge was him storing a ton of booleans and floats, which made it hard to de-spaghetti
oh yeah
i can do that
you're right
But yeah, honestly just simplifying as loup said will make it way easier
i will
for actual wall jump, would personally hard set velocity. directly assigning velocity to a specific number makes the jump arc unaffected by your prior movement, movement in any reference frame, or any inheritted movement etc
it is the opposite of how celeste is coded, where I believe madeline’s wall jump obeys the physics of the wall she jumps from
yeah that sounds like it would work.
i wanted more celeste type movement.
if you want celeste-like, then you need to apply impulse mode force
madeline inherits movement from all sorts of shit that she touches, and the effects all stack
i can experiment ig
yeah
this also means your wall jump gets gimped if wall jumping from a falling wall. or is affected by your sliding speed etc. so be mindful.